示例#1
0
def styles(request, name):
    src = ''
    namespace = Namespace()
    for tv in ThemeValue.objects.all():
        namespace.set_variable('${}-{}'.format(tv.group, tv.name), String(tv.value))
    compiler = Compiler(namespace=namespace)
    return HttpResponse(compiler.compile_string(src), content_type='text/css')
示例#2
0
    def style_scss(self, *path):
        css_namespace = Namespace()
        for key, value in self.settings['keys'].items():
            if isinstance(value, LCText):
                css_value = String(value)
            elif isinstance(value, LCColour):
                css_value = Color.from_hex(value)
            elif isinstance(value, LCBool):
                css_value = Boolean(value.simple())
            elif isinstance(value, LCSpin):
                css_value = Number(value.simple())
            else:
                raise ValueError("Unable to find comparable values")
            css_namespace.set_variable('${}'.format(key), css_value)

        cherrypy.response.headers['Content-Type'] = 'text/css'
        with open(os.path.join(self.settings['location'], *path), 'r') as css:
            css_content = css.read()
            compiler = Compiler(namespace=css_namespace, output_style='nested')
            # Something wrong with PyScss,
            #  Syntax error: Found u'100%' but expected one of ADD.
            # Doesn't happen on next attempt, so we are doing bad thing
            attempts = 0
            while attempts < 100:
                try:
                    attempts += 1
                    ret_string = compiler.compile_string(css_content)
                    return ret_string
                except Exception as exc:
                    if attempts == 100:
                        log.debug(exc)
示例#3
0
def render_scss_file(filename, namespace):
    root_dir = os.path.dirname(filename)
    base_name, base_extension = os.path.splitext(os.path.basename(filename))
    render_filename = os.path.join(root_dir, 'render_{}.css'.format(base_name))
    with open(filename, 'r') as css_file, open(render_filename, 'w') as render_file:
        css_content = css_file.read()
        compiler = Compiler(namespace=namespace, output_style='compressed')
        render_file.write(compiler.compile_string(css_content))
示例#4
0
def styles(request, name):
    src = ''
    namespace = Namespace()
    for tv in ThemeValue.objects.all():
        namespace.set_variable('${}-{}'.format(tv.group, tv.name),
                               String(tv.value))
    compiler = Compiler(namespace=namespace)
    return HttpResponse(compiler.compile_string(src), content_type='text/css')
示例#5
0
def cookWhenChangingSettings(context, bundle=None):
    """When our settings are changed, re-cook the not compilable bundles"""
    registry = getUtility(IRegistry)
    resources = registry.collectionOfInterface(
        IResourceRegistry, prefix="plone.resources", check=False
    )
    if bundle is None:
        # default to cooking legacy bundle
        bundles = registry.collectionOfInterface(
            IBundleRegistry, prefix="plone.bundles", check=False
        )
        if "plone-legacy" in bundles:
            bundle = bundles["plone-legacy"]
        else:
            bundle = bundles.setdefault("plone-legacy")
            bundle.resources = []

    if not bundle.resources:
        # you can have a bundle without any resources defined and it's just
        # shipped as a legacy compiled js file
        return

    js_path = bundle.jscompilation
    css_path = bundle.csscompilation

    if not js_path and not css_path:
        logger.warning(
            "No js_path or css_path found. We need a plone.resource "
            "based resource path in order to store the compiled JS and CSS."
        )
        return

    # Let's join all css and js
    css_compiler = Compiler(output_style="compressed")
    cooked_css = ""
    cooked_js = REQUIREJS_RESET_PREFIX
    siteUrl = getSite().absolute_url()
    request = getRequest()
    for package in bundle.resources or []:
        if package not in resources:
            continue
        resource = resources[package]

        if css_path:
            for css_resource in resource.css:
                css_url = siteUrl + "/" + css_resource
                response = subrequest(css_url)
                if response.status == 200:
                    logger.info("Cooking css %s", css_resource)
                    css = response.getBody()
                    if css_resource[-8:] != ".min.css":
                        css = css_compiler.compile_string(css)
                    if not isinstance(css, str):
                        css = css.decode("utf8")
                    cooked_css += "\n/* Resource: {} */\n{}\n".format(css_resource, css)
                else:
                    cooked_css += "\n/* Could not find resource: {} */\n\n".format(
                        css_resource
                    )
                    logger.warning("Could not find resource: %s", css_resource)
        if not resource.js or not js_path:
            continue
        js_url = siteUrl + "/" + resource.js
        response = subrequest(js_url)
        if response.status == 200:
            logger.info("Cooking js %s", resource.js)
            js = response.getBody()
            if not isinstance(js, str):
                js = js.decode("utf8")
            try:
                cooked_js += "\n/* resource: {} */\n{}".format(
                    resource.js,
                    js if resource.js.endswith(".min.js") else es5.minify_print(js),
                )
            except SyntaxError:
                cooked_js += "\n/* Resource (error cooking): {} */\n{}".format(
                    resource.js, js
                )
                logger.warning("Error cooking resource: %s", resource.js)
        else:
            logger.warning("Could not find resource: %s", resource.js)
            cooked_js += "\n/* Could not find resource: {} */\n\n".format(js_url)

    cooked_js += REQUIREJS_RESET_POSTFIX

    persistent_directory = getUtility(IResourceDirectory, name="persistent")
    if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory:
        persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME)
    container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]

    def _write_resource(resource_path, cooked_string):
        if not resource_path:
            return
        if "++plone++" in resource_path:
            resource_path = resource_path.split("++plone++")[-1]
        if "/" in resource_path:
            resource_name, resource_filepath = resource_path.split("/", 1)
        else:
            resource_name = "legacy"
            resource_filepath = resource_path
        if resource_name not in container:
            container.makeDirectory(resource_name)
        if not isinstance(
            cooked_string, bytes
        ):  # handle Error of OFS.Image  # noqa: E501
            cooked_string = cooked_string.encode("ascii", errors="ignore")
        try:
            folder = container[resource_name]
            fi = BytesIO(cooked_string)
            folder.writeFile(resource_filepath, fi)
            logger.info("Writing cooked resource: %s", resource_path)
        except NotFound:
            logger.warning("Error writing cooked resource: %s", resource_path)

    _write_resource(js_path, cooked_js)
    _write_resource(css_path, cooked_css)

    bundle.last_compilation = datetime.now()
    # refresh production meta bundles
    combine_bundles(context)

    # Disable CSRF protection on this request
    alsoProvides(request, IDisableCSRFProtection)
