Example #1
0
    def test_base(self):
        # simply just test the basic functions... while the top level
        # readme covers this, just ensure this covers it
        from calmjs.parse import es5

        src = u'var a;'
        self.assertTrue(isinstance(es5(src), asttypes.Node))
        self.assertEqual(es5.pretty_print(src).strip(), src)
        self.assertEqual(es5.minify_print(src), src)
        self.assertEqual(es5.minify_print(src, True, True), src)
Example #2
0
def main():
    lib_name = os.path.basename(os.path.abspath(os.path.dirname(__file__)))
    folder = os.path.abspath(os.path.dirname(__file__))
    destination = os.path.join(folder, "build", lib_name + ".js")

    src_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                              "src"))
    files = list(Path(src_folder).rglob('*.js'))
    filelist = []
    for file in files:
        path = str(file)
        if not os.path.isdir(path):
            filelist.append(path)

    filelist = sorted(filelist)

    with open(os.path.join(folder, "shell.js"), "r") as f:
        shell_text = f.read()

    shell_text = shell_text.replace("//LIBNAME", lib_name)

    for file in filelist:
        if not os.path.isfile(destination) or os.path.getctime(
                file) > os.path.getctime(destination):
            output = []
            imports = {}
            for file in filelist:
                js = get_javascript(file)
                output.append(js)

            text = shell_text.replace("//CONTENTS", "\n".join(output))

            with open(destination, "w") as f:
                f.write(text)

            mini = es5.minify_print(text, obfuscate=True)

            with open(os.path.join(folder, "build", lib_name + ".min.js"),
                      "w") as f:
                f.write(mini)

            break
Example #3
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)
Example #4
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)