Example #1
0
def test_get_filter():
    """Test filter resolving.
    """
    # By name - here using one of the builtins.
    assert isinstance(get_filter('jsmin'), Filter)
    assert_raises(ValueError, get_filter, 'notafilteractually')

    # By class.
    class MyFilter(Filter): pass
    assert isinstance(get_filter(MyFilter), MyFilter)
    assert_raises(ValueError, get_filter, object())

    # Passing an instance doesn't do anything.
    f = MyFilter()
    assert id(get_filter(f)) == id(f)

    # Passing a lone callable will give us a a filter back as well.
    assert hasattr(get_filter(lambda: None), 'output')

    # Arguments passed to get_filter are used for instance creation.
    assert get_filter('sass', scss=True).use_scss == True
    # However, this is not allowed when a filter instance is passed directly,
    # or a callable object.
    assert_raises(AssertionError, get_filter, f, 'test')
    assert_raises(AssertionError, get_filter, lambda: None, 'test')
Example #2
0
 def test_cssrewrite_change_folder(self):
     """Test the replace mode of the cssrewrite filter.
     """
     self.create_files({"in.css": """h1 { background: url(old/sub/icon.png) }"""})
     try:
         from collections import OrderedDict
     except ImportError:
         # Without OrderedDict available, use a simplified version
         # of this test.
         cssrewrite = get_filter(
             "cssrewrite",
             replace=dict((("o", "/error/"), ("old", "/new/"))),  # o does NOT match the old/ dir  # this will match
         )
     else:
         cssrewrite = get_filter(
             "cssrewrite",
             replace=OrderedDict(
                 (
                     ("o", "/error/"),  # o does NOT match the old/ dir
                     ("old", "/new/"),  # this will match
                     ("old/sub", "/error/"),  # the first match is used, so this won't be
                     ("new", "/error/"),  # neither will this one match
                 )
             ),
         )
     self.mkbundle("in.css", filters=cssrewrite, output="out.css").build()
     assert self.get("out.css") == """h1 { background: url(/new/sub/icon.png) }"""
 def test_change_folder(self):
     """Test the replace mode of the cssrewrite filter.
     """
     self.create_files(
         {'in.css': '''h1 { background: url(old/sub/icon.png) }'''})
     try:
         from collections import OrderedDict
     except ImportError:
         # Without OrderedDict available, use a simplified version
         # of this test.
         cssrewrite = get_filter(
             'cssrewrite',
             replace=dict((
                 ('o', '/error/'),  # o does NOT match the old/ dir
                 ('old', '/new/'),  # this will match
             )))
     else:
         cssrewrite = get_filter(
             'cssrewrite',
             replace=OrderedDict((
                 ('o', '/error/'),  # o does NOT match the old/ dir
                 ('old', '/new/'),  # this will match
                 ('old/sub',
                  '/error/'),  # the first match is used, so this won't be
                 ('new', '/error/'),  # neither will this one match
             )))
     self.mkbundle('in.css', filters=cssrewrite, output='out.css').build()
     assert self.get(
         'out.css') == '''h1 { background: url(/new/sub/icon.png) }'''
    def test_debug_info_option(self):
        # The debug_info argument to the sass filter can be configured via
        # a global SASS_DEBUG_INFO option.
        self.env.config['SASS_DEBUG_INFO'] = False
        self.mkbundle('foo.sass', filters=get_filter('sass'),
                      output='out.css').build(force=True)
        assert not '-sass-debug-info' in self.get('out.css')

        # However, an instance-specific debug_info option takes precedence.
        self.mkbundle('foo.sass',
                      filters=get_filter('sass', debug_info=True),
                      output='out.css').build(force=True)
        assert '-sass-debug-info' in self.get('out.css')

        # If the value is None (the default), then the filter will look
        # at the debug setting to determine whether to include debug info.
        self.env.config['SASS_DEBUG_INFO'] = None
        self.env.debug = True
        self.mkbundle('foo.sass',
                      filters=get_filter('sass'),
                      output='out.css',
                      debug=False).build(force=True)
        assert '-sass-debug-info' in self.get('out.css')
        self.env.debug = False
        self.mkbundle('foo.sass', filters=get_filter('sass'),
                      output='out.css').build(force=True)
        assert not '-sass-debug-info' in self.get('out.css')
Example #5
0
def test_get_filter():
    """Test filter resolving.
    """
    # By name - here using one of the builtins.
    assert isinstance(get_filter('jsmin'), Filter)
    assert_raises(ValueError, get_filter, 'notafilteractually')

    # By class.
    class MyFilter(Filter): pass
    assert isinstance(get_filter(MyFilter), MyFilter)
    assert_raises(ValueError, get_filter, object())

    # Passing an instance doesn't do anything.
    f = MyFilter()
    assert id(get_filter(f)) == id(f)

    # Passing a lone callable will give us a a filter back as well.
    assert hasattr(get_filter(lambda: None), 'output')

    # Arguments passed to get_filter are used for instance creation.
    assert get_filter('sass', scss=True).use_scss == True
    # However, this is not allowed when a filter instance is passed directly,
    # or a callable object.
    assert_raises(AssertionError, get_filter, f, 'test')
    assert_raises(AssertionError, get_filter, lambda: None, 'test')
