예제 #1
0
def createBackgroundPage(params):
  template = getTemplate('background.html.tmpl', autoEscape=True)
  return template.render(
    backgroundScripts=params['metadata'].get(
      'general', 'backgroundScripts'
    ).split()
  ).encode('utf-8')
예제 #2
0
def addMissingFiles(params, files):
    templateData = {
        'hasChrome': False,
        'hasChromeRequires': False,
        'hasShutdownHandlers': False,
        'hasXMLHttpRequest': False,
        'hasVersionPref': False,
        'chromeWindows': [],
        'requires': {},
        'metadata': params['metadata'],
        'multicompartment': params['multicompartment'],
        'applications': dict((v, k) for k, v in KNOWN_APPS.iteritems()),
    }

    def checkScript(name):
        content = files[name]
        for match in re.finditer(r'(?:^|\s)require\(\s*"([\w\-]+)"\s*\)',
                                 content):
            templateData['requires'][match.group(1)] = True
            if name.startswith('chrome/content/'):
                templateData['hasChromeRequires'] = True
        if name.startswith('lib/') and re.search(r'\bXMLHttpRequest\b',
                                                 content):
            templateData['hasXMLHttpRequest'] = True
        if not '/' in name or name.startswith('lib/'):
            if re.search(r'(?:^|\s)onShutdown\.', content):
                templateData['hasShutdownHandlers'] = True

    for name, content in files.iteritems():
        if name == 'chrome.manifest':
            templateData['hasChrome'] = True
        elif name == 'defaults/prefs.json':
            templateData['hasVersionPref'] = 'currentVersion' in json.loads(
                content).get('defaults', {})
        elif name.endswith('.js'):
            checkScript(name)
        elif name.endswith('.xul'):
            match = re.search(
                r'<(?:window|dialog)\s[^>]*\bwindowtype="([^">]+)"', content)
            if match:
                templateData['chromeWindows'].append(match.group(1))

    while True:
        missing = []
        for module in templateData['requires']:
            moduleFile = 'lib/' + module + '.js'
            if not moduleFile in files:
                import buildtools
                path = os.path.join(buildtools.__path__[0], moduleFile)
                if os.path.exists(path):
                    missing.append((path, moduleFile))
        if not len(missing):
            break
        for path, moduleFile in missing:
            files.read(path, moduleFile)
            checkScript(moduleFile)

    template = getTemplate('bootstrap.js.tmpl')
    files['bootstrap.js'] = template.render(templateData).encode('utf-8')
예제 #3
0
def createManifest(params):
  global KNOWN_APPS, defaultLocale
  template = getTemplate('install.rdf.tmpl', autoEscape=True)
  templateData = dict(params)
  templateData['localeMetadata'] = readLocaleMetadata(params['baseDir'], params['locales'])
  initTranslators(templateData['localeMetadata'])
  templateData['KNOWN_APPS'] = KNOWN_APPS
  templateData['defaultLocale'] = defaultLocale
  return template.render(templateData).encode('utf-8')
def createManifest(params):
  global KNOWN_APPS, defaultLocale
  template = getTemplate('install.rdf.tmpl', autoEscape=True)
  templateData = dict(params)
  templateData['localeMetadata'] = readLocaleMetadata(params['baseDir'], params['locales'])
  initTranslators(templateData['localeMetadata'])
  templateData['KNOWN_APPS'] = KNOWN_APPS
  templateData['defaultLocale'] = defaultLocale
  return template.render(templateData).encode('utf-8')
