Last active
August 29, 2015 13:59
-
-
Save luqmaan/10595407 to your computer and use it in GitHub Desktop.
Convert Sass to SCSS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from pprint import pprint | |
import re | |
def count_leading_spaces(line): | |
return len(line) - len(line.lstrip(' ')) | |
def sass_to_scss(sass_lines): | |
outlines = [] | |
cleaned = [] | |
css_rule = re.compile(r'\s+\w+:') | |
for line in sass_lines: | |
if line.isspace(): | |
continue | |
cleaned.append(line.replace('\n', '')) | |
for i, line in enumerate(cleaned): | |
indent = count_leading_spaces(sass_lines[i]) | |
try: | |
next_indent = count_leading_spaces(sass_lines[i + 1]) | |
except IndexError: | |
next_indent = 0 | |
try: | |
prev_indent = count_leading_spaces(sass_lines[i - 1]) | |
except IndexError: | |
prev_indent = 0 | |
if css_rule.match(line) is not None: | |
line += ';' | |
if indent < next_indent: | |
outlines.append(line + ' ' + '{') | |
elif indent > prev_indent and indent != next_indent: | |
outlines.append(line) | |
closed_indent = indent | |
spaces = indent - prev_indent | |
while closed_indent != next_indent: | |
insert = ' ' * (closed_indent - spaces) + '}' | |
outlines.append(insert) | |
closed_indent -= spaces | |
else: | |
outlines.append(line) | |
return '\n'.join(outlines) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from unittest import TestCase | |
import sass_to_scss | |
class TestSassToSCSS(TestCase): | |
def trim_docstring(self, docstring): | |
return '\n'.join(docstring.split('\n')[1:-1]) | |
def test_triple_nested_class(self): | |
sass = """ | |
.container | |
position: absolute | |
top: 0 | |
color: green | |
bottom: 0 | |
.right | |
right: 0 | |
border: 1px solid #fff | |
h1 | |
color: blue | |
.left | |
left: 0 | |
h1 | |
color: red | |
""" | |
scss = """ | |
.container { | |
position: absolute; | |
top: 0; | |
color: green; | |
bottom: 0; | |
.right { | |
right: 0; | |
border: 1px solid #fff; | |
h1 { | |
color: blue; | |
} | |
} | |
.left { | |
left: 0; | |
h1 { | |
color: red; | |
} | |
} | |
} | |
""" | |
input = self.trim_docstring(sass).split('\n') | |
actual = sass_to_scss.sass_to_scss(input) | |
expected = self.trim_docstring(scss) | |
print actual | |
self.assertEquals(expected, actual) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment