Ejemplo n.º 1
0
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()
Ejemplo n.º 2
0
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))
Ejemplo n.º 3
0
	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()
Ejemplo n.º 4
0
Archivo: build.py Proyecto: nehz/avalon
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')
Ejemplo n.º 5
0
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))
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
    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)
Ejemplo n.º 8
0
    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)
Ejemplo n.º 9
0
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()
Ejemplo n.º 10
0
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 )
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
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)
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
    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()
Ejemplo n.º 16
0
	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))
Ejemplo n.º 17
0
 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")))
Ejemplo n.º 18
0
 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
Ejemplo n.º 19
0
 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)
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
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')
Ejemplo n.º 22
0
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)
Ejemplo n.º 23
0
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
Ejemplo n.º 24
0
    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)
Ejemplo n.º 25
0
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
Ejemplo n.º 26
0
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')
Ejemplo n.º 27
0
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
Ejemplo n.º 28
0
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)
Ejemplo n.º 29
0
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()
Ejemplo n.º 30
0
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)
Ejemplo n.º 31
0
    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)
Ejemplo n.º 32
0
    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)
Ejemplo n.º 33
0
    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)
Ejemplo n.º 34
0
    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)
Ejemplo n.º 35
0
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))
Ejemplo n.º 36
0
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
Ejemplo n.º 37
0
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()
Ejemplo n.º 38
0
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()
Ejemplo n.º 39
0
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
Ejemplo n.º 40
0
    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
Ejemplo n.º 41
0
    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)
Ejemplo n.º 42
0
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()
Ejemplo n.º 43
0
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)
Ejemplo n.º 44
0
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()
Ejemplo n.º 45
0
 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
Ejemplo n.º 46
0
def test_pair(scss_fn, css_fn):
    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
Ejemplo n.º 47
0
def application_css():
    parser = Scss()

    stylesheets = _get_stylesheets()

    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")
Ejemplo n.º 48
0
    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
Ejemplo n.º 49
0
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))
Ejemplo n.º 50
0
        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)
Ejemplo n.º 51
0
 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
Ejemplo n.º 52
0
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
Ejemplo n.º 53
0
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()
Ejemplo n.º 54
0
    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
Ejemplo n.º 55
0
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)