PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/config/JarMaker.py

https://bitbucket.org/bgirard/mozilla-central
Python | 516 lines | 436 code | 14 blank | 66 comment | 2 complexity | 7de5739a9696b6640eea136dadee503a MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause, GPL-2.0, Apache-2.0, MIT, JSON, 0BSD, BSD-2-Clause, LGPL-3.0, AGPL-1.0
  1. # ***** BEGIN LICENSE BLOCK *****
  2. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. #
  4. # The contents of this file are subject to the Mozilla Public License Version
  5. # 1.1 (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. # http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS IS" basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # The Original Code is Mozilla build system.
  15. #
  16. # The Initial Developer of the Original Code is
  17. # Mozilla Foundation.
  18. # Portions created by the Initial Developer are Copyright (C) 2008
  19. # the Initial Developer. All Rights Reserved.
  20. #
  21. # Contributor(s):
  22. # Axel Hecht <l10n@mozilla.com>
  23. #
  24. # Alternatively, the contents of this file may be used under the terms of
  25. # either the GNU General Public License Version 2 or later (the "GPL"), or
  26. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  27. # in which case the provisions of the GPL or the LGPL are applicable instead
  28. # of those above. If you wish to allow use of your version of this file only
  29. # under the terms of either the GPL or the LGPL, and not to allow others to
  30. # use your version of this file under the terms of the MPL, indicate your
  31. # decision by deleting the provisions above and replace them with the notice
  32. # and other provisions required by the GPL or the LGPL. If you do not delete
  33. # the provisions above, a recipient may use your version of this file under
  34. # the terms of any one of the MPL, the GPL or the LGPL.
  35. #
  36. # ***** END LICENSE BLOCK *****
  37. '''jarmaker.py provides a python class to package up chrome content by
  38. processing jar.mn files.
  39. See the documentation for jar.mn on MDC for further details on the format.
  40. '''
  41. import sys
  42. import os
  43. import os.path
  44. import errno
  45. import re
  46. import logging
  47. from time import localtime
  48. from optparse import OptionParser
  49. from MozZipFile import ZipFile
  50. from cStringIO import StringIO
  51. from datetime import datetime
  52. from utils import pushback_iter, lockFile
  53. from Preprocessor import Preprocessor
  54. from buildlist import addEntriesToListFile
  55. if sys.platform == "win32":
  56. from ctypes import windll, WinError
  57. CreateHardLink = windll.kernel32.CreateHardLinkA
  58. __all__ = ['JarMaker']
  59. class ZipEntry:
  60. '''Helper class for jar output.
  61. This class defines a simple file-like object for a zipfile.ZipEntry
  62. so that we can consecutively write to it and then close it.
  63. This methods hooks into ZipFile.writestr on close().
  64. '''
  65. def __init__(self, name, zipfile):
  66. self._zipfile = zipfile
  67. self._name = name
  68. self._inner = StringIO()
  69. def write(self, content):
  70. 'Append the given content to this zip entry'
  71. self._inner.write(content)
  72. return
  73. def close(self):
  74. 'The close method writes the content back to the zip file.'
  75. self._zipfile.writestr(self._name, self._inner.getvalue())
  76. def getModTime(aPath):
  77. if not os.path.isfile(aPath):
  78. return 0
  79. mtime = os.stat(aPath).st_mtime
  80. return localtime(mtime)
  81. class JarMaker(object):
  82. '''JarMaker reads jar.mn files and process those into jar files or
  83. flat directories, along with chrome.manifest files.
  84. '''
  85. ignore = re.compile('\s*(\#.*)?$')
  86. jarline = re.compile('(?:(?P<jarfile>[\w\d.\-\_\\\/]+).jar\:)|(?:\s*(\#.*)?)\s*$')
  87. regline = re.compile('\%\s+(.*)$')
  88. entryre = '(?P<optPreprocess>\*)?(?P<optOverwrite>\+?)\s+'
  89. entryline = re.compile(entryre + '(?P<output>[\w\d.\-\_\\\/\+]+)\s*(\((?P<locale>\%?)(?P<source>[\w\d.\-\_\\\/]+)\))?\s*$')
  90. def __init__(self, outputFormat = 'flat', useJarfileManifest = True,
  91. useChromeManifest = False):
  92. self.outputFormat = outputFormat
  93. self.useJarfileManifest = useJarfileManifest
  94. self.useChromeManifest = useChromeManifest
  95. self.pp = Preprocessor()
  96. def getCommandLineParser(self):
  97. '''Get a optparse.OptionParser for jarmaker.
  98. This OptionParser has the options for jarmaker as well as
  99. the options for the inner PreProcessor.
  100. '''
  101. # HACK, we need to unescape the string variables we get,
  102. # the perl versions didn't grok strings right
  103. p = self.pp.getCommandLineParser(unescapeDefines = True)
  104. p.add_option('-f', type="choice", default="jar",
  105. choices=('jar', 'flat', 'symlink'),
  106. help="fileformat used for output", metavar="[jar, flat, symlink]")
  107. p.add_option('-v', action="store_true", dest="verbose",
  108. help="verbose output")
  109. p.add_option('-q', action="store_false", dest="verbose",
  110. help="verbose output")
  111. p.add_option('-e', action="store_true",
  112. help="create chrome.manifest instead of jarfile.manifest")
  113. p.add_option('--both-manifests', action="store_true",
  114. dest="bothManifests",
  115. help="create chrome.manifest and jarfile.manifest")
  116. p.add_option('-s', type="string", action="append", default=[],
  117. help="source directory")
  118. p.add_option('-t', type="string",
  119. help="top source directory")
  120. p.add_option('-c', '--l10n-src', type="string", action="append",
  121. help="localization directory")
  122. p.add_option('--l10n-base', type="string", action="append", default=[],
  123. help="base directory to be used for localization (multiple)")
  124. p.add_option('-j', type="string",
  125. help="jarfile directory")
  126. # backwards compat, not needed
  127. p.add_option('-a', action="store_false", default=True,
  128. help="NOT SUPPORTED, turn auto-registration of chrome off (installed-chrome.txt)")
  129. p.add_option('-d', type="string",
  130. help="UNUSED, chrome directory")
  131. p.add_option('-o', help="cross compile for auto-registration, ignored")
  132. p.add_option('-l', action="store_true",
  133. help="ignored (used to switch off locks)")
  134. p.add_option('-x', action="store_true",
  135. help="force Unix")
  136. p.add_option('-z', help="backwards compat, ignored")
  137. p.add_option('-p', help="backwards compat, ignored")
  138. return p
  139. def processIncludes(self, includes):
  140. '''Process given includes with the inner PreProcessor.
  141. Only use this for #defines, the includes shouldn't generate
  142. content.
  143. '''
  144. self.pp.out = StringIO()
  145. for inc in includes:
  146. self.pp.do_include(inc)
  147. includesvalue = self.pp.out.getvalue()
  148. if includesvalue:
  149. logging.info("WARNING: Includes produce non-empty output")
  150. self.pp.out = None
  151. pass
  152. def finalizeJar(self, jarPath, chromebasepath, register,
  153. doZip=True):
  154. '''Helper method to write out the chrome registration entries to
  155. jarfile.manifest or chrome.manifest, or both.
  156. The actual file processing is done in updateManifest.
  157. '''
  158. # rewrite the manifest, if entries given
  159. if not register:
  160. return
  161. chromeManifest = os.path.join(os.path.dirname(jarPath),
  162. '..', 'chrome.manifest')
  163. if self.useJarfileManifest:
  164. self.updateManifest(jarPath + '.manifest', chromebasepath % '',
  165. register)
  166. addEntriesToListFile(chromeManifest, ['manifest chrome/%s.manifest' % (os.path.basename(jarPath),)])
  167. if self.useChromeManifest:
  168. self.updateManifest(chromeManifest, chromebasepath % 'chrome/',
  169. register)
  170. def updateManifest(self, manifestPath, chromebasepath, register):
  171. '''updateManifest replaces the % in the chrome registration entries
  172. with the given chrome base path, and updates the given manifest file.
  173. '''
  174. lock = lockFile(manifestPath + '.lck')
  175. try:
  176. myregister = dict.fromkeys(map(lambda s: s.replace('%', chromebasepath),
  177. register.iterkeys()))
  178. manifestExists = os.path.isfile(manifestPath)
  179. mode = (manifestExists and 'r+b') or 'wb'
  180. mf = open(manifestPath, mode)
  181. if manifestExists:
  182. # import previous content into hash, ignoring empty ones and comments
  183. imf = re.compile('(#.*)?$')
  184. for l in re.split('[\r\n]+', mf.read()):
  185. if imf.match(l):
  186. continue
  187. myregister[l] = None
  188. mf.seek(0)
  189. for k in myregister.iterkeys():
  190. mf.write(k + os.linesep)
  191. mf.close()
  192. finally:
  193. lock = None
  194. def makeJar(self, infile=None,
  195. jardir='',
  196. sourcedirs=[], topsourcedir='', localedirs=None):
  197. '''makeJar is the main entry point to JarMaker.
  198. It takes the input file, the output directory, the source dirs and the
  199. top source dir as argument, and optionally the l10n dirs.
  200. '''
  201. if isinstance(infile, basestring):
  202. logging.info("processing " + infile)
  203. pp = self.pp.clone()
  204. pp.out = StringIO()
  205. pp.do_include(infile)
  206. lines = pushback_iter(pp.out.getvalue().splitlines())
  207. try:
  208. while True:
  209. l = lines.next()
  210. m = self.jarline.match(l)
  211. if not m:
  212. raise RuntimeError(l)
  213. if m.group('jarfile') is None:
  214. # comment
  215. continue
  216. self.processJarSection(m.group('jarfile'), lines,
  217. jardir, sourcedirs, topsourcedir,
  218. localedirs)
  219. except StopIteration:
  220. # we read the file
  221. pass
  222. return
  223. def makeJars(self, infiles, l10nbases,
  224. jardir='',
  225. sourcedirs=[], topsourcedir='', localedirs=None):
  226. '''makeJars is the second main entry point to JarMaker.
  227. It takes an iterable sequence of input file names, the l10nbases,
  228. the output directory, the source dirs and the
  229. top source dir as argument, and optionally the l10n dirs.
  230. It iterates over all inputs, guesses srcdir and l10ndir from the
  231. path and topsourcedir and calls into makeJar.
  232. The l10ndirs are created by guessing the relativesrcdir, and resolving
  233. that against the l10nbases. l10nbases can either be path strings, or
  234. callables. In the latter case, that will be called with the
  235. relativesrcdir as argument, and is expected to return a path string.
  236. This logic is disabled if the jar.mn path is not inside the topsrcdir.
  237. '''
  238. topsourcedir = os.path.normpath(os.path.abspath(topsourcedir))
  239. def resolveL10nBase(relpath):
  240. def _resolve(base):
  241. if isinstance(base, basestring):
  242. return os.path.join(base, relpath)
  243. if callable(base):
  244. return base(relpath)
  245. return base
  246. return _resolve
  247. for infile in infiles:
  248. srcdir = os.path.normpath(os.path.abspath(os.path.dirname(infile)))
  249. l10ndir = srcdir
  250. if os.path.basename(srcdir) == 'locales':
  251. l10ndir = os.path.dirname(l10ndir)
  252. l10ndirs = None
  253. # srcdir may not be a child of topsourcedir, in which case
  254. # we assume that the caller passed in suitable sourcedirs,
  255. # and just skip passing in localedirs
  256. if srcdir.startswith(topsourcedir):
  257. rell10ndir = l10ndir[len(topsourcedir):].lstrip(os.sep)
  258. l10ndirs = map(resolveL10nBase(rell10ndir), l10nbases)
  259. if localedirs is not None:
  260. l10ndirs += [os.path.normpath(os.path.abspath(s))
  261. for s in localedirs]
  262. srcdirs = [os.path.normpath(os.path.abspath(s))
  263. for s in sourcedirs] + [srcdir]
  264. self.makeJar(infile=infile,
  265. sourcedirs=srcdirs, topsourcedir=topsourcedir,
  266. localedirs=l10ndirs,
  267. jardir=jardir)
  268. def processJarSection(self, jarfile, lines,
  269. jardir, sourcedirs, topsourcedir, localedirs):
  270. '''Internal method called by makeJar to actually process a section
  271. of a jar.mn file.
  272. jarfile is the basename of the jarfile or the directory name for
  273. flat output, lines is a pushback_iterator of the lines of jar.mn,
  274. the remaining options are carried over from makeJar.
  275. '''
  276. # chromebasepath is used for chrome registration manifests
  277. # %s is getting replaced with chrome/ for chrome.manifest, and with
  278. # an empty string for jarfile.manifest
  279. chromebasepath = '%s' + jarfile
  280. if self.outputFormat == 'jar':
  281. chromebasepath = 'jar:' + chromebasepath + '.jar!'
  282. chromebasepath += '/'
  283. jarfile = os.path.join(jardir, jarfile)
  284. jf = None
  285. if self.outputFormat == 'jar':
  286. #jar
  287. jarfilepath = jarfile + '.jar'
  288. try:
  289. os.makedirs(os.path.dirname(jarfilepath))
  290. except OSError:
  291. pass
  292. jf = ZipFile(jarfilepath, 'a', lock = True)
  293. outHelper = self.OutputHelper_jar(jf)
  294. else:
  295. outHelper = getattr(self, 'OutputHelper_' + self.outputFormat)(jarfile)
  296. register = {}
  297. # This loop exits on either
  298. # - the end of the jar.mn file
  299. # - an line in the jar.mn file that's not part of a jar section
  300. # - on an exception raised, close the jf in that case in a finally
  301. try:
  302. while True:
  303. try:
  304. l = lines.next()
  305. except StopIteration:
  306. # we're done with this jar.mn, and this jar section
  307. self.finalizeJar(jarfile, chromebasepath, register)
  308. if jf is not None:
  309. jf.close()
  310. # reraise the StopIteration for makeJar
  311. raise
  312. if self.ignore.match(l):
  313. continue
  314. m = self.regline.match(l)
  315. if m:
  316. rline = m.group(1)
  317. register[rline] = 1
  318. continue
  319. m = self.entryline.match(l)
  320. if not m:
  321. # neither an entry line nor chrome reg, this jar section is done
  322. self.finalizeJar(jarfile, chromebasepath, register)
  323. if jf is not None:
  324. jf.close()
  325. lines.pushback(l)
  326. return
  327. self._processEntryLine(m, sourcedirs, topsourcedir, localedirs,
  328. outHelper, jf)
  329. finally:
  330. if jf is not None:
  331. jf.close()
  332. return
  333. def _processEntryLine(self, m,
  334. sourcedirs, topsourcedir, localedirs,
  335. outHelper, jf):
  336. out = m.group('output')
  337. src = m.group('source') or os.path.basename(out)
  338. # pick the right sourcedir -- l10n, topsrc or src
  339. if m.group('locale'):
  340. src_base = localedirs
  341. elif src.startswith('/'):
  342. # path/in/jar/file_name.xul (/path/in/sourcetree/file_name.xul)
  343. # refers to a path relative to topsourcedir, use that as base
  344. # and strip the leading '/'
  345. src_base = [topsourcedir]
  346. src = src[1:]
  347. else:
  348. # use srcdirs and the objdir (current working dir) for relative paths
  349. src_base = sourcedirs + [os.getcwd()]
  350. # check if the source file exists
  351. realsrc = None
  352. for _srcdir in src_base:
  353. if os.path.isfile(os.path.join(_srcdir, src)):
  354. realsrc = os.path.join(_srcdir, src)
  355. break
  356. if realsrc is None:
  357. if jf is not None:
  358. jf.close()
  359. raise RuntimeError('File "%s" not found in %s' % (src, ', '.join(src_base)))
  360. if m.group('optPreprocess'):
  361. outf = outHelper.getOutput(out)
  362. inf = open(realsrc)
  363. pp = self.pp.clone()
  364. if src[-4:] == '.css':
  365. pp.setMarker('%')
  366. pp.out = outf
  367. pp.do_include(inf)
  368. outf.close()
  369. inf.close()
  370. return
  371. # copy or symlink if newer or overwrite
  372. if (m.group('optOverwrite')
  373. or (getModTime(realsrc) >
  374. outHelper.getDestModTime(m.group('output')))):
  375. if self.outputFormat == 'symlink':
  376. outHelper.symlink(realsrc, out)
  377. return
  378. outf = outHelper.getOutput(out)
  379. # open in binary mode, this can be images etc
  380. inf = open(realsrc, 'rb')
  381. outf.write(inf.read())
  382. outf.close()
  383. inf.close()
  384. class OutputHelper_jar(object):
  385. '''Provide getDestModTime and getOutput for a given jarfile.
  386. '''
  387. def __init__(self, jarfile):
  388. self.jarfile = jarfile
  389. def getDestModTime(self, aPath):
  390. try :
  391. info = self.jarfile.getinfo(aPath)
  392. return info.date_time
  393. except:
  394. return 0
  395. def getOutput(self, name):
  396. return ZipEntry(name, self.jarfile)
  397. class OutputHelper_flat(object):
  398. '''Provide getDestModTime and getOutput for a given flat
  399. output directory. The helper method ensureDirFor is used by
  400. the symlink subclass.
  401. '''
  402. def __init__(self, basepath):
  403. self.basepath = basepath
  404. def getDestModTime(self, aPath):
  405. return getModTime(os.path.join(self.basepath, aPath))
  406. def getOutput(self, name):
  407. out = self.ensureDirFor(name)
  408. # remove previous link or file
  409. try:
  410. os.remove(out)
  411. except OSError, e:
  412. if e.errno != errno.ENOENT:
  413. raise
  414. return open(out, 'wb')
  415. def ensureDirFor(self, name):
  416. out = os.path.join(self.basepath, name)
  417. outdir = os.path.dirname(out)
  418. if not os.path.isdir(outdir):
  419. os.makedirs(outdir)
  420. return out
  421. class OutputHelper_symlink(OutputHelper_flat):
  422. '''Subclass of OutputHelper_flat that provides a helper for
  423. creating a symlink including creating the parent directories.
  424. '''
  425. def symlink(self, src, dest):
  426. out = self.ensureDirFor(dest)
  427. # remove previous link or file
  428. try:
  429. os.remove(out)
  430. except OSError, e:
  431. if e.errno != errno.ENOENT:
  432. raise
  433. if sys.platform != "win32":
  434. os.symlink(src, out)
  435. else:
  436. # On Win32, use ctypes to create a hardlink
  437. rv = CreateHardLink(out, src, None)
  438. if rv == 0:
  439. raise WinError()
  440. def main():
  441. jm = JarMaker()
  442. p = jm.getCommandLineParser()
  443. (options, args) = p.parse_args()
  444. jm.processIncludes(options.I)
  445. jm.outputFormat = options.f
  446. if options.e:
  447. jm.useChromeManifest = True
  448. jm.useJarfileManifest = False
  449. if options.bothManifests:
  450. jm.useChromeManifest = True
  451. jm.useJarfileManifest = True
  452. noise = logging.INFO
  453. if options.verbose is not None:
  454. noise = (options.verbose and logging.DEBUG) or logging.WARN
  455. if sys.version_info[:2] > (2,3):
  456. logging.basicConfig(format = "%(message)s")
  457. else:
  458. logging.basicConfig()
  459. logging.getLogger().setLevel(noise)
  460. topsrc = options.t
  461. topsrc = os.path.normpath(os.path.abspath(topsrc))
  462. if not args:
  463. jm.makeJar(infile=sys.stdin,
  464. sourcedirs=options.s, topsourcedir=topsrc,
  465. localedirs=options.l10n_src,
  466. jardir=options.j)
  467. else:
  468. jm.makeJars(args, options.l10n_base,
  469. jardir=options.j,
  470. sourcedirs=options.s, topsourcedir=topsrc,
  471. localedirs=options.l10n_src)
  472. if __name__ == "__main__":
  473. main()