Example #6
0
    def enhance_assets(self):
        """
        Add js, css/scss assets to the environment
        :param env:     webassets environment
        :return:
        """

        js_filters = []
        if self.config['filter_jsmin']:
            js_filters = ['jsmin']

        if self.config['filter_babel']:
            js_filters.append(
                get_filter('babel', presets=self.config['babel_presets']))

        scss_includes = []
        scss_depends = [
            utils.abs_path(os.path.join(folder, '*.scss'))
            for folder in self.config['scss_folders']
        ]

        for f in self.config['scss_libs']:
            scss_includes.append(
                self._find_file(f, self.config['scss_folders']))

        sass_compiler = get_filter('libsass', includes=scss_includes)

        scss_filters = [sass_compiler]

        if self.config['filter_autoprefixer']:
            scss_filters.append(
                get_filter('autoprefixer',
                           autoprefixer='autoprefixer-cli',
                           browsers='last 2 version'))

        #: JS assets
        [
            self.add_js_asset(asset, js_filters)
            for asset in self.config['js_assets']
        ]

        #: CSS assets
        for folder in self.config['scss_folders']:
            for f in os.listdir(folder):
                if f.endswith('scss') and not f.startswith('_'):
                    self.add_css_asset(f, folder, scss_filters, scss_depends)

        asset_groups = self.config['asset_groups']
        for k, v in asset_groups.items():
            css = v.get('css', [])
            if isinstance(css, basestring):
                asset_groups[k]['css'] = [css]
            js = v.get('js', [])
            if isinstance(js, basestring):
                asset_groups[k]['js'] = [js]
            ext = v.get('ext', [])
            if isinstance(ext, basestring):
                asset_groups[k]['ext'] = [ext]
        self.app.jinja_env.globals['asset_groups'] = asset_groups
Example #7
0
    def test_debug_info_option(self):
        # The debug_info argument to the sass filter can be configured via
        # a global SASS_DEBUG_INFO option.
        self.m.config['SASS_DEBUG_INFO'] = False
        self.mkbundle('foo.sass', filters=get_filter('sass'), output='out.css').build()
        assert not '-sass-debug-info' in self.get('out.css')

        # However, an instance-specific debug_info option takes precedence.
        self.mkbundle('foo.sass', filters=get_filter('sass', debug_info=True), output='out2.css').build()
        assert '-sass-debug-info' in self.get('out2.css')
def inject_filters():
    return {
        'babel':
        get_filter('babel',
                   presets='babili,env',
                   binary='node_modules/babel-cli/bin/babel.js'),
        'sass':
        get_filter('sass',
                   as_output=True,
                   style='compressed',
                   binary='node_modules/node-sass/bin/node-sass')
    }
Example #9
0
    def test_debug_info_option(self):
        # The debug_info argument to the sass filter can be configured via
        # a global SASS_DEBUG_INFO option.
        self.m.config['SASS_DEBUG_INFO'] = False
        self.mkbundle('foo.sass', filters=get_filter('sass'),
                      output='out.css').build()
        assert not '-sass-debug-info' in self.get('out.css')

        # However, an instance-specific debug_info option takes precedence.
        self.mkbundle('foo.sass',
                      filters=get_filter('sass', debug_info=True),
                      output='out2.css').build()
        assert '-sass-debug-info' in self.get('out2.css')
Example #10
0
 def test_scss(self):
     # SCSS is a CSS superset, should be able to compile the CSS file just fine
     scss = get_filter('scss', debug_info=False)
     self.mkbundle('foo.css', filters=scss, output='out.css').build()
     assert self.get(
         'out.css'
     ) == """/* line 2 */\nh1 {\n  font-family: "Verdana";\n  color: #FFFFFF;\n}\n"""
Example #11
0
def test_register_filter():
    """Test registration of custom filters.
    """
    # Needs to be a ``Filter`` subclass.
    assert_raises(ValueError, register_filter, object)

    # A name is required.
    class MyFilter(Filter):
        name = None

        def output(self, *a, **kw):
            pass

    assert_raises(ValueError, register_filter, MyFilter)

    # We should be able to register a filter with a name.
    MyFilter.name = "foo"
    register_filter(MyFilter)

    # A filter should be able to override a pre-registered filter of the same
    # name.
    class OverrideMyFilter(Filter):
        name = "foo"

        def output(self, *a, **kw):
            pass

    register_filter(OverrideMyFilter)
    assert_true(isinstance(get_filter("foo"), OverrideMyFilter))
Example #12
0
 def test_sass_import(self):
     """Test referencing other files in sass.
     """
     sass = get_filter('sass', debug_info=False)
     self.create_files({'import-test.sass': '''@import foo.sass'''})
     self.mkbundle('import-test.sass', filters=sass, output='out.css').build()
     assert doctest_match("""/* line 1, ...foo.sass */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n""", self.get('out.css'))
Example #13
0
 def test_template(self):
     self.create_files({'media/foo.html': '{{ num|filesizeformat }}'})
     self.mkbundle('foo.html',
                   output="out",
                   filters=get_filter('template',
                                      context={'num': 23232323})).build()
     assert self.get('media/out') == '22.2 MB'
Example #14
0
def test_register_filter():
    """Test registration of custom filters.
    """
    # Needs to be a ``Filter`` subclass.
    assert_raises(ValueError, register_filter, object)

    # A name is required.
    class MyFilter(Filter):
        name = None

        def output(self, *a, **kw):
            pass

    assert_raises(ValueError, register_filter, MyFilter)

    # We should be able to register a filter with a name.
    MyFilter.name = 'foo'
    register_filter(MyFilter)

    # A filter should be able to override a pre-registered filter of the same
    # name.
    class OverrideMyFilter(Filter):
        name = 'foo'

        def output(self, *a, **kw):
            pass

    register_filter(OverrideMyFilter)
    assert_true(isinstance(get_filter('foo'), OverrideMyFilter))
Example #15
0
 def test_sass_import(self):
     """Test referencing other files in sass.
     """
     sass = get_filter('sass', debug_info=False)
     self.create_files({'import-test.sass': '''@import foo.sass'''})
     self.mkbundle('import-test.sass', filters=sass, output='out.css').build()
     assert doctest_match("""/* line 1, ...foo.sass */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n""", self.get('out.css'))
    def __init__(self, *args, **kwargs):
        ignore_filters = kwargs.pop('ignore_filters', False) or False
        kwargs['debug'] = False

        try:
            filters = list(kwargs.pop('filters'))
        except KeyError:
            filters = []

        try:
            vars = kwargs.pop('vars')
        except KeyError:
            vars = {}

        fltr = get_filter('vars', vars=vars)

        if not ignore_filters:
            filters.extend([fltr])
        else:
            filters = fltr

        kwargs.update({
            'filters': filters
        })

        Bundle.__init__(self, *args, **kwargs)