예제 #5
0
def addMissingFiles(params, files):
  templateData = {
    'hasChrome': False,
    'hasChromeRequires': False,
    'hasShutdownHandlers': False,
    'hasXMLHttpRequest': False,
    'hasVersionPref': False,
    'chromeWindows': [],
    'requires': {},
    'metadata': params['metadata'],
    'multicompartment': params['multicompartment'],
    'applications': dict((v, k) for k, v in KNOWN_APPS.iteritems()),
  }

  def checkScript(name):
    content = files[name]
    for match in re.finditer(r'(?:^|\s)require\(\s*"([\w\-]+)"\s*\)', content):
      templateData['requires'][match.group(1)] = True
      if name.startswith('chrome/content/'):
        templateData['hasChromeRequires'] = True
    if name.startswith('lib/') and re.search(r'\bXMLHttpRequest\b', content):
      templateData['hasXMLHttpRequest'] = True
    if name == 'defaults/prefs.js':
      if re.search(r'\.currentVersion"', content):
        templateData['hasVersionPref'] = True
    if not '/' in name or name.startswith('lib/'):
      if re.search(r'(?:^|\s)onShutdown\.', content):
        templateData['hasShutdownHandlers'] = True

  for name, content in files.iteritems():
    if name == 'chrome.manifest':
      templateData['hasChrome'] = True
    elif name.endswith('.js'):
      checkScript(name)
    elif name.endswith('.xul'):
      match = re.search(r'<(?:window|dialog)\s[^>]*\bwindowtype="([^">]+)"', content)
      if match:
        templateData['chromeWindows'].append(match.group(1))

  while True:
    missing = []
    for module in templateData['requires']:
      moduleFile = 'lib/' + module + '.js'
      if not moduleFile in files:
        import buildtools
        path = os.path.join(buildtools.__path__[0], moduleFile)
        if os.path.exists(path):
          missing.append((path, moduleFile))
    if not len(missing):
      break
    for path, moduleFile in missing:
      files.read(path, moduleFile)
      checkScript(moduleFile)

  template = getTemplate('bootstrap.js.tmpl')
  files['bootstrap.js'] = template.render(templateData).encode('utf-8')
예제 #6
0
def convertJS(params, files):
    output_files = collections.OrderedDict()
    args = {}

    for item in params['metadata'].items('convert_js'):
        name, value = item
        filename, arg = re.search(r'^(.*?)(?:\[(.*)\])?$', name).groups()
        if arg is None:
            output_files[filename] = (value.split(), item.source)
        else:
            args.setdefault(filename, {})[arg] = value

    template = getTemplate('modules.js.tmpl')

    for filename, (input_files, origin) in output_files.iteritems():
        if '/' in filename and not files.isIncluded(filename):
            continue

        current_args = args.get(filename, {})
        current_args['autoload'] = [
            module for module in current_args.get('autoload', '').split(',')
            if module != ''
        ]

        base_dir = os.path.dirname(origin)
        modules = []

        for input_filename in input_files:
            module_name = os.path.splitext(os.path.basename(input_filename))[0]
            prefix = os.path.basename(os.path.dirname(input_filename))
            if prefix != 'lib':
                module_name = '{}_{}'.format(prefix, module_name)
            with open(os.path.join(base_dir, input_filename), 'r') as file:
                modules.append((module_name, file.read().decode('utf-8')))
            files.pop(input_filename, None)

        files[filename] = template.render(
            args=current_args,
            basename=params['metadata'].get('general', 'basename'),
            modules=modules,
            type=params['type'],
            version=params['metadata'].get('general',
                                           'version')).encode('utf-8')
예제 #7
0
def convertJS(params, files):
    output_files = collections.OrderedDict()
    args = {}

    for item in params['metadata'].items('convert_js'):
        name, value = item
        filename, arg = re.search(r'^(.*?)(?:\[(.*)\])?$', name).groups()
        if arg is None:
            output_files[filename] = (value.split(), item.source)
        else:
            args.setdefault(filename, {})[arg] = value

    template = getTemplate('modules.js.tmpl')

    for filename, (input_files, origin) in output_files.iteritems():
        if '/' in filename and not files.isIncluded(filename):
            continue

        current_args = args.get(filename, {})
        current_args['autoload'] = [module for module in
                                    current_args.get('autoload', '').split(',')
                                    if module != '']

        base_dir = os.path.dirname(origin)
        modules = []

        for input_filename in input_files:
            module_name = os.path.splitext(os.path.basename(input_filename))[0]
            prefix = os.path.basename(os.path.dirname(input_filename))
            if prefix != 'lib':
                module_name = '{}_{}'.format(prefix, module_name)
            with open(os.path.join(base_dir, input_filename), 'r') as file:
                modules.append((module_name, file.read().decode('utf-8')))
            files.pop(input_filename, None)

        files[filename] = template.render(
            args=current_args,
            modules=modules
        ).encode('utf-8')
예제 #8
0
def createManifest(params, files):
    template = getTemplate('Info.plist.tmpl', autoEscape=True)
    metadata = params['metadata']
    catalog = json.loads(files['_locales/%s/messages.json' % defaultLocale])

    def parse_section(section, depth=1):
        result = {}

        if not metadata.has_section(section):
            return result

        for opt in metadata.options(section):
            bits = opt.split('_', depth)
            key = bits.pop().replace('_', ' ').title()
            val = metadata.get(section, opt)

            try:
                val = int(val)
            except ValueError:
                try:
                    val = float(val)
                except ValueError:
                    pass

            reduce(lambda d, x: d.setdefault(x, {}), bits, result)[key] = val

        return result

    def get_optional(*args):
        try:
            return metadata.get(*args)
        except ConfigParser.Error:
            return None

    allowedDomains = set()
    allowAllDomains = False
    allowSecurePages = False

    for perm in metadata.get('general', 'permissions').split():
        if perm == '<all_urls>':
            allowAllDomains = True
            allowSecurePages = True
            continue

        url = urlparse(perm)

        if url.scheme == 'https':
            allowSecurePages = True
        elif url.scheme != 'http':
            continue

        if '*' in url.hostname:
            allowAllDomains = True
            continue

        allowedDomains.add(url.hostname)

    return template.render(
        basename=metadata.get('general', 'basename'),
        version=params['version'],
        releaseBuild=params['releaseBuild'],
        name=catalog['name']['message'],
        description=catalog['description']['message'],
        author=get_optional('general', 'author'),
        homepage=get_optional('general', 'homepage'),
        updateURL=get_optional('general', 'updateURL'),
        allowedDomains=allowedDomains,
        allowAllDomains=allowAllDomains,
        allowSecurePages=allowSecurePages,
        startScripts=(get_optional('contentScripts', 'document_start')
                      or '').split(),
        endScripts=(get_optional('contentScripts', 'document_end')
                    or '').split(),
        menus=parse_section('menus', 2),
        toolbarItems=parse_section('toolbar_items'),
        popovers=parse_section('popovers'),
        developerIdentifier=params.get('developerIdentifier')).encode('utf-8')
예제 #9
0
def createManifest(params):
  template = getTemplate('manifest.json.tmpl')
  templateData = dict(params)

  baseDir = templateData['baseDir']
  metadata = templateData['metadata']

  if metadata.has_option('general', 'pageAction') and metadata.get('general', 'pageAction') != '':
    if re.search(r'\s+', metadata.get('general', 'pageAction')):
      icon, popup = re.split(r'\s+', metadata.get('general', 'pageAction'), 1)
    else:
      icon, popup = (metadata.get('general', 'pageAction'), None)
    templateData['pageAction'] = {'icon': icon, 'popup': popup}

  if metadata.has_option('general', 'browserAction') and metadata.get('general', 'browserAction') != '':
    if re.search(r'\s+', metadata.get('general', 'browserAction')):
      icon, popup = re.split(r'\s+', metadata.get('general', 'browserAction'), 1)
    else:
      icon, popup = (metadata.get('general', 'browserAction'), None)
    templateData['browserAction'] = {'icon': icon, 'popup': popup}

  if metadata.has_option('general', 'icons'):
    icons = {}
    iconsDir = baseDir
    for dir in metadata.get('general', 'icons').split('/')[0:-1]:
      iconsDir = os.path.join(iconsDir, dir)

    prefix, suffix = metadata.get('general', 'icons').split('/')[-1].split('?', 1)
    for file in os.listdir(iconsDir):
      path = os.path.join(iconsDir, file)
      if os.path.isfile(path) and file.startswith(prefix) and file.endswith(suffix):
        size = file[len(prefix):-len(suffix)]
        if not re.search(r'\D', size):
          icons[size] = os.path.relpath(path, baseDir).replace('\\', '/')

    templateData['icons'] = icons

  if metadata.has_option('general', 'permissions'):
    templateData['permissions'] = re.split(r'\s+', metadata.get('general', 'permissions'))
    if params['experimentalAPI']:
      templateData['permissions'].append('experimental')

  if metadata.has_option('general', 'backgroundScripts'):
    templateData['backgroundScripts'] = re.split(r'\s+', metadata.get('general', 'backgroundScripts'))
    if params['devenv']:
      templateData['backgroundScripts'].append('devenvPoller__.js')

  if metadata.has_option('general', 'webAccessible') and metadata.get('general', 'webAccessible') != '':
    templateData['webAccessible'] = re.split(r'\s+', metadata.get('general', 'webAccessible'))

  if metadata.has_section('contentScripts'):
    contentScripts = []
    for run_at, scripts in metadata.items('contentScripts'):
      if scripts == '':
        continue
      contentScripts.append({
        'matches': ['http://*/*', 'https://*/*'],
        'js': re.split(r'\s+', scripts),
        'run_at': run_at,
        'all_frames': True,
      })
    templateData['contentScripts'] = contentScripts

  manifest = template.render(templateData)

  # Normalize JSON structure
  licenseComment = re.compile(r'/\*.*?\*/', re.S)
  data = json.loads(re.sub(licenseComment, '', manifest, 1))
  if '_dummy' in data:
    del data['_dummy']
  manifest = json.dumps(data, sort_keys=True, indent=2)

  return manifest.encode('utf-8')
