calcdeps.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2006 The Closure Library Authors. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS-IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Calculates JavaScript dependencies without requiring Google's build system.
  17. This tool is deprecated and is provided for legacy users.
  18. See build/closurebuilder.py and build/depswriter.py for the current tools.
  19. It iterates over a number of search paths and builds a dependency tree. With
  20. the inputs provided, it walks the dependency tree and outputs all the files
  21. required for compilation.
  22. """
  23. try:
  24. import distutils.version
  25. except ImportError:
  26. # distutils is not available in all environments
  27. distutils = None
  28. import logging
  29. import optparse
  30. import os
  31. import re
  32. import subprocess
  33. import sys
  34. _BASE_REGEX_STRING = '^\s*goog\.%s\(\s*[\'"](.+)[\'"]\s*\)'
  35. req_regex = re.compile(_BASE_REGEX_STRING % 'require')
  36. prov_regex = re.compile(_BASE_REGEX_STRING % 'provide')
  37. ns_regex = re.compile('^ns:((\w+\.)*(\w+))$')
  38. version_regex = re.compile('[\.0-9]+')
  39. def IsValidFile(ref):
  40. """Returns true if the provided reference is a file and exists."""
  41. return os.path.isfile(ref)
  42. def IsJsFile(ref):
  43. """Returns true if the provided reference is a Javascript file."""
  44. return ref.endswith('.js')
  45. def IsNamespace(ref):
  46. """Returns true if the provided reference is a namespace."""
  47. return re.match(ns_regex, ref) is not None
  48. def IsDirectory(ref):
  49. """Returns true if the provided reference is a directory."""
  50. return os.path.isdir(ref)
  51. def ExpandDirectories(refs):
  52. """Expands any directory references into inputs.
  53. Description:
  54. Looks for any directories in the provided references. Found directories
  55. are recursively searched for .js files, which are then added to the result
  56. list.
  57. Args:
  58. refs: a list of references such as files, directories, and namespaces
  59. Returns:
  60. A list of references with directories removed and replaced by any
  61. .js files that are found in them. Also, the paths will be normalized.
  62. """
  63. result = []
  64. for ref in refs:
  65. if IsDirectory(ref):
  66. # Disable 'Unused variable' for subdirs
  67. # pylint: disable=unused-variable
  68. for (directory, subdirs, filenames) in os.walk(ref):
  69. for filename in filenames:
  70. if IsJsFile(filename):
  71. result.append(os.path.join(directory, filename))
  72. else:
  73. result.append(ref)
  74. return map(os.path.normpath, result)
  75. class DependencyInfo(object):
  76. """Represents a dependency that is used to build and walk a tree."""
  77. def __init__(self, filename):
  78. self.filename = filename
  79. self.provides = []
  80. self.requires = []
  81. def __str__(self):
  82. return '%s Provides: %s Requires: %s' % (self.filename,
  83. repr(self.provides),
  84. repr(self.requires))
  85. def BuildDependenciesFromFiles(files):
  86. """Build a list of dependencies from a list of files.
  87. Description:
  88. Takes a list of files, extracts their provides and requires, and builds
  89. out a list of dependency objects.
  90. Args:
  91. files: a list of files to be parsed for goog.provides and goog.requires.
  92. Returns:
  93. A list of dependency objects, one for each file in the files argument.
  94. """
  95. result = []
  96. filenames = set()
  97. for filename in files:
  98. if filename in filenames:
  99. continue
  100. # Python 3 requires the file encoding to be specified
  101. if (sys.version_info[0] < 3):
  102. file_handle = open(filename, 'r')
  103. else:
  104. file_handle = open(filename, 'r', encoding='utf8')
  105. try:
  106. dep = CreateDependencyInfo(filename, file_handle)
  107. result.append(dep)
  108. finally:
  109. file_handle.close()
  110. filenames.add(filename)
  111. return result
  112. def CreateDependencyInfo(filename, source):
  113. """Create dependency info.
  114. Args:
  115. filename: Filename for source.
  116. source: File-like object containing source.
  117. Returns:
  118. A DependencyInfo object with provides and requires filled.
  119. """
  120. dep = DependencyInfo(filename)
  121. for line in source:
  122. if re.match(req_regex, line):
  123. dep.requires.append(re.search(req_regex, line).group(1))
  124. if re.match(prov_regex, line):
  125. dep.provides.append(re.search(prov_regex, line).group(1))
  126. return dep
  127. def BuildDependencyHashFromDependencies(deps):
  128. """Builds a hash for searching dependencies by the namespaces they provide.
  129. Description:
  130. Dependency objects can provide multiple namespaces. This method enumerates
  131. the provides of each dependency and adds them to a hash that can be used
  132. to easily resolve a given dependency by a namespace it provides.
  133. Args:
  134. deps: a list of dependency objects used to build the hash.
  135. Raises:
  136. Exception: If a multiple files try to provide the same namepace.
  137. Returns:
  138. A hash table { namespace: dependency } that can be used to resolve a
  139. dependency by a namespace it provides.
  140. """
  141. dep_hash = {}
  142. for dep in deps:
  143. for provide in dep.provides:
  144. if provide in dep_hash:
  145. raise Exception('Duplicate provide (%s) in (%s, %s)' % (
  146. provide,
  147. dep_hash[provide].filename,
  148. dep.filename))
  149. dep_hash[provide] = dep
  150. return dep_hash
  151. def CalculateDependencies(paths, inputs):
  152. """Calculates the dependencies for given inputs.
  153. Description:
  154. This method takes a list of paths (files, directories) and builds a
  155. searchable data structure based on the namespaces that each .js file
  156. provides. It then parses through each input, resolving dependencies
  157. against this data structure. The final output is a list of files,
  158. including the inputs, that represent all of the code that is needed to
  159. compile the given inputs.
  160. Args:
  161. paths: the references (files, directories) that are used to build the
  162. dependency hash.
  163. inputs: the inputs (files, directories, namespaces) that have dependencies
  164. that need to be calculated.
  165. Raises:
  166. Exception: if a provided input is invalid.
  167. Returns:
  168. A list of all files, including inputs, that are needed to compile the given
  169. inputs.
  170. """
  171. deps = BuildDependenciesFromFiles(paths + inputs)
  172. search_hash = BuildDependencyHashFromDependencies(deps)
  173. result_list = []
  174. seen_list = []
  175. for input_file in inputs:
  176. if IsNamespace(input_file):
  177. namespace = re.search(ns_regex, input_file).group(1)
  178. if namespace not in search_hash:
  179. raise Exception('Invalid namespace (%s)' % namespace)
  180. input_file = search_hash[namespace].filename
  181. if not IsValidFile(input_file) or not IsJsFile(input_file):
  182. raise Exception('Invalid file (%s)' % input_file)
  183. seen_list.append(input_file)
  184. file_handle = open(input_file, 'r')
  185. try:
  186. for line in file_handle:
  187. if re.match(req_regex, line):
  188. require = re.search(req_regex, line).group(1)
  189. ResolveDependencies(require, search_hash, result_list, seen_list)
  190. finally:
  191. file_handle.close()
  192. result_list.append(input_file)
  193. # All files depend on base.js, so put it first.
  194. base_js_path = FindClosureBasePath(paths)
  195. if base_js_path:
  196. result_list.insert(0, base_js_path)
  197. else:
  198. logging.warning('Closure Library base.js not found.')
  199. return result_list
  200. def FindClosureBasePath(paths):
  201. """Given a list of file paths, return Closure base.js path, if any.
  202. Args:
  203. paths: A list of paths.
  204. Returns:
  205. The path to Closure's base.js file including filename, if found.
  206. """
  207. for path in paths:
  208. pathname, filename = os.path.split(path)
  209. if filename == 'base.js':
  210. f = open(path)
  211. is_base = False
  212. # Sanity check that this is the Closure base file. Check that this
  213. # is where goog is defined. This is determined by the @provideGoog
  214. # flag.
  215. for line in f:
  216. if '@provideGoog' in line:
  217. is_base = True
  218. break
  219. f.close()
  220. if is_base:
  221. return path
  222. def ResolveDependencies(require, search_hash, result_list, seen_list):
  223. """Takes a given requirement and resolves all of the dependencies for it.
  224. Description:
  225. A given requirement may require other dependencies. This method
  226. recursively resolves all dependencies for the given requirement.
  227. Raises:
  228. Exception: when require does not exist in the search_hash.
  229. Args:
  230. require: the namespace to resolve dependencies for.
  231. search_hash: the data structure used for resolving dependencies.
  232. result_list: a list of filenames that have been calculated as dependencies.
  233. This variable is the output for this function.
  234. seen_list: a list of filenames that have been 'seen'. This is required
  235. for the dependency->dependent ordering.
  236. """
  237. if require not in search_hash:
  238. raise Exception('Missing provider for (%s)' % require)
  239. dep = search_hash[require]
  240. if not dep.filename in seen_list:
  241. seen_list.append(dep.filename)
  242. for sub_require in dep.requires:
  243. ResolveDependencies(sub_require, search_hash, result_list, seen_list)
  244. result_list.append(dep.filename)
  245. def GetDepsLine(dep, base_path):
  246. """Returns a JS string for a dependency statement in the deps.js file.
  247. Args:
  248. dep: The dependency that we're printing.
  249. base_path: The path to Closure's base.js including filename.
  250. """
  251. return 'goog.addDependency("%s", %s, %s);' % (
  252. GetRelpath(dep.filename, base_path), dep.provides, dep.requires)
  253. def GetRelpath(path, start):
  254. """Return a relative path to |path| from |start|."""
  255. # NOTE: Python 2.6 provides os.path.relpath, which has almost the same
  256. # functionality as this function. Since we want to support 2.4, we have
  257. # to implement it manually. :(
  258. path_list = os.path.abspath(os.path.normpath(path)).split(os.sep)
  259. start_list = os.path.abspath(
  260. os.path.normpath(os.path.dirname(start))).split(os.sep)
  261. common_prefix_count = 0
  262. for i in range(0, min(len(path_list), len(start_list))):
  263. if path_list[i] != start_list[i]:
  264. break
  265. common_prefix_count += 1
  266. # Always use forward slashes, because this will get expanded to a url,
  267. # not a file path.
  268. return '/'.join(['..'] * (len(start_list) - common_prefix_count) +
  269. path_list[common_prefix_count:])
  270. def PrintLine(msg, out):
  271. out.write(msg)
  272. out.write('\n')
  273. def PrintDeps(source_paths, deps, out):
  274. """Print out a deps.js file from a list of source paths.
  275. Args:
  276. source_paths: Paths that we should generate dependency info for.
  277. deps: Paths that provide dependency info. Their dependency info should
  278. not appear in the deps file.
  279. out: The output file.
  280. Returns:
  281. True on success, false if it was unable to find the base path
  282. to generate deps relative to.
  283. """
  284. base_path = FindClosureBasePath(source_paths + deps)
  285. if not base_path:
  286. return False
  287. PrintLine('// This file was autogenerated by calcdeps.py', out)
  288. excludesSet = set(deps)
  289. for dep in BuildDependenciesFromFiles(source_paths + deps):
  290. if not dep.filename in excludesSet:
  291. PrintLine(GetDepsLine(dep, base_path), out)
  292. return True
  293. def PrintScript(source_paths, out):
  294. for index, dep in enumerate(source_paths):
  295. PrintLine('// Input %d' % index, out)
  296. f = open(dep, 'r')
  297. PrintLine(f.read(), out)
  298. f.close()
  299. def GetJavaVersion():
  300. """Returns the string for the current version of Java installed."""
  301. proc = subprocess.Popen(['java', '-version'], stderr=subprocess.PIPE)
  302. proc.wait()
  303. version_line = proc.stderr.read().splitlines()[0]
  304. return version_regex.search(version_line.decode('utf-8')).group()
  305. def FilterByExcludes(options, files):
  306. """Filters the given files by the exlusions specified at the command line.
  307. Args:
  308. options: The flags to calcdeps.
  309. files: The files to filter.
  310. Returns:
  311. A list of files.
  312. """
  313. excludes = []
  314. if options.excludes:
  315. excludes = ExpandDirectories(options.excludes)
  316. excludesSet = set(excludes)
  317. return [i for i in files if not i in excludesSet]
  318. def GetPathsFromOptions(options):
  319. """Generates the path files from flag options.
  320. Args:
  321. options: The flags to calcdeps.
  322. Returns:
  323. A list of files in the specified paths. (strings).
  324. """
  325. search_paths = options.paths
  326. if not search_paths:
  327. search_paths = ['.'] # Add default folder if no path is specified.
  328. search_paths = ExpandDirectories(search_paths)
  329. return FilterByExcludes(options, search_paths)
  330. def GetInputsFromOptions(options):
  331. """Generates the inputs from flag options.
  332. Args:
  333. options: The flags to calcdeps.
  334. Returns:
  335. A list of inputs (strings).
  336. """
  337. inputs = options.inputs
  338. if not inputs: # Parse stdin
  339. logging.info('No inputs specified. Reading from stdin...')
  340. inputs = filter(None, [line.strip('\n') for line in sys.stdin.readlines()])
  341. logging.info('Scanning files...')
  342. inputs = ExpandDirectories(inputs)
  343. return FilterByExcludes(options, inputs)
  344. def Compile(compiler_jar_path, source_paths, out, flags=None):
  345. """Prepares command-line call to Closure compiler.
  346. Args:
  347. compiler_jar_path: Path to the Closure compiler .jar file.
  348. source_paths: Source paths to build, in order.
  349. flags: A list of additional flags to pass on to Closure compiler.
  350. """
  351. args = ['java', '-jar', compiler_jar_path]
  352. for path in source_paths:
  353. args += ['--js', path]
  354. if flags:
  355. args += flags
  356. logging.info('Compiling with the following command: %s', ' '.join(args))
  357. proc = subprocess.Popen(args, stdout=subprocess.PIPE)
  358. (stdoutdata, stderrdata) = proc.communicate()
  359. if proc.returncode != 0:
  360. logging.error('JavaScript compilation failed.')
  361. sys.exit(1)
  362. else:
  363. out.write(stdoutdata.decode('utf-8'))
  364. def main():
  365. """The entrypoint for this script."""
  366. logging.basicConfig(format='calcdeps.py: %(message)s', level=logging.INFO)
  367. usage = 'usage: %prog [options] arg'
  368. parser = optparse.OptionParser(usage)
  369. parser.add_option('-i',
  370. '--input',
  371. dest='inputs',
  372. action='append',
  373. help='The inputs to calculate dependencies for. Valid '
  374. 'values can be files, directories, or namespaces '
  375. '(ns:goog.net.XhrIo). Only relevant to "list" and '
  376. '"script" output.')
  377. parser.add_option('-p',
  378. '--path',
  379. dest='paths',
  380. action='append',
  381. help='The paths that should be traversed to build the '
  382. 'dependencies.')
  383. parser.add_option('-d',
  384. '--dep',
  385. dest='deps',
  386. action='append',
  387. help='Directories or files that should be traversed to '
  388. 'find required dependencies for the deps file. '
  389. 'Does not generate dependency information for names '
  390. 'provided by these files. Only useful in "deps" mode.')
  391. parser.add_option('-e',
  392. '--exclude',
  393. dest='excludes',
  394. action='append',
  395. help='Files or directories to exclude from the --path '
  396. 'and --input flags')
  397. parser.add_option('-o',
  398. '--output_mode',
  399. dest='output_mode',
  400. action='store',
  401. default='list',
  402. help='The type of output to generate from this script. '
  403. 'Options are "list" for a list of filenames, "script" '
  404. 'for a single script containing the contents of all the '
  405. 'file, "deps" to generate a deps.js file for all '
  406. 'paths, or "compiled" to produce compiled output with '
  407. 'the Closure compiler.')
  408. parser.add_option('-c',
  409. '--compiler_jar',
  410. dest='compiler_jar',
  411. action='store',
  412. help='The location of the Closure compiler .jar file.')
  413. parser.add_option('-f',
  414. '--compiler_flag',
  415. '--compiler_flags', # for backwards compatibility
  416. dest='compiler_flags',
  417. action='append',
  418. help='Additional flag to pass to the Closure compiler. '
  419. 'May be specified multiple times to pass multiple flags.')
  420. parser.add_option('--output_file',
  421. dest='output_file',
  422. action='store',
  423. help=('If specified, write output to this path instead of '
  424. 'writing to standard output.'))
  425. (options, args) = parser.parse_args()
  426. search_paths = GetPathsFromOptions(options)
  427. if options.output_file:
  428. out = open(options.output_file, 'w')
  429. else:
  430. out = sys.stdout
  431. if options.output_mode == 'deps':
  432. result = PrintDeps(search_paths, ExpandDirectories(options.deps or []), out)
  433. if not result:
  434. logging.error('Could not find Closure Library in the specified paths')
  435. sys.exit(1)
  436. return
  437. inputs = GetInputsFromOptions(options)
  438. logging.info('Finding Closure dependencies...')
  439. deps = CalculateDependencies(search_paths, inputs)
  440. output_mode = options.output_mode
  441. if output_mode == 'script':
  442. PrintScript(deps, out)
  443. elif output_mode == 'list':
  444. # Just print out a dep per line
  445. for dep in deps:
  446. PrintLine(dep, out)
  447. elif output_mode == 'compiled':
  448. # Make sure a .jar is specified.
  449. if not options.compiler_jar:
  450. logging.error('--compiler_jar flag must be specified if --output is '
  451. '"compiled"')
  452. sys.exit(1)
  453. # User friendly version check.
  454. if distutils and not (distutils.version.LooseVersion(GetJavaVersion()) >
  455. distutils.version.LooseVersion('1.6')):
  456. logging.error('Closure Compiler requires Java 1.6 or higher.')
  457. logging.error('Please visit http://www.java.com/getjava')
  458. sys.exit(1)
  459. Compile(options.compiler_jar, deps, out, options.compiler_flags)
  460. else:
  461. logging.error('Invalid value for --output flag.')
  462. sys.exit(1)
  463. if __name__ == '__main__':
  464. main()