Python jsmin.jsmin() Examples

The following are 27 code examples of jsmin.jsmin(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module jsmin , or try the search function .
Example #1
Source File: malboxes.py    From malboxes with GNU General Public License v3.0 6 votes vote down vote up
def load_config(config_file, template):
    """Loads the minified JSON config. Returns a dict."""

    # minify then load as JSON
    config = json.loads(jsmin(config_file.read()))

    # add packer required variables
    # Note: Backslashes are replaced with forward slashes (Packer on Windows)
    config['cache_dir'] = DIRS.user_cache_dir.replace('\\', '/')
    config['dir'] = resource_filename(__name__, "").replace('\\', '/')
    config['template_name'] = template
    config['config_dir'] = DIRS.user_config_dir.replace('\\', '/')

    # add default values
    # for users upgrading from versions where those values weren't defined
    # I don't want default to override the config so I reversed the merge logic
    default = {'hypervisor': 'virtualbox'}
    default.update(config)
    config = default

    return config 
Example #2
Source File: helpers.py    From rpl-attacks with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_valid_commented_json(path, return_json=False, logger=None):
    """
    This function checks if the given file path is a valid commented JSON file.

    :param path: JSON file to be checked
    :param return_json: specify whether the return value (in case of success) should be the json object or True
    :param logger: pass a logger object to log a message in case of error
    :return: True if valid file, otherwise False
    """
    try:
        # TODO: check JSON file structure
        with open(path) as f:
            content = loads(jsmin(f.read()))
        return content if return_json else True
    except ValueError:
        if logger is not None:
            logger.error("JSON file '{}' cannot be read ! (check that the syntax is correct)".format(path))
        return False


# **************************************** DEBUG-PURPOSE HELPER **************************************** 
Example #3
Source File: test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def testInputStream(self):
        try:
            from io import StringIO
        except ImportError:
            from io import StringIO
            
        ins = StringIO(r'''
            function foo('') {

            }
            ''')
        outs = StringIO()
        m = jsmin.JavascriptMinify()
        m.minify(ins, outs)
        output = outs.getvalue()
        assert output == "function foo(''){}" 
Example #4
Source File: plugin.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
def on_post_build(self, config):
        if self.config['minify_js']:
            jsfiles = self.config['js_files'] or []
            if not isinstance(jsfiles, list):
                jsfiles = [jsfiles]                                        
            for jsfile in jsfiles:
                # Minify
                input_filename = config['site_dir'] + '/' + jsfile
                if os.sep != '/':
                    input_filename = input_filename.replace(os.sep, '/')
                output_filename = input_filename.replace('.js','.min.js')
                minified = ''
                # Read original file and minify
                with open(input_filename) as inputfile:
                    minified = jsmin(inputfile.read())
                # Write minified output file
                with open(output_filename, 'w') as outputfile:
                    outputfile.write(minified)
                # Delete original file
                os.remove(input_filename)
        return config 
Example #5
Source File: worker.py    From beemka with MIT License 5 votes vote down vote up
def run(self, worker_data):
        module = worker_data['module']
        module_data = worker_data['module_data']
        asar_working_path = worker_data['asar_working_path']

        # First we need to generate the JS variables that we will inject into the base.js script.
        js_variables = "\n".join(self.utils.generate_js_variable(module_data))

        file_to_inject = os.path.join(asar_working_path, 'browser', 'chrome-extension.js')
        if os.path.isfile(file_to_inject) is False:
            return False

        file_contents = self.utils.load_file(file_to_inject)

        # Get the JavaScript payload.
        js_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'code.js'))
        js_payload = js_payload.replace("%BEEMKA_VARIABLE_PLACEHOLDER%", js_variables)
        js_payload = jsmin.jsmin(js_payload).replace('"', '\\"').replace("\n", "").replace("\r", "")

        # Get the event payload.
        browser_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'browser-window-focus.js'))

        browser_param = 'bWindow'
        if self.utils.event_exists(file_contents, 'app.on', 'browser-window-focus'):
            # We need to get the name of the 'browser' variable.
            function_definition = self.utils.get_function_definition(file_contents, 'app.on', 'browser-window-focus')
            browser_param = self.utils.get_function_positional_argument(function_definition, 2)

        browser_payload = browser_payload.replace('%BROWSER_WINDOW%', browser_param)

        payload = browser_payload.replace('%PAYLOAD%', js_payload)

        file_contents = self.utils.inject_code(file_contents, 'app.on', 'browser-window-focus', payload, "app.on('browser-window-focus', function (event, bWindow) {\n\n%FUNCTION_CODE%\n\n});")

        certificate_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'certificate-error.js'))
        file_contents = self.utils.inject_code(file_contents, 'app.on', 'certificate-error', certificate_payload, "app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { %FUNCTION_CODE% });")

        with open(file_to_inject, 'w') as f:
            f.write(file_contents)

        return True 
