def sass(path): import glob import sass for filename in sorted(glob.glob(path)): print("SCSS compiling %s" % filename) sass.compile(filename=filename, precision=3)
def main(): if len(sys.argv) != 2: print "Usage: python sass-cli.py filename.sass" sys.exit(1) filename = sys.argv[1] with codecs.open(filename, encoding="utf-8", mode="r") as f: print sass.compile(string=f.read())
def build_rinds(args): """ Compile Sass found at rinds in user-specified order """ for rindpath in args.rinds: print sass.compile(**{ 'filename': rindpath, 'output_style': 'compressed' if args.prod else 'expanded', })
def test_compile_string(self): actual = sass.compile(string='a { b { color: blue; } }') assert actual == 'a b {\n color: blue; }\n' commented = sass.compile(string='''a { b { color: blue; } color: red; }''', source_comments=True) assert commented == '''/* line 1, stdin */ a { color: red; } /* line 2, stdin */ a b { color: blue; } ''' actual = sass.compile(string=u'a { color: blue; } /* 유니코드 */') self.assertEqual( u'''@charset "UTF-8"; a { color: blue; } /* 유니코드 */ ''', actual ) self.assertRaises(sass.CompileError, sass.compile, string='a { b { color: blue; }') # sass.CompileError should be a subtype of ValueError self.assertRaises(ValueError, sass.compile, string='a { b { color: blue; }') self.assertRaises(TypeError, sass.compile, string=1234) self.assertRaises(TypeError, sass.compile, string=[])
def test_compile_string(self): actual = sass.compile(string='a { b { color: blue; } }') assert actual == 'a b {\n color: blue; }\n' commented = sass.compile(string='''a { b { color: blue; } color: red; }''', source_comments='line_numbers') assert commented == '''/* line 1, source string */ a { color: red; } /* line 2, source string */ a b { color: blue; } ''' actual = sass.compile(string=u'a { color: blue; } /* 유니코드 */') self.assertEqual( u'''a { color: blue; } /* 유니코드 */''', actual ) self.assertRaises(sass.CompileError, sass.compile, string='a { b { color: blue; }') # sass.CompileError should be a subtype of ValueError self.assertRaises(ValueError, sass.compile, string='a { b { color: blue; }') self.assertRaises(TypeError, sass.compile, string=1234) self.assertRaises(TypeError, sass.compile, string=[]) # source maps are available only when the input is a filename self.assertRaises(sass.CompileError, sass.compile, string='a { b { color: blue; }', source_comments='map')
def compile_sass(sass_source_dir, css_destination_dir, lookup_paths, **kwargs): """ Compile given sass files. Exceptions: ValueError: Raised if sass source directory does not exist. Args: sass_source_dir (path.Path): directory path containing source sass files css_destination_dir (path.Path): directory path where compiled css files would be placed lookup_paths (list): a list of all paths that need to be consulted to resolve @imports from sass Returns: A tuple containing sass source dir, css destination dir and duration of sass compilation process """ output_style = kwargs.get('output_style', 'compressed') source_comments = kwargs.get('source_comments', False) start = datetime.datetime.now() if not sass_source_dir.isdir(): logger.warning("Sass dir '%s' does not exist.", sass_source_dir) raise ValueError("Sass dir '{dir}' must be a valid directory.".format(dir=sass_source_dir)) if not css_destination_dir.isdir(): # If css destination directory does not exist, then create one css_destination_dir.mkdir_p() sass.compile( dirname=(sass_source_dir, css_destination_dir), include_paths=lookup_paths, source_comments=source_comments, output_style=output_style, ) duration = datetime.datetime.now() - start return sass_source_dir, css_destination_dir, duration
def build(src_dir, dst_dir, opts): sass.compile(dirname=(src_dir, dst_dir)) # Copy non-scss files over for (src_path, dst_path) in futil.pairwalk(src_dir, dst_dir): if futil.ext(src_path) not in ['.scss', '.swp']: futil.try_mkdirs(os.path.dirname(dst_path)) shutil.copy2(src_path, dst_path)
def compile_sass(options): """ Compile Sass to CSS. """ # Note: import sass only when it is needed and not at the top of the file. # This allows other paver commands to operate even without libsass being # installed. In particular, this allows the install_prereqs command to be # used to install the dependency. import sass debug = options.get('debug') force = options.get('force') systems = getattr(options, 'system', ALL_SYSTEMS) if isinstance(systems, basestring): systems = systems.split(',') if debug: source_comments = True output_style = 'nested' else: source_comments = False output_style = 'compressed' timing_info = [] system_sass_directories = applicable_sass_directories(systems) all_sass_directories = applicable_sass_directories() dry_run = tasks.environment.dry_run for sass_dir in system_sass_directories: start = datetime.now() css_dir = sass_dir.parent / "css" if force: if dry_run: tasks.environment.info("rm -rf {css_dir}/*.css".format( css_dir=css_dir, )) else: sh("rm -rf {css_dir}/*.css".format(css_dir=css_dir)) if dry_run: tasks.environment.info("libsass {sass_dir}".format( sass_dir=sass_dir, )) else: sass.compile( dirname=(sass_dir, css_dir), include_paths=SASS_LOAD_PATHS + all_sass_directories, source_comments=source_comments, output_style=output_style, ) duration = datetime.now() - start timing_info.append((sass_dir, css_dir, duration)) print("\t\tFinished compiling Sass:") if not dry_run: for sass_dir, css_dir, duration in timing_info: print(">> {} -> {} in {}s".format(sass_dir, css_dir, duration))
def compile_file(self, infile, outfile, outdated=False, force=False): """Process sass file.""" myfile = codecs.open(outfile, 'w', 'utf-8') if settings.DEBUG: myfile.write(sass.compile(filename=infile)) else: myfile.write(sass.compile(filename=infile, output_style='compressed')) return myfile.close()
def test_ignores_underscored_files(self): with tempdir() as tmpdir: input_dir = os.path.join(tmpdir, 'input') output_dir = os.path.join(tmpdir, 'output') os.mkdir(input_dir) write_file(os.path.join(input_dir, 'f1.scss'), '@import "f2";') write_file(os.path.join(input_dir, '_f2.scss'), 'a{color:red}') sass.compile(dirname=(input_dir, output_dir)) assert not os.path.exists(os.path.join(output_dir, '_f2.css'))
def compiled(): #begin XML parse tree = ET.parse(config) root = tree.getroot() #create primary scss file file = open("style.scss", "w") #download and write imports for all scss files for x in range(0, len(root)): if root[x].tag == "links": for y in range(0, len(root[x])): #gets array of attributes and puts files in appropriate directories if len(root[x][y].attrib) > 0: if 'saveas' in root[x][y].attrib: if 'folder' in root[x][y].attrib: try: os.stat(root[x][y].attrib['folder']) except: os.makedirs(root[x][y].attrib['folder']) if root[x][y].text[:4] == "http": if not os.path.isfile(root[x][y].attrib["folder"] + "/" + root[x][y].attrib["saveas"]): urllib.urlretrieve (root[x][y].text, root[x][y].attrib["folder"] + "/" + root[x][y].attrib["saveas"]) if root[x][y].attrib["saveas"][-4:] == "scss" or root[x][y].attrib["saveas"][-4:] == "sass": file.write("@import \"" + root[x][y].attrib["folder"] + "/" + root[x][y].attrib["saveas"] + "\";\n") else: if 'folder' in root[x][y].attrib: try: os.stat(root[x][y].attrib['folder']) except: os.makedirs(root[x][y].attrib['folder']) if root[x][y].text[:4] == "http": if not os.path.isfile(root[x][y].attrib["folder"] + "/" + root[x][y].text.split('/')[-1]): urllib.urlretrieve (root[x][y].text, root[x][y].attrib["folder"] + "/" + root[x][y].text.split('/')[-1]) if root[x][y].text.split('/')[-1][-4:] == "scss" or root[x][y].text.split('/')[-1][-4:] == "sass": file.write("@import \"" + root[x][y].attrib["folder"] + "/" + root[x][y].text.split('/')[-1] + "\";\n") #grabs all other files and drops them in the main directory else: if not os.path.isfile(root[x][y].text.split('/')[-1]) and root[x][y].text[:4] == "http": urllib.urlretrieve (root[x][y].text, root[x][y].text.split('/')[-1]) #close main scss file file.close() #compile style.scss if len(sys.argv) <= 2: compiledString = sass.compile(filename="style.scss") else: for x in range(0, len(sys.argv)): if sys.argv[x][:1] == "-": compiledString = sass.compile(filename="style.scss", output_style=sys.argv[x].strip('-')) #write compiled sass to file outputFile = open("style.css", "w") outputFile.write(compiledString) outputFile.close()
def test_stack_trace_formatting(): try: sass.compile(string=u'a{☃') raise AssertionError('expected to raise CompileError') except sass.CompileError: tb = traceback.format_exc() assert tb.endswith( 'CompileError: Error: Invalid CSS after "a{☃": expected "{", was ""\n' ' on line 1 of stdin\n' '>> a{☃\n' ' --^\n\n' )
def test_compile_disallows_arbitrary_arguments(self): for args in ( {'string': 'a{b:c}'}, {'filename': 'test/a.scss'}, {'dirname': ('test', '/dev/null')}, ): with pytest.raises(TypeError) as excinfo: sass.compile(herp='derp', harp='darp', **args) msg, = excinfo.value.args assert msg == ( "compile() got unexpected keyword argument(s) 'harp', 'herp'" )
def test_error(self): with tempdir() as tmpdir: input_dir = os.path.join(tmpdir, 'input') os.makedirs(input_dir) write_file(os.path.join(input_dir, 'bad.scss'), 'a {') with pytest.raises(sass.CompileError) as excinfo: sass.compile( dirname=(input_dir, os.path.join(tmpdir, 'output')) ) msg, = excinfo.value.args assert msg.startswith('Error: Invalid CSS after ')
def test_compile_string_deprecated_source_comments_line_numbers(self): source = '''a { b { color: blue; } color: red; }''' expected = sass.compile(string=source, source_comments=True) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') actual = sass.compile(string=source, source_comments='line_numbers') assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) assert expected == actual
def test_compile_filename(self): actual = sass.compile(filename='test/a.scss') assert actual == A_EXPECTED_CSS actual = sass.compile(filename='test/c.scss') assert actual == C_EXPECTED_CSS actual = sass.compile(filename='test/d.scss') assert D_EXPECTED_CSS == actual actual = sass.compile(filename='test/e.scss') assert actual == E_EXPECTED_CSS self.assertRaises(IOError, sass.compile, filename='test/not-exist.sass') self.assertRaises(TypeError, sass.compile, filename=1234) self.assertRaises(TypeError, sass.compile, filename=[])
def compile_sass(): """Compiles sass files to css""" import sass static_dir = os.path.join(".", "synnefo_admin", "admin", "static") sass_dir = os.path.join(static_dir, "sass") css_dir = os.path.join(static_dir, "css") output_style = "nested" if "develop" in sys.argv else "compressed" try: sass.compile(dirname=(sass_dir, css_dir,), output_style=output_style) except Exception as e: print(e) raise Exception('Sass compile failed')
def test_importers_raises_exception(self): def importer(path): raise ValueError('Bad path: {0}'.format(path)) with assert_raises_compile_error(RegexMatcher( r'^Error: \n' r' Traceback \(most recent call last\):\n' r'.+' r'ValueError: Bad path: hi\n' r' on line 1 of stdin\n' r'>> @import "hi";\n' r' --------\^\n' )): sass.compile(string='@import "hi";', importers=((0, importer),))
def test_compile_filename(self): actual = sass.compile(filename='test/a.scss') assert actual == A_EXPECTED_CSS actual = sass.compile(filename='test/c.scss') assert actual == C_EXPECTED_CSS actual = sass.compile(filename='test/d.scss') if text_type is str: self.assertEqual(D_EXPECTED_CSS, actual) else: self.assertEqual(D_EXPECTED_CSS.decode('utf-8'), actual) self.assertRaises(IOError, sass.compile, filename='test/not-exist.sass') self.assertRaises(TypeError, sass.compile, filename=1234) self.assertRaises(TypeError, sass.compile, filename=[])
def test_compile_directories_unicode(self): with tempdir() as tmpdir: input_dir = os.path.join(tmpdir, 'input') output_dir = os.path.join(tmpdir, 'output') os.makedirs(input_dir) with io.open( os.path.join(input_dir, 'test.scss'), 'w', encoding='UTF-8', ) as f: f.write(u'a { content: "☃"; }') # Raised a UnicodeEncodeError in py2 before #82 (issue #72) # Also raised a UnicodeEncodeError in py3 if the default encoding # couldn't represent it (such as cp1252 on windows) sass.compile(dirname=(input_dir, output_dir)) assert os.path.exists(os.path.join(output_dir, 'test.css'))
def test_importer_returns_wrong_tuple_size_too_big(self): def importer(path): return (('a', 'b', 'c', 'd'),) with assert_raises_compile_error(RegexMatcher( r'^Error: \n' r' Traceback \(most recent call last\):\n' r'.+' r'ValueError: Expected importer result to be a tuple of ' r"length \(1, 2, 3\) but got 4: \('a', 'b', 'c', 'd'\)\n" r' on line 1 of stdin\n' r'>> @import "hi";\n' r' --------\^\n' )): sass.compile(string='@import "hi";', importers=((0, importer),))
def build_one(self, package_dir, filename, source_map=False): """Builds one Sass/SCSS file. :param package_dir: the path of package directory :type package_dir: :class:`str`, :class:`basestring` :param filename: the filename of Sass/SCSS source to compile :type filename: :class:`str`, :class:`basestring` :param source_map: whether to use source maps. if :const:`True` it also write a source map to a ``filename`` followed by :file:`.map` suffix. default is :const:`False` :type source_map: :class:`bool` :returns: the filename of compiled CSS :rtype: :class:`str`, :class:`basestring` .. versionadded:: 0.4.0 Added optional ``source_map`` parameter. """ sass_filename, css_filename = self.resolve_filename( package_dir, filename, ) root_path = os.path.join(package_dir, self.sass_path) css_path = os.path.join(package_dir, self.css_path, css_filename) if source_map: source_map_path = css_filename + '.map' css, source_map = compile( filename=sass_filename, include_paths=[root_path], source_map_filename=source_map_path, # FIXME output_filename_hint=css_path, ) else: css = compile(filename=sass_filename, include_paths=[root_path]) source_map_path = None source_map = None css_folder = os.path.dirname(css_path) if not os.path.exists(css_folder): os.makedirs(css_folder) with io.open(css_path, 'w', encoding='utf-8', newline='') as f: f.write(css) if source_map: # Source maps are JSON, and JSON has to be UTF-8 encoded with io.open( source_map_path, 'w', encoding='utf-8', newline='', ) as f: f.write(source_map) return css_filename
def main(argv): args = parse_args(argv) try: args.config = config.get_config(args.configfile, const._app_name) except Exception: sys.stderr.write('ERROR: Could not process config file:\n') sys.stderr.write(traceback.format_exc()) return 1 # AWS ACCESS DETAILS AWS_ACCESS_KEY_ID = get_config_item(args, 'aws_access_key_id') AWS_SECRET_ACCESS_KEY = get_config_item(args, 'aws_secret_access_key') bucket_name = get_config_item(args, 'bucket_name', 'cioc-cdn') conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(bucket_name) location = 'fontello/' + gethash() + '/' print 'Uploading to Amazon S3 path', location filebase = os.path.join(const._app_path, 'fonts') for filename, mime_type in files: upload_file(bucket, location, filename, mime_type, filebase=filebase) top = open(os.path.join(const._app_path, 'fonts', 'fontello.css')).read().split('}', 1)[0] + '}' bottom = open(os.path.join(const._app_path, 'styles', 'sass', '_fontello.scss')).read().split('}', 1)[1] css = sass.compile(string=top + bottom, output_style='compressed') upload_file(bucket, location, 'fontello.css', 'text/css', css) scss = ''' $bootstrap-sass-asset-helper: false; $icon-font-path: "./"; $icon-font-name: "glyphicons-halflings-regular" !default; $icon-font-svg-id: "glyphicons_halflingsregular" !default; @import "bootstrap/glyphicons"; ''' location = 'bootstrap-3.3.5/' filebase = os.path.join(const._app_path, 'fonts', 'bootstrap') print 'Uploading to Amazon S3 path', location for filename, mime_type in bootstrap_files: upload_file(bucket, location, filename, mime_type, filebase=filebase) css = sass.compile(string=scss, include_paths=[const._sass_dir], output_style='compressed') upload_file(bucket, location, 'glyphicons.css', 'text/css', css) return 0
def catch_all(path): # Verify the file exists, then send it to the client if not isfile(path): return (Helpers.fourohfour(path), 404) else: # Let's be adventurous: just run Python! The script being run # should set output content into `globals()['output']` and, if # necessary, the MIME type in `globals()['output_type']` if path.endswith('.py'): gDict = {'output': None, 'output_type': 'text/html'} execfile(path, gDict) if gDict['output'] is None: msg = 'ERROR: globals()["output"] not set by {}'.format(path) return (Helpers.fiveohoh(path, msg), 500) else: return Response(gDict['output'], mimetype=gDict['output_type']) # Run SASS/SCSS/LESS files through the appropriate compiler if path.endswith('.scss') or path.endswith('.sass'): return sass.compile(string=Helpers.returncontent(path), output_style='compressed') if path.endswith('.less'): return lesscpy.compile(Helpers.returncontent(path), minify=True) # For everything else, just send it content = Helpers.returncontent(path) mtype = Helpers.gettype(path) return Response(content, mimetype=mtype)
def compile_sass(_in, out, **kw): out.write( libsass.compile( string=_in.read(), include_paths=[__toolkit_scss_dir, __styleguide_scss_dir] ) )
def render(self, context): path = self._path.resolve(context) basename, ext = os.path.splitext(path) filename = find_file(path) if ext not in self._sass_exts: # return the given path, since it ends neither in `.scss` nor in `.sass` return urljoin(self.prefix, path) # compare timestamp of sourcemap file with all its dependencies, and check if we must recompile css_filename = basename + '.css' url = urljoin(self.prefix, css_filename) if not getattr(settings, 'SASS_PROCESSOR_ENABLED', settings.DEBUG): return url sourcemap_filename = css_filename + '.map' if self.is_latest(sourcemap_filename): return url # otherwise compile the SASS/SCSS file into .css and store it sourcemap_url = self.storage.url(sourcemap_filename) content, sourcemap = sass.compile(filename=filename, source_map_filename=sourcemap_url, include_paths=self.include_paths) if self.storage.exists(css_filename): self.storage.delete(css_filename) self.storage.save(css_filename, ContentFile(content)) if self.storage.exists(sourcemap_filename): self.storage.delete(sourcemap_filename) self.storage.save(sourcemap_filename, ContentFile(sourcemap)) return url
def compile(self, source, target): import sass print(source, target) css = sass.compile(filename=source, output_style=self.output_style) with open(target, 'w') as f: f.write(css) log.info('%s CSS written to %s' % (self.output_style, target))
def build_directory(sass_path, css_path, _root_sass=None, _root_css=None): """Compiles all SASS/SCSS files in ``path`` to CSS. :param sass_path: the path of the directory which contains source files to compile :type sass_path: :class:`str`, :class:`basestring` :param css_path: the path of the directory compiled CSS files will go :type css_path: :class:`str`, :class:`basestring` :returns: a dictionary of source filenames to compiled CSS filenames :rtype: :class:`collections.Mapping` """ if _root_sass is None or _root_css is None: _root_sass = sass_path _root_css = css_path result = {} if not os.path.isdir(css_path): os.mkdir(css_path) for name in os.listdir(sass_path): sass_fullname = os.path.join(sass_path, name) if SUFFIX_PATTERN.search(name) and os.path.isfile(sass_fullname): css_fullname = os.path.join(css_path, name) + '.css' css = compile(filename=sass_fullname, include_paths=[_root_sass]) with io.open(css_fullname, 'w', encoding='utf-8') as css_file: css_file.write(css) result[os.path.relpath(sass_fullname, _root_sass)] = \ os.path.relpath(css_fullname, _root_css) elif os.path.isdir(sass_fullname): css_fullname = os.path.join(css_path, name) subresult = build_directory(sass_fullname, css_fullname, _root_sass, _root_css) result.update(subresult) return result
def test_importers_other_iterables(self): def importer_one(path): if path == 'one': # Need to do this to avoid returning empty generator def gen(): yield (path, 'a { color: red; }') yield (path + 'other', 'b { color: orange; }') return gen() def importer_two(path): assert path == 'two' # List of lists return [ [path, 'c { color: yellow; }'], [path + 'other', 'd { color: green; }'], ] ret = sass.compile( string='@import "one"; @import "two";', # Importers can also be lists importers=[[0, importer_one], [0, importer_two]], output_style='compressed', ) assert ret == ( 'a{color:red}b{color:orange}c{color:yellow}d{color:green}\n' )
def build_directory(self, sass_path, css_path, _root_sass=None, _root_css=None): _root_sass = sass_path if _root_sass is None else _root_sass _root_css = css_path if _root_css is None else _root_css result = {} if not os.path.isdir(css_path): os.mkdir(css_path) for name in os.listdir(sass_path): if not SUFFIX_PATTERN.search(name) or name.startswith('_'): continue sass_fullname = os.path.join(sass_path, name) if os.path.isfile(sass_fullname): css_fullname = os.path.join(css_path, os.path.splitext(name)[0]) + self.suffix css = sass.compile(filename=sass_fullname, include_paths=[_root_sass]) with open(css_fullname, 'w') as css_file: css_file.write(css) result[sass_fullname] = css_fullname elif os.path.isdir(sass_fullname): css_fullname = os.path.join(css_path, name) subresult = self.build_directory(sass_fullname, css_fullname, _root_sass, _root_css) result.update(subresult) for sass_path, out_path in result.iteritems(): logging.info('Compiled {} -> {}'.format(sass_path.replace(self.pod.root, ''), out_path.replace(self.pod.root, ''))) return result
def convert(scss, css): """ Converts the *scss* file to a *css* file. """ try: with open(css, 'w') as fp: fp.write(libsass.compile(filename=scss)) except Exception: try: os.remove(css) except OSError as exc: if exc.errno != errno.EOENT: raise raise
def compile(self, source): if libsass is None: return super(ScssStylesheetAsset, self).compile(source) try: return libsass.compile( string=source, include_paths=[ self.bootstrap_path, ], output_style=self.output_style, precision=self.precision, ) except libsass.CompileError as e: raise CompileError(e.args[0])
def build_theme(ctx): """Build the site theme (if you changed a .scss file).""" src_path = os.path.join(conf.THEME, conf.BOOTSTRAP_THEME, "build.scss") css = sass.compile(filename=src_path, output_style="compressed", precision=8) dest_path = os.path.join( conf.THEME, "static", "css", "bootstrap.{}.min.css".format(conf.BOOTSTRAP_THEME)) with open(dest_path, "w") as dest: dest.write(css) ctx.run("node_modules/postcss-cli/bin/postcss " "--use autoprefixer --replace " + dest_path)
def compile(**kwargs): """Perform sass.compile, but with the appropriate include_paths for Django added""" kwargs = kwargs.copy() if PRECISION is not None: kwargs['precision'] = PRECISION kwargs['include_paths'] = (kwargs.get('include_paths') or []) + get_include_paths() custom_functions = CUSTOM_FUNCTIONS.copy() custom_functions.update(kwargs.get('custom_functions', {})) kwargs['custom_functions'] = custom_functions if SOURCEMAPS and kwargs.get('filename', None): # We need to pass source_map_file to libsass so it generates # correct paths to source files. base_path = os.path.dirname(kwargs['filename']) sourcemap_filename = os.path.join(base_path, 'sourcemap.map') kwargs['source_map_filename'] = sourcemap_filename libsass_output, sourcemap = sass.compile(**kwargs) sourcemap = prefix_sourcemap(sourcemap, base_path) output = embed_sourcemap(libsass_output, sourcemap) else: output = sass.compile(**kwargs) return output
def style_for_print(options: Options) -> str: scss = f""" :root {{ string-set: author '{options.author}'; string-set: copyright '{options.copyright}'; }} h1, h2, h3 {{ string-set: chapter content(); }} """ root = sass.compile(string=scss) base_path = os.path.abspath(os.path.dirname(__file__)) filename = os.path.join(base_path, "report-print.scss") for_printing = sass.compile(filename=filename, output_style='compressed') if options.cover: filename = os.path.join(base_path, "cover.scss") for_cover = sass.compile(filename=filename, output_style='compressed') else: for_cover = '' return root + for_printing + for_cover
def compile_file(name): # print name try: # outfile = open("../web-project/skins/" + name + "/sass/skin.scss", 'r') # k = outfile.read() os.chdir(PATH + name + "/sass") my_output = sass.compile(filename="skin.scss", output_style='expanded') with open("../css/skin.css", 'w') as out: out.write(my_output) print name + ' compiled' except Exception as e: pass print type(e), name, e.message finally: os.chdir(os.path.dirname(os.path.realpath(__file__)))
def compile_sass(sass_source_dir, css_destination_dir, lookup_paths, **kwargs): """ Compile given sass files. Exceptions: ValueError: Raised if sass source directory does not exist. Args: sass_source_dir (path.Path): directory path containing source sass files css_destination_dir (path.Path): directory path where compiled css files would be placed lookup_paths (list): a list of all paths that need to be consulted to resolve @imports from sass Returns: A tuple containing sass source dir, css destination dir and duration of sass compilation process """ output_style = kwargs.get('output_style', 'compressed') source_comments = kwargs.get('source_comments', False) start = datetime.datetime.now() if not sass_source_dir.isdir(): logger.warning("Sass dir '%s' does not exist.", sass_source_dir) raise ValueError("Sass dir '{dir}' must be a valid directory.".format( dir=sass_source_dir)) if not css_destination_dir.isdir(): # If css destination directory does not exist, then create one css_destination_dir.mkdir_p() sass.compile( dirname=(sass_source_dir, css_destination_dir), include_paths=lookup_paths, source_comments=source_comments, output_style=output_style, ) duration = datetime.datetime.now() - start return sass_source_dir, css_destination_dir, duration
def test_importer_does_not_handle_returns_None(self): def importer_one(path): if path == 'one': return ((path, 'a { color: red; }'), ) def importer_two(path): assert path == 'two' return ((path, 'b { color: blue; }'), ) ret = sass.compile( string='@import "one"; @import "two";', importers=((0, importer_one), (0, importer_two)), output_style='compressed', ) assert ret == 'a{color:red}b{color:blue}\n'
def __call__(self, path): basename, ext = os.path.splitext(path) filename = find_file(path) if filename is None: raise FileNotFoundError("Unable to locate file {path}".format(path=path)) if ext not in self.sass_extensions: # return the given path, since it ends neither in `.scss` nor in `.sass` return path # compare timestamp of sourcemap file with all its dependencies, and check if we must recompile css_filename = basename + '.css' if not self.processor_enabled: return css_filename sourcemap_filename = css_filename + '.map' if find_file(css_filename) and self.is_latest(sourcemap_filename): return css_filename # with offline compilation, raise an error, if css file could not be found. if sass is None: msg = "Offline compiled file `{}` is missing and libsass has not been installed." raise ImproperlyConfigured(msg.format(css_filename)) # add a function to be used from inside SASS custom_functions = {'get-setting': get_setting} # otherwise compile the SASS/SCSS file into .css and store it sourcemap_url = self.storage.url(sourcemap_filename) compile_kwargs = { 'filename': filename, 'source_map_filename': sourcemap_url, 'include_paths': self.include_paths + APPS_INCLUDE_DIRS, 'custom_functions': custom_functions, } if self.sass_precision: compile_kwargs['precision'] = self.sass_precision if self.sass_output_style: compile_kwargs['output_style'] = self.sass_output_style content, sourcemap = sass.compile(**compile_kwargs) content = force_bytes(content) sourcemap = force_bytes(sourcemap) if self.storage.exists(css_filename): self.storage.delete(css_filename) self.storage.save(css_filename, ContentFile(content)) if self.storage.exists(sourcemap_filename): self.storage.delete(sourcemap_filename) self.storage.save(sourcemap_filename, ContentFile(sourcemap)) return css_filename
def _get_bulma_css(self): """Compiles the bulma css file and returns its relative path.""" # Start by unpacking the users custom variables scss_string = "" for var, value in self.variables.items(): scss_string += f"${var}: {value};\n" # SASS wants paths with forward slash: sass_bulma_path = str(self.simple_bulma_path).replace('\\', '/') # Now load bulma scss_string += f'@import "{sass_bulma_path}/bulma.sass";' # Now load in the extensions that the user wants if self.extensions == "_all": scss_string += f'@import "{sass_bulma_path}/sass/extensions/_all";\n' elif isinstance(self.extensions, list): for extension in self.extensions: # Check if the extension exists extensions_folder = self.simple_bulma_path / "sass" / "extensions" extensions = [ extension.stem[1:] for extension in extensions_folder.iterdir() ] if extension in extensions: scss_string += f'@import "{sass_bulma_path}/sass/extensions/_{extension}";\n' # Store this as a css file if hasattr(sass, "libsass_version"): css_string = sass.compile(string=scss_string) else: # If the user has the sass module installed in addition to libsass, # warn the user and fail hard. raise UserWarning( "There was an error compiling your Bulma CSS. This error is " "probably caused by having the `sass` module installed, as the two modules " "are in conflict, causing django-simple-bulma to import the wrong sass namespace." "\n" "Please ensure you have only the `libsass` module installed, " "not both `sass` and `libsass`, or this application will not work." ) css_path = self.simple_bulma_path / "css" / "bulma.css" with open(css_path, "w") as bulma_css: bulma_css.write(css_string) return "css/bulma.css"
def build_directory(self, sass_path, css_path, _root_sass=None, _root_css=None): if self.config.image_path: image_path = os.path.abspath(os.path.join(self.root, self.config.image_path.lstrip('/'))) else: image_path = None _root_sass = sass_path if _root_sass is None else _root_sass _root_css = css_path if _root_css is None else _root_css result = {} if not os.path.isdir(css_path): os.mkdir(css_path) for name in os.listdir(sass_path): if not SUFFIX_PATTERN.search(name) or name.startswith('_'): continue sass_fullname = os.path.join(sass_path, name) if os.path.isfile(sass_fullname): basename = os.path.splitext(name)[0] css_fullname = os.path.join(css_path, basename) + self.config.suffix try: kwargs = { 'filename': sass_fullname, 'include_paths': [_root_sass], 'output_style': self.config.output_style, } if self.config.output_style is not None: kwargs['output_style'] = self.config.output_style if image_path is not None: kwargs['image_path'] = image_path if self.config.image_path is not None: kwargs['image_path'] = image_path css = sass.compile(**kwargs) except sass.CompileError as e: logging.error(str(e)) return result with open(css_fullname, 'w') as css_file: if isinstance(css, unicode): css = css.encode('utf-8') css_file.write(css) result[sass_fullname] = css_fullname elif os.path.isdir(sass_fullname): css_fullname = os.path.join(css_path, name) subresult = self.build_directory(sass_fullname, css_fullname, _root_sass, _root_css) result.update(subresult) for sass_path, out_path in result.iteritems(): self.logger.info( 'Compiled: {} -> {}'.format(sass_path.replace(self.root, ''), out_path.replace(self.root, ''))) return result
def compiled_string(self, overrides=None): bsv = self.get_vars(overrides) src = ['$bootstrap-sass-asset-helper:false;'] for name, value in bsv.all_value_pairs(): src.append('$%s:%s;' % (name, value)) src.append('@import "%s";' % self.version.compile_filename) if getattr(settings, 'BSEDITOR_TRACK_LAST_COMPILE', False): filename = os.path.abspath( os.path.join(settings.BSEDITOR_DEPLOY_DIR, "last_compile.txt")) with open(filename, 'w') as f: f.write('\n'.join(src)) return sass.compile(string='\n'.join(src))
def compile_theme(self): if f"{self.settings.theme}.scss" in os.listdir(custom_themes_folder): theme_scss_file = os.path.join(custom_themes_folder, f"{self.settings.theme}.scss") else: theme_scss_file = os.path.join(system_themes_folder, f"{self.settings.theme}.scss") dm_css = os.path.join(static_folder, "css", "vendors", "bootstrap.min.css") css = sass.compile( filename=theme_scss_file, output_style="compressed", ) with open(dm_css, "w") as css_file: css_file.write(css)
def minify_css(self, decl): if 'href' in decl: sources = [decl['href']] else: sources = decl['hrefs'] text = "" for source in sources: if source.startswith('/'): source = os.path.join(self.root, source[1:]) else: source = os.path.join(self.root, source) source = resolve_file(source, extension_map={'.css': ['.scss']}) text += sass.compile(filename=source, output_style='compressed') text += "\n" return text
def compile_file(self, infile, outfile, outdated=False, force=False): for path in settings.STATICFILES_DIRS: outfile = outfile.replace(path, "").strip("/") import sass out_value = sass.compile( filename=infile, output_style="compressed", include_paths=settings.SASS_INCLUDE_PATHS, ) if type(out_value) == bytes: out_value = out_value.decode("utf8") with staticfiles_storage.open(outfile, "w") as out: out.write(out_value) return out_value
def generate(self, path): log.debug("Compiling CSS for %s", path) if path.startswith('/'): path = os.path.join(self.root, path[1:]) else: path = os.path.join(self.root, path) try: path = resolve_file(path, extension_map={'.css': ['.scss']}) except FileNotFoundError: raise tornado.web.HTTPError(404, "No such file %s." % path) if not path.startswith(self.root): raise tornado.web.HTTPError(404, "No such file %s." % path) return 'text/css', sass.compile(filename=path)
def postBuild(site): for path in fileList(CSS_PATH): if not path.endswith('.scss'): continue with open(path, 'rw') as f: data = f.read() css, map = sass.compile( filename=path, source_map_filename=path.replace('.scss', '.css') + ".map", ) with open(path.replace('.scss', '.css'), 'w') as f: f.write(css) with open(path.replace('.scss', '.css') + ".map", "wb") as mapsock: mapsock.write(map.encode('utf8'))
def test_importer_one_arg(self): """Demonstrates one-arg importers + chaining.""" def importer_returning_one_argument(path): assert type(path) is text_type return ( # Trigger the import of an actual file ('test/b.scss',), (path, '.{0}-one-arg {{ color: blue; }}'.format(path)), ) ret = sass.compile( string="@import 'foo';", importers=((0, importer_returning_one_argument),), output_style='compressed', ) assert ret == 'b i{font-size:20px}.foo-one-arg{color:blue}\n'
def process_scss(): """Compiles SCSS into CSS in the Static Assets folder""" paths = [ os.path.join(settings.BASE_DIR, 'themes/OLH/assets/foundation-sites/scss/'), os.path.join(settings.BASE_DIR, 'themes/OLH/assets/motion-ui/src/') ] # File dirs app_scss_file = os.path.join(settings.BASE_DIR, 'themes/OLH/assets/scss/app.scss') app_css_file = os.path.join(settings.BASE_DIR, 'static/OLH/css/app.css') compiled_css_from_file = sass.compile(filename=app_scss_file, include_paths=paths) # Open the CSS file and write into it write_file = open(app_css_file, 'w', encoding="utf-8") write_file.write(compiled_css_from_file)
def compile_file(input_path, output_path): if os.path.exists(output_path): os.remove(output_path) try: css = sass.compile(filename=input_path, output_style="compressed", include_paths=["./scss/"]) except sass.CompileError as err: print("Failed to compile {} !".format(input_path)) print(err) exit(2) css_file = open(output_path, "wb") css_file.write(css.encode("utf-8")) css_file.close()
def _compile_sass(self): """ compile css from scss """ self._write_css_config() css_fn = os.path.splitext(scss_file)[0] + ".css" source_map_fn = css_fn + ".map" compiled_css, source_map = sass.compile( filename=scss_file, source_map_filename=source_map_fn) with open(css_fn, "w") as css_file: css_file.write(compiled_css) with open(source_map_fn, "w") as map_file: map_file.write(source_map) log.info("compiled sass {} -> {}".format(scss_file, css_fn)) return css_fn
def compile_sass(self, params): if not self.is_active: return if libsass is None: # pragma: no cover raise ImportError( 'In order, to use `SASS` tags, please install the `libsass` using: `pip install libsass`', name='libsass', ) src, dst = params.split('>') if '>' in params else params.split(' ') src, dst = src.strip(), dst.strip() try: with open(dst, 'w') as f: f.write(libsass.compile(filename=src)) except libsass.CompileError: traceback.print_exc()
def setup_sass(css_path, **sass_vars): """Setup sass.""" os.makedirs(os.path.dirname(css_path), exist_ok=True) sass_vars = [ f'${var.replace("_", "-")}: {val};' for var, val in sass_vars.items() ] header = '\n'.join(sass_vars) + '\n' with open(os.path.join(WHERE_AM_I, 'main.scss'), 'r') as file_in: source = file_in.read() if source: css = sass.compile(string=header + source, include_paths=[WHERE_AM_I]) else: css = '' with open(css_path, 'w') as file_out: file_out.write(css)
def compile_file(self, infile, outfile, outdated=False, force=False): if not outdated: return open(outfile).read() import sass out_value = sass.compile( filename=infile, output_style="compressed", include_paths=settings.SASS_INCLUDE_PATHS, ) if type(out_value) == bytes: out_value = out_value.decode("utf8") with staticfiles_storage.open(outfile, "w") as out: out.write(out_value) return out_value
def board_dark_css(boardname, x): board=get_guild(boardname) if int(x) != board.color_nonce: return redirect(board.css_dark_url) with open("ruqqus/assets/style/board_dark.scss", "r") as file: raw=file.read() #This doesn't use python's string formatting because #of some odd behavior with css files scss=raw.replace("{boardcolor}", board.color) resp=Response(sass.compile(string=scss), mimetype='text/css') resp.headers.add("Cache-Control", "public") return resp
def to_style(self, config, **kwargs): base_path = os.path.join(os.path.dirname(__file__), 'scss') if os.name == "nt": import_path = posixpath.join(*base_path.split('\\')) else: import_path = base_path scss_file = os.path.join(base_path, 'overrides.tmpl') config.update({'path': import_path}) with open(scss_file, 'r') as file: scss_template_string = file.read() config = self.config_to_camelCase(config) scss_string = scss_template_string.format(**config) new_css = sass.compile(string=scss_string) style_string = "<style>\n{0}\n</style>".format(new_css) font_names = [config["headingFont"], config["bodyFont"]] links = self.get_fonts(font_names) return links + style_string
def compile_scss(object, file="main.scss", fonts=True): sassdir = os.path.join(settings.STATIC_ROOT, 'pretixpresale/scss') def static(path): sp = _static(path) if not settings.MEDIA_URL.startswith("/") and sp.startswith("/"): domain = get_domain(object.organizer if isinstance(object, Event) else object) if domain: siteurlsplit = urlsplit(settings.SITE_URL) if siteurlsplit.port and siteurlsplit.port not in (80, 443): domain = '%s:%d' % (domain, siteurlsplit.port) sp = urljoin('%s://%s' % (siteurlsplit.scheme, domain), sp) else: sp = urljoin(settings.SITE_URL, sp) return '"{}"'.format(sp) sassrules = [] if object.settings.get('primary_color'): sassrules.append('$brand-primary: {};'.format(object.settings.get('primary_color'))) if object.settings.get('theme_color_success'): sassrules.append('$brand-success: {};'.format(object.settings.get('theme_color_success'))) if object.settings.get('theme_color_danger'): sassrules.append('$brand-danger: {};'.format(object.settings.get('theme_color_danger'))) font = object.settings.get('primary_font') if font != 'Open Sans' and fonts: sassrules.append(get_font_stylesheet(font)) sassrules.append( '$font-family-sans-serif: "{}", "Open Sans", "OpenSans", "Helvetica Neue", Helvetica, Arial, sans-serif ' '!default'.format( font )) sassrules.append('@import "{}";'.format(file)) cf = dict(django_libsass.CUSTOM_FUNCTIONS) cf['static'] = static css = sass.compile( string="\n".join(sassrules), include_paths=[sassdir], output_style='nested', custom_functions=cf ) cssf = CSSCompressorFilter(css) css = cssf.output() checksum = hashlib.sha1(css.encode('utf-8')).hexdigest() return css, checksum
def load_style_sheet(): """Load css styles file and parse to include custom variables.""" with open(GLOBAL_SASS_STYLES_PATH, 'r') as f: sass_data = f.read() load_sass_variables(sass_data) if sass_module_installed and DEV: # Needed on OSX try: sass_data = sass_data.encode() except Exception: pass try: # Using https://github.com/dahlia/libsass-python data = sass.compile(string=sass_data) except Exception: pass try: # Using https://github.com/pistolero/python-scss data = sass.compile_string(sass_data) except Exception: pass # Needed on OSX try: data = data.decode() except Exception: pass with open(GLOBAL_STYLES_PATH, 'w') as f: f.write(data) with open(GLOBAL_STYLES_PATH, 'r') as f: data = f.read() if os.name == 'nt': data = data.replace('$IMAGE_PATH', images.IMAGE_PATH.replace('\\', '/')) else: data = data.replace('$IMAGE_PATH', images.IMAGE_PATH) return data
def regenerate_css(event_id: int): event = Event.objects.select_related('organizer').get(pk=event_id) sassdir = os.path.join(settings.STATIC_ROOT, 'pretixpresale/scss') def static(path): sp = _static(path) if not settings.MEDIA_URL.startswith("/") and sp.startswith("/"): domain = get_domain(event.organizer) if domain: siteurlsplit = urlsplit(settings.SITE_URL) if siteurlsplit.port and siteurlsplit.port not in (80, 443): domain = '%s:%d' % (domain, siteurlsplit.port) sp = urljoin('%s://%s' % (siteurlsplit.scheme, domain), sp) else: sp = urljoin(settings.SITE_URL, sp) return '"{}"'.format(sp) sassrules = [] if event.settings.get('primary_color'): sassrules.append('$brand-primary: {};'.format( event.settings.get('primary_color'))) font = event.settings.get('primary_font') if font != 'Open Sans': sassrules.append(get_font_stylesheet(font)) sassrules.append( '$font-family-sans-serif: "{}", "Open Sans", "OpenSans", "Helvetica Neue", Helvetica, Arial, sans-serif !default' .format(font)) sassrules.append('@import "main.scss";') cf = dict(django_libsass.CUSTOM_FUNCTIONS) cf['static'] = static css = sass.compile(string="\n".join(sassrules), include_paths=[sassdir], output_style='compressed', custom_functions=cf) checksum = hashlib.sha1(css.encode('utf-8')).hexdigest() fname = '{}/{}/presale.{}.css'.format(event.organizer.slug, event.slug, checksum[:16]) if event.settings.get('presale_css_checksum', '') != checksum: newname = default_storage.save(fname, ContentFile(css.encode('utf-8'))) event.settings.set('presale_css_file', newname) event.settings.set('presale_css_checksum', checksum)
def main(): parser = argparse.ArgumentParser(description="Minifying the .js and .css with -c option") parser.add_argument('-c', action='store_true') args = parser.parse_args() months, plants, appartenance, examples, categories, cat_plants, cat_animals, interactions = generate_js("static/js/data.js") print(months['Carotte']) minified = "" if args.c: minified = "min." for js_path in ["static/js/MonPotager.js", "static/js/data.js"]: with open(js_path, 'r') as js_file: jsminified = jsmin(js_file.read()) jsminified_file = open(js_path.replace('.js', ".min.js"), "w") jsminified_file.write(jsminified) jsminified_file.close() print(OKBLUE + "Minifying " + js_path + ENDC) else: print(OKBLUE + ".js and .css not minified, use -c option if you wish to compress files." + ENDC) css = open("static/css/MonPotager." + minified + "css", "w") css.write(sass.compile(filename='static/MonPotager.css.scss', output_style=('compressed' if args.c else "nested"))) css.close() env = jinja2.Environment(loader=jinja2.FileSystemLoader('./')) template = env.get_template('static/MonPotager.html') first_letter = sorted(set([name[0].upper() for key, name in plants.items() if (appartenance[key] in cat_plants)])) sorted_appartenance = sorted(appartenance.items(), key=lambda pl: plants[pl[0]].lower()) output_from_parsed_template = template.stream(months=months, plants=plants, examples=examples, minified=minified, cat_plants=cat_plants, cat_animals=cat_animals, categories=categories, first_letter=first_letter, interactions=interactions, appartenance=sorted_appartenance).dump('index.html') print(OKGREEN + "Application generated.\nOpen the file {0}/index.html to open the application.".format( os.getcwd()) + ENDC)