示例#6
0
def cookWhenChangingSettings(context, bundle=None):
    """When our settings are changed, re-cook the not compilable bundles
    """
    registry = getUtility(IRegistry)
    resources = registry.collectionOfInterface(
        IResourceRegistry, prefix="plone.resources", check=False)
    if bundle is None:
        # default to cooking legacy bundle
        bundles = registry.collectionOfInterface(
            IBundleRegistry, prefix="plone.bundles", check=False)
        if 'plone-legacy' in bundles:
            bundle = bundles['plone-legacy']
        else:
            bundle = bundles.setdefault('plone-legacy')
            bundle.resources = []

    if not bundle.resources:
        # you can have a bundle without any resources defined and it's just
        # shipped as a legacy compiled js file
        return

    js_path = bundle.jscompilation
    css_path = bundle.csscompilation

    if not js_path and not css_path:
        logger.warn(
            'No js_path or css_path found. We need a plone.resource '
            'based resource path in order to store the compiled JS and CSS.'
        )
        return

    # Let's join all css and js
    css_compiler = Compiler(output_style='compressed')
    cooked_css = u''
    cooked_js = REQUIREJS_RESET_PREFIX
    siteUrl = getSite().absolute_url()
    request = getRequest()
    for package in bundle.resources or []:
        if package not in resources:
            continue
        resource = resources[package]

        if css_path:
            for css_resource in resource.css:
                css_url = siteUrl + '/' + css_resource
                response = subrequest(css_url)
                if response.status == 200:
                    logger.info('Cooking css %s', css_resource)
                    css = response.getBody()
                    if css_resource[-8:] != '.min.css':
                        css = css_compiler.compile_string(css)
                    if not isinstance(css, six.text_type):
                        css = css.decode('utf8')
                    cooked_css += u'\n/* Resource: {0} */\n{1}\n'.format(
                        css_resource,
                        css
                    )
                else:
                    cooked_css +=\
                        u'\n/* Could not find resource: {0} */\n\n'.format(
                            css_resource
                        )
                    logger.warn('Could not find resource: %s', css_resource)
        if not resource.js or not js_path:
            continue
        js_url = siteUrl + '/' + resource.js
        response = subrequest(js_url)
        if response.status == 200:
            js = response.getBody()
            try:
                logger.info('Cooking js %s', resource.js)
                if not isinstance(js, six.text_type):
                    js = js.decode('utf8')
                cooked_js += '\n/* resource: {0} */\n{1}'.format(
                    resource.js,
                    js if '.min.js' == resource.js[-7:] else
                    es5.minify_print(js)
                )
            except SyntaxError:
                cooked_js +=\
                    '\n/* Resource (error cooking): {0} */\n{1}'.format(
                        resource.js,
                        js
                    )
                logger.warn('Error cooking resource: %s', resource.js)
        else:
            logger.warn('Could not find resource: %s', resource.js)
            cooked_js += '\n/* Could not find resource: {0} */\n\n'.format(
                js_url
            )

    cooked_js += REQUIREJS_RESET_POSTFIX

    persistent_directory = getUtility(IResourceDirectory, name="persistent")
    if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory:
        persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME)
    container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]

    def _write_resource(resource_path, cooked_string):
        if not resource_path:
            return
        resource_path = resource_path.split('++plone++')[-1]
        resource_name, resource_filepath = resource_path.split('/', 1)
        if resource_name not in container:
            container.makeDirectory(resource_name)
        if not isinstance(cooked_string, six.binary_type):  # handle Error of OFS.Image  # noqa: E501
            cooked_string = cooked_string.encode('ascii', errors='ignore')
        try:
            folder = container[resource_name]
            fi = BytesIO(cooked_string)
            folder.writeFile(resource_filepath, fi)
            logger.info('Writing cooked resource: %s', resource_path)
        except NotFound:
            logger.warn('Error writing cooked resource: %s', resource_path)

    _write_resource(js_path, cooked_js)
    _write_resource(css_path, cooked_css)

    bundle.last_compilation = datetime.now()
    # refresh production meta bundles
    combine_bundles(context)

    # Disable CSRF protection on this request
    alsoProvides(request, IDisableCSRFProtection)