Example #17
0
def configure_assets(app):
    assets = Environment(app)
    js = Bundle(*BUNDLE_JS, filters='jsmin', output='output/packed.js')
    css_rewrite = get_filter('cssrewrite', replace={'/static/': '../'})
    css = Bundle(*BUNDLE_CSS,
                 filters=(css_rewrite, 'cssmin'),
                 output='output/packed.css')
    ie7_css = Bundle(*BUNDLE_IE7_CSS,
                     filters='cssmin',
                     output='output/packed_ie7.css')
    ie8_css = Bundle(*BUNDLE_IE8_CSS,
                     filters='cssmin',
                     output='output/packed_ie8.css')
    ie9_css = Bundle(*BUNDLE_IE9_CSS,
                     filters='cssmin',
                     output='output/packed_ie9.css')
    print_css = Bundle(*BUNDLE_PRINT_CSS,
                       filters='cssmin',
                       output='output/packed_print.css')

    assets.register('packed_js', js)
    assets.register('packed_css', css)
    assets.register('packed_ie7_css', ie7_css)
    assets.register('packed_ie8_css', ie8_css)
    assets.register('packed_ie9_css', ie9_css)
    assets.register('packed_print_css', print_css)
Example #18
0
 def test_clevercss(self):
     try:
         import clevercss
     except ImportError: 
         raise SkipTest()
     clevercss = get_filter('clevercss')
     self.mkbundle('foo.clevercss', filters=clevercss, output='out.css').build()
     assert self.get('out.css') == """a {
Example #19
0
 def test_replacement_lambda(self):
     self.create_files(
         {'in.css': '''h1 { background: url(old/sub/icon.png) }'''})
     cssrewrite = get_filter(
         'cssrewrite', replace=lambda url: re.sub(r'^/?old/', '/new/', url))
     self.mkbundle('in.css', filters=cssrewrite, output='out.css').build()
     assert self.get(
         'out.css') == '''h1 { background: url(/new/sub/icon.png) }'''
Example #20
0
    def input(self, _in, out, **kwargs):
        filepath = kwargs["source_path"]
        source = kwargs.get("source")

        if not source:
            # this happens when this filters is not used as a "source" filter, i.e _in
            # is a webasset hunk instance
            source = filepath
        # output = kwargs['output']
        base_dir = Path(filepath).parent
        rel_dir = Path(source).parent

        self.logger.debug('process "%s"', filepath)

        for line in _in.readlines():
            import_match = self._IMPORT_RE.search(line)
            if import_match is None:
                out.write(line)
                continue

            filename = import_match.group("filename")
            abs_filename = os.path.abspath(base_dir / filename)
            rel_filename = os.path.normpath(rel_dir / filename)

            start, end = import_match.span()
            if start > 0:
                out.write(line[:start])
                out.write("\n")

            with open(abs_filename, "r") as included:
                # rewrite url() statements
                buf = StringIO()
                url_rewriter = get_filter("cssrewrite")
                url_rewriter.set_context(self.ctx)
                url_rewriter.setup()
                url_rewriter.input(
                    included,
                    buf,
                    source=rel_filename,
                    source_path=abs_filename,
                    output=source,
                    output_path=filepath,
                )
            buf.seek(0)
            # now process '@includes' directives in included file
            self.input(
                buf,
                out,
                source=rel_filename,
                source_path=abs_filename,
                output=source,
                output_path=filepath,
            )

            if end < len(line):
                out.write(line[end:])
            else:
                out.write("\n")
Example #21
0
 def test_as_output_filter(self):
     """The sass filter can be configured to work as on output filter,
     first merging the sources together, then applying sass.
     """
     # To test this, split a sass rules into two files.
     sass_output = get_filter('sass', debug_info=False, as_output=True)
     self.create_files({'p1': 'h1', 'p2': '\n  color: #FFFFFF'})
     self.mkbundle('p1', 'p2', filters=sass_output, output='out.css').build()
     assert self.get('out.css') == """/* line 1 */\nh1 {\n  color: white;\n}\n"""
Example #22
0
 def test_as_output_filter(self):
     """The sass filter can be configured to work as on output filter,
     first merging the sources together, then applying sass.
     """
     # To test this, split a sass rules into two files.
     sass_output = get_filter('sass', debug_info=False, as_output=True)
     self.create_files({'p1': 'h1', 'p2': '\n  color: #FFFFFF'})
     self.mkbundle('p1', 'p2', filters=sass_output, output='out.css').build()
     assert self.get('out.css') == """/* line 1 */\nh1 {\n  color: white;\n}\n"""
Example #23
0
 def test_custom_include_path(self):
     """Test a custom include_path.
     """
     sass_output = get_filter("sass", debug_info=False, as_output=True, includes_dir=self.path("includes"))
     self.create_files(
         {"includes/vars.sass": "$a_color: #FFFFFF", "base.sass": "@import vars.sass\nh1\n  color: $a_color"}
     )
     self.mkbundle("base.sass", filters=sass_output, output="out.css").build()
     assert self.get("out.css") == """/* line 2 */\nh1 {\n  color: white;\n}\n"""
Example #24
0
 def test_sass_import(self):
     """Test referencing other files in sass.
     """
     sass = get_filter("sass", debug_info=False)
     self.create_files({"import-test.sass": """@import foo.sass"""})
     self.mkbundle("import-test.sass", filters=sass, output="out.css").build()
     assert (
         self.get("out.css") == """/* line 1, ./foo.sass */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""
     )