예제 #10
0
def createPoller(params):
  template = getTemplate('chromeDevenvPoller__.js.tmpl')
  return template.render(params).encode('utf-8');
def createManifest(params, files):
  template = getTemplate('manifest.json.tmpl')
  templateData = dict(params)

  baseDir = templateData['baseDir']
  metadata = templateData['metadata']

  for opt in ('browserAction', 'pageAction'):
    if not metadata.has_option('general', opt):
      continue

    icons = metadata.get('general', opt).split()
    if not icons:
      continue

    if len(icons) == 1:
      # ... = icon.png
      icon, popup = icons[0], None
    elif len(icons) == 2:
      # ... = icon.png popup.html
      icon, popup = icons
    else:
      # ... = icon-19.png icon-38.png popup.html
      popup = icons.pop()
      icon = makeIcons(files, icons)

    templateData[opt] = {'icon': icon, 'popup': popup}

  if metadata.has_option('general', 'icons'):
    templateData['icons'] = makeIcons(files,
                                      metadata.get('general', 'icons').split())

  if metadata.has_option('general', 'permissions'):
    templateData['permissions'] = metadata.get('general', 'permissions').split()

  if metadata.has_option('general', 'optionalPermissions'):
    templateData['optionalPermissions'] = metadata.get(
      'general', 'optionalPermissions').split()

  if metadata.has_option('general', 'backgroundScripts'):
    templateData['backgroundScripts'] = metadata.get(
      'general', 'backgroundScripts').split()
    if params['devenv']:
      templateData['backgroundScripts'].append('devenvPoller__.js')

  if metadata.has_option('general', 'webAccessible') and metadata.get('general', 'webAccessible') != '':
    templateData['webAccessible'] = metadata.get('general',
                                                 'webAccessible').split()

  if metadata.has_section('contentScripts'):
    contentScripts = []
    for run_at, scripts in metadata.items('contentScripts'):
      if scripts == '':
        continue
      contentScripts.append({
        'matches': ['http://*/*', 'https://*/*'],
        'js': scripts.split(),
        'run_at': run_at,
        'all_frames': True,
        'match_about_blank': True,
      })
    templateData['contentScripts'] = contentScripts

  manifest = template.render(templateData)

  # Normalize JSON structure
  licenseComment = re.compile(r'/\*.*?\*/', re.S)
  data = json.loads(re.sub(licenseComment, '', manifest, 1))
  if '_dummy' in data:
    del data['_dummy']
  manifest = json.dumps(data, sort_keys=True, indent=2)

  return manifest.encode('utf-8')
예제 #12
0
def createInfoModule(params):
    if params['type'] == 'gecko-webext':
        template = getTemplate('geckoInfo.js.tmpl')
    else:
        template = getTemplate('chromeInfo.js.tmpl')
    return template.render(params).encode('utf-8')
