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