Example #25
0
 def test_as_output_filter(self):
     """The sass filter can be configured to work as on output filter,
     first merging the sources together, then applying sass.
     """
     # To test this, split a sass rules into two files.
     sass_output = get_filter("sass", debug_info=False, as_output=True)
     self.create_files({"p1": "h1", "p2": "\n  color: #FFFFFF"})
     self.mkbundle("p1", "p2", filters=sass_output, output="out.css").build()
     assert self.get("out.css") == """/* line 1 */\nh1 {\n  color: white;\n}\n"""
Example #26
0
 def test_template(self):
     self.create_files(
         {'media/foo.html': u'Ünicôdé-Chèck: {{ num|filesizeformat }}'})
     self.mkbundle('foo.html',
                   output="out",
                   filters=get_filter('template',
                                      context={'num': 23232323})).build()
     # Depending on Django version "filesizeformat" may contain a breaking space
     assert self.get('media/out') in ('Ünicôdé-Chèck: 22.2\xa0MB',
                                      'Ünicôdé-Chèck: 22.2 MB')
Example #27
0
    def test_replace_with_cache(self):
        """[Regression] Test replace mode while cache is active.

        This used to fail due to an unhashable key being returned by
        the filter."""
        cssrewrite = get_filter("cssrewrite", replace={"old": "new"})
        self.env.cache = True
        self.create_files({"in.css": """h1 { background: url(old/sub/icon.png) }"""})
        # Does not raise an exception.
        self.mkbundle("in.css", filters=cssrewrite, output="out.css").build()
Example #28
0
    def test_coffeescript(self):
        coffeescript = get_filter("coffeescript")
        self.mkbundle("foo.coffee", filters=coffeescript, output="out.js").build()
        assert (
            self.get("out.js")
            == """if (typeof elvis != "undefined" && elvis !== null) {
  alert("I knew it!");
}
"""
        )
Example #29
0
 def test_custom_include_path(self):
     """Test a custom include_path.
     """
     sass_output = get_filter('sass', debug_info=False, as_output=True,
                              includes_dir=self.path('includes'))
     self.create_files({
         'includes/vars.sass': '$a_color: #FFFFFF',
         'base.sass': '@import vars.sass\nh1\n  color: $a_color'})
     self.mkbundle('base.sass', filters=sass_output, output='out.css').build()
     assert self.get('out.css') == """/* line 2 */\nh1 {\n  color: white;\n}\n"""
Example #30
0
 def test_custom_include_path(self):
     """Test a custom include_path.
     """
     sass_output = get_filter('sass', debug_info=False, as_output=True,
                              includes_dir=self.path('includes'))
     self.create_files({
         'includes/vars.sass': '$a_color: #FFFFFF',
         'base.sass': '@import vars.sass\nh1\n  color: $a_color'})
     self.mkbundle('base.sass', filters=sass_output, output='out.css').build()
     assert self.get('out.css') == """/* line 2 */\nh1 {\n  color: white;\n}\n"""
Example #31
0
    def test_replace_with_cache(self):
        """[Regression] Test replace mode while cache is active.

        This used to fail due to an unhashable key being returned by
        the filter."""
        cssrewrite = get_filter('cssrewrite', replace={'old': 'new'})
        self.env.cache = True
        self.create_files({'in.css': '''h1 { background: url(old/sub/icon.png) }'''})
        # Does not raise an exception.
        self.mkbundle('in.css', filters=cssrewrite, output='out.css').build()
Example #32
0
def get_rules(kind):
    if kind == '.css':
        return Bunch(
            final_filter = ["yui_css", get_filter('cssrewrite', replace=proxied)],
            compilers = {".scss": "pyscss"},
            kwargs = defaultdict(dict)
        )
    elif kind == '.js':
        return Bunch(final_filter="yui_js", compilers={".coffee": "coffeescript", ".jst": "register_jst"},
                     kwargs=defaultdict(dict))
    raise RuntimeError("unknown bundle kind: %s" % (kind,))
Example #33
0
    def __init__(self, flask_app):
        self.app = flask_app
        self.styles_path = os.path.join(self.app.config['ASSETS_PATH'], 'styles')
        self.scripts_path = os.path.join(self.app.config['ASSETS_PATH'], 'scripts')

        # add filters
        self.pyscss = get_filter('pyscss')
        self.pyscss.load_paths = [self.styles_path]

        self.css_filters = (self.pyscss, 'cssmin')
        self.js_filters = (Pipeline.pycoffee, 'jsmin')
Example #34
0
    def test_debug_info_option(self):
        # The debug_info argument to the sass filter can be configured via
        # a global SASS_DEBUG_INFO option.
        self.env.config["SASS_DEBUG_INFO"] = False
        self.mkbundle("foo.sass", filters=get_filter("sass"), output="out.css").build(force=True)
        assert not "-sass-debug-info" in self.get("out.css")

        # However, an instance-specific debug_info option takes precedence.
        self.mkbundle("foo.sass", filters=get_filter("sass", debug_info=True), output="out.css").build(force=True)
        assert "-sass-debug-info" in self.get("out.css")

        # If the value is None (the default), then the filter will look
        # at the debug setting to determine whether to include debug info.
        self.env.config["SASS_DEBUG_INFO"] = None
        self.env.debug = True
        self.mkbundle("foo.sass", filters=get_filter("sass"), output="out.css", debug=False).build(force=True)
        assert "-sass-debug-info" in self.get("out.css")
        self.env.debug = False
        self.mkbundle("foo.sass", filters=get_filter("sass"), output="out.css").build(force=True)
        assert not "-sass-debug-info" in self.get("out.css")
