summaryrefslogtreecommitdiffstats
path: root/build/print_python_deps.py
blob: da83684dd21336043ff903d517e75c47beaee90f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Prints all non-system dependencies for the given module.

The primary use-case for this script is to genererate the list of python modules
required for .isolate files.
"""

import argparse
import imp
import os
import pipes
import sys

# Don't use any helper modules, or else they will end up in the results.


_SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))


def ComputePythonDependencies(root):
  """Gets the paths of imported non-system python modules.

  A path is assumed to be a "system" import if it is outside of chromium's
  src/. The paths will be relative to the current directory.
  """
  module_paths = (m.__file__ for m in sys.modules.values()
                  if m and hasattr(m, '__file__'))

  src_paths = set()
  for path in module_paths:
    if path == __file__:
      continue
    path = os.path.abspath(path)
    if not path.startswith(_SRC_ROOT):
      continue

    if path.endswith('.pyc'):
      path = path[:-1]
    src_paths.add(os.path.relpath(path, root))

  return sorted(src_paths)


def main():
  parser = argparse.ArgumentParser(
      description='Prints all non-system dependencies for the given module.')
  parser.add_argument('module',
                      help='The python module to analyze.')
  parser.add_argument('--root', default='.',
                      help='Directory to make paths relative to.')
  parser.add_argument('--output',
                      help='Write output to a file rather than stdout.')
  options = parser.parse_args()
  sys.path.append(os.path.dirname(options.module))
  imp.load_source('NAME', options.module)
  out = open(options.output, 'w') if options.output else sys.stdout
  with out:
    out.write('# Generated by //build/print_python_deps.py\n')
    out.write('# root: //%s\n' % os.path.relpath(options.root, _SRC_ROOT))
    out.write('# target: //%s\n' % os.path.relpath(options.module, _SRC_ROOT))
    for path in ComputePythonDependencies(options.root):
      out.write(path + '\n')


if __name__ == '__main__':
  sys.exit(main())