示例#7
0
def cookWhenChangingSettings(context, bundle=None):
    """When our settings are changed, re-cook the not compilable bundles
    """
    registry = getUtility(IRegistry)
    resources = registry.collectionOfInterface(IResourceRegistry,
                                               prefix="plone.resources",
                                               check=False)
    if bundle is None:
        # default to cooking legacy bundle
        bundles = registry.collectionOfInterface(IBundleRegistry,
                                                 prefix="plone.bundles",
                                                 check=False)
        if 'plone-legacy' in bundles:
            bundle = bundles['plone-legacy']
        else:
            bundle = bundles.setdefault('plone-legacy')
            bundle.resources = []

    if not bundle.resources:
        # you can have a bundle without any resources defined and it's just
        # shipped as a legacy compiled js file
        return

    js_path = bundle.jscompilation
    css_path = bundle.csscompilation

    if not js_path and not css_path:
        logger.warn(
            'No js_path or css_path found. We need a plone.resource '
            'based resource path in order to store the compiled JS and CSS.')
        return

    # Let's join all css and js
    css_compiler = Compiler(output_style='compressed')
    cooked_css = u''
    cooked_js = REQUIREJS_RESET_PREFIX
    siteUrl = getSite().absolute_url()
    request = getRequest()
    for package in bundle.resources or []:
        if package not in resources:
            continue
        resource = resources[package]

        if css_path:
            for css_resource in resource.css:
                css_url = siteUrl + '/' + css_resource
                response = subrequest(css_url)
                if response.status == 200:
                    logger.info('Cooking css %s', css_resource)
                    css = response.getBody()
                    if css_resource[-8:] != '.min.css':
                        css = css_compiler.compile_string(css)
                    cooked_css += u'\n/* Resource: {0} */\n{1}\n'.format(
                        css_resource, css)
                else:
                    cooked_css +=\
                        u'\n/* Could not find resource: {0} */\n\n'.format(
                            css_resource
                        )
                    logger.warn('Could not find resource: %s', css_resource)
        if not resource.js or not js_path:
            continue
        js_url = siteUrl + '/' + resource.js
        response = subrequest(js_url)
        if response.status == 200:
            js = response.getBody()
            try:
                logger.info('Cooking js %s', resource.js)
                cooked_js += '\n/* resource: {0} */\n{1}'.format(
                    resource.js, js if '.min.js' == resource.js[-7:] else
                    minify(js, mangle=False, mangle_toplevel=False))
            except SyntaxError:
                cooked_js +=\
                    '\n/* Resource (error cooking): {0} */\n{1}'.format(
                        resource.js,
                        js
                    )
                logger.warn('Error cooking resource: %s', resource.js)
        else:
            logger.warn('Could not find resource: %s', resource.js)
            cooked_js += '\n/* Could not find resource: {0} */\n\n'.format(
                js_url)

    cooked_js += REQUIREJS_RESET_POSTFIX

    persistent_directory = getUtility(IResourceDirectory, name="persistent")
    if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory:
        persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME)
    container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME]

    def _write_resource(resource_path, cooked_string):
        if not resource_path:
            return
        resource_path = resource_path.split('++plone++')[-1]
        resource_name, resource_filepath = resource_path.split('/', 1)
        if resource_name not in container:
            container.makeDirectory(resource_name)
        if not isinstance(cooked_string, str):  # handle Error of OFS.Image
            cooked_string = cooked_string.encode('ascii', errors='ignore')
        try:
            folder = container[resource_name]
            fi = StringIO(cooked_string)
            folder.writeFile(resource_filepath, fi)
            logger.info('Writing cooked resource: %s', resource_path)
        except NotFound:
            logger.warn('Error writing cooked resource: %s', resource_path)

    _write_resource(js_path, cooked_js)
    _write_resource(css_path, cooked_css)

    bundle.last_compilation = datetime.now()
    # refresh production meta bundles
    combine_bundles(context)

    # Disable CSRF protection on this request
    alsoProvides(request, IDisableCSRFProtection)