Example #35
0
    def test_replace_with_cache(self):
        """[Regression] Test replace mode while cache is active.

        This used to fail due to an unhashable key being returned by
        the filter."""
        cssrewrite = get_filter('cssrewrite', replace={'old/': 'new/'})
        self.env.cache = True
        self.create_files({'in.css': '''h1 { background: url(old/sub/icon.png) }'''})
        # Does not raise an exception.
        self.mkbundle('in.css', filters=cssrewrite, output='out.css').build()
        assert self.get('out.css') == '''h1 { background: url(new/sub/icon.png) }'''
Example #36
0
    def test_template(self):
        self.create_files({
            'media/foo.html': 'Ünicôdé-Chèck: {{ num|filesizeformat }}',
        })
        self.mkbundle(
            'foo.html',
            output="out",
            filters=get_filter('template', context={'num': 23232323}),
        ).build()

        # Depending on Django version "filesizeformat" may contain a breaking space
        assert self.get('media/out') in ('Ünicôdé-Chèck: 22.2\xa0MB', 'Ünicôdé-Chèck: 22.2 MB')
Example #37
0
  def input(self, _in, out, **kwargs):
    filepath = kwargs['source_path']
    source = kwargs.get('source')

    if not source:
      # this happens when this filters is not used as a "source" filter, i.e _in
      # is a webasset hunk instance
      source = filepath
    # output = kwargs['output']
    base_dir = os.path.dirname(filepath)
    rel_dir = os.path.dirname(source)

    self.logger.debug('process "%s"', filepath)

    for line in _in.readlines():
      import_match = self._IMPORT_RE.search(line)
      if import_match is None:
        out.write(line)
        continue

      filename = import_match.group('filename')
      abs_filename = os.path.abspath(os.path.join(base_dir, filename))
      rel_filename= os.path.normpath(os.path.join(rel_dir, filename))

      start, end = import_match.span()
      if start > 0:
        out.write(line[:start])
        out.write('\n')

      with open(abs_filename, 'r') as included:
        # rewrite url() statements
        buf = StringIO()
        url_rewriter = get_filter('cssrewrite')
        url_rewriter.set_context(self.ctx)
        url_rewriter.setup()
        url_rewriter.input(included, buf,
                           source=rel_filename,
                           source_path=abs_filename,
                           output=source,
                           output_path=filepath)
      buf.seek(0)
      # now process '@includes' directives in included file
      self.input(buf, out,
                 source=rel_filename,
                 source_path=abs_filename,
                 output=source,
                 output_path=filepath)

      if end < len(line):
        out.write(line[end:])
      else:
        out.write('\n')
Example #38
0
 def test_change_folder(self):
     """Test the replace mode of the cssrewrite filter.
     """
     self.create_files({'in.css': '''h1 { background: url(old/sub/icon.png) }'''})
     try:
         from collections import OrderedDict
     except ImportError:
         # Without OrderedDict available, use a simplified version
         # of this test.
         cssrewrite = get_filter('cssrewrite', replace=dict((
             ('o', '/error/'),       # o does NOT match the old/ dir
             ('old', '/new/'),       # this will match
         )))
     else:
         cssrewrite = get_filter('cssrewrite', replace=OrderedDict((
             ('o', '/error/'),       # o does NOT match the old/ dir
             ('old', '/new/'),       # this will match
             ('old/sub', '/error/'), # the first match is used, so this won't be
             ('new', '/error/'),     # neither will this one match
         )))
     self.mkbundle('in.css', filters=cssrewrite, output='out.css').build()
     assert self.get('out.css') == '''h1 { background: url(/new/sub/icon.png) }'''
Example #39
0
    def test_clevercss(self):
        try:
            import clevercss
        except ImportError:
            raise SkipTest()
        clevercss = get_filter("clevercss")
        self.mkbundle("foo.clevercss", filters=clevercss, output="out.css").build()
        assert (
            self.get("out.css")
            == """a {
  color: #7f7f7f;
}"""
        )
Example #40
0
def _register_plugin(plugin_path):
    plugin_config = os.path.join(plugin_path, 'plugin.json')

    if not os.path.isfile(plugin_config):
        log.warn('Unable to load plugin %s missing' % plugin_config)
        return
    try:
        with open(plugin_config, 'r') as f:
            config = json.load(f)
    except IOError as e:
        log.error('Error loading plugin config %s as %s' % (plugin_config, str(e)))
        return
    except ValueError as e:
        log.error('Invalid plugin config %s as %s' % (plugin_config, str(e)))
        return

    name = config.get('name')
    if not name:
        log.error('Error loading plugin missing name in ' % plugin_config)
        return

    if name in _plugins:
        log.error('Error loading plugin %s with name %s as it\'s already registered ' % (plugin_config, name))
        return

    version = config.get('version', '1.0')
    _plugins[name] = {'path': plugin_path, 'config': config, version: version}

    # Register CSS/SASS assets
    if config.get('sass'):
        sass_path = os.path.normpath(os.path.join(plugin_path, 'sass'))
        sass_file = os.path.join(sass_path, config['sass'])
        libsass = get_filter('libsass', includes=[os.path.join(webui_path, 'sass'), sass_path])
        register_asset('plugins_css', Bundle(sass_file, output='css/%s.css' % name, filters=(libsass,)))

    css_path = os.path.join(plugin_path, 'css')
    if os.path.isdir(css_path):
        for css_file in _find(css_path, "*.css"):
            register_asset('plugins_css', css_file)

    # Register JS assets
    if config.get('js'):
        for js_file in config['js']:
            js_file = '%s.js' % os.path.normpath(os.path.join(plugin_path, 'js', js_file))
            register_asset('plugins_js', js_file)
    else:
        js_path = os.path.join(plugin_path, 'js')
        if os.path.isdir(js_path):
            # Register JS assets
            for js_file in _find(js_path, "*.js"):
                register_asset('plugins_js', js_file)