예제 #13
0
def createManifest(params, files):
  template = getTemplate('Info.plist.tmpl', autoEscape=True)
  metadata = params['metadata']
  catalog = json.loads(files['_locales/%s/messages.json' % defaultLocale])

  def parse_section(section, depth=1):
    result = {}

    if not metadata.has_section(section):
      return result

    for opt in metadata.options(section):
      bits = opt.split('_', depth)
      key = bits.pop().replace('_', ' ').title()
      val = metadata.get(section, opt)

      try:
        val = int(val)
      except ValueError:
        try:
          val = float(val)
        except ValueError:
          pass

      reduce(lambda d, x: d.setdefault(x, {}), bits, result)[key] = val

    return result

  def get_optional(*args):
    try:
      return metadata.get(*args)
    except ConfigParser.Error:
      return None

  allowedDomains = set()
  allowAllDomains = False
  allowSecurePages = False

  for perm in metadata.get('general', 'permissions').split():
    if perm == '<all_urls>':
      allowAllDomains = True
      allowSecurePages = True
      continue

    url = urlparse(perm)

    if url.scheme == 'https':
      allowSecurePages = True
    elif url.scheme != 'http':
      continue

    if '*' in url.hostname:
      allowAllDomains = True
      continue

    allowedDomains.add(url.hostname)

  return template.render(
    basename=metadata.get('general', 'basename'),
    version=params['version'],
    releaseBuild=params['releaseBuild'],
    name=catalog['name']['message'],
    description=catalog['description_safari']['message'],
    author=get_optional('general', 'author'),
    homepage=get_optional('general', 'homepage'),
    updateURL=get_optional('general', 'updateURL'),
    allowedDomains=allowedDomains,
    allowAllDomains=allowAllDomains,
    allowSecurePages=allowSecurePages,
    startScripts=(get_optional('contentScripts', 'document_start') or '').split(),
    endScripts=(get_optional('contentScripts', 'document_end') or '').split(),
    menus=parse_section('menus', 2),
    toolbarItems=parse_section('toolbar_items'),
    popovers=parse_section('popovers'),
    developerIdentifier=params.get('developerIdentifier')
  ).encode('utf-8')
예제 #14
0
def createScriptPage(params, template_name, script_option):
    template = getTemplate(template_name, autoEscape=True)
    return template.render(
        basename=params['metadata'].get('general', 'basename'),
        scripts=params['metadata'].get(*script_option).split(),
    ).encode('utf-8')
예제 #15
0
def createManifest(params, files):
    template = getTemplate("Info.plist.tmpl", autoEscape=True)
    metadata = params["metadata"]
    catalog = json.loads(files["_locales/%s/messages.json" % defaultLocale])

    def parse_section(section, depth=1):
        result = {}

        if not metadata.has_section(section):
            return result

        for opt in metadata.options(section):
            bits = opt.split("_", depth)
            key = bits.pop().replace("_", " ").title()
            val = metadata.get(section, opt)

            try:
                val = int(val)
            except ValueError:
                try:
                    val = float(val)
                except ValueError:
                    pass

            reduce(lambda d, x: d.setdefault(x, {}), bits, result)[key] = val

        return result

    def get_optional(*args):
        try:
            return metadata.get(*args)
        except ConfigParser.Error:
            return None

    allowedDomains = set()
    allowAllDomains = False
    allowSecurePages = False

    for perm in metadata.get("general", "permissions").split():
        if perm == "<all_urls>":
            allowAllDomains = True
            allowSecurePages = True
            continue

        url = urlparse(perm)

        if url.scheme == "https":
            allowSecurePages = True
        elif url.scheme != "http":
            continue

        if "*" in url.hostname:
            allowAllDomains = True
            continue

        allowedDomains.add(url.hostname)

    return template.render(
        basename=metadata.get("general", "basename"),
        version=params["version"],
        releaseBuild=params["releaseBuild"],
        name=catalog["name"]["message"],
        description=catalog["description"]["message"],
        author=get_optional("general", "author"),
        homepage=get_optional("general", "homepage"),
        updateURL=get_optional("general", "updateURL"),
        allowedDomains=allowedDomains,
        allowAllDomains=allowAllDomains,
        allowSecurePages=allowSecurePages,
        startScripts=(get_optional("contentScripts", "document_start") or "").split(),
        endScripts=(get_optional("contentScripts", "document_end") or "").split(),
        menus=parse_section("menus", 2),
        toolbarItems=parse_section("toolbar_items"),
        popovers=parse_section("popovers"),
        developerIdentifier=params.get("developerIdentifier"),
    ).encode("utf-8")
예제 #16
0
def _get_template_for(filename):
    return packager.getTemplate('edge/{}.tmpl'.format(filename))