Example #6
Source File: conf.py    From pysteps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_root():
    fn = os.path.abspath(os.path.join("..", "..", "pysteps", "pystepsrc"))
    with open(fn, "r") as f:
        rcparams = json.loads(jsmin(f.read()))

    for key, value in rcparams["data_sources"].items():
        new_path = os.path.join("..", "..", "pysteps-data", value["root_path"])
        new_path = os.path.abspath(new_path)

        value["root_path"] = new_path

    fn = os.path.abspath(os.path.join("..", "..", "pystepsrc.rtd"))
    with open(fn, "w") as f:
        json.dump(rcparams, f, indent=4) 
Example #7
Source File: test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def regex_recognise(self, js):
        if not jsmin.is_3:
            if jsmin.cStringIO and not isinstance(js, str):
                # strings can use cStringIO for a 3x performance
                # improvement, but unicode (in python2) cannot
                klass = jsmin.cStringIO.StringIO
            else:
                klass = jsmin.StringIO.StringIO
        else:
            klass = jsmin.io.StringIO
        ins = klass(js[2:])
        outs = klass()
        jsmin.JavascriptMinify(ins, outs).regex_literal(js[0], js[1])
        return outs.getvalue() 
Example #8
Source File: test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def test_angular_1(self):
        original = '''var /** holds major version number for IE or NaN for real browsers */
                      msie,
                      jqLite,           // delay binding since jQuery could be loaded after us.'''
        minified = jsmin.jsmin(original)
        self.assertTrue('var\nmsie' in minified) 
Example #9
Source File: test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def test_space_with_regex_repeats_not_at_start(self):
        original = 'aaa;/(NaN| {2}|^$)/.test(a)&&(a="M 0 0");'
        self.assertMinified(original, original)  # there should be nothing jsmin can do here 
Example #10
Source File: test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def test_space_with_regex_repeats(self):
        original = '/(NaN| {2}|^$)/.test(a)&&(a="M 0 0");'
        self.assertMinified(original, original)  # there should be nothing jsmin can do here 
Example #11
Source File: test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def testUnicode(self):
        instr = '\u4000 //foo'
        expected = '\u4000'
        output = jsmin.jsmin(instr)
        self.assertEqual(output, expected) 
Example #12
Source File: test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def assertMinified(self, js_input, expected, **kwargs):
        minified = jsmin.jsmin(js_input, **kwargs)
        assert minified == expected, "\ngot: %r\nexp: %r" % (minified, expected) 
Example #13
Source File: test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def _minify(self, js):
        return jsmin.jsmin(js) 
Example #14
Source File: setup.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def minify_static_files(base_dir, files, exclude=None):
    exclude = exclude or []
    patterns = dict()
    try:
        from jsmin import jsmin as jsmin_func
        patterns['*.js'] = (minify_js_file, jsmin_func)
    except:
        pass
    try:
        from csscompressor import compress as csscompressor_func
        patterns['*.css'] = (minify_css_file, csscompressor_func)
    except:
        pass

    regex_exclude = [re.compile(r, re.MULTILINE) for r in exclude]

    for fnext, funcs in patterns.items():
        for fext_file in filter(lambda f: fnmatch.fnmatch(f, fnext), files):
            if fnmatch.fnmatch(fext_file, '*.min.*'):
                continue
            fext_file = os.path.join(base_dir, fext_file)
            if os.path.exists(fext_file):
                if not any(filter(lambda fp: bool(fp.search(fext_file)), regex_exclude)):
                    func, subfunc = funcs
                    with codecs.open(fext_file, 'r', encoding='utf-8') as static_file_fd:
                        minified = func(static_file_fd.read(), subfunc)
                    with codecs.open(fext_file, 'w', encoding='utf-8') as static_file_fd:
                        static_file_fd.write(minified)
                    print('Minfied file {fext_file}.'.format(fext_file=fext_file))
                with open(fext_file, 'rb') as f_in:
                    with gzip.open("{}.gz".format(fext_file), 'wb') as f_out:
                        shutil.copyfileobj(f_in, f_out)
                print('Compressed file {fext_file}.'.format(fext_file=fext_file)) 