Example #41
0
    def _apply_less(self, in_, out, output_path, output, **kw):
        # Set working directory to the source file so that includes are found
        args = [self.less or "lessc"]
        if self.line_numbers:
            args.append(f"--line-numbers={self.line_numbers}")

        if self.paths:
            paths = [
                path if isabs(path) else self.ctx.resolver.resolve_source(path)
                for path in self.pathsep
            ]
            args.append(f"--include-path={os.pathsep.join(paths)}")

        #
        # Commented out since this doesn't work with the current lessc compiler.
        # (See also just below)
        #
        # source_map = self.source_map_file and self.ctx.debug
        # if source_map:
        #     source_map_dest = os.path.join(self.ctx.directory,
        #                                    self.source_map_file)
        #     self.logger.debug('Generate source map to "%s"', source_map_dest)
        #     args.append('--source-map={}'.format(source_map_dest))
        #     args.append('--source-map-url={}'.format(self.source_map_file))

        if self.extra_args:
            args.extend(self.extra_args)

        args.append("-")
        buf = StringIO()
        with working_directory(filename=output_path):
            self.subprocess(args, buf, in_)

        # if source_map:
        #     self.fix_source_map_urls(source_map_dest)

        # rewrite css url()
        replace_url = partial(self.fix_url, os.path.dirname(output_path))
        buf.seek(0)
        url_rewriter = get_filter("cssrewrite", replace=replace_url)
        url_rewriter.set_context(self.ctx)
        url_rewriter.setup()
        url_rewriter.input(
            buf,
            out,
            source=output,
            source_path=output_path,
            output=output,
            output_path=output_path,
        )
Example #42
0
 def test_load_filters(self):
     """Check that filters can be loaded from YAML """
     # Delete the less filter
     import webassets.filter
     del webassets.filter._FILTERS['less']
     # Verify that it was deleted
     assert_raises(ValueError, get_filter, 'less')
     # Load it again from YAML
     self.loader("""
     filters:
         - webassets.filter.less.Less
     """).load_environment()
     # Check that it's back
     assert_true(isinstance(get_filter('less'), Filter))
Example #43
0
    def test_debug_info_option(self):
        # The debug_info argument to the sass filter can be configured via
        # a global SASS_DEBUG_INFO option.
        self.env.config['SASS_DEBUG_INFO'] = False
        self.mkbundle('foo.sass', filters=get_filter('sass'), output='out.css').build(force=True)
        assert not '-sass-debug-info' in self.get('out.css')

        # However, an instance-specific debug_info option takes precedence.
        self.mkbundle('foo.sass', filters=get_filter('sass', debug_info=True), output='out.css').build(force=True)
        assert '-sass-debug-info' in self.get('out.css')

        # If the value is None (the default), then the filter will look
        # at the global debug setting to determine whether to include debug
        # info. Note: It looks at environment.debug! The local bundle.debug
        # is likely to be always False for Sass, so is of little help.
        self.env.config['SASS_DEBUG_INFO'] = None
        self.env.debug = True
        self.mkbundle('foo.sass', filters=get_filter('sass'),
                      output='out.css', debug=False).build(force=True)
        assert '-sass-debug-info' in self.get('out.css')
        self.env.debug = False
        self.mkbundle('foo.sass', filters=get_filter('sass'),
                      output='out.css').build(force=True)
        assert not '-sass-debug-info' in self.get('out.css')
Example #44
0
def get_rules(kind):
    if kind == '.css':
        return Bunch(final_filter=[
            "yui_css", get_filter('cssrewrite', replace=proxied)
        ],
                     compilers={".scss": "pyscss"},
                     kwargs=defaultdict(dict))
    elif kind == '.js':
        return Bunch(final_filter="yui_js",
                     compilers={
                         ".coffee": "coffeescript",
                         ".jst": "register_jst"
                     },
                     kwargs=defaultdict(dict))
    raise RuntimeError("unknown bundle kind: %s" % (kind, ))
Example #45
0
def configure_assets(app):
    assets = Environment(app)
    js = Bundle(*BUNDLE_JS, filters='jsmin', output='output/packed.js')
    css_rewrite = get_filter('cssrewrite', replace={'/static/':'../'})
    css = Bundle(*BUNDLE_CSS, filters=(css_rewrite, 'cssmin'),
                 output='output/packed.css')
    ie_css7 = Bundle(*BUNDLE_IE_CSS7, filters='cssmin', output='output/ie7.css')
    ie_css8 = Bundle(*BUNDLE_IE_CSS8, filters='cssmin', output='output/ie8.css')
    ie_css9 = Bundle(*BUNDLE_IE_CSS9, filters='cssmin', output='output/ie9.css')

    assets.register('packed_js', js)
    assets.register('packed_css', css)
    assets.register('packed_ie_css7', ie_css7)
    assets.register('packed_ie_css8', ie_css8)
    assets.register('packed_ie_css9', ie_css9)
Example #46
0
    def build_js(self):
        """
        js -> babel -> minify -> (later) uglify

        [babel setting]
        - install babel-cli globally : `npm install -g babel-cli`
        - install babel-preset-env locally : `npm install --save babel-preset-env`
        """
        babel = get_filter('babel', presets='babel-preset-env')
        for js in self.templates_path.rglob('*.js'):
            print(js)
            self.assets.register(
                js.name,
                Bundle(str(js),
                       output=f'gen/js/{js.stem}.min.js',
                       filters=[babel, 'rjsmin']))