예제 #17
0
def create_bundles(params, files, bundle_tests):
    base_extension_path = params['baseDir']
    info_templates = {
        'chrome': 'chromeInfo.js.tmpl',
        'edge': 'edgeInfo.js.tmpl',
        'gecko': 'geckoInfo.js.tmpl',
    }
    aliases = {
        # To use our custom loader for the info module we must first set up an
        # alias to a file that exists.
        'info$': os.path.join(os.path.dirname(__file__), 'info.js'),
        # Prevent builtin Node.js modules from being used instead of our own
        # when the names clash. Once relative paths are used this won't be
        # necessary.
        'url$': 'url.js',
        'events$': 'events.js',
        'punycode$': 'punycode.js',
    }
    try:
        aliases.update(params['metadata'].items('module_alias'))
    except ConfigParser.NoSectionError:
        pass

    # Historically we didn't use relative paths when requiring modules, so in
    # order for webpack to know where to find them we need to pass in a list of
    # resolve paths. Going forward we should always use relative paths, once we
    # do that consistently this can be removed. See issues 5760, 5761 and 5762.
    resolve_paths = [os.path.join(base_extension_path, dir, 'lib')
                     for dir in ['', 'adblockpluscore', 'adblockplusui']]

    info_template = getTemplate(info_templates[params['type']])
    info_module = info_template.render(
        basename=params['metadata'].get('general', 'basename'),
        version=params['version'],
    ).encode('utf-8')

    configuration = {
        'bundles': [],
        'extension_path': base_extension_path,
        'info_module': info_module,
        'resolve_paths': resolve_paths,
        'aliases': aliases,
    }

    for item in params['metadata'].items('bundles'):
        name, value = item
        base_item_path = os.path.dirname(item.source)

        bundle_file = os.path.relpath(os.path.join(base_item_path, name),
                                      base_extension_path)
        entry_files = [os.path.join(base_item_path, module_path)
                       for module_path in value.split()]
        configuration['bundles'].append({
            'bundle_name': bundle_file,
            'entry_points': entry_files,
        })

    if bundle_tests:
        test_paths = os.path.join(base_extension_path, 'qunit', 'tests', '*.js')
        configuration['bundles'].append({
            'bundle_name': 'qunit/tests.js',
            'entry_points': glob.glob(test_paths),
        })

    cmd = ['node', os.path.join(os.path.dirname(__file__), 'webpack_runner.js')]
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                               stdin=subprocess.PIPE)
    output = process.communicate(input=toJson(configuration))[0]
    if process.returncode != 0:
        raise subprocess.CalledProcessError(process.returncode, cmd=cmd)
    output = json.loads(output)

    # Clear the mapping for any files included in a bundle, to avoid them being
    # duplicated in the build.
    for to_ignore in output['included']:
        files.pop(to_ignore, None)

    for bundle in output['files']:
        files[bundle] = output['files'][bundle].encode('utf-8')
예제 #18
0
def createInfoModule(params):
    if params['type'] == 'gecko-webext':
        template = getTemplate('geckoInfo.js.tmpl')
    else:
        template = getTemplate('chromeInfo.js.tmpl')
    return template.render(params).encode('utf-8')
예제 #19
0
def createInfoModule(params):
    template = getTemplate('safariInfo.js.tmpl')
    return template.render(params).encode('utf-8')
예제 #20
0
def create_bundles(params, files, bundle_tests):
    base_extension_path = params['baseDir']
    info_templates = {
        'chrome': 'chromeInfo.js.tmpl',
        'edge': 'edgeInfo.js.tmpl',
        'gecko': 'geckoInfo.js.tmpl',
    }
    aliases = {
        # To use our custom loader for the info module we must first set up an
        # alias to a file that exists.
        'info$': os.path.join(os.path.dirname(__file__), 'info.js'),
        # Prevent builtin Node.js modules from being used instead of our own
        # when the names clash. Once relative paths are used this won't be
        # necessary.
        'url$': 'url.js',
        'events$': 'events.js',
        'punycode$': 'punycode.js',
    }
    try:
        aliases.update(params['metadata'].items('module_alias'))
    except ConfigParser.NoSectionError:
        pass

    # Historically we didn't use relative paths when requiring modules, so in
    # order for webpack to know where to find them we need to pass in a list of
    # resolve paths. Going forward we should always use relative paths, once we
    # do that consistently this can be removed. See issues 5760, 5761 and 5762.
    resolve_paths = [
        os.path.join(base_extension_path, dir, 'lib')
        for dir in ['', 'adblockpluscore', 'bladeui']
    ]

    info_template = getTemplate(info_templates[params['type']])
    info_module = info_template.render(
        basename=params['metadata'].get('general', 'basename'),
        version=params['version'],
    ).encode('utf-8')

    configuration = {
        'bundles': [],
        'extension_path': base_extension_path,
        'info_module': info_module,
        'resolve_paths': resolve_paths,
        'aliases': aliases,
    }

    for item in params['metadata'].items('bundles'):
        name, value = item
        base_item_path = os.path.dirname(item.source)

        bundle_file = os.path.relpath(os.path.join(base_item_path, name),
                                      base_extension_path)
        entry_files = [
            os.path.join(base_item_path, module_path)
            for module_path in value.split()
        ]
        configuration['bundles'].append({
            'bundle_name': bundle_file,
            'entry_points': entry_files,
        })

    if bundle_tests:
        qunit_path = os.path.join(base_extension_path, 'qunit')
        qunit_files = ([os.path.join(qunit_path, 'common.js')] +
                       glob.glob(os.path.join(qunit_path, 'tests', '*.js')))
        configuration['bundles'].append({
            'bundle_name': 'qunit/tests.js',
            'entry_points': qunit_files,
        })

    cmd = [
        'node',
        os.path.join(os.path.dirname(__file__), 'webpack_runner.js')
    ]
    process = subprocess.Popen(cmd,
                               stdout=subprocess.PIPE,
                               stdin=subprocess.PIPE)
    output = process.communicate(input=toJson(configuration))[0]
    if process.returncode != 0:
        raise subprocess.CalledProcessError(process.returncode, cmd=cmd)
    output = json.loads(output)

    # Clear the mapping for any files included in a bundle, to avoid them being
    # duplicated in the build.
    for to_ignore in output['included']:
        files.pop(to_ignore, None)

    for bundle in output['files']:
        files[bundle] = output['files'][bundle].encode('utf-8')