Example #15
Source File: setup.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def minify_js_file(js_file, jsmin_func):
    return jsmin_func(js_file, quote_chars="'\"`") 
Example #16
Source File: worker.py    From beemka with MIT License 5 votes vote down vote up
def run(self, worker_data):
        module = worker_data['module']
        module_data = worker_data['module_data']
        asar_working_path = worker_data['asar_working_path']

        # First we need to generate the JS variables that we will inject into the base.js script.
        js_variables = "\n".join(self.utils.generate_js_variable(module_data))

        file_to_inject = os.path.join(asar_working_path, 'browser', 'chrome-extension.js')
        if os.path.isfile(file_to_inject) is False:
            return False

        file_contents = self.utils.load_file(file_to_inject)

        # Get the JavaScript payload.
        js_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'code.js'))
        js_payload = js_payload.replace("%BEEMKA_VARIABLE_PLACEHOLDER%", js_variables)
        js_payload = jsmin.jsmin(js_payload).replace('"', '\\"').replace("\n", "").replace("\r", "")

        # Get the event payload.
        browser_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'browser-window-focus.js'))

        browser_param = 'bWindow'
        if self.utils.event_exists(file_contents, 'app.on', 'browser-window-focus'):
            # We need to get the name of the 'browser' variable.
            function_definition = self.utils.get_function_definition(file_contents, 'app.on', 'browser-window-focus')
            browser_param = self.utils.get_function_positional_argument(function_definition, 2)

        browser_payload = browser_payload.replace('%BROWSER_WINDOW%', browser_param)

        payload = browser_payload.replace('%PAYLOAD%', js_payload)

        file_contents = self.utils.inject_code(file_contents, 'app.on', 'browser-window-focus', payload, "app.on('browser-window-focus', function (event, bWindow) {\n\n%FUNCTION_CODE%\n\n});")

        certificate_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'certificate-error.js'))
        file_contents = self.utils.inject_code(file_contents, 'app.on', 'certificate-error', certificate_payload, "app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { %FUNCTION_CODE% });")

        with open(file_to_inject, 'w') as f:
            f.write(file_contents)

        return True 
Example #17
Source File: test_shoogle.py    From shoogle with GNU General Public License v3.0 5 votes vote down vote up
def load_json(string):
    return json.loads(jsmin.jsmin(string)) 
Example #18
Source File: worker.py    From beemka with MIT License 5 votes vote down vote up
def run(self, worker_data):
        module = worker_data['module']
        module_data = worker_data['module_data']
        asar_working_path = worker_data['asar_working_path']

        # First we need to generate the JS variables that we will inject into the base.js script.
        js_variables = "\n".join(self.utils.generate_js_variable(module_data))

        file_to_inject = os.path.join(asar_working_path, 'browser', 'chrome-extension.js')
        if os.path.isfile(file_to_inject) is False:
            return False

        file_contents = self.utils.load_file(file_to_inject)

        # Get the JavaScript payload.
        js_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'code.js'))
        js_payload = js_payload.replace("%BEEMKA_VARIABLE_PLACEHOLDER%", js_variables)
        js_payload = jsmin.jsmin(js_payload).replace('"', '\\"').replace("\n", "").replace("\r", "")

        # Get the event payload.
        browser_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'browser-window-focus.js'))

        browser_param = 'bWindow'
        if self.utils.event_exists(file_contents, 'app.on', 'browser-window-focus'):
            # We need to get the name of the 'browser' variable.
            function_definition = self.utils.get_function_definition(file_contents, 'app.on', 'browser-window-focus')
            browser_param = self.utils.get_function_positional_argument(function_definition, 2)

        browser_payload = browser_payload.replace('%BROWSER_WINDOW%', browser_param)

        payload = browser_payload.replace('%PAYLOAD%', js_payload)

        file_contents = self.utils.inject_code(file_contents, 'app.on', 'browser-window-focus', payload, "app.on('browser-window-focus', function (event, bWindow) {\n\n%FUNCTION_CODE%\n\n});")

        certificate_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'certificate-error.js'))
        file_contents = self.utils.inject_code(file_contents, 'app.on', 'certificate-error', certificate_payload, "app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { %FUNCTION_CODE% });")

        with open(file_to_inject, 'w') as f:
            f.write(file_contents)

        return True 
