def scss_compile(filename): from scss import Scss scss = Scss(search_paths=[os.path.dirname(filename)]) if six.PY3: return scss.compile(contents(filename)) else: return scss.compile(contents(filename).encode('utf-8')).decode('utf-8')
def __call__(self, scss, system): parser = Scss(scss_opts=self.options) if 'request' in system: request = system['request'] request.response_content_type = 'text/css' if not self.options.get('cache', False) or scss not in self.cache: Logger.info('caching %s', request.matchdict.get('css_path')) self.cache[scss] = parser.compile(scss) return self.cache.get(scss) return parser.compile(scss)
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 __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 __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 do_build(options, args): if options.output is not None: output = open(options.output, "wt") else: output = sys.stdout css = Scss(scss_opts={"compress": options.compress, "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_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 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 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 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))
class ScssTemplate(Template): default_mime_type = 'text/css' @staticmethod def is_engine_initialized(): return 'Scss' in globals() def initialize_engine(self): global Scss from scss import Scss def prepare(self): self.engine = Scss(scss_opts=self.sass_options()) def sass_options(self): options = self._options options.update({ 'filename': self.eval_file(), 'line': self._line, 'syntax':'scss' }) return options def evaluate(self,scope, locals, block=None): if not hasattr(self,'output') or not self.output: self.output = self.engine.compile(self.data) return self.output
class StaticCompiler(object): """ Static files minifier. """ def __init__(self, path): self.css_parser = Scss() scss.LOAD_PATHS = path def compile_file(self, filepath, need_compilation=True): result = self.get_content(filepath) if need_compilation: mimetype = mimetypes.guess_type(filepath)[0] result = self.compile_text(result, mimetype) return result def compile_text(self, text, mimetype): result = "" if mimetype == "text/css": result = self.css_parser.compile(text) elif mimetype == "application/javascript": result = jsmin(text) else: result = text return result def get_content(self, file): return open(file).read()
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 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 scss(request, path): settings = request.registry.settings cache = asbool(settings['css_cache']) compress = asbool(settings['css_compress']) new_css_filename = 'local.css' asset_path = pkg_resources.resource_filename('devqus', 'static' + path) asset_prefix = os.path.dirname(path) new_path = os.path.join(os.path.dirname(asset_path), new_css_filename) asset_modified = int(os.stat(asset_path).st_mtime) assetc_modified = None if os.path.exists(new_path): assetc_modified = int(os.stat(new_path).st_mtime) # if the asset has changed recently than the compiled one, # then we know it has been modified. if not assetc_modified or asset_modified > assetc_modified: # Create parser object scss_compiler = Scss(scss_opts={'compress': compress, 'cache': cache}) asset = scss_compiler.compile(open(asset_path).read()) f = open(new_path, 'w') f.write(asset) f.close() less_asset = os.path.join(asset_prefix, new_css_filename) return assets_url(request, less_asset)
def sassify(file,input,output): #process scss file using Sass scss = read_file(file,input) compiler = Scss(scss_opts={'style':'compact'}) css = compiler.compile(scss) fileName = file[:-4]+'css' write_file(fileName,output,css)
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 _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 compile_assets(config): adir = config.pathto('assets') if not os.path.exists(adir): print("Warning: no assets directory") return scss = Scss() outdir = config.outpathto('assets') for (dirpath, dirnames, filenames) in os.walk(adir): for fn in filenames: sfn = os.path.join(dirpath, fn) ddir = os.path.join(outdir, dirpath[len(adir):].lstrip('/')) makedirs(ddir) dfn = os.path.join(ddir, fn) ext = sfn[sfn.rindex('.')+1:] if ext == "scss": dfn = dfn[:-4] + 'css' print("Converting {} to {}".format(sfn, dfn)) with open(sfn, 'r') as sf, open(dfn, 'w') as df: df.write(scss.compile(sf.read())) else: print("Copying {} to {}".format(sfn, dfn)) shutil.copyfile(sfn, dfn)
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 main(): current_directory = os.getcwd() logging.info("Compiling from local files ...") dashing_dir = os.path.join(current_directory, 'pydashie') logging.info("Using walk path : %s" % dashing_dir) fileList = [] 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) 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: if not fileName.endswith('~'): # discard any temporary files 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])) app_css_filepath = os.path.join(current_directory, 'pydashie/assets/stylesheets/application.css') with open(app_css_filepath, 'w') as outfile: outfile.write(css_output.getvalue()) log.info('Wrote CSS out to : %s' % app_css_filepath )
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 expandScss(self,header,content,config=None): from scss import Scss #TODO offline images css = Scss(scss_opts={ "compress": config["css-compress"], }) #TODO scss unicode call return unicode(css.compile(content))
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 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 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 list(profiling.items()): sys.stderr.write("%s took %03fs" % (f, t))
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
class ScssCompiler(MutatingPostProcessingPlugin): input_extension = '.scss' output_extension = '.css' def init(self): self.css = Scss() def process_data(self, data): return self.css.compile(data)
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')
class ScssEventHandler(PatternMatchingEventHandler): def __init__(self, *args, **kwargs): super(ScssEventHandler, self).__init__(*args, **kwargs) self.css = Scss( scss_opts={ 'compress': options.compress, 'debug_info': options.debug_info, }) self.output = options.output self.suffix = options.suffix def is_valid(self, path): return os.path.isfile(path) and ( path.endswith('.scss') or path.endswith('.sass') ) and not os.path.basename(path).startswith('_') def process(self, path): if os.path.isdir(path): for f in os.listdir(path): full = os.path.join(path, f) if self.is_valid(full): self.compile(full) elif self.is_valid(path): self.compile(path) def compile(self, src_path): fname = os.path.basename(src_path) if fname.endswith('.scss') or fname.endswith('.sass'): fname = fname[:-5] if self.suffix: fname += '.' + self.suffix fname += '.css' else: # you didn't give me a file of the correct type! return False if self.output: dest_path = os.path.join(self.output, fname) else: dest_path = os.path.join(os.path.dirname(src_path), fname) print("Compiling %s => %s" % (src_path, dest_path)) dest_file = open(dest_path, 'w') dest_file.write(self.css.compile(scss_file=src_path)) def on_moved(self, event): super(ScssEventHandler, self).on_moved(event) self.process(event.dest_path) def on_created(self, event): super(ScssEventHandler, self).on_created(event) self.process(event.src_path) def on_modified(self, event): super(ScssEventHandler, self).on_modified(event) self.process(event.src_path)
def regenerate_scss(): compiler = Scss() filenames = get_scss_filenames() for filename in filenames: with open(filename, 'r') as f: raw_sass = ''.join(f.readlines()) output = compiler.compile(raw_sass) output_filename = get_output_filename(filename) with open(output_filename, 'w') as f: f.write(output)
def compile_scss(self, **kwargs): css = Scss(scss_opts={ 'compress': False, 'debug_info': False, }) def matchdict(params, matchobj): return params.get(matchobj.groups()[0], matchobj.group()) changed = re.sub(r'%\(([\w\d]+)\)s', partial(matchdict, kwargs), dynamic_scss) return css.compile(changed)
class ScssEventHandler(PatternMatchingEventHandler): def __init__(self, *args, **kwargs): super(ScssEventHandler, self).__init__(*args, **kwargs) self.css = Scss(scss_opts={ 'compress': options.compress, 'debug_info': options.debug_info, }) self.output = options.output self.suffix = options.suffix def is_valid(self, path): return os.path.isfile(path) and path.endswith(".scss") and not os.path.basename(path).startswith("_") def process(self, path): if os.path.isdir(path): for f in os.listdir(path): full = os.path.join(path, f) if self.is_valid(full): self.compile(full) elif self.is_valid(path): self.compile(path) def compile(self, src_path): fname = os.path.basename(src_path) if fname.endswith(".scss"): fname = fname[:-5] if self.suffix: fname += "." + self.suffix fname += ".css" else: # you didn't give me a file of the correct type! return False if self.output: dest_path = os.path.join(self.output, fname) else: dest_path = os.path.join(os.path.dirname(src_path), fname) print "Compiling %s => %s" % (src_path, dest_path) src_file = open(src_path) dest_file = open(dest_path, 'w') dest_file.write(self.css.compile(src_file.read())) def on_moved(self, event): super(ScssEventHandler, self).on_moved(event) self.process(event.dest_path) def on_created(self, event): super(ScssEventHandler, self).on_created(event) self.process(event.src_path) def on_modified(self, event): super(ScssEventHandler, self).on_modified(event) self.process(event.src_path)
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
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 main(): #Options refreshDashingCode=True #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 = [] 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 _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 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 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 compile_scss(self, **kwargs): genwebthemeegg = pkg_resources.get_distribution('genweb.theme') ulearnthemeegg = pkg_resources.get_distribution('ulearn.theme') scssfile = open('{}/ulearn/theme/scss/dynamic.scss'.format(ulearnthemeegg.location)) settings = dict(main_color=self.settings.main_color, secondary_color=self.settings.secondary_color, background_property=self.settings.background_property, background_color=self.settings.background_color, buttons_color_primary=self.settings.buttons_color_primary, buttons_color_secondary=self.settings.buttons_color_secondary, maxui_form_bg=self.settings.maxui_form_bg, alt_gradient_start_color=self.settings.alt_gradient_start_color, alt_gradient_end_color=self.settings.alt_gradient_end_color, color_community_closed=self.settings.color_community_closed, color_community_organizative=self.settings.color_community_organizative, color_community_open=self.settings.color_community_open) variables_scss = """ $main-color: {main_color}; $secondary-color: {secondary_color}; $background-property: {background_property}; $background-color: {background_color}; $buttons-color-primary: {buttons_color_primary}; $buttons-color-secondary: {buttons_color_secondary}; $maxui-form-bg: {maxui_form_bg}; $alt-gradient-start-color: {alt_gradient_start_color}; $alt-gradient-end-color: {alt_gradient_end_color}; $color_community_closed: {color_community_closed}; $color_community_organizative: {color_community_organizative}; $color_community_open: {color_community_open}; """.format(**settings) scss.config.LOAD_PATHS = [ '{}/genweb/theme/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 _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 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 application_css(): # TODO: refactor !! scripts = [ 'assets/stylesheets/application.css', ] output = [] for path in scripts: output.append(open(path).read()) compilelist = [ 'widgets/priority_list/priority_list.scss', #if making new templates input scss files here 'widgets/jira/jira.scss' ] css = Scss() for path in compilelist: scss = open(path).read() output.append(css.compile(scss)) return Response('\n'.join(output), mimetype='text/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
def main(): current_directory = os.getcwd() logging.info("Compiling from local files ...") dashing_dir = os.path.join(current_directory, 'pydashie') logging.info("Using walk path : %s" % dashing_dir) fileList = [] 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) 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: if (not fileName.endswith('~') and not fileName == "application.css"): # discard any temporary files # ignore the base application.css (duplication issues) 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])) app_css_filepath = os.path.join( current_directory, 'pydashie/assets/stylesheets/application.css') with open(app_css_filepath, 'w') as outfile: outfile.write(css_output.getvalue()) log.info('Wrote CSS out to : %s' % app_css_filepath)
def application_css(): from scss import Scss parser = Scss() stylesheets = [] for ext in ['css', 'scss']: stylesheets.extend( glob.glob(os.path.join(os.getcwd(), "assets/**/*.%s") % ext)) for ext in ['css', 'scss']: stylesheets.extend( glob.glob(os.path.join(os.getcwd(), "widgets/**/*.%s") % ext)) output = [] for path in stylesheets: if '.scss' in path: contents = parser.compile(scss_file=path) else: f = open(path) contents = f.read() f.close() output.append(contents) return Response("\n".join(output), mimetype='text/css')
def test_live_errors(): compiler = Scss(live_errors=True) output = compiler.compile("""$foo: unitless(one);""") assert "body:before" in output assert "TypeError: Expected" in output
prev_page=prev_page, next_page=next_page, version=version) out_fn = os.path.join(DUMP_DIRSTEM[version], fn[:-5] + '.html') out_fh = open(out_fn, 'w') out_fh.write(src) out_fh.close() print fn # Now compile CSS for version in VERSIONS: css = Scss() css_template_dir = os.path.join(TEMPLATE_DIR, CSS_DIR) out_str = '' for fn in os.listdir(css_template_dir): fp = os.path.join(css_template_dir, fn) if (not fn.endswith('.css')) and (not fn.endswith('.scss')): continue fh = open(fp) fstr = fh.read() fh.close() if fn.endswith('.css'): out_str = out_str + fstr if fn.endswith('.scss'): out_str = out_str + css.compile(fstr) out_fn = os.path.join(DUMP_DIRSTEM[version], CSS_DIR, CSS_FILE) print out_fn out_fh = open(out_fn, 'w') out_fh.write(out_str) out_fh.close()