Example #47
0
File: app.py Project: eea/eea.sanap
def configure_assets(app):
    assets = Environment(app)
    js = Bundle(*BUNDLE_JS, filters="jsmin", output="output/packed.js")
    css_rewrite = get_filter("cssrewrite", replace={"/static/": "../"})
    css = Bundle(*BUNDLE_CSS, filters=(css_rewrite, "cssmin"), output="output/packed.css")
    ie7_css = Bundle(*BUNDLE_IE7_CSS, filters="cssmin", output="output/packed_ie7.css")
    ie8_css = Bundle(*BUNDLE_IE8_CSS, filters="cssmin", output="output/packed_ie8.css")
    ie9_css = Bundle(*BUNDLE_IE9_CSS, filters="cssmin", output="output/packed_ie9.css")
    print_css = Bundle(*BUNDLE_PRINT_CSS, filters="cssmin", output="output/packed_print.css")

    assets.register("packed_js", js)
    assets.register("packed_css", css)
    assets.register("packed_ie7_css", ie7_css)
    assets.register("packed_ie8_css", ie8_css)
    assets.register("packed_ie9_css", ie9_css)
    assets.register("packed_print_css", print_css)
Example #48
0
    def _apply_less(self, in_, out, output_path, output, **kw):
        # Set working directory to the source file so that includes are found
        args = [self.less or 'lessc']
        if self.line_numbers:
            args.append('--line-numbers=%s' % self.line_numbers)

        if self.paths:
            paths = [
                path if isabs(path) else self.ctx.resolver.resolve_source(path)
                for path in self.pathsep
            ]
            args.append('--include-path={0}'.format(os.pathsep.join(paths)))

        source_map = self.source_map_file and self.ctx.debug
        if source_map:
            source_map_dest = os.path.join(self.ctx.directory,
                                           self.source_map_file)
            self.logger.debug('Generate source map to "%s"', source_map_dest)
            args.append('--source-map={}'.format(source_map_dest))
            args.append('--source-map-url={}'.format(self.source_map_file))

        if self.extra_args:
            args.extend(self.extra_args)

        args.append('-')
        buf = StringIO()
        with working_directory(filename=output_path):
            self.subprocess(args, buf, in_)

        if source_map:
            self.fix_source_map_urls(source_map_dest)

        # rewrite css url()
        replace_url = partial(self.fix_url, os.path.dirname(output_path))
        buf.seek(0)
        url_rewriter = get_filter('cssrewrite', replace=replace_url)
        url_rewriter.set_context(self.ctx)
        url_rewriter.setup()
        url_rewriter.input(buf,
                           out,
                           source=output,
                           source_path=output_path,
                           output=output,
                           output_path=output_path)
Example #49
0
  def _apply_less(self, in_, out, output_path, output, **kw):
    # Set working directory to the source file so that includes are found
    args = [self.less or 'lessc']
    if self.line_numbers:
      args.append('--line-numbers=%s' % self.line_numbers)

    if self.paths:
      paths = [path if isabs(path) else self.ctx.resolver.resolve_source(path)
               for path in self.pathsep]
      args.append('--include-path={0}'.format(os.pathsep.join(paths)))

    source_map = self.source_map_file and self.ctx.debug
    if source_map:
      source_map_dest = os.path.join(self.ctx.directory, self.source_map_file)
      self.logger.debug('Generate source map to "%s"', source_map_dest)
      args.append('--source-map={}'.format(source_map_dest))
      args.append('--source-map-url={}'.format(self.source_map_file))

    if self.extra_args:
      args.extend(self.extra_args)

    args.append('-')
    buf = StringIO()
    with working_directory(filename=output_path):
      self.subprocess(args, buf, in_)

    if source_map:
      self.fix_source_map_urls(source_map_dest)

    # rewrite css url()
    replace_url = partial(self.fix_url, os.path.dirname(output_path))
    buf.seek(0)
    url_rewriter = get_filter('cssrewrite', replace=replace_url)
    url_rewriter.set_context(self.ctx)
    url_rewriter.setup()
    url_rewriter.input(buf, out,
                       source=output, source_path=output_path,
                       output=output, output_path=output_path)
Example #50
0
FILEAPI_JS = Bundle("fileapi/FileAPI.js")

FONTAWESOME_LESS = Bundle("font-awesome/less/font-awesome.less")

REQUIRE_JS = Bundle("requirejs/require.js", "requirejs/domReady.js")

SELECT2_LESS = Bundle("select2/select2.css", "select2/select2-bootstrap.css")
SELECT2_JS = Bundle("select2/select2.js")

TYPEAHEAD_LESS = Bundle("typeahead/typeahead.js-bootstrap.less")
TYPEAHEAD_JS = Bundle("typeahead/typeahead.js", "typeahead/hogan-2.0.0.js")

ABILIAN_LESS = Bundle("less/abilian.less", "less/print.less")

es2015 = get_filter("babel", presets="es2015")

ABILIAN_JS_NS = Bundle("js/abilian-namespace.js")
ABILIAN_JS = Bundle(
    "js/abilian.js",
    "js/datatables-setup.js",
    "js/datatables-advanced-search.js",
    "js/widgets/base.js",
    "js/widgets/select2.js",
    "js/widgets/richtext.js",
    "js/widgets/delete.js",
    "js/widgets/file.js",
    "js/widgets/image.js",
    "js/widgets/tags.js",
    "js/widgets/dynamic-row.js",
)
Example #51
0
 def test_scss(self):
     # SCSS is a CSS superset, should be able to compile the CSS file just fine
     scss = get_filter('scss', debug_info=False)
     self.mkbundle('foo.css', filters=scss, output='out.css').build()
     assert self.get('out.css') == """/* line 2 */\nh1 {\n  font-family: "Verdana";\n  color: #FFFFFF;\n}\n"""
Example #52
0
 def cssrewrite(self):
     return get_filter('cssrewrite', replace={
         # self.theme.path: '',
         self.theme.static_path: '_themes/{0}'.format(self.theme.name),
     })