예제 #21
0
def createBackgroundPage(params):
    template = getTemplate('background.html.tmpl', autoEscape=True)
    return template.render(backgroundScripts=params['metadata'].get(
        'general', 'backgroundScripts').split()).encode('utf-8')
예제 #22
0
def createManifest(params, files):
    template = getTemplate('manifest.json.tmpl')
    templateData = dict(params)

    baseDir = templateData['baseDir']
    metadata = templateData['metadata']

    for opt in ('browserAction', 'pageAction'):
        if not metadata.has_option('general', opt):
            continue

        icons = metadata.get('general', opt).split()
        if not icons:
            continue

        if len(icons) == 1:
            # ... = icon.png
            icon, popup = icons[0], None
        elif icons[-1].endswith('.html'):
            if len(icons) == 2:
                # ... = icon.png popup.html
                icon, popup = icons
            else:
                # ... = icon-19.png icon-38.png popup.html
                popup = icons.pop()
                icon = makeIcons(files, icons)
        else:
            # ... = icon-16.png icon-32.png icon-48.png
            icon = makeIcons(files, icons)
            popup = None

        templateData[opt] = {'icon': icon, 'popup': popup}

    if metadata.has_option('general', 'icons'):
        templateData['icons'] = makeIcons(
            files,
            metadata.get('general', 'icons').split())

    if metadata.has_option('general', 'backgroundScripts'):
        templateData['backgroundScripts'] = metadata.get(
            'general', 'backgroundScripts').split()
        if params['devenv']:
            templateData['backgroundScripts'].append('devenvPoller__.js')

    if metadata.has_section('contentScripts'):
        contentScripts = []
        for run_at, scripts in metadata.items('contentScripts'):
            if scripts == '':
                continue
            contentScripts.append({
                'matches': ['http://*/*', 'https://*/*'],
                'js': scripts.split(),
                'run_at': run_at,
                'all_frames': False,
                'match_about_blank': True,
            })
        templateData['contentScripts'] = contentScripts
    if params['type'] == 'gecko':
        templateData['app_id'] = get_app_id(params['releaseBuild'], metadata)

    manifest = template.render(templateData)

    # Normalize JSON structure
    licenseComment = re.compile(r'/\*.*?\*/', re.S)
    data = json.loads(re.sub(licenseComment, '', manifest, 1))
    if '_dummy' in data:
        del data['_dummy']

    metadata.serialize_section_if_present('manifest', data)
    manifest = json.dumps(data, sort_keys=True, indent=2)

    return manifest.encode('utf-8')
def createScriptPage(params, template_name, script_option):
  template = getTemplate(template_name, autoEscape=True)
  return template.render(
    basename=params['metadata'].get('general', 'basename'),
    scripts=params['metadata'].get(*script_option).split()
  ).encode('utf-8')
예제 #24
0
def createInfoModule(params):
  template = getTemplate('safariInfo.js.tmpl')
  return template.render(params).encode('utf-8')
예제 #25
0
def _get_template_for(filename):
    return packager.getTemplate('edge/{}.tmpl'.format(filename))