1 #!/usr/bin/env vpython3
2 # Copyright 2016 The Chromium Authors
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 """Prints all non-system dependencies for the given module.
8 The primary use-case for this script is to generate the list of python modules
9 required for .isolate files.
17 # Don't use any helper modules, or else they will end up in the results.
20 _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
23 def ComputePythonDependencies():
24 """Gets the paths of imported non-system python modules.
26 A path is assumed to be a "system" import if it is outside of chromium's
27 src/. The paths will be relative to the current directory.
29 module_paths = (m.__file__ for m in sys.modules.values()
30 if m and hasattr(m, '__file__') and m.__file__)
33 for path in module_paths:
36 path = os.path.abspath(path)
37 if not path.startswith(_SRC_ROOT):
40 if (path.endswith('.pyc')
41 or (path.endswith('c') and not os.path.splitext(path)[1])):
49 if string.count(' ') > 0:
50 return '"%s"' % string
55 def _NormalizeCommandLine(options):
56 """Returns a string that when run from SRC_ROOT replicates the command."""
57 args = ['build/print_python_deps.py']
58 root = os.path.relpath(options.root, _SRC_ROOT)
60 args.extend(('--root', root))
62 args.extend(('--output', os.path.relpath(options.output, _SRC_ROOT)))
64 args.extend(('--gn-paths',))
65 for allowlist in sorted(options.allowlists):
66 args.extend(('--allowlist', os.path.relpath(allowlist, _SRC_ROOT)))
67 args.append(os.path.relpath(options.module, _SRC_ROOT))
69 return ' '.join(quote(x) for x in args).replace('\\', '/')
71 return ' '.join(shlex.quote(x) for x in args)
74 def _FindPythonInDirectory(directory, allow_test):
75 """Returns an iterable of all non-test python files in the given directory."""
76 for root, _dirnames, filenames in os.walk(directory):
77 for filename in filenames:
78 if filename.endswith('.py') and (allow_test
79 or not filename.endswith('_test.py')):
80 yield os.path.join(root, filename)
83 def _ImportModuleByPath(module_path):
84 """Imports a module by its source file."""
85 # Replace the path entry for print_python_deps.py with the one for the given
87 sys.path[0] = os.path.dirname(module_path)
89 # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
90 module_name = os.path.splitext(os.path.basename(module_path))[0]
91 import importlib.util # Python 3 only, since it's unavailable in Python 2.
92 spec = importlib.util.spec_from_file_location(module_name, module_path)
93 module = importlib.util.module_from_spec(spec)
94 sys.modules[module_name] = module
95 spec.loader.exec_module(module)
99 parser = argparse.ArgumentParser(
100 description='Prints all non-system dependencies for the given module.')
101 parser.add_argument('module',
102 help='The python module to analyze.')
103 parser.add_argument('--root', default='.',
104 help='Directory to make paths relative to.')
105 parser.add_argument('--output',
106 help='Write output to a file rather than stdout.')
107 parser.add_argument('--inplace', action='store_true',
108 help='Write output to a file with the same path as the '
109 'module, but with a .pydeps extension. Also sets the '
110 'root to the module\'s directory.')
111 parser.add_argument('--no-header', action='store_true',
112 help='Do not write the "# Generated by" header.')
113 parser.add_argument('--gn-paths', action='store_true',
114 help='Write paths as //foo/bar/baz.py')
115 parser.add_argument('--did-relaunch', action='store_true',
116 help=argparse.SUPPRESS)
117 parser.add_argument('--allowlist',
121 help='Recursively include all non-test python files '
122 'within this directory. May be specified multiple times.')
123 options = parser.parse_args()
127 parser.error('Cannot use --inplace and --output at the same time!')
128 if not options.module.endswith('.py'):
129 parser.error('Input module path should end with .py suffix!')
130 options.output = options.module + 'deps'
131 options.root = os.path.dirname(options.module)
133 modules = [options.module]
134 if os.path.isdir(options.module):
135 modules = list(_FindPythonInDirectory(options.module, allow_test=True))
137 parser.error('Input directory does not contain any python files!')
139 is_vpython = 'vpython' in sys.executable
141 # Prevent infinite relaunch if something goes awry.
142 assert not options.did_relaunch
143 # Re-launch using vpython will cause us to pick up modules specified in
144 # //.vpython, but does not cause it to pick up modules defined inline via
145 # [VPYTHON:BEGIN] ... [VPYTHON:END] comments.
146 # TODO(agrieve): Add support for this if the need ever arises.
147 os.execvp('vpython3', ['vpython3'] + sys.argv + ['--did-relaunch'])
149 # Work-around for protobuf library not being loadable via importlib
150 # This is needed due to compile_resources.py.
151 import importlib._bootstrap_external
152 importlib._bootstrap_external._NamespacePath.sort = lambda self, **_: 0
156 for module in modules:
157 _ImportModuleByPath(module)
158 paths_set.update(ComputePythonDependencies())
160 # Output extra diagnostics when loading the script fails.
161 sys.stderr.write('Error running print_python_deps.py.\n')
162 sys.stderr.write('is_vpython={}\n'.format(is_vpython))
163 sys.stderr.write('did_relanuch={}\n'.format(options.did_relaunch))
164 sys.stderr.write('python={}\n'.format(sys.executable))
167 for path in options.allowlists:
170 for p in _FindPythonInDirectory(path, allow_test=False))
172 paths = [os.path.relpath(p, options.root) for p in paths_set]
174 normalized_cmdline = _NormalizeCommandLine(options)
175 out = open(options.output, 'w', newline='') if options.output else sys.stdout
177 if not options.no_header:
178 out.write('# Generated by running:\n')
179 out.write('# %s\n' % normalized_cmdline)
180 prefix = '//' if options.gn_paths else ''
181 for path in sorted(paths):
182 out.write(prefix + path.replace('\\', '/') + '\n')
185 if __name__ == '__main__':