Example #53
0
 def test_sass(self):
     sass = get_filter('sass', debug_info=False)
     self.mkbundle('foo.sass', filters=sass, output='out.css').build()
     assert self.get('out.css') == """/* line 1 */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""
Example #54
0
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with Inboxen.  If not, see <http://www.gnu.org/licenses/>.
##

import os

from django.conf import settings

from django_assets import Bundle, register
from webassets.filter import get_filter

thirdparty_path = os.path.join(settings.BASE_DIR, "node_modules")
sass = get_filter('scss', style="compressed", load_paths=(thirdparty_path, ))

css = Bundle(
    "css/inboxen.scss",
    filters=(sass, ),
    output="compiled/css/website.%(version)s.css",
)

js = Bundle(
    "thirdparty/jquery/dist/jquery.js",
    "js/alert.js",
    "js/menu.js",
    "js/home.js",
    "js/search.js",
    "js/inbox.js",
    filters="jsmin",
Example #55
0
def create_app(configfile=None):
    app = Flask(__name__)

    app.config.from_object('web.config.Config')

    markdown = Markdown(app)

    # Typography Jinja2 Filter
    app.jinja_env.filters['typogrify'] = typogrify_filters.typogrify

    # Static Assets Config (Javascript and SCSS)
    env = assets.Environment(app)

    env.load_path = [
        os.path.join(app.config['STATIC_PATH'], 'bower'),
        os.path.join(app.config['STATIC_PATH'], 'scss'),
        os.path.join(app.config['STATIC_PATH'], 'javascript')
    ]

    env.register(
        'js_all',
        assets.Bundle('jquery/dist/jquery.min.js',
                      'leaflet/dist/leaflet.js',
                      assets.Bundle('iconic.min.js'),
                      assets.Bundle('app.js'),
                      output='app.js'))

    sass = get_filter('scss')
    sass.load_paths = env.load_path

    env.register(
        'css_all',
        assets.Bundle('app.scss',
                      filters=(sass, ),
                      depends=(os.path.join(app.config['STATIC_PATH'],
                                            'scss/**/*.scss')),
                      output='app.css'))

    # i18n Config
    babel = Babel(app)

    @app.url_defaults
    def set_language_code(endpoint, values):
        if 'lang_code' in values or not g.get('lang_code', None):
            return
        if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
            values['lang_code'] = g.lang_code

    @app.url_value_preprocessor
    def get_lang_code(endpoint, values):
        if values is not None:
            g.lang_code = values.pop('lang_code', None)

    @app.before_request
    def ensure_lang_support():
        lang_code = g.get('lang_code', None)
        if lang_code and lang_code not in app.config['LANGUAGES'].keys():
            return abort(404)

    @babel.localeselector
    def get_locale():
        return g.get('lang_code', app.config['BABEL_DEFAULT_LOCALE'])

    @babel.timezoneselector
    def get_timezone():
        return app.config['BABEL_DEFAULT_TIMEZONE']

    @app.context_processor
    def utility_processor():
        def get_talk(slug):
            return filters.get_talk(slug)

        return dict(get_talk=get_talk)

    # Register the Blueprints
    app.register_blueprint(view_pages, url_prefix='/<lang_code>')
    app.register_blueprint(view_schedule, url_prefix='/<lang_code>/schedule')

    # Register the filters
    app.jinja_env.filters['format_datetime'] = filters.format_datetime
    app.jinja_env.filters['format_date'] = filters.format_date
    app.jinja_env.filters['format_time'] = filters.format_time

    return app
Example #56
0
 def test_sass(self):
     sass = get_filter('sass', debug_info=False)
     self.mkbundle('foo.sass', filters=sass, output='out.css').build()
     assert self.get('out.css') == """/* line 1 */\nh1 {\n  font-family: "Verdana";\n  color: white;\n}\n"""
Example #57
0
from django.conf import settings

from django_assets import Bundle, register
from webassets.filter import get_filter

libsass = get_filter("libsass", style="compressed")

css_libs = Bundle(settings.BASE_DIR + "/assets/styles/css/libs/normalize.css",
                  filters="cssutils",
                  output="css/libs.css")

css_custom = Bundle(
    settings.BASE_DIR + "/assets/styles/sass/base.sass",
    filters=libsass,
    output="css/style.css",
    depends="/**/*.sass",
)

register("css_libs", css_libs)
register("css_custom", css_custom)
Example #58
0
db = SQLAlchemy(metadata=MetaData(naming_convention=naming_convention))

cache = Cache()
csrf = CsrfProtect()
migrate = Migrate()
manager = VersioningManager(options={'strategy': 'subquery'})
make_versioned(manager=manager, plugins=[FlaskPlugin()])
mail = Mail()
cdn = CDN()
login_manager = LoginManager()
assets = Environment()
toolbar = DebugToolbarExtension()
gocardless_client = None
volunteer_admin = None

pyscss = get_filter('pyscss', style='compressed')
assets.register(
    'css_main',
    Bundle('css/main.scss',
           output='gen/main-packed.css',
           depends='css/*.scss',
           filters=pyscss))
assets.register(
    'css_admin',
    Bundle('css/admin.scss',
           output='gen/admin-packed.css',
           depends='css/*.scss',
           filters=pyscss))
assets.register(
    'css_volunteer',
    Bundle('css/volunteer.scss',
Example #59
0
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with Inboxen.  If not, see <http://www.gnu.org/licenses/>.
##

import os

from django.conf import settings

from django_assets import Bundle, register
from webassets.filter import get_filter

thirdparty_path = os.path.join(settings.BASE_DIR, "node_modules")
sass = get_filter("scss",
                  style="compressed",
                  load_paths=("./css", thirdparty_path))

uglify_args = ["--comments", "/^!/", "-m", "-c"]
uglify = get_filter("uglifyjs",
                    binary=os.path.join(thirdparty_path, ".bin", "uglifyjs"),
                    extra_args=uglify_args)

css = Bundle(
    "css/inboxen.scss",
    filters=(sass, ),
    output="compiled/css/website.%(version)s.css",
)
register("inboxen_css", css)

js = Bundle(