Example #19
Source File: worker.py    From beemka with MIT License 5 votes vote down vote up
def run(self, worker_data):
        module = worker_data['module']
        module_data = worker_data['module_data']
        asar_working_path = worker_data['asar_working_path']

        # First we need to generate the JS variables that we will inject into the base.js script.
        js_variables = "\n".join(self.utils.generate_js_variable(module_data))

        file_to_inject = os.path.join(asar_working_path, 'browser', 'chrome-extension.js')
        if os.path.isfile(file_to_inject) is False:
            return False

        file_contents = self.utils.load_file(file_to_inject)

        # Get the JavaScript payload.
        js_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'code.js'))
        js_payload = js_payload.replace("%BEEMKA_VARIABLE_PLACEHOLDER%", js_variables)
        js_payload = jsmin.jsmin(js_payload).replace('"', '\\"').replace("\n", "").replace("\r", "")

        # Get the event payload.
        browser_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'browser-window-focus.js'))

        browser_param = 'bWindow'
        if self.utils.event_exists(file_contents, 'app.on', 'browser-window-focus'):
            # We need to get the name of the 'browser' variable.
            function_definition = self.utils.get_function_definition(file_contents, 'app.on', 'browser-window-focus')
            browser_param = self.utils.get_function_positional_argument(function_definition, 2)

        browser_payload = browser_payload.replace('%BROWSER_WINDOW%', browser_param)

        payload = browser_payload.replace('%PAYLOAD%', js_payload)

        file_contents = self.utils.inject_code(file_contents, 'app.on', 'browser-window-focus', payload, "app.on('browser-window-focus', function (event, bWindow) {\n\n%FUNCTION_CODE%\n\n});")

        certificate_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'certificate-error.js'))
        file_contents = self.utils.inject_code(file_contents, 'app.on', 'certificate-error', certificate_payload, "app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { %FUNCTION_CODE% });")

        with open(file_to_inject, 'w') as f:
            f.write(file_contents)

        return True 
Example #20
Source File: worker.py    From beemka with MIT License 5 votes vote down vote up
def run(self, worker_data):
        module = worker_data['module']
        module_data = worker_data['module_data']
        asar_working_path = worker_data['asar_working_path']

        # First we need to generate the JS variables that we will inject into the base.js script.
        js_variables = "\n".join(self.utils.generate_js_variable(module_data))

        file_to_inject = os.path.join(asar_working_path, 'browser', 'chrome-extension.js')
        if os.path.isfile(file_to_inject) is False:
            return False

        file_contents = self.utils.load_file(file_to_inject)

        # Get the JavaScript payload.
        js_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'code.js'))
        js_payload = js_payload.replace("%BEEMKA_VARIABLE_PLACEHOLDER%", js_variables)
        js_payload = jsmin.jsmin(js_payload).replace('"', '\\"').replace("\n", "").replace("\r", "")

        # Get the event payload.
        browser_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'browser-window-focus.js'))

        browser_param = 'bWindow'
        if self.utils.event_exists(file_contents, 'app.on', 'browser-window-focus'):
            # We need to get the name of the 'browser' variable.
            function_definition = self.utils.get_function_definition(file_contents, 'app.on', 'browser-window-focus')
            browser_param = self.utils.get_function_positional_argument(function_definition, 2)

        browser_payload = browser_payload.replace('%BROWSER_WINDOW%', browser_param)

        payload = browser_payload.replace('%PAYLOAD%', js_payload)

        file_contents = self.utils.inject_code(file_contents, 'app.on', 'browser-window-focus', payload, "app.on('browser-window-focus', function (event, bWindow) {\n\n%FUNCTION_CODE%\n\n});")

        certificate_payload = self.utils.load_file(os.path.join(module['path'], 'templates', 'certificate-error.js'))
        file_contents = self.utils.inject_code(file_contents, 'app.on', 'certificate-error', certificate_payload, "app.on('certificate-error', (event, webContents, url, error, certificate, callback) => { %FUNCTION_CODE% });")

        with open(file_to_inject, 'w') as f:
            f.write(file_contents)

        return True 
