2 # Copyright 2014 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
16 sys.path.append(os.path.join(
17 os.path.dirname(os.path.realpath(__file__)), os.pardir, 'telemetry'))
18 from telemetry import test
19 from telemetry.core import discover
20 from telemetry.core import util
21 from telemetry.page import cloud_storage
24 import telemetry_bootstrap
27 DEPS_FILE = 'bootstrap_deps'
30 def _InDirectory(subdirectory, directory):
31 subdirectory = os.path.realpath(subdirectory)
32 directory = os.path.realpath(directory)
33 common_prefix = os.path.commonprefix([subdirectory, directory])
34 return common_prefix == directory
37 def FindBootstrapDependencies(base_dir):
38 deps_file = os.path.join(base_dir, DEPS_FILE)
39 if not os.path.exists(deps_file):
41 deps_paths = telemetry_bootstrap.ListAllDepsPaths(deps_file)
43 os.path.realpath(os.path.join(util.GetChromiumSrcDir(), os.pardir, path))
44 for path in deps_paths)
47 def FindPythonDependencies(module_path):
48 logging.info('Finding Python dependencies of %s' % module_path)
50 # Load the module to inherit its sys.path modifications.
52 os.path.splitext(os.path.basename(module_path))[0], module_path)
54 # Analyze the module for its imports.
55 finder = modulefinder.ModuleFinder()
56 finder.run_script(module_path)
58 # Filter for only imports in Chromium.
59 for module in finder.modules.itervalues():
60 # If it's an __init__.py, module.__path__ gives the package's folder.
61 module_path = module.__path__[0] if module.__path__ else module.__file__
65 module_path = os.path.realpath(module_path)
66 if not _InDirectory(module_path, util.GetChromiumSrcDir()):
72 def FindPageSetDependencies(base_dir):
73 logging.info('Finding page sets in %s' % base_dir)
75 # Add base_dir to path so our imports relative to base_dir will work.
76 sys.path.append(base_dir)
77 tests = discover.DiscoverClasses(base_dir, base_dir, test.Test,
78 index_by_class_name=True)
80 for test_class in tests.itervalues():
81 test_obj = test_class()
83 # Ensure the test's default options are set if needed.
84 parser = optparse.OptionParser()
85 test_obj.AddTestCommandLineOptions(parser)
86 options = optparse.Values()
87 for k, v in parser.get_default_values().__dict__.iteritems():
88 options.ensure_value(k, v)
90 # Page set paths are relative to their runner script, not relative to us.
91 util.GetBaseDir = lambda: base_dir
92 # TODO: Loading the page set will automatically download its Cloud Storage
93 # deps. This is really expensive, and we don't want to do this by default.
94 page_set = test_obj.CreatePageSet(options)
96 # Add all of its serving_dirs as dependencies.
97 for serving_dir in page_set.serving_dirs:
101 yield page.serving_dir
104 def FindExcludedFiles(files, options):
105 def MatchesConditions(path, conditions):
106 for condition in conditions:
111 # Define some filters for files.
113 for pathname_component in path.split(os.sep):
114 if pathname_component.startswith('.'):
118 return os.path.splitext(path)[1] == '.pyc'
119 def IsInCloudStorage(path):
120 return os.path.exists(path + '.sha1')
121 def MatchesExcludeOptions(path):
122 for pattern in options.exclude:
123 if (fnmatch.fnmatch(path, pattern) or
124 fnmatch.fnmatch(os.path.basename(path), pattern)):
128 # Collect filters we're going to use to exclude files.
129 exclude_conditions = [
133 MatchesExcludeOptions,
136 # Check all the files against the filters.
138 if MatchesConditions(path, exclude_conditions):
142 def FindDependencies(paths, options):
145 if not os.path.exists(path):
146 raise ValueError('Path does not exist: %s' % path)
148 dependencies = path_set.PathSet()
150 # Including this file will include Telemetry and its dependencies.
151 # If the user doesn't pass any arguments, we just have Telemetry.
152 dependencies |= FindPythonDependencies(os.path.realpath(__file__))
156 base_dir = os.path.dirname(os.path.realpath(path))
158 dependencies.add(base_dir)
159 dependencies |= FindBootstrapDependencies(base_dir)
160 dependencies |= FindPythonDependencies(path)
161 if options.include_page_set_data:
162 dependencies |= FindPageSetDependencies(base_dir)
164 # Remove excluded files.
165 dependencies -= FindExcludedFiles(set(dependencies), options)
170 def ZipDependencies(paths, dependencies, options):
171 base_dir = os.path.dirname(os.path.realpath(util.GetChromiumSrcDir()))
173 with zipfile.ZipFile(options.zip, 'w', zipfile.ZIP_DEFLATED) as zip_file:
174 # Add dependencies to archive.
175 for path in dependencies:
176 path_in_archive = os.path.join(
177 'telemetry', os.path.relpath(path, base_dir))
178 zip_file.write(path, path_in_archive)
180 # Add symlinks to executable paths, for ease of use.
182 link_info = zipfile.ZipInfo(
183 os.path.join('telemetry', os.path.basename(path)))
184 link_info.create_system = 3 # Unix attributes.
185 # 010 is regular file, 0111 is the permission bits rwxrwxrwx.
186 link_info.external_attr = 0100777 << 16 # Octal.
188 relative_path = os.path.relpath(path, base_dir)
190 '#!/usr/bin/env python\n\n'
193 'script = os.path.join(os.path.dirname(__file__), \'%s\')\n'
194 'os.execv(sys.executable, [sys.executable, script] + sys.argv[1:])'
197 zip_file.writestr(link_info, link_script)
199 # Add gsutil to the archive, if it's available. The gsutil in
200 # depot_tools is modified to allow authentication using prodaccess.
201 # TODO: If there's a gsutil in telemetry/third_party/, bootstrap_deps
202 # will include it. Then there will be two copies of gsutil at the same
203 # location in the archive. This can be confusing for users.
204 gsutil_path = cloud_storage.FindGsutil()
205 if cloud_storage.SupportsProdaccess(gsutil_path):
206 gsutil_dependencies = path_set.PathSet()
207 gsutil_dependencies.add(os.path.dirname(gsutil_path))
208 gsutil_dependencies -= FindExcludedFiles(
209 set(gsutil_dependencies), options)
211 gsutil_base_dir = os.path.join(os.path.dirname(gsutil_path), os.pardir)
212 for path in gsutil_dependencies:
213 path_in_archive = os.path.join(
214 'telemetry', os.path.relpath(util.GetTelemetryDir(), base_dir),
215 'third_party', os.path.relpath(path, gsutil_base_dir))
216 zip_file.write(path, path_in_archive)
219 def ParseCommandLine():
220 parser = optparse.OptionParser()
222 '-v', '--verbose', action='count', dest='verbosity',
223 help='Increase verbosity level (repeat as needed).')
226 '-p', '--include-page-set-data', action='store_true', default=False,
227 help='Scan tests for page set data and include them.')
230 '-e', '--exclude', action='append', default=[],
231 help='Exclude paths matching EXCLUDE. Can be used multiple times.')
235 help='Store files in a zip archive at ZIP.')
237 options, args = parser.parse_args()
239 if options.verbosity >= 2:
240 logging.getLogger().setLevel(logging.DEBUG)
241 elif options.verbosity:
242 logging.getLogger().setLevel(logging.INFO)
244 logging.getLogger().setLevel(logging.WARNING)
250 options, paths = ParseCommandLine()
252 dependencies = FindDependencies(paths, options)
255 ZipDependencies(paths, dependencies, options)
256 print 'Zip archive written to %s.' % options.zip
258 print '\n'.join(sorted(dependencies))
261 if __name__ == '__main__':