def do_build(options, args): if options.output is not None: out = open(options.output, 'wb') else: out = sys.stdout # Get the unencoded stream on Python 3 out = getattr(out, 'buffer', out) css = Scss(scss_opts={ 'style': options.style, 'debug_info': options.debug_info, }) if args: source_files = [ SourceFile.from_file(sys.stdin, "<stdin>", is_sass=options.is_sass) if path == '-' else SourceFile.from_filename( path, is_sass=options.is_sass) for path in args ] else: source_files = [ SourceFile.from_file(sys.stdin, "<stdin>", is_sass=options.is_sass) ] encodings = set(source.encoding for source in source_files) if len(encodings) > 1: sys.stderr.write("Can't combine these files! " "They have different encodings: {0}\n".format( ', '.join(encodings))) sys.exit(3) output = css.compile(source_files=source_files) out.write(output.encode(source_files[0].encoding)) for f, t in profiling.items(): sys.stderr.write("%s took %03fs" % (f, t))
def transform(self, result, encoding): css = u'' javascript = u'' for parent in parents(self.published.context, iface=IFlowFolder): css = parent._v_css = getattr( # noqa: P001 parent, '_v_css', Scss().compile(parent.css or u''), ) javascript =\ (parent.javascript or u'').strip().replace(u'\r\n', u'\n') break root = result.tree.getroot() if css: head = root.find('head') # trick LXML to render styles with //<!CDATA[[ style = builder.STYLE(u'\n/*', type='text/css') style.append(builder.S(CDATA(u'*/\n' + css + u'\n/*'))) style.getchildren()[0].tail = u'*/\n' head.append(style) # head.append(builder.STYLE( # css, # type='text/css', # )) if javascript: body = root.find('body') # trick LXML to render script with //<!CDATA[[ script = builder.SCRIPT(u'\n//', type='application/javascript') script.append(builder.S(CDATA(u'\n' + javascript + u'\n//'))) script.getchildren()[0].tail = u'\n' body.append(script) return result
def _convert(src, dst): css = Scss() source = codecs.open(src, 'r', encoding='utf-8').read() output = css.compile(source) outfile = codecs.open(dst, 'w', encoding='utf-8') outfile.write(output) outfile.close()
def test_extend_across_files(): compiler = Scss(scss_opts=dict(compress=0)) compiler._scss_files = OrderedDict() compiler._scss_files['first.css'] = ''' @option style:legacy, short_colors:yes, reverse_colors:yes; .specialClass extends .basicClass { padding: 10px; font-size: 14px; } ''' compiler._scss_files['second.css'] = ''' @option style:legacy, short_colors:yes, reverse_colors:yes; .basicClass { padding: 20px; background-color: #FF0000; } ''' actual = compiler.compile() expected = """\ .specialClass { padding: 10px; font-size: 14px; } .basicClass, .specialClass { padding: 20px; background-color: #FF0000; } """ assert expected == actual
def compile_scss(self, **kwargs): genwebthemeegg = pkg_resources.get_distribution('genweb.alternatheme') scssfile = open('{}/genweb/alternatheme/scss/_dynamic.scss'.format( genwebthemeegg.location)) settings = dict(especific1=self.especific1, especific2=self.especific2) variables_scss = """ $genwebPrimary: {especific1}; $genwebTitles: {especific2}; """.format(**settings) scss.config.LOAD_PATHS = [ '{}/genweb/alternatheme/bootstrap/scss/compass_twitter_bootstrap'. format(genwebthemeegg.location) ] css = Scss(scss_opts={ 'compress': False, 'debug_info': False, }) dynamic_scss = ''.join([variables_scss, scssfile.read()]) return css.compile(dynamic_scss)
def test_debug_info(): # nb: debug info doesn't work if the source isn't a file compiler = Scss(scss_opts=dict(style='expanded', debug_info=True)) compiler._scss_files = {} compiler._scss_files['input.css'] = """\ div { color: green; } table { color: red; } """ expected = """\ @media -sass-debug-info{filename{font-family:file\:\/\/input\.css}line{font-family:\\000031}} div { color: green; } @media -sass-debug-info{filename{font-family:file\:\/\/input\.css}line{font-family:\\000034}} table { color: red; } """ output = compiler.compile() assert expected == output
def preprocessCSS(self, targetFile): from scss import Scss logging.basicConfig() scssVariables = {} scssCompiler = Scss( scss_vars=None, scss_opts={ 'compress': True, # 'debug_info': True, }, scss_files=self.loadIndividualFilesContent('scss', self.settings['scss']), # super_selector = None, # live_errors = False, # library = ALL_BUILTINS_LIBRARY, search_paths=[os.path.join(self.absolutePathForSources(), 'scss')]) cssFileContent = scssCompiler.compile() dst = targetFile dst = os.path.join(os.path.dirname(dst), "_" + os.path.basename(dst)) main.createFolder(os.path.dirname(dst)) file = open(dst, 'w') file.write(cssFileContent.encode('utf-8')) file.close()
def __init__(self, *args, **kwargs): super(ScssEventHandler, self).__init__(*args, **kwargs) self.css = Scss(scss_opts={ 'style': options.style, 'debug_info': options.debug_info, }) self.output = options.output self.suffix = options.suffix
def get_dev_output(self, name, variation, content=None): compiler = Scss() # here we support piped output if not content: content = super(ScssFilter, self).get_dev_output(name, variation) return compiler.compile(str(content.encode("utf8")))
def _bake_css_file(input_filename, output_filename): css_f = open(input_filename, 'r') css_content = Scss().compile(css_f.read()) css_f.close() dest = open(output_filename, 'w') dest.write(css_content) dest.close()
def __init__(self, is_sass=False): self.css = Scss() self.namespace = self.css.root_namespace self.options = self.css.scss_opts self.source_file = SourceFile.from_string('', '<shell>', line_numbers=False, is_sass=is_sass) self.calculator = Calculator(self.namespace)
def test_unicode_files(): compiler = Scss(scss_opts=dict(style='expanded')) unicode_input = u"""q { quotes: "“" "”" "‘" "’"; } """ output = compiler.compile(unicode_input) assert output == unicode_input
def main(): #Options refreshDashingCode = False #Check out dashing into temp directory current_directory = os.getcwd() tmp_dir = os.path.join(current_directory, 'tmp') if not os.path.exists(tmp_dir): log.info('Creating tmp dir %s' % tmp_dir) os.mkdir(tmp_dir) tmp_build_dir = os.path.join(tmp_dir, 'bin') if not os.path.exists(tmp_build_dir): log.info('Creating bin dir %s' % tmp_build_dir) os.mkdir(tmp_build_dir) dashing_dir = os.path.join(current_directory, 'tmp', 'dashing') if refreshDashingCode: if os.path.exists(dashing_dir): log.info('Removing old Dashing Clone') shutil.rmtree(dashing_dir) log.info('Creating dashing tmp dir %s' % dashing_dir) os.mkdir(dashing_dir) os.chdir(dashing_dir) if refreshDashingCode: log.info('Cloning Dashing Code') subprocess.call("git clone https://github.com/Shopify/dashing", shell=True) fileList = [] print dashing_dir for root, subFolders, files in os.walk(dashing_dir): for fileName in files: if 'scss' in fileName: fileList.append(os.path.join(root, fileName)) log.info('Found SCSS to compile: %s' % fileName) import StringIO css_output = StringIO.StringIO() css = Scss() css_output.write('\n'.join( [css.compile(open(filePath).read()) for filePath in fileList])) fileList = [] for root, subFolders, files in os.walk(dashing_dir): for fileName in files: if 'css' in fileName and 'scss' not in fileName: fileList.append(os.path.join(root, fileName)) log.info('Found CSS to append: %s' % fileName) css_output.write('\n'.join( [open(filePath).read() for filePath in fileList])) with open(os.path.join(tmp_build_dir, 'application.css'), 'w') as outfile: outfile.write(css_output.getvalue()) log.info('Wrote CSS out')
def serve(self, request): try: resp = super(ScssMediaHandler, self).serve(request) except Http404: path = request.path[len(settings.STATIC_URL):] resp = serve(request, path[:-4] + '.scss') resp.content = Scss().compile(resp.content) resp['Content-Length'] = len(resp.content) resp['Content-Type'] = 'text/css' return resp
def bake_css(): css_f = open(os.path.join(os.path.dirname(__file__), "../static/style/_sass.scss"), 'r') css_content = Scss().compile(css_f.read()) css_f.close() create_baked_directory() dest = open(os.path.join(os.path.dirname(__file__), "../static/baked/", str(get_build_number()), "style.css"), 'w') dest.write(css_content) dest.close() css_f = open(os.path.join(os.path.dirname(__file__), "../static/style4/_sass.scss"), 'r') css_content = Scss().compile(css_f.read()) css_f.close() create_baked_directory() dest = open(os.path.join(os.path.dirname(__file__), "../static/baked/", str(get_build_number()), "style4.css"), 'w') dest.write(css_content) dest.close()
def render(source, **kwargs): compiler = Scss(scss_opts=dict(compress=False), **kwargs) css = compiler.compile(source) # TODO chumptastic hack; sass and pyscss have slightly different # "non-compressed" output import re css = re.sub(r'\n *[}]$', ' }', css) #css = re.sub(r'; [}]', ';\n }', css) return css
class SassFilter(CssAbsoluteFilter): compiler = Scss() def __init__(self, content, attributes, filter_type=None, filename=None): return super(SassFilter, self).__init__(content, filter_type=filter_type, filename=filename) def input(self, *args, **kwargs): compiler = Scss( search_paths=[os.path.dirname(self.filename)] ) self.content = compiler.compile(self.content.encode('utf-8')) return super(SassFilter, self).input(*args, **kwargs)
def assert_rendering(input, expected, **kwargs): compiler = Scss(scss_opts=dict(compress=False), **kwargs) css = compiler.compile(input) # TODO chumptastic hack; sass and pyscss have slightly different # "non-compressed" output import re css = re.sub(r'(?m)\n *[}]$', ' }\n', css).rstrip("\n") + "\n" #css = re.sub(r'; [}]', ';\n }', css) #css = re.sub(r'\n *[}]$', ' }', css) assert expected == css
def run(): # Available values are 'nested', 'expanded', 'compact', 'compressed' and 'legacy': compiler = Scss(scss_opts={"style": "expanded"}) for fname in os.listdir("_scss"): name, ext = os.path.splitext(fname) if ext != ".scss": continue css = compiler.compile(open(os.path.join("_scss", fname)).read()) with open( zf.util.path_join(zf.writer.output_dir, "css", "%s.css" % name), "w") as out: out.write(css)
def _convert(dir, src, dst): original_wd = os.getcwd() os.chdir(dir) css = Scss() source = codecs.open(src, 'r', encoding='utf-8').read() output = css.compile(source) os.chdir(original_wd) outfile = codecs.open(dst, 'w', encoding='utf-8') outfile.write(output) outfile.close()
def __call__(self, scss, system): parser = Scss(scss_opts=self.options) if 'request' in system: request = system.get('request') request.response.content_type = 'text/css' key = request.matchdict.get('css_path') if not self.options.get('cache', False) or key not in self.cache: Logger.info('generating %s', key) self.cache[key] = parser.compile(scss) return self.cache.get(key) return parser.compile(scss)
def fix_css(prefix_id, css_data): # remove fontface with scss bug fontface = [] for m in regex_fontface.findall(css_data): fontface.append(m) data = regex_fontface.sub('', css_data) # with compressed css = Scss(scss_opts={'style': True}) data = css.compile('#%s .mdict { %s }' % (prefix_id, data)) data = regex_body.sub(r'\2 \1 \3', data) # add fontface data = '\n'.join(fontface) + data return data
def draw_css_button(width=200, height=50, text='This is a button', color=rgb(200, 100, 50)): """ Draws a simple CSS button. """ # TODO: once we've decided on a scss compiler, import it at the top instead from scss import Scss # TODO: make this customizable css_class = 'button' html = '<a class="{0}" href="TODO">{1}</a>'.format(css_class, text) css = Scss() scss_str = "a.{0} {{color: red + green;}}".format(css_class) css.compile(scss_str)
def _scss(file,root): SCSS = Scss() source_path = root + "/" + file destination_directory = "static/css/" + root.replace("templates/","") destination_path = destination_directory + "/" + file.replace(".scss",".css") # Create directories if they don't exist if not os.path.exists(destination_directory): os.makedirs(destination_directory) source_data = codecs.open(source_path,"r",encoding="utf-8").read() compiled_data = SCSS.compile(source_data) destination_data = codecs.open(destination_path,"w",encoding="utf-8") destination_data.write(compiled_data) destination_data.close()
def generate_css(self): css = Scss() scss_input = ['@option style:compressed;'] # add variables scss_input.append(self.read_file('variables.scss')) # add overwritten variables scss_input.append(self.get_options().encode('utf8')) # add component files for scss_file in SCSS_FILES: scss_input.append(self.read_file(scss_file)) # add overwritten component files # for now its not possible to add custom styles styles = css.compile('\n'.join(scss_input)) styles = replace_custom_keywords(styles, self.context) return styles
def do_build(options, args): if options.output is not None: output = open(options.output, 'wt') else: output = sys.stdout css = Scss(scss_opts={ 'style': options.style, 'debug_info': options.debug_info, }) if args: for path in args: output.write(css.compile(scss_file=path, is_sass=options.is_sass)) else: output.write(css.compile(sys.stdin.read(), is_sass=options.is_sass)) for f, t in profiling.items(): sys.stderr.write("%s took %03fs" % (f, t))
def test_pair_programmatic(scss_file_pair): scss_fn, css_fn = scss_file_pair with open(scss_fn) as fh: source = fh.read() with open(css_fn) as fh: expected = fh.read() directory, _ = os.path.split(scss_fn) include_dir = os.path.join(directory, 'include') compiler = Scss(scss_opts=dict(compress=0), search_paths=[include_dir]) actual = compiler.compile(source) # Normalize leading and trailing newlines actual = actual.strip('\n') expected = expected.strip('\n') assert expected == actual
def generate_css(self): css = Scss() scss_input = ['@option style:compressed;'] # add variables scss_input.append(self.read_file('variables.scss')) # add overwritten variables scss_input.append(self.get_options().encode('utf8')) # add component files registry = getUtility(ISCSSRegistry) for path in registry.get_files(self.context, self.request): with open(path, 'r') as file_: scss_input.append(file_.read()) # add overwritten component files # for now its not possible to add custom styles styles = css.compile('\n'.join(scss_input)) styles = replace_custom_keywords(styles, self.context) return styles
def generate_stylesheet(app, exception): # TODO: make this inclusive of HTML builders # instead, or something if app.builder.name == 'latex': return to_gen = app._builder_scss compiler = Scss(scss_opts={"style": "expanded"}) if exception: return for static_path, name in to_gen: css = compiler.compile( open(os.path.join(static_path, "%s.scss" % name)).read()) dest = os.path.join(app.builder.outdir, '_static', '%s.css' % name) #copyfile(os.path.join(source, "%s.css" % name), dest) with open(dest, "w") as out: out.write(css)
def test_super_selector(): compiler = Scss(scss_opts=dict(style='expanded')) input = """\ foo, bar { a: b; } baz { c: d; } """ expected = """\ super foo, super bar { a: b; } super baz { c: d; } """ output = compiler.compile(input, super_selector='super') assert expected == output