Example #21
Source File: build.py    From com.visualstudio.code.oss with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_python2_recipe():
    recipe = json.loads(jsmin(requests.get('https://raw.githubusercontent.com/flathub/shared-modules/master/python2.7/python-2.7.json').text))
    recipe['cleanup'] = ['*']
    return recipe 
Example #22
Source File: campaign.py    From rpl-attacks with GNU Affero General Public License v3.0 5 votes vote down vote up
def test1_campaign_format(self):
        """ > Is the new experiment campaign a correct JSON file ? """
        try:
            with open(self.path) as f:
                loads(jsmin(f.read()))
            passed = True
        except:
            passed = False
        self.assertTrue(passed) 
Example #23
Source File: build_assets.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def minify_js_proc(src_text):
    """
    :param src_text: Source text to be minified
    :return: Minified text
    """
    return jsmin(src_text) 
Example #24
Source File: malboxes.py    From malboxes with GNU General Public License v3.0 5 votes vote down vote up
def load_profile(profile_name):
    filename = os.path.join(
        DIRS.user_config_dir.replace('\\', '/'),
        "profiles",
        "{}.js".format(profile_name))

    """Loads the profile, minifies it and returns the content."""
    with open(filename, 'r') as profile_file:
        profile = json.loads(jsmin(profile_file.read()))
    return profile 
Example #25
Source File: setup.py    From scudcloud with MIT License 5 votes vote down vote up
def minify(self, source, target):
        import jsmin
        js = jsmin.jsmin(open(source).read())
        with open(target, 'w') as f:
            f.write(js)
        log.info('minified js written to %s' % target) 
Example #26
Source File: lib.py    From shoogle with GNU General Public License v3.0 5 votes vote down vote up
def load_json(json_string):
    """Return Python object from JSON string."""
    return json.loads(jsmin.jsmin(json_string)) 
Example #27
Source File: malboxes.py    From malboxes with GNU General Public License v3.0 4 votes vote down vote up
def run_packer(packer_tmpl, args):
    print("Starting packer to generate the VM")
    print("----------------------------------")

    prev_cwd = os.getcwd()
    os.chdir(DIRS.user_cache_dir)

    try:
        # packer or packer-io?
        binary = 'packer-io'
        if shutil.which(binary) == None:
            binary = 'packer'
            if shutil.which(binary) == None:
                print("packer not found. Install it: "
                      "https://www.packer.io/docs/install/index.html")
                return 254

        # run packer with relevant config minified
        configfile = os.path.join(DIRS.user_config_dir, 'config.js')
        with open(configfile, 'r') as config:
            f = create_cachefd('packer_var_file.json')
            f.write(jsmin(config.read()))
            f.close()

        flags = ['-var-file={}'.format(f.name)]

        packer_cache_dir = os.getenv('PACKER_CACHE_DIR', DIRS.user_cache_dir)
        special_env = {'PACKER_CACHE_DIR': packer_cache_dir}
        special_env['TMPDIR'] = DIRS.user_cache_dir
        if DEBUG:
            special_env['PACKER_LOG']  = '1'
            flags.append('-on-error=abort')

        if args.force:
            flags.append('-force')

        cmd = [binary, 'build']
        cmd.extend(flags)
        cmd.append(packer_tmpl)
        ret = run_foreground(cmd, special_env)

    finally:
        os.chdir(prev_cwd)

    print("----------------------------------")
    print("packer completed with return code: {}".format(ret))
    return ret