Exemplo n.º 1
0
def main(args):
    pp = Preprocessor()
    optparser = pp.getCommandLineParser()
    optparser.add_option('--nss-file', action='append',
                         type='string', dest='nss_files', default=[],
                         help='Specify a .def file that should have NSS\'s processing rules applied to it')
    options, deffiles = optparser.parse_args(args)

    symbols = set()
    for f in options.nss_files:
        symbols |= extract_symbols(nss_preprocess_file(f))
    for f in deffiles:
        # Start each deffile off with a clean slate.
        defpp = pp.clone()
        symbols |= extract_symbols(preprocess_file(defpp, f))

    script = """{
global:
  %s
local:
  *;
};
"""
    with FileAvoidWrite(options.output) as f:
        f.write(script % '\n  '.join("%s;" % s for s in sorted(symbols)))
Exemplo n.º 2
0
class JarMaker(object):
    '''JarMaker reads jar.mn files and process those into jar files or
      flat directories, along with chrome.manifest files.
      '''

    def __init__(self, outputFormat='flat', useJarfileManifest=True,
        useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.l10nmerge = None
        self.relativesrcdir = None
        self.rootManifestAppId = None
        self._seen_output = set()

    def getCommandLineParser(self):
        '''Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        '''

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option('-f', type='choice', default='jar',
            choices=('jar', 'flat', 'symlink'),
            help='fileformat used for output',
            metavar='[jar, flat, symlink]',
            )
        p.add_option('-v', action='store_true', dest='verbose',
                     help='verbose output')
        p.add_option('-q', action='store_false', dest='verbose',
                     help='verbose output')
        p.add_option('-e', action='store_true',
                     help='create chrome.manifest instead of jarfile.manifest'
                     )
        p.add_option('-s', type='string', action='append', default=[],
                     help='source directory')
        p.add_option('-t', type='string', help='top source directory')
        p.add_option('-c', '--l10n-src', type='string', action='append'
                     , help='localization directory')
        p.add_option('--l10n-base', type='string', action='store',
                     help='base directory to be used for localization (requires relativesrcdir)'
                     )
        p.add_option('--locale-mergedir', type='string', action='store'
                     ,
                     help='base directory to be used for l10n-merge (requires l10n-base and relativesrcdir)'
                     )
        p.add_option('--relativesrcdir', type='string',
                     help='relativesrcdir to be used for localization')
        p.add_option('-d', type='string', help='base directory')
        p.add_option('--root-manifest-entry-appid', type='string',
                     help='add an app id specific root chrome manifest entry.'
                     )
        return p

    def finalizeJar(self, jardir, jarbase, jarname, chromebasepath, register, doZip=True):
        '''Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        '''

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(jardir, jarbase, 'chrome.manifest')

        if self.useJarfileManifest:
            self.updateManifest(os.path.join(jardir, jarbase,
                                             jarname + '.manifest'),
                                chromebasepath.format(''), register)
            if jarname != 'chrome':
                addEntriesToListFile(chromeManifest,
                                     ['manifest {0}.manifest'.format(jarname)])
        if self.useChromeManifest:
            chromebase = os.path.dirname(jarname) + '/'
            self.updateManifest(chromeManifest,
                                chromebasepath.format(chromebase), register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = \
                os.path.join(os.path.normpath(os.path.dirname(chromeManifest)),
                             '..', 'chrome.manifest')
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = \
                os.path.basename(os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s"
                          % (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(rootChromeManifest,
                                 ['manifest %s/chrome.manifest application=%s'
                                  % (chromeDir,
                                 self.rootManifestAppId)])

    def updateManifest(self, manifestPath, chromebasepath, register):
        '''updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        '''
        myregister = dict.fromkeys(map(lambda s: s.replace('%',
            chromebasepath), register))
        addEntriesToListFile(manifestPath, myregister.iterkeys())

    def makeJar(self, infile, jardir):
        '''makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        '''

        # making paths absolute, guess srcdir if file and add to sourcedirs
        _normpath = lambda p: os.path.normpath(os.path.abspath(p))
        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = \
                self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, basestring):
            logging.info('processing ' + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = JarManifestParser()
        pp.do_include(infile)

        for info in pp.out:
            self.processJarSection(info, jardir)

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == 'locales':
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales dirs, merge, l10nbase, en-US
        if self.l10nmerge:
            locdirs.append(os.path.join(self.l10nmerge, l10nrelsrcdir))
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        if self.l10nmerge or not self.l10nbase:
            # add en-US if we merge, or if it's not l10n
            locdirs.append(os.path.join(self.topsourcedir,
                           relativesrcdir, 'en-US'))
        return locdirs

    def processJarSection(self, jarinfo, jardir):
        '''Internal method called by makeJar to actually process a section
        of a jar.mn file.
        '''

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = '{0}' + os.path.basename(jarinfo.name)
        if self.outputFormat == 'jar':
            chromebasepath = 'jar:' + chromebasepath + '.jar!'
        chromebasepath += '/'

        jarfile = os.path.join(jardir, jarinfo.base, jarinfo.name)
        jf = None
        if self.outputFormat == 'jar':
            # jar
            jarfilepath = jarfile + '.jar'
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError, error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, 'a', lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else:
Exemplo n.º 3
0
class JarMaker(object):
    '''JarMaker reads jar.mn files and process those into jar files or
      flat directories, along with chrome.manifest files.
      '''

    def __init__(self, outputFormat='flat', useJarfileManifest=True,
                 useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.l10nmerge = None
        self.relativesrcdir = None
        self.rootManifestAppId = None
        self._seen_output = set()

    def getCommandLineParser(self):
        '''Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        '''

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option('-f', type='choice', default='jar',
                     choices=('jar', 'flat', 'symlink'),
                     help='fileformat used for output',
                     metavar='[jar, flat, symlink]',
                     )
        p.add_option('-v', action='store_true', dest='verbose',
                     help='verbose output')
        p.add_option('-q', action='store_false', dest='verbose',
                     help='verbose output')
        p.add_option('-e', action='store_true',
                     help='create chrome.manifest instead of jarfile.manifest'
                     )
        p.add_option('-s', type='string', action='append', default=[],
                     help='source directory')
        p.add_option('-t', type='string', help='top source directory')
        p.add_option('-c', '--l10n-src', type='string',
                     action='append', help='localization directory')
        p.add_option('--l10n-base', type='string', action='store',
                     help='base directory to be used for localization (requires relativesrcdir)'
                     )
        p.add_option('--locale-mergedir', type='string', action='store',
                     help='base directory to be used for l10n-merge '
                     '(requires l10n-base and relativesrcdir)'
                     )
        p.add_option('--relativesrcdir', type='string',
                     help='relativesrcdir to be used for localization')
        p.add_option('-d', type='string', help='base directory')
        p.add_option('--root-manifest-entry-appid', type='string',
                     help='add an app id specific root chrome manifest entry.'
                     )
        return p

    def finalizeJar(self, jardir, jarbase, jarname, chromebasepath, register, doZip=True):
        '''Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        '''

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(jardir, jarbase, 'chrome.manifest')

        if self.useJarfileManifest:
            self.updateManifest(os.path.join(jardir, jarbase,
                                             jarname + '.manifest'),
                                chromebasepath.format(''), register)
            if jarname != 'chrome':
                addEntriesToListFile(chromeManifest,
                                     ['manifest {0}.manifest'.format(jarname)])
        if self.useChromeManifest:
            chromebase = os.path.dirname(jarname) + '/'
            self.updateManifest(chromeManifest,
                                chromebasepath.format(chromebase), register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = \
                os.path.join(os.path.normpath(os.path.dirname(chromeManifest)),
                             '..', 'chrome.manifest')
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = \
                os.path.basename(os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s"
                         % (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(rootChromeManifest,
                                 ['manifest %s/chrome.manifest application=%s'
                                  % (chromeDir,
                                     self.rootManifestAppId)])

    def updateManifest(self, manifestPath, chromebasepath, register):
        '''updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        '''
        myregister = dict.fromkeys(map(lambda s: s.replace('%',
                                                           chromebasepath), register))
        addEntriesToListFile(manifestPath, six.iterkeys(myregister))

    def makeJar(self, infile, jardir):
        '''makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        '''

        # making paths absolute, guess srcdir if file and add to sourcedirs
        def _normpath(p): return os.path.normpath(os.path.abspath(p))
        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = \
                self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, basestring):
            logging.info('processing ' + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = JarManifestParser()
        pp.do_include(infile)

        for info in pp.out:
            self.processJarSection(info, jardir)

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == 'locales':
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales dirs, merge, l10nbase, en-US
        if self.l10nmerge:
            locdirs.append(os.path.join(self.l10nmerge, l10nrelsrcdir))
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        if self.l10nmerge or not self.l10nbase:
            # add en-US if we merge, or if it's not l10n
            locdirs.append(os.path.join(self.topsourcedir,
                                        relativesrcdir, 'en-US'))
        return locdirs

    def processJarSection(self, jarinfo, jardir):
        '''Internal method called by makeJar to actually process a section
        of a jar.mn file.
        '''

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = '{0}' + os.path.basename(jarinfo.name)
        if self.outputFormat == 'jar':
            chromebasepath = 'jar:' + chromebasepath + '.jar!'
        chromebasepath += '/'

        jarfile = os.path.join(jardir, jarinfo.base, jarinfo.name)
        jf = None
        if self.outputFormat == 'jar':
            # jar
            jarfilepath = jarfile + '.jar'
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError as error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, 'a', lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else:
            outHelper = getattr(self, 'OutputHelper_'
                                + self.outputFormat)(jarfile)

        if jarinfo.relativesrcdir:
            self.localedirs = self.generateLocaleDirs(jarinfo.relativesrcdir)

        for e in jarinfo.entries:
            self._processEntryLine(e, outHelper, jf)

        self.finalizeJar(jardir, jarinfo.base, jarinfo.name, chromebasepath,
                         jarinfo.chrome_manifests)
        if jf is not None:
            jf.close()

    def _processEntryLine(self, e, outHelper, jf):
        out = e.output
        src = e.source

        # pick the right sourcedir -- l10n, topsrc or src

        if e.is_locale:
            # If the file is a Fluent l10n resource, we want to skip the
            # 'en-US' fallbacking.
            #
            # To achieve that, we're testing if we have more than one localedir,
            # and if the last of those has 'en-US' in it.
            # If that's the case, we're removing the last one.
            if (e.source.endswith('.ftl') and
                len(self.localedirs) > 1 and
                'en-US' in self.localedirs[-1]):
                src_base = self.localedirs[:-1]
            else:
                src_base = self.localedirs
        elif src.startswith('/'):
            # path/in/jar/file_name.xul     (/path/in/sourcetree/file_name.xul)
            # refers to a path relative to topsourcedir, use that as base
            # and strip the leading '/'
            src_base = [self.topsourcedir]
            src = src[1:]
        else:
            # use srcdirs and the objdir (current working dir) for relative paths
            src_base = self.sourcedirs + [os.getcwd()]

        if '*' in src:
            def _prefix(s):
                for p in s.split('/'):
                    if '*' not in p:
                        yield p + '/'
            prefix = ''.join(_prefix(src))
            emitted = set()
            for _srcdir in src_base:
                finder = FileFinder(_srcdir)
                for path, _ in finder.find(src):
                    # If the path was already seen in one of the other source
                    # directories, skip it. That matches the non-wildcard case
                    # below, where we pick the first existing file.
                    reduced_path = path[len(prefix):]
                    if reduced_path in emitted:
                        continue
                    emitted.add(reduced_path)
                    e = JarManifestEntry(
                        mozpath.join(out, reduced_path),
                        path,
                        is_locale=e.is_locale,
                        preprocess=e.preprocess,
                    )
                    self._processEntryLine(e, outHelper, jf)
            return

        # check if the source file exists
        realsrc = None
        for _srcdir in src_base:
            if os.path.isfile(os.path.join(_srcdir, src)):
                realsrc = os.path.join(_srcdir, src)
                break
        if realsrc is None:
            if jf is not None:
                jf.close()
            raise RuntimeError('File "{0}" not found in {1}'.format(src,
                                                                    ', '.join(src_base)))

        if out in self._seen_output:
            raise RuntimeError('%s already added' % out)
        self._seen_output.add(out)

        if e.preprocess:
            outf = outHelper.getOutput(out)
            inf = open(realsrc)
            pp = self.pp.clone()
            if src[-4:] == '.css':
                pp.setMarker('%')
            pp.out = outf
            pp.do_include(inf)
            pp.failUnused(realsrc)
            outf.close()
            inf.close()
            return

        # copy or symlink if newer

        if getModTime(realsrc) > outHelper.getDestModTime(e.output):
            if self.outputFormat == 'symlink':
                outHelper.symlink(realsrc, out)
                return
            outf = outHelper.getOutput(out)

            # open in binary mode, this can be images etc

            inf = open(realsrc, 'rb')
            outf.write(inf.read())
            outf.close()
            inf.close()

    class OutputHelper_jar(object):
        '''Provide getDestModTime and getOutput for a given jarfile.'''

        def __init__(self, jarfile):
            self.jarfile = jarfile

        def getDestModTime(self, aPath):
            try:
                info = self.jarfile.getinfo(aPath)
                return info.date_time
            except Exception:
                return 0

        def getOutput(self, name):
            return ZipEntry(name, self.jarfile)

    class OutputHelper_flat(object):
        '''Provide getDestModTime and getOutput for a given flat
        output directory. The helper method ensureDirFor is used by
        the symlink subclass.
        '''

        def __init__(self, basepath):
            self.basepath = basepath

        def getDestModTime(self, aPath):
            return getModTime(os.path.join(self.basepath, aPath))

        def getOutput(self, name):
            out = self.ensureDirFor(name)

            # remove previous link or file
            try:
                os.remove(out)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
            return open(out, 'wb')

        def ensureDirFor(self, name):
            out = os.path.join(self.basepath, name)
            outdir = os.path.dirname(out)
            if not os.path.isdir(outdir):
                try:
                    os.makedirs(outdir)
                except OSError as error:
                    if error.errno != errno.EEXIST:
                        raise
            return out

    class OutputHelper_symlink(OutputHelper_flat):
        '''Subclass of OutputHelper_flat that provides a helper for
        creating a symlink including creating the parent directories.
        '''

        def symlink(self, src, dest):
            out = self.ensureDirFor(dest)

            # remove previous link or file
            try:
                os.remove(out)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
            if sys.platform != 'win32':
                os.symlink(src, out)
            else:
                # On Win32, use ctypes to create a hardlink
                rv = CreateHardLink(ensure_bytes(out), ensure_bytes(src), None)
                if rv == 0:
                    raise WinError()
Exemplo n.º 4
0
class JarMaker(object):
    '''JarMaker reads jar.mn files and process those into jar files or
      flat directories, along with chrome.manifest files.
      '''

    ignore = re.compile('\s*(\#.*)?$')
    jarline = re.compile('(?:(?P<jarfile>[\w\d.\-\_\\\/{}]+).jar\:)|(?:\s*(\#.*)?)\s*$')
    relsrcline = re.compile('relativesrcdir\s+(?P<relativesrcdir>.+?):')
    regline = re.compile('\%\s+(.*)$')
    entryre = '(?P<optPreprocess>\*)?(?P<optOverwrite>\+?)\s+'
    entryline = re.compile(entryre
                           + '(?P<output>[\w\d.\-\_\\\/\+\@]+)\s*(\((?P<locale>\%?)(?P<source>[\w\d.\-\_\\\/\@\*]+)\))?\s*$'
                           )

    def __init__(self, outputFormat='flat', useJarfileManifest=True,
        useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.l10nmerge = None
        self.relativesrcdir = None
        self.rootManifestAppId = None

    def getCommandLineParser(self):
        '''Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        '''

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option('-f', type='choice', default='jar',
            choices=('jar', 'flat', 'symlink'),
            help='fileformat used for output',
            metavar='[jar, flat, symlink]',
            )
        p.add_option('-v', action='store_true', dest='verbose',
                     help='verbose output')
        p.add_option('-q', action='store_false', dest='verbose',
                     help='verbose output')
        p.add_option('-e', action='store_true',
                     help='create chrome.manifest instead of jarfile.manifest'
                     )
        p.add_option('-s', type='string', action='append', default=[],
                     help='source directory')
        p.add_option('-t', type='string', help='top source directory')
        p.add_option('-c', '--l10n-src', type='string', action='append'
                     , help='localization directory')
        p.add_option('--l10n-base', type='string', action='store',
                     help='base directory to be used for localization (requires relativesrcdir)'
                     )
        p.add_option('--locale-mergedir', type='string', action='store'
                     ,
                     help='base directory to be used for l10n-merge (requires l10n-base and relativesrcdir)'
                     )
        p.add_option('--relativesrcdir', type='string',
                     help='relativesrcdir to be used for localization')
        p.add_option('-j', type='string', help='jarfile directory')
        p.add_option('--root-manifest-entry-appid', type='string',
                     help='add an app id specific root chrome manifest entry.'
                     )
        return p

    def processIncludes(self, includes):
        '''Process given includes with the inner PreProcessor.

        Only use this for #defines, the includes shouldn't generate
        content.
        '''

        self.pp.out = StringIO()
        for inc in includes:
            self.pp.do_include(inc)
        includesvalue = self.pp.out.getvalue()
        if includesvalue:
            logging.info('WARNING: Includes produce non-empty output')
        self.pp.out = None

    def finalizeJar(self, jarPath, chromebasepath, register, doZip=True):
        '''Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        '''

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(os.path.dirname(jarPath), '..',
                'chrome.manifest')

        if self.useJarfileManifest:
            self.updateManifest(jarPath + '.manifest',
                                chromebasepath.format(''), register)
            addEntriesToListFile(chromeManifest,
                                 ['manifest chrome/{0}.manifest'.format(os.path.basename(jarPath))])
        if self.useChromeManifest:
            self.updateManifest(chromeManifest,
                                chromebasepath.format('chrome/'),
                                register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = \
                os.path.join(os.path.normpath(os.path.dirname(chromeManifest)),
                             '..', 'chrome.manifest')
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = \
                os.path.basename(os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s"
                          % (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(rootChromeManifest,
                                 ['manifest %s/chrome.manifest application=%s'
                                  % (chromeDir,
                                 self.rootManifestAppId)])

    def updateManifest(self, manifestPath, chromebasepath, register):
        '''updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        '''

        ensureParentDir(manifestPath)
        lock = lock_file(manifestPath + '.lck')
        try:
            myregister = dict.fromkeys(map(lambda s: s.replace('%',
                    chromebasepath), register.iterkeys()))
            manifestExists = os.path.isfile(manifestPath)
            mode = manifestExists and 'r+b' or 'wb'
            mf = open(manifestPath, mode)
            if manifestExists:
                # import previous content into hash, ignoring empty ones and comments
                imf = re.compile('(#.*)?$')
                for l in re.split('[\r\n]+', mf.read()):
                    if imf.match(l):
                        continue
                    myregister[l] = None
                mf.seek(0)
            for k in sorted(myregister.iterkeys()):
                mf.write(k + os.linesep)
            mf.close()
        finally:
            lock = None

    def makeJar(self, infile, jardir):
        '''makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        '''

        # making paths absolute, guess srcdir if file and add to sourcedirs
        _normpath = lambda p: os.path.normpath(os.path.abspath(p))
        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = \
                self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, basestring):
            logging.info('processing ' + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = StringIO()
        pp.do_include(infile)
        lines = PushbackIter(pp.out.getvalue().splitlines())
        try:
            while True:
                l = lines.next()
                m = self.jarline.match(l)
                if not m:
                    raise RuntimeError(l)
                if m.group('jarfile') is None:
                    # comment
                    continue
                self.processJarSection(m.group('jarfile'), lines,
                        jardir)
        except StopIteration:
            # we read the file
            pass
        return

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == 'locales':
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales dirs, merge, l10nbase, en-US
        if self.l10nmerge:
            locdirs.append(os.path.join(self.l10nmerge, l10nrelsrcdir))
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        if self.l10nmerge or not self.l10nbase:
            # add en-US if we merge, or if it's not l10n
            locdirs.append(os.path.join(self.topsourcedir,
                           relativesrcdir, 'en-US'))
        return locdirs

    def processJarSection(self, jarfile, lines, jardir):
        '''Internal method called by makeJar to actually process a section
        of a jar.mn file.

        jarfile is the basename of the jarfile or the directory name for
        flat output, lines is a PushbackIter of the lines of jar.mn,
        the remaining options are carried over from makeJar.
        '''

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = '{0}' + os.path.basename(jarfile)
        if self.outputFormat == 'jar':
            chromebasepath = 'jar:' + chromebasepath + '.jar!'
        chromebasepath += '/'

        jarfile = os.path.join(jardir, jarfile)
        jf = None
        if self.outputFormat == 'jar':
            # jar
            jarfilepath = jarfile + '.jar'
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError, error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, 'a', lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else:
Exemplo n.º 5
0
Arquivo: jar.py Projeto: bigmangfu/smv
class JarMaker(object):
    '''JarMaker reads jar.mn files and process those into jar files or
      flat directories, along with chrome.manifest files.
      '''
    def __init__(self,
                 outputFormat='flat',
                 useJarfileManifest=True,
                 useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.l10nmerge = None
        self.relativesrcdir = None
        self.rootManifestAppId = None

    def getCommandLineParser(self):
        '''Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        '''

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option(
            '-f',
            type='choice',
            default='jar',
            choices=('jar', 'flat', 'symlink'),
            help='fileformat used for output',
            metavar='[jar, flat, symlink]',
        )
        p.add_option('-v',
                     action='store_true',
                     dest='verbose',
                     help='verbose output')
        p.add_option('-q',
                     action='store_false',
                     dest='verbose',
                     help='verbose output')
        p.add_option('-e',
                     action='store_true',
                     help='create chrome.manifest instead of jarfile.manifest')
        p.add_option('-s',
                     type='string',
                     action='append',
                     default=[],
                     help='source directory')
        p.add_option('-t', type='string', help='top source directory')
        p.add_option('-c',
                     '--l10n-src',
                     type='string',
                     action='append',
                     help='localization directory')
        p.add_option(
            '--l10n-base',
            type='string',
            action='store',
            help=
            'base directory to be used for localization (requires relativesrcdir)'
        )
        p.add_option(
            '--locale-mergedir',
            type='string',
            action='store',
            help=
            'base directory to be used for l10n-merge (requires l10n-base and relativesrcdir)'
        )
        p.add_option('--relativesrcdir',
                     type='string',
                     help='relativesrcdir to be used for localization')
        p.add_option('-d', type='string', help='base directory')
        p.add_option('--root-manifest-entry-appid',
                     type='string',
                     help='add an app id specific root chrome manifest entry.')
        return p

    def processIncludes(self, includes):
        '''Process given includes with the inner PreProcessor.

        Only use this for #defines, the includes shouldn't generate
        content.
        '''

        self.pp.out = StringIO()
        for inc in includes:
            self.pp.do_include(inc)
        includesvalue = self.pp.out.getvalue()
        if includesvalue:
            logging.info('WARNING: Includes produce non-empty output')
        self.pp.out = None

    def finalizeJar(self,
                    jardir,
                    jarbase,
                    jarname,
                    chromebasepath,
                    register,
                    doZip=True):
        '''Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        '''

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(jardir, jarbase, 'chrome.manifest')

        if self.useJarfileManifest:
            self.updateManifest(
                os.path.join(jardir, jarbase, jarname + '.manifest'),
                chromebasepath.format(''), register)
            if jarname != 'chrome':
                addEntriesToListFile(chromeManifest,
                                     ['manifest {0}.manifest'.format(jarname)])
        if self.useChromeManifest:
            chromebase = os.path.dirname(jarname) + '/'
            self.updateManifest(chromeManifest,
                                chromebasepath.format(chromebase), register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = \
                os.path.join(os.path.normpath(os.path.dirname(chromeManifest)),
                             '..', 'chrome.manifest')
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = \
                os.path.basename(os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s" %
                         (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(rootChromeManifest, [
                'manifest %s/chrome.manifest application=%s' %
                (chromeDir, self.rootManifestAppId)
            ])

    def updateManifest(self, manifestPath, chromebasepath, register):
        '''updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        '''
        myregister = dict.fromkeys(
            map(lambda s: s.replace('%', chromebasepath), register))
        addEntriesToListFile(manifestPath, myregister.iterkeys())

    def makeJar(self, infile, jardir):
        '''makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        '''

        # making paths absolute, guess srcdir if file and add to sourcedirs
        _normpath = lambda p: os.path.normpath(os.path.abspath(p))
        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = \
                self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, basestring):
            logging.info('processing ' + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = JarManifestParser()
        pp.do_include(infile)

        for info in pp.out:
            self.processJarSection(info, jardir)

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == 'locales':
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales dirs, merge, l10nbase, en-US
        if self.l10nmerge:
            locdirs.append(os.path.join(self.l10nmerge, l10nrelsrcdir))
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        if self.l10nmerge or not self.l10nbase:
            # add en-US if we merge, or if it's not l10n
            locdirs.append(
                os.path.join(self.topsourcedir, relativesrcdir, 'en-US'))
        return locdirs

    def processJarSection(self, jarinfo, jardir):
        '''Internal method called by makeJar to actually process a section
        of a jar.mn file.
        '''

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = '{0}' + os.path.basename(jarinfo.name)
        if self.outputFormat == 'jar':
            chromebasepath = 'jar:' + chromebasepath + '.jar!'
        chromebasepath += '/'

        jarfile = os.path.join(jardir, jarinfo.base, jarinfo.name)
        jf = None
        if self.outputFormat == 'jar':
            # jar
            jarfilepath = jarfile + '.jar'
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError, error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, 'a', lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else:
Exemplo n.º 6
0
class JarMaker(object):
    '''JarMaker reads jar.mn files and process those into jar files or
      flat directories, along with chrome.manifest files.
      '''

    ignore = re.compile('\s*(\#.*)?$')
    jarline = re.compile('(?:(?P<jarfile>[\w\d.\-\_\\\/]+).jar\:)|(?:\s*(\#.*)?)\s*$')
    relsrcline = re.compile('relativesrcdir\s+(?P<relativesrcdir>.+?):')
    regline = re.compile('\%\s+(.*)$')
    entryre = '(?P<optPreprocess>\*)?(?P<optOverwrite>\+?)\s+'
    entryline = re.compile(entryre
                           + '(?P<output>[\w\d.\-\_\\\/\+\@]+)\s*(\((?P<locale>\%?)(?P<source>[\w\d.\-\_\\\/\@]+)\))?\s*$'
                           )

    def __init__(self, outputFormat='flat', useJarfileManifest=True,
        useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.l10nmerge = None
        self.relativesrcdir = None
        self.rootManifestAppId = None

    def getCommandLineParser(self):
        '''Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        '''

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option('-f', type='choice', default='jar',
            choices=('jar', 'flat', 'symlink'),
            help='fileformat used for output',
            metavar='[jar, flat, symlink]',
            )
        p.add_option('-v', action='store_true', dest='verbose',
                     help='verbose output')
        p.add_option('-q', action='store_false', dest='verbose',
                     help='verbose output')
        p.add_option('-e', action='store_true',
                     help='create chrome.manifest instead of jarfile.manifest'
                     )
        p.add_option('-s', type='string', action='append', default=[],
                     help='source directory')
        p.add_option('-t', type='string', help='top source directory')
        p.add_option('-c', '--l10n-src', type='string', action='append'
                     , help='localization directory')
        p.add_option('--l10n-base', type='string', action='store',
                     help='base directory to be used for localization (requires relativesrcdir)'
                     )
        p.add_option('--locale-mergedir', type='string', action='store'
                     ,
                     help='base directory to be used for l10n-merge (requires l10n-base and relativesrcdir)'
                     )
        p.add_option('--relativesrcdir', type='string',
                     help='relativesrcdir to be used for localization')
        p.add_option('-j', type='string', help='jarfile directory')
        p.add_option('--root-manifest-entry-appid', type='string',
                     help='add an app id specific root chrome manifest entry.'
                     )
        return p

    def processIncludes(self, includes):
        '''Process given includes with the inner PreProcessor.

        Only use this for #defines, the includes shouldn't generate
        content.
        '''

        self.pp.out = StringIO()
        for inc in includes:
            self.pp.do_include(inc)
        includesvalue = self.pp.out.getvalue()
        if includesvalue:
            logging.info('WARNING: Includes produce non-empty output')
        self.pp.out = None

    def finalizeJar(self, jarPath, chromebasepath, register, doZip=True):
        '''Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        '''

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(os.path.dirname(jarPath), '..',
                'chrome.manifest')

        if self.useJarfileManifest:
            self.updateManifest(jarPath + '.manifest',
                                chromebasepath.format(''), register)
            addEntriesToListFile(chromeManifest,
                                 ['manifest chrome/{0}.manifest'.format(os.path.basename(jarPath))])
        if self.useChromeManifest:
            self.updateManifest(chromeManifest,
                                chromebasepath.format('chrome/'),
                                register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = \
                os.path.join(os.path.normpath(os.path.dirname(chromeManifest)),
                             '..', 'chrome.manifest')
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = \
                os.path.basename(os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s"
                          % (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(rootChromeManifest,
                                 ['manifest %s/chrome.manifest application=%s'
                                  % (chromeDir,
                                 self.rootManifestAppId)])

    def updateManifest(self, manifestPath, chromebasepath, register):
        '''updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        '''

        lock = lock_file(manifestPath + '.lck')
        try:
            myregister = dict.fromkeys(map(lambda s: s.replace('%',
                    chromebasepath), register.iterkeys()))
            manifestExists = os.path.isfile(manifestPath)
            mode = manifestExists and 'r+b' or 'wb'
            mf = open(manifestPath, mode)
            if manifestExists:
                # import previous content into hash, ignoring empty ones and comments
                imf = re.compile('(#.*)?$')
                for l in re.split('[\r\n]+', mf.read()):
                    if imf.match(l):
                        continue
                    myregister[l] = None
                mf.seek(0)
            for k in sorted(myregister.iterkeys()):
                mf.write(k + os.linesep)
            mf.close()
        finally:
            lock = None

    def makeJar(self, infile, jardir):
        '''makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        '''

        # making paths absolute, guess srcdir if file and add to sourcedirs
        _normpath = lambda p: os.path.normpath(os.path.abspath(p))
        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = \
                self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, basestring):
            logging.info('processing ' + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = StringIO()
        pp.do_include(infile)
        lines = PushbackIter(pp.out.getvalue().splitlines())
        try:
            while True:
                l = lines.next()
                m = self.jarline.match(l)
                if not m:
                    raise RuntimeError(l)
                if m.group('jarfile') is None:
                    # comment
                    continue
                self.processJarSection(m.group('jarfile'), lines,
                        jardir)
        except StopIteration:
            # we read the file
            pass
        return

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == 'locales':
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales dirs, merge, l10nbase, en-US
        if self.l10nmerge:
            locdirs.append(os.path.join(self.l10nmerge, l10nrelsrcdir))
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        if self.l10nmerge or not self.l10nbase:
            # add en-US if we merge, or if it's not l10n
            locdirs.append(os.path.join(self.topsourcedir,
                           relativesrcdir, 'en-US'))
        return locdirs

    def processJarSection(self, jarfile, lines, jardir):
        '''Internal method called by makeJar to actually process a section
        of a jar.mn file.

        jarfile is the basename of the jarfile or the directory name for
        flat output, lines is a PushbackIter of the lines of jar.mn,
        the remaining options are carried over from makeJar.
        '''

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = '{0}' + os.path.basename(jarfile)
        if self.outputFormat == 'jar':
            chromebasepath = 'jar:' + chromebasepath + '.jar!'
        chromebasepath += '/'

        jarfile = os.path.join(jardir, jarfile)
        jf = None
        if self.outputFormat == 'jar':
            # jar
            jarfilepath = jarfile + '.jar'
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError, error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, 'a', lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else:
Exemplo n.º 7
0
class JarMaker(object):
    '''JarMaker reads jar.mn files and process those into jar files or
      flat directories, along with chrome.manifest files.
      '''

    def __init__(self, outputFormat='flat', useJarfileManifest=True,
        useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.l10nmerge = None
        self.relativesrcdir = None
        self.rootManifestAppId = None
        self._seen_output = set()

    def getCommandLineParser(self):
        '''Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        '''

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option('-f', type='choice', default='jar',
            choices=('jar', 'flat', 'symlink'),
            help='fileformat used for output',
            metavar='[jar, flat, symlink]',
            )
        p.add_option('-v', action='store_true', dest='verbose',
                     help='verbose output')
        p.add_option('-q', action='store_false', dest='verbose',
                     help='verbose output')
        p.add_option('-e', action='store_true',
                     help='create chrome.manifest instead of jarfile.manifest'
                     )
        p.add_option('-s', type='string', action='append', default=[],
                     help='source directory')
        p.add_option('-t', type='string', help='top source directory')
        p.add_option('-c', '--l10n-src', type='string', action='append'
                     , help='localization directory')
        p.add_option('--l10n-base', type='string', action='store',
                     help='base directory to be used for localization (requires relativesrcdir)'
                     )
        p.add_option('--locale-mergedir', type='string', action='store'
                     ,
                     help='base directory to be used for l10n-merge (requires l10n-base and relativesrcdir)'
                     )
        p.add_option('--relativesrcdir', type='string',
                     help='relativesrcdir to be used for localization')
        p.add_option('-d', type='string', help='base directory')
        p.add_option('--root-manifest-entry-appid', type='string',
                     help='add an app id specific root chrome manifest entry.'
                     )
        return p

    def finalizeJar(self, jardir, jarbase, jarname, chromebasepath, register, doZip=True):
        '''Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        '''

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(jardir, jarbase, 'chrome.manifest')

        if self.useJarfileManifest:
            self.updateManifest(os.path.join(jardir, jarbase,
                                             jarname + '.manifest'),
                                chromebasepath.format(''), register)
            if jarname != 'chrome':
                addEntriesToListFile(chromeManifest,
                                     ['manifest {0}.manifest'.format(jarname)])
        if self.useChromeManifest:
            chromebase = os.path.dirname(jarname) + '/'
            self.updateManifest(chromeManifest,
                                chromebasepath.format(chromebase), register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = \
                os.path.join(os.path.normpath(os.path.dirname(chromeManifest)),
                             '..', 'chrome.manifest')
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = \
                os.path.basename(os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s"
                          % (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(rootChromeManifest,
                                 ['manifest %s/chrome.manifest application=%s'
                                  % (chromeDir,
                                 self.rootManifestAppId)])

    def updateManifest(self, manifestPath, chromebasepath, register):
        '''updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        '''
        myregister = dict.fromkeys(map(lambda s: s.replace('%',
            chromebasepath), register))
        addEntriesToListFile(manifestPath, myregister.iterkeys())

    def makeJar(self, infile, jardir):
        '''makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        '''

        # making paths absolute, guess srcdir if file and add to sourcedirs
        _normpath = lambda p: os.path.normpath(os.path.abspath(p))
        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = \
                self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, basestring):
            logging.info('processing ' + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = JarManifestParser()
        pp.do_include(infile)

        for info in pp.out:
            self.processJarSection(info, jardir)

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == 'locales':
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales dirs, merge, l10nbase, en-US
        if self.l10nmerge:
            locdirs.append(os.path.join(self.l10nmerge, l10nrelsrcdir))
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        if self.l10nmerge or not self.l10nbase:
            # add en-US if we merge, or if it's not l10n
            locdirs.append(os.path.join(self.topsourcedir,
                           relativesrcdir, 'en-US'))
        return locdirs

    def processJarSection(self, jarinfo, jardir):
        '''Internal method called by makeJar to actually process a section
        of a jar.mn file.
        '''

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = '{0}' + os.path.basename(jarinfo.name)
        if self.outputFormat == 'jar':
            chromebasepath = 'jar:' + chromebasepath + '.jar!'
        chromebasepath += '/'

        jarfile = os.path.join(jardir, jarinfo.base, jarinfo.name)
        jf = None
        if self.outputFormat == 'jar':
            # jar
            jarfilepath = jarfile + '.jar'
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError as error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, 'a', lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else:
            outHelper = getattr(self, 'OutputHelper_'
                                + self.outputFormat)(jarfile)

        if jarinfo.relativesrcdir:
            self.localedirs = self.generateLocaleDirs(jarinfo.relativesrcdir)

        for e in jarinfo.entries:
            self._processEntryLine(e, outHelper, jf)

        self.finalizeJar(jardir, jarinfo.base, jarinfo.name, chromebasepath,
                         jarinfo.chrome_manifests)
        if jf is not None:
            jf.close()

    def _processEntryLine(self, e, outHelper, jf):
        out = e.output
        src = e.source

        # pick the right sourcedir -- l10n, topsrc or src

        if e.is_locale:
            # If the file is a Fluent l10n resource, we want to skip the
            # 'en-US' fallbacking.
            #
            # To achieve that, we're testing if we have more than one localedir,
            # and if the last of those has 'en-US' in it.
            # If that's the case, we're removing the last one.
            if (e.source.endswith('.ftl') and
                len(self.localedirs) > 1 and
                'en-US' in self.localedirs[-1]):
                src_base = self.localedirs[:-1]
            else:
                src_base = self.localedirs
        elif src.startswith('/'):
            # path/in/jar/file_name.xul     (/path/in/sourcetree/file_name.xul)
            # refers to a path relative to topsourcedir, use that as base
            # and strip the leading '/'
            src_base = [self.topsourcedir]
            src = src[1:]
        else:
            # use srcdirs and the objdir (current working dir) for relative paths
            src_base = self.sourcedirs + [os.getcwd()]

        if '*' in src:
            def _prefix(s):
                for p in s.split('/'):
                    if '*' not in p:
                        yield p + '/'
            prefix = ''.join(_prefix(src))
            emitted = set()
            for _srcdir in src_base:
                finder = FileFinder(_srcdir)
                for path, _ in finder.find(src):
                    # If the path was already seen in one of the other source
                    # directories, skip it. That matches the non-wildcard case
                    # below, where we pick the first existing file.
                    reduced_path = path[len(prefix):]
                    if reduced_path in emitted:
                        continue
                    emitted.add(reduced_path)
                    e = JarManifestEntry(
                        mozpath.join(out, reduced_path),
                        path,
                        is_locale=e.is_locale,
                        preprocess=e.preprocess,
                    )
                    self._processEntryLine(e, outHelper, jf)
            return

        # check if the source file exists
        realsrc = None
        for _srcdir in src_base:
            if os.path.isfile(os.path.join(_srcdir, src)):
                realsrc = os.path.join(_srcdir, src)
                break
        if realsrc is None:
            if jf is not None:
                jf.close()
            raise RuntimeError('File "{0}" not found in {1}'.format(src,
                               ', '.join(src_base)))

        if out in self._seen_output:
            raise RuntimeError('%s already added' % out)
        self._seen_output.add(out)

        if e.preprocess:
            outf = outHelper.getOutput(out)
            inf = open(realsrc)
            pp = self.pp.clone()
            if src[-4:] == '.css':
                pp.setMarker('%')
            pp.out = outf
            pp.do_include(inf)
            pp.failUnused(realsrc)
            outf.close()
            inf.close()
            return

        # copy or symlink if newer

        if getModTime(realsrc) > outHelper.getDestModTime(e.output):
            if self.outputFormat == 'symlink':
                outHelper.symlink(realsrc, out)
                return
            outf = outHelper.getOutput(out)

            # open in binary mode, this can be images etc

            inf = open(realsrc, 'rb')
            outf.write(inf.read())
            outf.close()
            inf.close()

    class OutputHelper_jar(object):
        '''Provide getDestModTime and getOutput for a given jarfile.'''

        def __init__(self, jarfile):
            self.jarfile = jarfile

        def getDestModTime(self, aPath):
            try:
                info = self.jarfile.getinfo(aPath)
                return info.date_time
            except:
                return 0

        def getOutput(self, name):
            return ZipEntry(name, self.jarfile)

    class OutputHelper_flat(object):
        '''Provide getDestModTime and getOutput for a given flat
        output directory. The helper method ensureDirFor is used by
        the symlink subclass.
        '''

        def __init__(self, basepath):
            self.basepath = basepath

        def getDestModTime(self, aPath):
            return getModTime(os.path.join(self.basepath, aPath))

        def getOutput(self, name):
            out = self.ensureDirFor(name)

            # remove previous link or file
            try:
                os.remove(out)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
            return open(out, 'wb')

        def ensureDirFor(self, name):
            out = os.path.join(self.basepath, name)
            outdir = os.path.dirname(out)
            if not os.path.isdir(outdir):
                try:
                    os.makedirs(outdir)
                except OSError as error:
                    if error.errno != errno.EEXIST:
                        raise
            return out

    class OutputHelper_symlink(OutputHelper_flat):
        '''Subclass of OutputHelper_flat that provides a helper for
        creating a symlink including creating the parent directories.
        '''

        def symlink(self, src, dest):
            out = self.ensureDirFor(dest)

            # remove previous link or file
            try:
                os.remove(out)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
            if sys.platform != 'win32':
                os.symlink(src, out)
            else:
                # On Win32, use ctypes to create a hardlink
                rv = CreateHardLink(out, src, None)
                if rv == 0:
                    raise WinError()
Exemplo n.º 8
0
class JarMaker(object):
    """JarMaker reads jar.mn files and process those into jar files or
    flat directories, along with chrome.manifest files.
    """
    def __init__(self,
                 outputFormat="flat",
                 useJarfileManifest=True,
                 useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.relativesrcdir = None
        self.rootManifestAppId = None
        self._seen_output = set()

    def getCommandLineParser(self):
        """Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        """

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option(
            "-f",
            type="choice",
            default="jar",
            choices=("jar", "flat", "symlink"),
            help="fileformat used for output",
            metavar="[jar, flat, symlink]",
        )
        p.add_option("-v",
                     action="store_true",
                     dest="verbose",
                     help="verbose output")
        p.add_option("-q",
                     action="store_false",
                     dest="verbose",
                     help="verbose output")
        p.add_option(
            "-e",
            action="store_true",
            help="create chrome.manifest instead of jarfile.manifest",
        )
        p.add_option("-s",
                     type="string",
                     action="append",
                     default=[],
                     help="source directory")
        p.add_option("-t", type="string", help="top source directory")
        p.add_option(
            "-c",
            "--l10n-src",
            type="string",
            action="append",
            help="localization directory",
        )
        p.add_option(
            "--l10n-base",
            type="string",
            action="store",
            help=
            "merged directory to be used for localization (requires relativesrcdir)",
        )
        p.add_option(
            "--relativesrcdir",
            type="string",
            help="relativesrcdir to be used for localization",
        )
        p.add_option("-d", type="string", help="base directory")
        p.add_option(
            "--root-manifest-entry-appid",
            type="string",
            help="add an app id specific root chrome manifest entry.",
        )
        return p

    def finalizeJar(self,
                    jardir,
                    jarbase,
                    jarname,
                    chromebasepath,
                    register,
                    doZip=True):
        """Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        """

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(jardir, jarbase, "chrome.manifest")

        if self.useJarfileManifest:
            self.updateManifest(
                os.path.join(jardir, jarbase, jarname + ".manifest"),
                chromebasepath.format(""),
                register,
            )
            if jarname != "chrome":
                addEntriesToListFile(chromeManifest,
                                     ["manifest {0}.manifest".format(jarname)])
        if self.useChromeManifest:
            chromebase = os.path.dirname(jarname) + "/"
            self.updateManifest(chromeManifest,
                                chromebasepath.format(chromebase), register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = os.path.join(
                os.path.normpath(os.path.dirname(chromeManifest)),
                "..",
                "chrome.manifest",
            )
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = os.path.basename(
                os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s" %
                         (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(
                rootChromeManifest,
                [
                    "manifest %s/chrome.manifest application=%s" %
                    (chromeDir, self.rootManifestAppId)
                ],
            )

    def updateManifest(self, manifestPath, chromebasepath, register):
        """updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        """
        myregister = dict.fromkeys(
            map(lambda s: s.replace("%", chromebasepath), register))
        addEntriesToListFile(manifestPath, six.iterkeys(myregister))

    def makeJar(self, infile, jardir):
        """makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        """

        # making paths absolute, guess srcdir if file and add to sourcedirs
        def _normpath(p):
            return os.path.normpath(os.path.abspath(p))

        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, six.text_type):
            logging.info("processing " + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = JarManifestParser()
        pp.do_include(infile)

        for info in pp.out:
            self.processJarSection(info, jardir)

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == "locales":
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales merge or en-US
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        else:
            # add en-US if it's not l10n
            locdirs.append(
                os.path.join(self.topsourcedir, relativesrcdir, "en-US"))
        return locdirs

    def processJarSection(self, jarinfo, jardir):
        """Internal method called by makeJar to actually process a section
        of a jar.mn file.
        """

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = "{0}" + os.path.basename(jarinfo.name)
        if self.outputFormat == "jar":
            chromebasepath = "jar:" + chromebasepath + ".jar!"
        chromebasepath += "/"

        jarfile = os.path.join(jardir, jarinfo.base, jarinfo.name)
        jf = None
        if self.outputFormat == "jar":
            # jar
            jarfilepath = jarfile + ".jar"
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError as error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, "a", lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else:
            outHelper = getattr(self,
                                "OutputHelper_" + self.outputFormat)(jarfile)

        if jarinfo.relativesrcdir:
            self.localedirs = self.generateLocaleDirs(jarinfo.relativesrcdir)

        for e in jarinfo.entries:
            self._processEntryLine(e, outHelper, jf)

        self.finalizeJar(jardir, jarinfo.base, jarinfo.name, chromebasepath,
                         jarinfo.chrome_manifests)
        if jf is not None:
            jf.close()

    def _processEntryLine(self, e, outHelper, jf):
        out = e.output
        src = e.source

        # pick the right sourcedir -- l10n, topsrc or src

        if e.is_locale:
            # If the file is a Fluent l10n resource, we want to skip the
            # 'en-US' fallbacking.
            #
            # To achieve that, we're testing if we have more than one localedir,
            # and if the last of those has 'en-US' in it.
            # If that's the case, we're removing the last one.
            if (e.source.endswith(".ftl") and len(self.localedirs) > 1
                    and "en-US" in self.localedirs[-1]):
                src_base = self.localedirs[:-1]
            else:
                src_base = self.localedirs
        elif src.startswith("/"):
            # path/in/jar/file_name.xul     (/path/in/sourcetree/file_name.xul)
            # refers to a path relative to topsourcedir, use that as base
            # and strip the leading '/'
            src_base = [self.topsourcedir]
            src = src[1:]
        else:
            # use srcdirs and the objdir (current working dir) for relative paths
            src_base = self.sourcedirs + [os.getcwd()]

        if "*" in src:

            def _prefix(s):
                for p in s.split("/"):
                    if "*" not in p:
                        yield p + "/"

            prefix = "".join(_prefix(src))
            emitted = set()
            for _srcdir in src_base:
                finder = FileFinder(_srcdir)
                for path, _ in finder.find(src):
                    # If the path was already seen in one of the other source
                    # directories, skip it. That matches the non-wildcard case
                    # below, where we pick the first existing file.
                    reduced_path = path[len(prefix):]
                    if reduced_path in emitted:
                        continue
                    emitted.add(reduced_path)
                    e = JarManifestEntry(
                        mozpath.join(out, reduced_path),
                        path,
                        is_locale=e.is_locale,
                        preprocess=e.preprocess,
                    )
                    self._processEntryLine(e, outHelper, jf)
            return

        # check if the source file exists
        realsrc = None
        for _srcdir in src_base:
            if os.path.isfile(os.path.join(_srcdir, src)):
                realsrc = os.path.join(_srcdir, src)
                break
        if realsrc is None:
            if jf is not None:
                jf.close()
            raise RuntimeError('File "{0}" not found in {1}'.format(
                src, ", ".join(src_base)))

        if out in self._seen_output:
            raise RuntimeError("%s already added" % out)
        self._seen_output.add(out)

        if e.preprocess:
            outf = outHelper.getOutput(out, mode="w")
            inf = io.open(realsrc, encoding="utf-8")
            pp = self.pp.clone()
            if src[-4:] == ".css":
                pp.setMarker("%")
            pp.out = outf
            pp.do_include(inf)
            pp.failUnused(realsrc)
            outf.close()
            inf.close()
            return

        # copy or symlink if newer

        if getModTime(realsrc) > outHelper.getDestModTime(e.output):
            if self.outputFormat == "symlink":
                outHelper.symlink(realsrc, out)
                return
            outf = outHelper.getOutput(out)

            # open in binary mode, this can be images etc

            inf = open(realsrc, "rb")
            outf.write(inf.read())
            outf.close()
            inf.close()

    class OutputHelper_jar(object):
        """Provide getDestModTime and getOutput for a given jarfile."""
        def __init__(self, jarfile):
            self.jarfile = jarfile

        def getDestModTime(self, aPath):
            try:
                info = self.jarfile.getinfo(aPath)
                return info.date_time
            except Exception:
                return localtime(0)

        def getOutput(self, name, mode="wb"):
            return ZipEntry(name, self.jarfile)

    class OutputHelper_flat(object):
        """Provide getDestModTime and getOutput for a given flat
        output directory. The helper method ensureDirFor is used by
        the symlink subclass.
        """
        def __init__(self, basepath):
            self.basepath = basepath

        def getDestModTime(self, aPath):
            return getModTime(os.path.join(self.basepath, aPath))

        def getOutput(self, name, mode="wb"):
            out = self.ensureDirFor(name)

            # remove previous link or file
            try:
                os.remove(out)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
            if "b" in mode:
                return io.open(out, mode)
            else:
                return io.open(out, mode, encoding="utf-8", newline="\n")

        def ensureDirFor(self, name):
            out = os.path.join(self.basepath, name)
            outdir = os.path.dirname(out)
            if not os.path.isdir(outdir):
                try:
                    os.makedirs(outdir)
                except OSError as error:
                    if error.errno != errno.EEXIST:
                        raise
            return out

    class OutputHelper_symlink(OutputHelper_flat):
        """Subclass of OutputHelper_flat that provides a helper for
        creating a symlink including creating the parent directories.
        """
        def symlink(self, src, dest):
            out = self.ensureDirFor(dest)

            # remove previous link or file
            try:
                os.remove(out)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
            if sys.platform != "win32":
                os.symlink(src, out)
            else:
                # On Win32, use ctypes to create a hardlink
                rv = CreateHardLink(ensure_bytes(out), ensure_bytes(src), None)
                if rv == 0:
                    raise WinError()
Exemplo n.º 9
0
class JarMaker(object):
    """JarMaker reads jar.mn files and process those into jar files or
      flat directories, along with chrome.manifest files.
      """

    ignore = re.compile("\s*(\#.*)?$")
    jarline = re.compile("(?:(?P<jarfile>[\w\d.\-\_\\\/{}]+).jar\:)|(?:\s*(\#.*)?)\s*$")
    relsrcline = re.compile("relativesrcdir\s+(?P<relativesrcdir>.+?):")
    regline = re.compile("\%\s+(.*)$")
    entryre = "(?P<optPreprocess>\*)?(?P<optOverwrite>\+?)\s+"
    entryline = re.compile(
        entryre + "(?P<output>[\w\d.\-\_\\\/\+\@]+)\s*(\((?P<locale>\%?)(?P<source>[\w\d.\-\_\\\/\@\*]+)\))?\s*$"
    )

    def __init__(self, outputFormat="flat", useJarfileManifest=True, useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.l10nmerge = None
        self.relativesrcdir = None
        self.rootManifestAppId = None

    def getCommandLineParser(self):
        """Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        """

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option(
            "-f",
            type="choice",
            default="jar",
            choices=("jar", "flat", "symlink"),
            help="fileformat used for output",
            metavar="[jar, flat, symlink]",
        )
        p.add_option("-v", action="store_true", dest="verbose", help="verbose output")
        p.add_option("-q", action="store_false", dest="verbose", help="verbose output")
        p.add_option("-e", action="store_true", help="create chrome.manifest instead of jarfile.manifest")
        p.add_option("-s", type="string", action="append", default=[], help="source directory")
        p.add_option("-t", type="string", help="top source directory")
        p.add_option("-c", "--l10n-src", type="string", action="append", help="localization directory")
        p.add_option(
            "--l10n-base",
            type="string",
            action="store",
            help="base directory to be used for localization (requires relativesrcdir)",
        )
        p.add_option(
            "--locale-mergedir",
            type="string",
            action="store",
            help="base directory to be used for l10n-merge (requires l10n-base and relativesrcdir)",
        )
        p.add_option("--relativesrcdir", type="string", help="relativesrcdir to be used for localization")
        p.add_option("-j", type="string", help="jarfile directory")
        p.add_option(
            "--root-manifest-entry-appid", type="string", help="add an app id specific root chrome manifest entry."
        )
        return p

    def processIncludes(self, includes):
        """Process given includes with the inner PreProcessor.

        Only use this for #defines, the includes shouldn't generate
        content.
        """

        self.pp.out = StringIO()
        for inc in includes:
            self.pp.do_include(inc)
        includesvalue = self.pp.out.getvalue()
        if includesvalue:
            logging.info("WARNING: Includes produce non-empty output")
        self.pp.out = None

    def finalizeJar(self, jarPath, chromebasepath, register, doZip=True):
        """Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        """

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(os.path.dirname(jarPath), "..", "chrome.manifest")

        if self.useJarfileManifest:
            self.updateManifest(jarPath + ".manifest", chromebasepath.format(""), register)
            addEntriesToListFile(chromeManifest, ["manifest chrome/{0}.manifest".format(os.path.basename(jarPath))])
        if self.useChromeManifest:
            self.updateManifest(chromeManifest, chromebasepath.format("chrome/"), register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = os.path.join(
                os.path.normpath(os.path.dirname(chromeManifest)), "..", "chrome.manifest"
            )
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = os.path.basename(os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s" % (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(
                rootChromeManifest, ["manifest %s/chrome.manifest application=%s" % (chromeDir, self.rootManifestAppId)]
            )

    def updateManifest(self, manifestPath, chromebasepath, register):
        """updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        """

        lock = lock_file(manifestPath + ".lck")
        try:
            myregister = dict.fromkeys(map(lambda s: s.replace("%", chromebasepath), register.iterkeys()))
            manifestExists = os.path.isfile(manifestPath)
            mode = manifestExists and "r+b" or "wb"
            mf = open(manifestPath, mode)
            if manifestExists:
                # import previous content into hash, ignoring empty ones and comments
                imf = re.compile("(#.*)?$")
                for l in re.split("[\r\n]+", mf.read()):
                    if imf.match(l):
                        continue
                    myregister[l] = None
                mf.seek(0)
            for k in sorted(myregister.iterkeys()):
                mf.write(k + os.linesep)
            mf.close()
        finally:
            lock = None

    def makeJar(self, infile, jardir):
        """makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        """

        # making paths absolute, guess srcdir if file and add to sourcedirs
        _normpath = lambda p: os.path.normpath(os.path.abspath(p))
        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, basestring):
            logging.info("processing " + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = StringIO()
        pp.do_include(infile)
        lines = PushbackIter(pp.out.getvalue().splitlines())
        try:
            while True:
                l = lines.next()
                m = self.jarline.match(l)
                if not m:
                    raise RuntimeError(l)
                if m.group("jarfile") is None:
                    # comment
                    continue
                self.processJarSection(m.group("jarfile"), lines, jardir)
        except StopIteration:
            # we read the file
            pass
        return

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == "locales":
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales dirs, merge, l10nbase, en-US
        if self.l10nmerge:
            locdirs.append(os.path.join(self.l10nmerge, l10nrelsrcdir))
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        if self.l10nmerge or not self.l10nbase:
            # add en-US if we merge, or if it's not l10n
            locdirs.append(os.path.join(self.topsourcedir, relativesrcdir, "en-US"))
        return locdirs

    def processJarSection(self, jarfile, lines, jardir):
        """Internal method called by makeJar to actually process a section
        of a jar.mn file.

        jarfile is the basename of the jarfile or the directory name for
        flat output, lines is a PushbackIter of the lines of jar.mn,
        the remaining options are carried over from makeJar.
        """

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = "{0}" + os.path.basename(jarfile)
        if self.outputFormat == "jar":
            chromebasepath = "jar:" + chromebasepath + ".jar!"
        chromebasepath += "/"

        jarfile = os.path.join(jardir, jarfile)
        jf = None
        if self.outputFormat == "jar":
            # jar
            jarfilepath = jarfile + ".jar"
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError, error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, "a", lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else:
Exemplo n.º 10
0
class JarMaker(object):
    """JarMaker reads jar.mn files and process those into jar files or
      flat directories, along with chrome.manifest files.
      """

    def __init__(self, outputFormat="flat", useJarfileManifest=True, useChromeManifest=False):

        self.outputFormat = outputFormat
        self.useJarfileManifest = useJarfileManifest
        self.useChromeManifest = useChromeManifest
        self.pp = Preprocessor()
        self.topsourcedir = None
        self.sourcedirs = []
        self.localedirs = None
        self.l10nbase = None
        self.l10nmerge = None
        self.relativesrcdir = None
        self.rootManifestAppId = None

    def getCommandLineParser(self):
        """Get a optparse.OptionParser for jarmaker.

        This OptionParser has the options for jarmaker as well as
        the options for the inner PreProcessor.
        """

        # HACK, we need to unescape the string variables we get,
        # the perl versions didn't grok strings right

        p = self.pp.getCommandLineParser(unescapeDefines=True)
        p.add_option(
            "-f",
            type="choice",
            default="jar",
            choices=("jar", "flat", "symlink"),
            help="fileformat used for output",
            metavar="[jar, flat, symlink]",
        )
        p.add_option("-v", action="store_true", dest="verbose", help="verbose output")
        p.add_option("-q", action="store_false", dest="verbose", help="verbose output")
        p.add_option("-e", action="store_true", help="create chrome.manifest instead of jarfile.manifest")
        p.add_option("-s", type="string", action="append", default=[], help="source directory")
        p.add_option("-t", type="string", help="top source directory")
        p.add_option("-c", "--l10n-src", type="string", action="append", help="localization directory")
        p.add_option(
            "--l10n-base",
            type="string",
            action="store",
            help="base directory to be used for localization (requires relativesrcdir)",
        )
        p.add_option(
            "--locale-mergedir",
            type="string",
            action="store",
            help="base directory to be used for l10n-merge (requires l10n-base and relativesrcdir)",
        )
        p.add_option("--relativesrcdir", type="string", help="relativesrcdir to be used for localization")
        p.add_option("-d", type="string", help="base directory")
        p.add_option(
            "--root-manifest-entry-appid", type="string", help="add an app id specific root chrome manifest entry."
        )
        return p

    def processIncludes(self, includes):
        """Process given includes with the inner PreProcessor.

        Only use this for #defines, the includes shouldn't generate
        content.
        """

        self.pp.out = StringIO()
        for inc in includes:
            self.pp.do_include(inc)
        includesvalue = self.pp.out.getvalue()
        if includesvalue:
            logging.info("WARNING: Includes produce non-empty output")
        self.pp.out = None

    def finalizeJar(self, jardir, jarbase, jarname, chromebasepath, register, doZip=True):
        """Helper method to write out the chrome registration entries to
         jarfile.manifest or chrome.manifest, or both.

        The actual file processing is done in updateManifest.
        """

        # rewrite the manifest, if entries given
        if not register:
            return

        chromeManifest = os.path.join(jardir, jarbase, "chrome.manifest")

        if self.useJarfileManifest:
            self.updateManifest(
                os.path.join(jardir, jarbase, jarname + ".manifest"), chromebasepath.format(""), register
            )
            if jarname != "chrome":
                addEntriesToListFile(chromeManifest, ["manifest {0}.manifest".format(jarname)])
        if self.useChromeManifest:
            chromebase = os.path.dirname(jarname) + "/"
            self.updateManifest(chromeManifest, chromebasepath.format(chromebase), register)

        # If requested, add a root chrome manifest entry (assumed to be in the parent directory
        # of chromeManifest) with the application specific id. In cases where we're building
        # lang packs, the root manifest must know about application sub directories.

        if self.rootManifestAppId:
            rootChromeManifest = os.path.join(
                os.path.normpath(os.path.dirname(chromeManifest)), "..", "chrome.manifest"
            )
            rootChromeManifest = os.path.normpath(rootChromeManifest)
            chromeDir = os.path.basename(os.path.dirname(os.path.normpath(chromeManifest)))
            logging.info("adding '%s' entry to root chrome manifest appid=%s" % (chromeDir, self.rootManifestAppId))
            addEntriesToListFile(
                rootChromeManifest, ["manifest %s/chrome.manifest application=%s" % (chromeDir, self.rootManifestAppId)]
            )

    def updateManifest(self, manifestPath, chromebasepath, register):
        """updateManifest replaces the % in the chrome registration entries
        with the given chrome base path, and updates the given manifest file.
        """
        myregister = dict.fromkeys(map(lambda s: s.replace("%", chromebasepath), register))
        addEntriesToListFile(manifestPath, myregister.iterkeys())

    def makeJar(self, infile, jardir):
        """makeJar is the main entry point to JarMaker.

        It takes the input file, the output directory, the source dirs and the
        top source dir as argument, and optionally the l10n dirs.
        """

        # making paths absolute, guess srcdir if file and add to sourcedirs
        _normpath = lambda p: os.path.normpath(os.path.abspath(p))
        self.topsourcedir = _normpath(self.topsourcedir)
        self.sourcedirs = [_normpath(p) for p in self.sourcedirs]
        if self.localedirs:
            self.localedirs = [_normpath(p) for p in self.localedirs]
        elif self.relativesrcdir:
            self.localedirs = self.generateLocaleDirs(self.relativesrcdir)
        if isinstance(infile, basestring):
            logging.info("processing " + infile)
            self.sourcedirs.append(_normpath(os.path.dirname(infile)))
        pp = self.pp.clone()
        pp.out = JarManifestParser()
        pp.do_include(infile)

        for info in pp.out:
            self.processJarSection(info, jardir)

    def generateLocaleDirs(self, relativesrcdir):
        if os.path.basename(relativesrcdir) == "locales":
            # strip locales
            l10nrelsrcdir = os.path.dirname(relativesrcdir)
        else:
            l10nrelsrcdir = relativesrcdir
        locdirs = []

        # generate locales dirs, merge, l10nbase, en-US
        if self.l10nmerge:
            locdirs.append(os.path.join(self.l10nmerge, l10nrelsrcdir))
        if self.l10nbase:
            locdirs.append(os.path.join(self.l10nbase, l10nrelsrcdir))
        if self.l10nmerge or not self.l10nbase:
            # add en-US if we merge, or if it's not l10n
            locdirs.append(os.path.join(self.topsourcedir, relativesrcdir, "en-US"))
        return locdirs

    def processJarSection(self, jarinfo, jardir):
        """Internal method called by makeJar to actually process a section
        of a jar.mn file.
        """

        # chromebasepath is used for chrome registration manifests
        # {0} is getting replaced with chrome/ for chrome.manifest, and with
        # an empty string for jarfile.manifest

        chromebasepath = "{0}" + os.path.basename(jarinfo.name)
        if self.outputFormat == "jar":
            chromebasepath = "jar:" + chromebasepath + ".jar!"
        chromebasepath += "/"

        jarfile = os.path.join(jardir, jarinfo.base, jarinfo.name)
        jf = None
        if self.outputFormat == "jar":
            # jar
            jarfilepath = jarfile + ".jar"
            try:
                os.makedirs(os.path.dirname(jarfilepath))
            except OSError, error:
                if error.errno != errno.EEXIST:
                    raise
            jf = ZipFile(jarfilepath, "a", lock=True)
            outHelper = self.OutputHelper_jar(jf)
        else: