Fix FullScreen crash in Webapp
[platform/framework/web/chromium-efl.git] / build / print_python_deps.py
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.
5
6 """Prints all non-system dependencies for the given module.
7
8 The primary use-case for this script is to generate the list of python modules
9 required for .isolate files.
10 """
11
12 import argparse
13 import os
14 import shlex
15 import sys
16
17 # Don't use any helper modules, or else they will end up in the results.
18
19
20 _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
21
22
23 def ComputePythonDependencies():
24   """Gets the paths of imported non-system python modules.
25
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.
28   """
29   module_paths = (m.__file__ for m in sys.modules.values()
30                   if m and hasattr(m, '__file__') and m.__file__)
31
32   src_paths = set()
33   for path in module_paths:
34     if path == __file__:
35       continue
36     path = os.path.abspath(path)
37     if not path.startswith(_SRC_ROOT):
38       continue
39
40     if (path.endswith('.pyc')
41         or (path.endswith('c') and not os.path.splitext(path)[1])):
42       path = path[:-1]
43     src_paths.add(path)
44
45   return src_paths
46
47
48 def quote(string):
49   if string.count(' ') > 0:
50     return '"%s"' % string
51   else:
52     return string
53
54
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)
59   if root != '.':
60     args.extend(('--root', root))
61   if options.output:
62     args.extend(('--output', os.path.relpath(options.output, _SRC_ROOT)))
63   if options.gn_paths:
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))
68   if os.name == 'nt':
69     return ' '.join(quote(x) for x in args).replace('\\', '/')
70   else:
71     return ' '.join(shlex.quote(x) for x in args)
72
73
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)
81
82
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
86   # module.
87   sys.path[0] = os.path.dirname(module_path)
88
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)
96
97
98 def main():
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',
118                       default=[],
119                       action='append',
120                       dest='allowlists',
121                       help='Recursively include all non-test python files '
122                       'within this directory. May be specified multiple times.')
123   options = parser.parse_args()
124
125   if options.inplace:
126     if options.output:
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)
132
133   modules = [options.module]
134   if os.path.isdir(options.module):
135     modules = list(_FindPythonInDirectory(options.module, allow_test=True))
136   if not modules:
137     parser.error('Input directory does not contain any python files!')
138
139   is_vpython = 'vpython' in sys.executable
140   if not is_vpython:
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'])
148
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
153
154   paths_set = set()
155   try:
156     for module in modules:
157       _ImportModuleByPath(module)
158       paths_set.update(ComputePythonDependencies())
159   except Exception:
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))
165     raise
166
167   for path in options.allowlists:
168     paths_set.update(
169         os.path.abspath(p)
170         for p in _FindPythonInDirectory(path, allow_test=False))
171
172   paths = [os.path.relpath(p, options.root) for p in paths_set]
173
174   normalized_cmdline = _NormalizeCommandLine(options)
175   out = open(options.output, 'w', newline='') if options.output else sys.stdout
176   with out:
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')
183
184
185 if __name__ == '__main__':
186   sys.exit(main())