import re data border 1px base-color fff include another_file css incl

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import re
data = """
@border: 1px;
@base-color: #fff;
@include(another_file.css);
@include(another_file.css);
@new_function(value);
#header {
color: @base-color;
border-left: @border-width @border-width @border-width @border-width;
border-right: 3px;
}
.footer {
color: #1999998;
}
"""
REGEX_FUNCTION = re.compile(r'@(.[0-9a-z-_ ]+)\((.[a-z-_\.\/\\]+)\);', re.S);
REGEX_VARIABLE = re.compile(r'@(.[0-9a-z-_]+)', re.S)
STORE_VARIABLES = {}
STORE_FUNCTIONS = {}
def function(f):
STORE_FUNCTIONS[f.__name__] = f
@function
def include(filename):
file = open(filename, 'r')
try:
data = file.read()
finally:
file.close()
return parse_css(data)
def parse_css(data):
for line in data.splitlines():
if line.startswith('@'):
if ':' in line:
var_name, value = line.split(':', 1)
STORE_VARIABLES[var_name] = value[:-1]
data = data.replace(line, '')
elif '(' in line and\
')' in line:
result = REGEX_FUNCTION.search(line)
func_name = ''
if result:
func_name, arg = list(result.groups())
func = STORE_FUNCTIONS.get(func_name, None)
if func:
result = func(arg)
data = data.replace(line, result)
else:
data = data.replace(line, '')
elif not line.startswith('@') and '@' in line:
result = REGEX_VARIABLE.search(line).groups()
for var_name in result:
var_name = '@'+var_name
value = STORE_VARIABLES.get(var_name, None)
if value:
result = line.replace(var_name, value)
data = data.replace(line, result)
return data