blob: 4b8cbfec99a0d31b47230c7288ae30c91514d799 [file] [log] [blame]
dprankefe4602312015-04-08 16:20:351#!/usr/bin/env python
2# Copyright 2015 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.
5
Dirk Pranke8cb6aa782017-12-16 02:31:336"""MB - the Meta-Build wrapper around GN.
dprankefe4602312015-04-08 16:20:357
Dirk Pranked181a1a2017-12-14 01:47:118MB is a wrapper script for GN that can be used to generate build files
dprankefe4602312015-04-08 16:20:359for sets of canned configurations and analyze them.
10"""
11
12from __future__ import print_function
13
14import argparse
15import ast
dprankec3441d12015-06-23 23:01:3516import errno
dprankefe4602312015-04-08 16:20:3517import json
18import os
dpranke68d1cb182015-09-17 23:30:0019import pipes
Dirk Pranke8cb6aa782017-12-16 02:31:3320import platform
dpranked8113582015-06-05 20:08:2521import pprint
dpranke3cec199c2015-09-22 23:29:0222import re
dprankefe4602312015-04-08 16:20:3523import shutil
24import sys
25import subprocess
dprankef61de2f2015-05-14 04:09:5626import tempfile
dprankebbe6d4672016-04-19 06:56:5727import traceback
dpranke867bcf4a2016-03-14 22:28:3228import urllib2
Dirk Prankef24e6b22018-03-27 20:12:3029import zipfile
dpranke867bcf4a2016-03-14 22:28:3230
31from collections import OrderedDict
dprankefe4602312015-04-08 16:20:3532
dprankeeca4a782016-04-14 01:42:3833CHROMIUM_SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
34 os.path.abspath(__file__))))
35sys.path = [os.path.join(CHROMIUM_SRC_DIR, 'build')] + sys.path
36
37import gn_helpers
38
39
dprankefe4602312015-04-08 16:20:3540def main(args):
dprankeee5b51f62015-04-09 00:03:2241 mbw = MetaBuildWrapper()
dpranke255085e2016-03-16 05:23:5942 return mbw.Main(args)
dprankefe4602312015-04-08 16:20:3543
44
45class MetaBuildWrapper(object):
46 def __init__(self):
dprankeeca4a782016-04-14 01:42:3847 self.chromium_src_dir = CHROMIUM_SRC_DIR
48 self.default_config = os.path.join(self.chromium_src_dir, 'tools', 'mb',
49 'mb_config.pyl')
kjellander902bcb62016-10-26 06:20:5050 self.default_isolate_map = os.path.join(self.chromium_src_dir, 'testing',
51 'buildbot', 'gn_isolate_map.pyl')
dpranke8c2cfd32015-09-17 20:12:3352 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5153 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3354 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3555 self.args = argparse.Namespace()
56 self.configs = {}
Peter Collingbourne4dfb64a2017-08-12 01:00:5557 self.luci_tryservers = {}
dprankefe4602312015-04-08 16:20:3558 self.masters = {}
59 self.mixins = {}
dprankefe4602312015-04-08 16:20:3560
dpranke255085e2016-03-16 05:23:5961 def Main(self, args):
62 self.ParseArgs(args)
63 try:
64 ret = self.args.func()
65 if ret:
66 self.DumpInputFiles()
67 return ret
68 except KeyboardInterrupt:
dprankecb4a2e242016-09-19 01:13:1469 self.Print('interrupted, exiting')
dpranke255085e2016-03-16 05:23:5970 return 130
dprankebbe6d4672016-04-19 06:56:5771 except Exception:
dpranke255085e2016-03-16 05:23:5972 self.DumpInputFiles()
dprankebbe6d4672016-04-19 06:56:5773 s = traceback.format_exc()
74 for l in s.splitlines():
75 self.Print(l)
dpranke255085e2016-03-16 05:23:5976 return 1
77
dprankefe4602312015-04-08 16:20:3578 def ParseArgs(self, argv):
79 def AddCommonOptions(subp):
80 subp.add_argument('-b', '--builder',
81 help='builder name to look up config from')
82 subp.add_argument('-m', '--master',
83 help='master name to look up config from')
84 subp.add_argument('-c', '--config',
85 help='configuration to analyze')
shenghuazhang804b21542016-10-11 02:06:4986 subp.add_argument('--phase',
87 help='optional phase name (used when builders '
88 'do multiple compiles with different '
89 'arguments in a single build)')
dprankefe4602312015-04-08 16:20:3590 subp.add_argument('-f', '--config-file', metavar='PATH',
91 default=self.default_config,
92 help='path to config file '
kjellander902bcb62016-10-26 06:20:5093 '(default is %(default)s)')
94 subp.add_argument('-i', '--isolate-map-file', metavar='PATH',
kjellander902bcb62016-10-26 06:20:5095 help='path to isolate map file '
Zhiling Huang66958462018-02-03 00:28:2096 '(default is %(default)s)',
97 default=[],
98 action='append',
99 dest='isolate_map_files')
dpranked0c138b2016-04-13 18:28:47100 subp.add_argument('-g', '--goma-dir',
101 help='path to goma directory')
agrieve41d21a72016-04-14 18:02:26102 subp.add_argument('--android-version-code',
Dirk Pranked181a1a2017-12-14 01:47:11103 help='Sets GN arg android_default_version_code')
agrieve41d21a72016-04-14 18:02:26104 subp.add_argument('--android-version-name',
Dirk Pranked181a1a2017-12-14 01:47:11105 help='Sets GN arg android_default_version_name')
dprankefe4602312015-04-08 16:20:35106 subp.add_argument('-n', '--dryrun', action='store_true',
107 help='Do a dry run (i.e., do nothing, just print '
108 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:40109 subp.add_argument('-v', '--verbose', action='store_true',
110 help='verbose logging')
dprankefe4602312015-04-08 16:20:35111
112 parser = argparse.ArgumentParser(prog='mb')
113 subps = parser.add_subparsers()
114
115 subp = subps.add_parser('analyze',
116 help='analyze whether changes to a set of files '
117 'will cause a set of binaries to be rebuilt.')
118 AddCommonOptions(subp)
Dirk Prankef24e6b22018-03-27 20:12:30119 subp.add_argument('path',
dprankefe4602312015-04-08 16:20:35120 help='path build was generated into.')
Dirk Prankef24e6b22018-03-27 20:12:30121 subp.add_argument('input_path',
dprankefe4602312015-04-08 16:20:35122 help='path to a file containing the input arguments '
123 'as a JSON object.')
Dirk Prankef24e6b22018-03-27 20:12:30124 subp.add_argument('output_path',
dprankefe4602312015-04-08 16:20:35125 help='path to a file containing the output arguments '
126 'as a JSON object.')
127 subp.set_defaults(func=self.CmdAnalyze)
128
dprankef37aebb92016-09-23 01:14:49129 subp = subps.add_parser('export',
130 help='print out the expanded configuration for'
131 'each builder as a JSON object')
132 subp.add_argument('-f', '--config-file', metavar='PATH',
133 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50134 help='path to config file (default is %(default)s)')
dprankef37aebb92016-09-23 01:14:49135 subp.add_argument('-g', '--goma-dir',
136 help='path to goma directory')
137 subp.set_defaults(func=self.CmdExport)
138
dprankefe4602312015-04-08 16:20:35139 subp = subps.add_parser('gen',
140 help='generate a new set of build files')
141 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39142 subp.add_argument('--swarming-targets-file',
143 help='save runtime dependencies for targets listed '
144 'in file.')
Dirk Prankef24e6b22018-03-27 20:12:30145 subp.add_argument('path',
dprankefe4602312015-04-08 16:20:35146 help='path to generate build into')
147 subp.set_defaults(func=self.CmdGen)
148
dpranke751516a2015-10-03 01:11:34149 subp = subps.add_parser('isolate',
150 help='generate the .isolate files for a given'
151 'binary')
152 AddCommonOptions(subp)
Dirk Prankef24e6b22018-03-27 20:12:30153 subp.add_argument('--no-build', dest='build', default=True,
154 action='store_false',
155 help='Do not build, just isolate')
156 subp.add_argument('-j', '--jobs', type=int,
157 help='Number of jobs to pass to ninja')
158 subp.add_argument('path',
dpranke751516a2015-10-03 01:11:34159 help='path build was generated into')
Dirk Prankef24e6b22018-03-27 20:12:30160 subp.add_argument('target',
dpranke751516a2015-10-03 01:11:34161 help='ninja target to generate the isolate for')
162 subp.set_defaults(func=self.CmdIsolate)
163
dprankefe4602312015-04-08 16:20:35164 subp = subps.add_parser('lookup',
165 help='look up the command for a given config or '
166 'builder')
167 AddCommonOptions(subp)
168 subp.set_defaults(func=self.CmdLookup)
169
dpranke030d7a6d2016-03-26 17:23:50170 subp = subps.add_parser(
171 'run',
172 help='build and run the isolated version of a '
173 'binary',
174 formatter_class=argparse.RawDescriptionHelpFormatter)
175 subp.description = (
176 'Build, isolate, and run the given binary with the command line\n'
177 'listed in the isolate. You may pass extra arguments after the\n'
178 'target; use "--" if the extra arguments need to include switches.\n'
179 '\n'
180 'Examples:\n'
181 '\n'
182 ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n'
183 ' //out/Default content_browsertests\n'
184 '\n'
185 ' % tools/mb/mb.py run out/Default content_browsertests\n'
186 '\n'
187 ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n'
188 ' --test-launcher-retry-limit=0'
189 '\n'
190 )
dpranke751516a2015-10-03 01:11:34191 AddCommonOptions(subp)
Dirk Prankef24e6b22018-03-27 20:12:30192 subp.add_argument('-j', '--jobs', type=int,
dpranke751516a2015-10-03 01:11:34193 help='Number of jobs to pass to ninja')
194 subp.add_argument('--no-build', dest='build', default=True,
195 action='store_false',
196 help='Do not build, just isolate and run')
Dirk Prankef24e6b22018-03-27 20:12:30197 subp.add_argument('path',
dpranke030d7a6d2016-03-26 17:23:50198 help=('path to generate build into (or use).'
199 ' This can be either a regular path or a '
200 'GN-style source-relative path like '
201 '//out/Default.'))
Dirk Pranke8cb6aa782017-12-16 02:31:33202 subp.add_argument('-s', '--swarmed', action='store_true',
203 help='Run under swarming with the default dimensions')
204 subp.add_argument('-d', '--dimension', default=[], action='append', nargs=2,
205 dest='dimensions', metavar='FOO bar',
206 help='dimension to filter on')
207 subp.add_argument('--no-default-dimensions', action='store_false',
208 dest='default_dimensions', default=True,
209 help='Do not automatically add dimensions to the task')
Dirk Prankef24e6b22018-03-27 20:12:30210 subp.add_argument('target',
dpranke751516a2015-10-03 01:11:34211 help='ninja target to build and run')
dpranke030d7a6d2016-03-26 17:23:50212 subp.add_argument('extra_args', nargs='*',
213 help=('extra args to pass to the isolate to run. Use '
214 '"--" as the first arg if you need to pass '
215 'switches'))
dpranke751516a2015-10-03 01:11:34216 subp.set_defaults(func=self.CmdRun)
217
dprankefe4602312015-04-08 16:20:35218 subp = subps.add_parser('validate',
219 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17220 subp.add_argument('-f', '--config-file', metavar='PATH',
221 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50222 help='path to config file (default is %(default)s)')
dprankefe4602312015-04-08 16:20:35223 subp.set_defaults(func=self.CmdValidate)
224
Peter Collingbourne4dfb64a2017-08-12 01:00:55225 subp = subps.add_parser('gerrit-buildbucket-config',
226 help='Print buildbucket.config for gerrit '
227 '(see MB user guide)')
228 subp.add_argument('-f', '--config-file', metavar='PATH',
229 default=self.default_config,
230 help='path to config file (default is %(default)s)')
231 subp.set_defaults(func=self.CmdBuildbucket)
232
Dirk Prankef24e6b22018-03-27 20:12:30233 subp = subps.add_parser('zip',
234 help='generate a .zip containing the files needed '
235 'for a given binary')
236 AddCommonOptions(subp)
237 subp.add_argument('--no-build', dest='build', default=True,
238 action='store_false',
239 help='Do not build, just isolate')
240 subp.add_argument('-j', '--jobs', type=int,
241 help='Number of jobs to pass to ninja')
242 subp.add_argument('path',
243 help='path build was generated into')
244 subp.add_argument('target',
245 help='ninja target to generate the isolate for')
246 subp.add_argument('zip_path',
247 help='path to zip file to create')
248 subp.set_defaults(func=self.CmdZip)
249
dprankefe4602312015-04-08 16:20:35250 subp = subps.add_parser('help',
251 help='Get help on a subcommand.')
252 subp.add_argument(nargs='?', action='store', dest='subcommand',
253 help='The command to get help for.')
254 subp.set_defaults(func=self.CmdHelp)
255
256 self.args = parser.parse_args(argv)
257
dprankeb2be10a2016-02-22 17:11:00258 def DumpInputFiles(self):
259
dprankef7b7eb7a2016-03-28 22:42:59260 def DumpContentsOfFilePassedTo(arg_name, path):
dprankeb2be10a2016-02-22 17:11:00261 if path and self.Exists(path):
dprankef7b7eb7a2016-03-28 22:42:59262 self.Print("\n# To recreate the file passed to %s:" % arg_name)
dprankecb4a2e242016-09-19 01:13:14263 self.Print("%% cat > %s <<EOF" % path)
dprankeb2be10a2016-02-22 17:11:00264 contents = self.ReadFile(path)
dprankef7b7eb7a2016-03-28 22:42:59265 self.Print(contents)
266 self.Print("EOF\n%\n")
dprankeb2be10a2016-02-22 17:11:00267
dprankef7b7eb7a2016-03-28 22:42:59268 if getattr(self.args, 'input_path', None):
269 DumpContentsOfFilePassedTo(
Dirk Prankef24e6b22018-03-27 20:12:30270 'argv[0] (input_path)', self.args.input_path)
dprankef7b7eb7a2016-03-28 22:42:59271 if getattr(self.args, 'swarming_targets_file', None):
272 DumpContentsOfFilePassedTo(
273 '--swarming-targets-file', self.args.swarming_targets_file)
dprankeb2be10a2016-02-22 17:11:00274
dprankefe4602312015-04-08 16:20:35275 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34276 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11277 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35278
dprankef37aebb92016-09-23 01:14:49279 def CmdExport(self):
280 self.ReadConfigFile()
281 obj = {}
282 for master, builders in self.masters.items():
283 obj[master] = {}
284 for builder in builders:
285 config = self.masters[master][builder]
286 if not config:
287 continue
288
shenghuazhang804b21542016-10-11 02:06:49289 if isinstance(config, dict):
290 args = {k: self.FlattenConfig(v)['gn_args']
291 for k, v in config.items()}
dprankef37aebb92016-09-23 01:14:49292 elif config.startswith('//'):
293 args = config
294 else:
295 args = self.FlattenConfig(config)['gn_args']
296 if 'error' in args:
297 continue
298
299 obj[master][builder] = args
300
301 # Dump object and trim trailing whitespace.
302 s = '\n'.join(l.rstrip() for l in
303 json.dumps(obj, sort_keys=True, indent=2).splitlines())
304 self.Print(s)
305 return 0
306
dprankefe4602312015-04-08 16:20:35307 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34308 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11309 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35310
311 def CmdHelp(self):
312 if self.args.subcommand:
313 self.ParseArgs([self.args.subcommand, '--help'])
314 else:
315 self.ParseArgs(['--help'])
316
dpranke751516a2015-10-03 01:11:34317 def CmdIsolate(self):
318 vals = self.GetConfig()
319 if not vals:
320 return 1
Dirk Prankef24e6b22018-03-27 20:12:30321 if self.args.build:
322 ret = self.Build(self.args.target)
323 if ret:
324 return ret
Dirk Pranked181a1a2017-12-14 01:47:11325 return self.RunGNIsolate(vals)
dpranke751516a2015-10-03 01:11:34326
327 def CmdLookup(self):
328 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11329 cmd = self.GNCmd('gen', '_path_')
330 gn_args = self.GNArgs(vals)
331 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
332 env = None
dpranke751516a2015-10-03 01:11:34333
334 self.PrintCmd(cmd, env)
335 return 0
336
337 def CmdRun(self):
338 vals = self.GetConfig()
339 if not vals:
340 return 1
Dirk Pranked181a1a2017-12-14 01:47:11341 if self.args.build:
Dirk Prankef24e6b22018-03-27 20:12:30342 ret = self.Build(self.args.target)
dpranke751516a2015-10-03 01:11:34343 if ret:
344 return ret
Dirk Pranked181a1a2017-12-14 01:47:11345 ret = self.RunGNIsolate(vals)
346 if ret:
347 return ret
dpranke751516a2015-10-03 01:11:34348
Dirk Pranke8cb6aa782017-12-16 02:31:33349 if self.args.swarmed:
Dirk Prankef24e6b22018-03-27 20:12:30350 return self._RunUnderSwarming(self.args.path, self.args.target)
Dirk Pranke8cb6aa782017-12-16 02:31:33351 else:
Dirk Prankef24e6b22018-03-27 20:12:30352 return self._RunLocallyIsolated(self.args.path, self.args.target)
353
354 def CmdZip(self):
355 ret = self.CmdIsolate()
356 if ret:
357 return ret
358
359 zip_dir = None
360 try:
361 zip_dir = self.TempDir()
362 remap_cmd = [
363 self.executable,
364 self.PathJoin(self.chromium_src_dir, 'tools', 'swarming_client',
365 'isolate.py'),
366 'remap',
367 '-s', self.PathJoin(self.args.path, self.args.target + '.isolated'),
368 '-o', zip_dir
369 ]
370 self.Run(remap_cmd)
371
372 zip_path = self.args.zip_path
373 with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as fp:
374 for root, _, files in os.walk(zip_dir):
375 for filename in files:
376 path = self.PathJoin(root, filename)
377 fp.write(path, self.RelPath(path, zip_dir))
378 finally:
379 if zip_dir:
380 self.RemoveDirectory(zip_dir)
Dirk Pranke8cb6aa782017-12-16 02:31:33381
Robert Iannucci5a9d75f62018-03-02 05:28:20382 @staticmethod
383 def _AddBaseSoftware(cmd):
384 # HACK(iannucci): These packages SHOULD NOT BE HERE.
385 # Remove method once Swarming Pool Task Templates are implemented.
386 # crbug.com/812428
387
388 # Add in required base software. This should be kept in sync with the
389 # `swarming` recipe module in build.git. All references to `swarming_module`
390 # below are purely due to this.
391 cipd_packages = [
392 ('infra/python/cpython/${platform}',
393 'version:2.7.14.chromium14'),
394 ('infra/tools/luci/logdog/butler/${platform}',
395 'git_revision:e1abc57be62d198b5c2f487bfb2fa2d2eb0e867c'),
396 ('infra/tools/luci/vpython-native/${platform}',
397 'git_revision:e1abc57be62d198b5c2f487bfb2fa2d2eb0e867c'),
398 ('infra/tools/luci/vpython/${platform}',
399 'git_revision:e1abc57be62d198b5c2f487bfb2fa2d2eb0e867c'),
400 ]
401 for pkg, vers in cipd_packages:
402 cmd.append('--cipd-package=.swarming_module:%s:%s' % (pkg, vers))
403
404 # Add packages to $PATH
405 cmd.extend([
406 '--env-prefix=PATH', '.swarming_module',
407 '--env-prefix=PATH', '.swarming_module/bin',
408 ])
409
410 # Add cache directives for vpython.
411 vpython_cache_path = '.swarming_module_cache/vpython'
412 cmd.extend([
413 '--named-cache=swarming_module_cache_vpython', vpython_cache_path,
414 '--env-prefix=VPYTHON_VIRTUALENV_ROOT', vpython_cache_path,
415 ])
416
Dirk Pranke8cb6aa782017-12-16 02:31:33417 def _RunUnderSwarming(self, build_dir, target):
418 # TODO(dpranke): Look up the information for the target in
419 # the //testing/buildbot.json file, if possible, so that we
420 # can determine the isolate target, command line, and additional
421 # swarming parameters, if possible.
422 #
423 # TODO(dpranke): Also, add support for sharding and merging results.
424 dimensions = []
425 for k, v in self._DefaultDimensions() + self.args.dimensions:
426 dimensions += ['-d', k, v]
427
428 cmd = [
429 self.executable,
430 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
431 'archive',
432 '-s',
433 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
434 '-I', 'isolateserver.appspot.com',
435 ]
436 ret, out, _ = self.Run(cmd, force_verbose=False)
437 if ret:
438 return ret
439
440 isolated_hash = out.splitlines()[0].split()[0]
441 cmd = [
442 self.executable,
443 self.PathJoin('tools', 'swarming_client', 'swarming.py'),
444 'run',
445 '-s', isolated_hash,
446 '-I', 'isolateserver.appspot.com',
447 '-S', 'chromium-swarm.appspot.com',
448 ] + dimensions
Robert Iannucci5a9d75f62018-03-02 05:28:20449 self._AddBaseSoftware(cmd)
Dirk Pranke8cb6aa782017-12-16 02:31:33450 if self.args.extra_args:
451 cmd += ['--'] + self.args.extra_args
452 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
453 return ret
454
455 def _RunLocallyIsolated(self, build_dir, target):
dpranke030d7a6d2016-03-26 17:23:50456 cmd = [
dpranke751516a2015-10-03 01:11:34457 self.executable,
458 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
459 'run',
460 '-s',
dpranke030d7a6d2016-03-26 17:23:50461 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
Dirk Pranke8cb6aa782017-12-16 02:31:33462 ]
dpranke030d7a6d2016-03-26 17:23:50463 if self.args.extra_args:
Dirk Pranke8cb6aa782017-12-16 02:31:33464 cmd += ['--'] + self.args.extra_args
465 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
dpranke751516a2015-10-03 01:11:34466 return ret
467
Dirk Pranke8cb6aa782017-12-16 02:31:33468 def _DefaultDimensions(self):
469 if not self.args.default_dimensions:
470 return []
471
472 # This code is naive and just picks reasonable defaults per platform.
473 if self.platform == 'darwin':
Mike Meaded12fd0f2018-04-10 01:02:40474 os_dim = ('os', 'Mac-10.13')
Dirk Pranke8cb6aa782017-12-16 02:31:33475 elif self.platform.startswith('linux'):
476 os_dim = ('os', 'Ubuntu-14.04')
477 elif self.platform == 'win32':
Mike Meaded12fd0f2018-04-10 01:02:40478 os_dim = ('os', 'Windows-10')
Dirk Pranke8cb6aa782017-12-16 02:31:33479 else:
480 raise MBErr('unrecognized platform string "%s"' % self.platform)
481
482 return [('pool', 'Chrome'),
483 ('cpu', 'x86-64'),
484 os_dim]
485
Peter Collingbourne4dfb64a2017-08-12 01:00:55486 def CmdBuildbucket(self):
487 self.ReadConfigFile()
488
489 self.Print('# This file was generated using '
490 '"tools/mb/mb.py gerrit-buildbucket-config".')
491
492 for luci_tryserver in sorted(self.luci_tryservers):
493 self.Print('[bucket "luci.%s"]' % luci_tryserver)
494 for bot in sorted(self.luci_tryservers[luci_tryserver]):
495 self.Print('\tbuilder = %s' % bot)
496
497 for master in sorted(self.masters):
498 if master.startswith('tryserver.'):
499 self.Print('[bucket "master.%s"]' % master)
500 for bot in sorted(self.masters[master]):
501 self.Print('\tbuilder = %s' % bot)
502
503 return 0
504
dpranke0cafc162016-03-19 00:41:10505 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35506 errs = []
507
508 # Read the file to make sure it parses.
509 self.ReadConfigFile()
510
dpranke3be00142016-03-17 22:46:04511 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35512 all_configs = {}
dprankefe4602312015-04-08 16:20:35513 for master in self.masters:
dpranke3be00142016-03-17 22:46:04514 for config in self.masters[master].values():
shenghuazhang804b21542016-10-11 02:06:49515 if isinstance(config, dict):
516 for c in config.values():
dprankeb9380a12016-07-21 21:44:09517 all_configs[c] = master
518 else:
519 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35520
dpranke9dd5e252016-04-14 04:23:09521 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35522 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09523 if config.startswith('//'):
524 if not self.Exists(self.ToAbsPath(config)):
525 errs.append('Unknown args file "%s" referenced from "%s".' %
526 (config, loc))
527 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35528 errs.append('Unknown config "%s" referenced from "%s".' %
529 (config, loc))
530
531 # Check that every actual config is actually referenced.
532 for config in self.configs:
533 if not config in all_configs:
534 errs.append('Unused config "%s".' % config)
535
536 # Figure out the whole list of mixins, and check that every mixin
537 # listed by a config or another mixin actually exists.
538 referenced_mixins = set()
539 for config, mixins in self.configs.items():
540 for mixin in mixins:
541 if not mixin in self.mixins:
542 errs.append('Unknown mixin "%s" referenced by config "%s".' %
543 (mixin, config))
544 referenced_mixins.add(mixin)
545
546 for mixin in self.mixins:
547 for sub_mixin in self.mixins[mixin].get('mixins', []):
548 if not sub_mixin in self.mixins:
549 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
550 (sub_mixin, mixin))
551 referenced_mixins.add(sub_mixin)
552
553 # Check that every mixin defined is actually referenced somewhere.
554 for mixin in self.mixins:
555 if not mixin in referenced_mixins:
556 errs.append('Unreferenced mixin "%s".' % mixin)
557
dpranke255085e2016-03-16 05:23:59558 # If we're checking the Chromium config, check that the 'chromium' bots
559 # which build public artifacts do not include the chrome_with_codecs mixin.
560 if self.args.config_file == self.default_config:
561 if 'chromium' in self.masters:
562 for builder in self.masters['chromium']:
563 config = self.masters['chromium'][builder]
564 def RecurseMixins(current_mixin):
565 if current_mixin == 'chrome_with_codecs':
566 errs.append('Public artifact builder "%s" can not contain the '
567 '"chrome_with_codecs" mixin.' % builder)
568 return
569 if not 'mixins' in self.mixins[current_mixin]:
570 return
571 for mixin in self.mixins[current_mixin]['mixins']:
572 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41573
dpranke255085e2016-03-16 05:23:59574 for mixin in self.configs[config]:
575 RecurseMixins(mixin)
576 else:
577 errs.append('Missing "chromium" master. Please update this '
578 'proprietary codecs check with the name of the master '
579 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41580
dprankefe4602312015-04-08 16:20:35581 if errs:
dpranke4323c80632015-08-10 22:53:54582 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17583 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35584
dpranke0cafc162016-03-19 00:41:10585 if print_ok:
586 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35587 return 0
588
589 def GetConfig(self):
Dirk Prankef24e6b22018-03-27 20:12:30590 build_dir = self.args.path
dpranke751516a2015-10-03 01:11:34591
dprankef37aebb92016-09-23 01:14:49592 vals = self.DefaultVals()
dpranke751516a2015-10-03 01:11:34593 if self.args.builder or self.args.master or self.args.config:
594 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11595 # Re-run gn gen in order to ensure the config is consistent with the
596 # build dir.
597 self.RunGNGen(vals)
dpranke751516a2015-10-03 01:11:34598 return vals
599
Dirk Pranked181a1a2017-12-14 01:47:11600 toolchain_path = self.PathJoin(self.ToAbsPath(build_dir),
601 'toolchain.ninja')
602 if not self.Exists(toolchain_path):
603 self.Print('Must either specify a path to an existing GN build dir '
604 'or pass in a -m/-b pair or a -c flag to specify the '
605 'configuration')
606 return {}
dpranke751516a2015-10-03 01:11:34607
Dirk Pranked181a1a2017-12-14 01:47:11608 vals['gn_args'] = self.GNArgsFromDir(build_dir)
dpranke751516a2015-10-03 01:11:34609 return vals
610
dprankef37aebb92016-09-23 01:14:49611 def GNArgsFromDir(self, build_dir):
brucedawsonecc0c1cd2016-06-02 18:24:58612 args_contents = ""
613 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
614 if self.Exists(gn_args_path):
615 args_contents = self.ReadFile(gn_args_path)
dpranke751516a2015-10-03 01:11:34616 gn_args = []
617 for l in args_contents.splitlines():
618 fields = l.split(' ')
619 name = fields[0]
620 val = ' '.join(fields[2:])
621 gn_args.append('%s=%s' % (name, val))
622
dprankef37aebb92016-09-23 01:14:49623 return ' '.join(gn_args)
dpranke751516a2015-10-03 01:11:34624
625 def Lookup(self):
dprankef37aebb92016-09-23 01:14:49626 vals = self.ReadIOSBotConfig()
dprankee0f486f2015-11-19 23:42:00627 if not vals:
628 self.ReadConfigFile()
629 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09630 if config.startswith('//'):
631 if not self.Exists(self.ToAbsPath(config)):
632 raise MBErr('args file "%s" not found' % config)
dprankef37aebb92016-09-23 01:14:49633 vals = self.DefaultVals()
634 vals['args_file'] = config
dpranke9dd5e252016-04-14 04:23:09635 else:
636 if not config in self.configs:
637 raise MBErr('Config "%s" not found in %s' %
638 (config, self.args.config_file))
639 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34640 return vals
dprankefe4602312015-04-08 16:20:35641
dprankef37aebb92016-09-23 01:14:49642 def ReadIOSBotConfig(self):
dprankee0f486f2015-11-19 23:42:00643 if not self.args.master or not self.args.builder:
644 return {}
645 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
646 self.args.master, self.args.builder + '.json')
647 if not self.Exists(path):
648 return {}
649
650 contents = json.loads(self.ReadFile(path))
dprankee0f486f2015-11-19 23:42:00651 gn_args = ' '.join(contents.get('gn_args', []))
652
dprankef37aebb92016-09-23 01:14:49653 vals = self.DefaultVals()
654 vals['gn_args'] = gn_args
dprankef37aebb92016-09-23 01:14:49655 return vals
dprankee0f486f2015-11-19 23:42:00656
dprankefe4602312015-04-08 16:20:35657 def ReadConfigFile(self):
658 if not self.Exists(self.args.config_file):
659 raise MBErr('config file not found at %s' % self.args.config_file)
660
661 try:
662 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
663 except SyntaxError as e:
664 raise MBErr('Failed to parse config file "%s": %s' %
665 (self.args.config_file, e))
666
dprankefe4602312015-04-08 16:20:35667 self.configs = contents['configs']
Peter Collingbourne4dfb64a2017-08-12 01:00:55668 self.luci_tryservers = contents.get('luci_tryservers', {})
dprankefe4602312015-04-08 16:20:35669 self.masters = contents['masters']
670 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35671
dprankecb4a2e242016-09-19 01:13:14672 def ReadIsolateMap(self):
Zhiling Huang66958462018-02-03 00:28:20673 if not self.args.isolate_map_files:
674 self.args.isolate_map_files = [self.default_isolate_map]
675
676 for f in self.args.isolate_map_files:
677 if not self.Exists(f):
678 raise MBErr('isolate map file not found at %s' % f)
679 isolate_maps = {}
680 for isolate_map in self.args.isolate_map_files:
681 try:
682 isolate_map = ast.literal_eval(self.ReadFile(isolate_map))
683 duplicates = set(isolate_map).intersection(isolate_maps)
684 if duplicates:
685 raise MBErr(
686 'Duplicate targets in isolate map files: %s.' %
687 ', '.join(duplicates))
688 isolate_maps.update(isolate_map)
689 except SyntaxError as e:
690 raise MBErr(
691 'Failed to parse isolate map file "%s": %s' % (isolate_map, e))
692 return isolate_maps
dprankecb4a2e242016-09-19 01:13:14693
dprankefe4602312015-04-08 16:20:35694 def ConfigFromArgs(self):
695 if self.args.config:
696 if self.args.master or self.args.builder:
697 raise MBErr('Can not specific both -c/--config and -m/--master or '
698 '-b/--builder')
699
700 return self.args.config
701
702 if not self.args.master or not self.args.builder:
703 raise MBErr('Must specify either -c/--config or '
704 '(-m/--master and -b/--builder)')
705
706 if not self.args.master in self.masters:
707 raise MBErr('Master name "%s" not found in "%s"' %
708 (self.args.master, self.args.config_file))
709
710 if not self.args.builder in self.masters[self.args.master]:
711 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
712 (self.args.builder, self.args.master, self.args.config_file))
713
dprankeb9380a12016-07-21 21:44:09714 config = self.masters[self.args.master][self.args.builder]
shenghuazhang804b21542016-10-11 02:06:49715 if isinstance(config, dict):
dprankeb9380a12016-07-21 21:44:09716 if self.args.phase is None:
717 raise MBErr('Must specify a build --phase for %s on %s' %
718 (self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49719 phase = str(self.args.phase)
720 if phase not in config:
721 raise MBErr('Phase %s doesn\'t exist for %s on %s' %
dprankeb9380a12016-07-21 21:44:09722 (phase, self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49723 return config[phase]
dprankeb9380a12016-07-21 21:44:09724
725 if self.args.phase is not None:
726 raise MBErr('Must not specify a build --phase for %s on %s' %
727 (self.args.builder, self.args.master))
728 return config
dprankefe4602312015-04-08 16:20:35729
730 def FlattenConfig(self, config):
731 mixins = self.configs[config]
dprankef37aebb92016-09-23 01:14:49732 vals = self.DefaultVals()
dprankefe4602312015-04-08 16:20:35733
734 visited = []
735 self.FlattenMixins(mixins, vals, visited)
736 return vals
737
dprankef37aebb92016-09-23 01:14:49738 def DefaultVals(self):
739 return {
740 'args_file': '',
741 'cros_passthrough': False,
742 'gn_args': '',
dprankef37aebb92016-09-23 01:14:49743 }
744
dprankefe4602312015-04-08 16:20:35745 def FlattenMixins(self, mixins, vals, visited):
746 for m in mixins:
747 if m not in self.mixins:
748 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22749
dprankefe4602312015-04-08 16:20:35750 visited.append(m)
751
752 mixin_vals = self.mixins[m]
dpranke73ed0d62016-04-25 19:18:34753
754 if 'cros_passthrough' in mixin_vals:
755 vals['cros_passthrough'] = mixin_vals['cros_passthrough']
Dirk Pranke6b99f072017-04-05 00:58:30756 if 'args_file' in mixin_vals:
757 if vals['args_file']:
758 raise MBErr('args_file specified multiple times in mixins '
759 'for %s on %s' % (self.args.builder, self.args.master))
760 vals['args_file'] = mixin_vals['args_file']
dprankefe4602312015-04-08 16:20:35761 if 'gn_args' in mixin_vals:
762 if vals['gn_args']:
763 vals['gn_args'] += ' ' + mixin_vals['gn_args']
764 else:
765 vals['gn_args'] = mixin_vals['gn_args']
dpranke73ed0d62016-04-25 19:18:34766
dprankefe4602312015-04-08 16:20:35767 if 'mixins' in mixin_vals:
768 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
769 return vals
770
Dirk Prankea3727f92017-07-17 17:30:33771 def RunGNGen(self, vals, compute_grit_inputs_for_analyze=False):
Dirk Prankef24e6b22018-03-27 20:12:30772 build_dir = self.args.path
Dirk Pranke0fd41bcd2015-06-19 00:05:50773
dprankeeca4a782016-04-14 01:42:38774 cmd = self.GNCmd('gen', build_dir, '--check')
775 gn_args = self.GNArgs(vals)
Dirk Prankea3727f92017-07-17 17:30:33776 if compute_grit_inputs_for_analyze:
777 gn_args += ' compute_grit_inputs_for_analyze=true'
dprankeeca4a782016-04-14 01:42:38778
779 # Since GN hasn't run yet, the build directory may not even exist.
780 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
781
782 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
dpranke4ff8b9f2016-04-15 03:07:54783 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
dpranke74559b52015-06-10 21:20:39784
785 swarming_targets = []
dpranke751516a2015-10-03 01:11:34786 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39787 # We need GN to generate the list of runtime dependencies for
788 # the compile targets listed (one per line) in the file so
dprankecb4a2e242016-09-19 01:13:14789 # we can run them via swarming. We use gn_isolate_map.pyl to convert
dpranke74559b52015-06-10 21:20:39790 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00791 path = self.args.swarming_targets_file
792 if not self.Exists(path):
793 self.WriteFailureAndRaise('"%s" does not exist' % path,
794 output_path=None)
795 contents = self.ReadFile(path)
796 swarming_targets = set(contents.splitlines())
dprankeb2be10a2016-02-22 17:11:00797
dprankecb4a2e242016-09-19 01:13:14798 isolate_map = self.ReadIsolateMap()
799 err, labels = self.MapTargetsToLabels(isolate_map, swarming_targets)
dprankeb2be10a2016-02-22 17:11:00800 if err:
dprankecb4a2e242016-09-19 01:13:14801 raise MBErr(err)
dpranke74559b52015-06-10 21:20:39802
dpranke751516a2015-10-03 01:11:34803 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankecb4a2e242016-09-19 01:13:14804 self.WriteFile(gn_runtime_deps_path, '\n'.join(labels) + '\n')
dpranke74559b52015-06-10 21:20:39805 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
806
dprankefe4602312015-04-08 16:20:35807 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40808 if ret:
809 # If `gn gen` failed, we should exit early rather than trying to
810 # generate isolates. Run() will have already logged any error output.
811 self.Print('GN gen failed: %d' % ret)
812 return ret
dpranke74559b52015-06-10 21:20:39813
jbudoricke3c4f95e2016-04-28 23:17:38814 android = 'target_os="android"' in vals['gn_args']
Kevin Marshallf35fa5f2018-01-29 19:24:42815 fuchsia = 'target_os="fuchsia"' in vals['gn_args']
Nico Weberd94b71a2018-02-22 22:00:30816 win = self.platform == 'win32' or 'target_os="win"' in vals['gn_args']
dpranke74559b52015-06-10 21:20:39817 for target in swarming_targets:
jbudoricke3c4f95e2016-04-28 23:17:38818 if android:
819 # Android targets may be either android_apk or executable. The former
jbudorick91c8a6012016-01-29 23:20:02820 # will result in runtime_deps associated with the stamp file, while the
821 # latter will result in runtime_deps associated with the executable.
dprankecb4a2e242016-09-19 01:13:14822 label = isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02823 runtime_deps_targets = [
dprankecb4a2e242016-09-19 01:13:14824 target + '.runtime_deps',
dpranke48ccf8f2016-03-28 23:58:28825 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
Kevin Marshallf35fa5f2018-01-29 19:24:42826 elif fuchsia:
827 # Only emit a runtime deps file for the group() target on Fuchsia.
828 label = isolate_map[target]['label']
829 runtime_deps_targets = [
830 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
dprankecb4a2e242016-09-19 01:13:14831 elif (isolate_map[target]['type'] == 'script' or
832 isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11833 # For script targets, the build target is usually a group,
834 # for which gn generates the runtime_deps next to the stamp file
eyaich82d5ac942016-11-03 12:13:49835 # for the label, which lives under the obj/ directory, but it may
836 # also be an executable.
dprankecb4a2e242016-09-19 01:13:14837 label = isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28838 runtime_deps_targets = [
839 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
Nico Weberd94b71a2018-02-22 22:00:30840 if win:
eyaich82d5ac942016-11-03 12:13:49841 runtime_deps_targets += [ target + '.exe.runtime_deps' ]
842 else:
843 runtime_deps_targets += [ target + '.runtime_deps' ]
Nico Weberd94b71a2018-02-22 22:00:30844 elif win:
dpranke48ccf8f2016-03-28 23:58:28845 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52846 else:
dpranke48ccf8f2016-03-28 23:58:28847 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02848
dpranke48ccf8f2016-03-28 23:58:28849 for r in runtime_deps_targets:
850 runtime_deps_path = self.ToAbsPath(build_dir, r)
851 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02852 break
853 else:
dpranke48ccf8f2016-03-28 23:58:28854 raise MBErr('did not generate any of %s' %
855 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39856
dprankecb4a2e242016-09-19 01:13:14857 command, extra_files = self.GetIsolateCommand(target, vals)
dpranked5b2b9432015-06-23 16:55:30858
dpranke48ccf8f2016-03-28 23:58:28859 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30860
dpranke751516a2015-10-03 01:11:34861 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
862 extra_files)
dpranked5b2b9432015-06-23 16:55:30863
dpranke751516a2015-10-03 01:11:34864 return 0
865
866 def RunGNIsolate(self, vals):
Dirk Prankef24e6b22018-03-27 20:12:30867 target = self.args.target
dprankecb4a2e242016-09-19 01:13:14868 isolate_map = self.ReadIsolateMap()
869 err, labels = self.MapTargetsToLabels(isolate_map, [target])
870 if err:
871 raise MBErr(err)
872 label = labels[0]
dpranke751516a2015-10-03 01:11:34873
Dirk Prankef24e6b22018-03-27 20:12:30874 build_dir = self.args.path
dprankecb4a2e242016-09-19 01:13:14875 command, extra_files = self.GetIsolateCommand(target, vals)
dpranke751516a2015-10-03 01:11:34876
dprankeeca4a782016-04-14 01:42:38877 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20878 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34879 if ret:
dpranke030d7a6d2016-03-26 17:23:50880 if out:
881 self.Print(out)
dpranke751516a2015-10-03 01:11:34882 return ret
883
884 runtime_deps = out.splitlines()
885
886 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
887 extra_files)
888
889 ret, _, _ = self.Run([
890 self.executable,
891 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
892 'check',
893 '-i',
894 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
895 '-s',
896 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
897 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30898
dprankefe4602312015-04-08 16:20:35899 return ret
900
dpranke751516a2015-10-03 01:11:34901 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
902 extra_files):
903 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
904 self.WriteFile(isolate_path,
905 pprint.pformat({
906 'variables': {
907 'command': command,
908 'files': sorted(runtime_deps + extra_files),
909 }
910 }) + '\n')
911
912 self.WriteJSON(
913 {
914 'args': [
915 '--isolated',
916 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
917 '--isolate',
918 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
919 ],
920 'dir': self.chromium_src_dir,
921 'version': 1,
922 },
923 isolate_path + 'd.gen.json',
924 )
925
dprankecb4a2e242016-09-19 01:13:14926 def MapTargetsToLabels(self, isolate_map, targets):
927 labels = []
928 err = ''
929
dprankecb4a2e242016-09-19 01:13:14930 for target in targets:
931 if target == 'all':
932 labels.append(target)
933 elif target.startswith('//'):
934 labels.append(target)
935 else:
936 if target in isolate_map:
thakis024d6f32017-05-16 23:21:42937 if isolate_map[target]['type'] == 'unknown':
dprankecb4a2e242016-09-19 01:13:14938 err += ('test target "%s" type is unknown\n' % target)
939 else:
thakis024d6f32017-05-16 23:21:42940 labels.append(isolate_map[target]['label'])
dprankecb4a2e242016-09-19 01:13:14941 else:
942 err += ('target "%s" not found in '
943 '//testing/buildbot/gn_isolate_map.pyl\n' % target)
944
945 return err, labels
946
dprankeeca4a782016-04-14 01:42:38947 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51948 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20949 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51950 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20951 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51952 else:
dpranke40da0202016-02-13 05:05:20953 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38954
dpranke40da0202016-02-13 05:05:20955 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranke10118bf2016-09-16 23:16:08956 return [gn_path, subcommand, path] + list(args)
dpranke9aba8b212016-09-16 22:52:52957
dprankecb4a2e242016-09-19 01:13:14958
dprankeeca4a782016-04-14 01:42:38959 def GNArgs(self, vals):
dpranke73ed0d62016-04-25 19:18:34960 if vals['cros_passthrough']:
961 if not 'GN_ARGS' in os.environ:
962 raise MBErr('MB is expecting GN_ARGS to be in the environment')
963 gn_args = os.environ['GN_ARGS']
dpranke40260182016-04-27 04:45:16964 if not re.search('target_os.*=.*"chromeos"', gn_args):
dpranke39f3be02016-04-27 04:07:30965 raise MBErr('GN_ARGS is missing target_os = "chromeos": (GN_ARGS=%s)' %
dpranke73ed0d62016-04-25 19:18:34966 gn_args)
967 else:
968 gn_args = vals['gn_args']
969
dpranked0c138b2016-04-13 18:28:47970 if self.args.goma_dir:
971 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38972
agrieve41d21a72016-04-14 18:02:26973 android_version_code = self.args.android_version_code
974 if android_version_code:
975 gn_args += ' android_default_version_code="%s"' % android_version_code
976
977 android_version_name = self.args.android_version_name
978 if android_version_name:
979 gn_args += ' android_default_version_name="%s"' % android_version_name
980
dprankeeca4a782016-04-14 01:42:38981 # Canonicalize the arg string into a sorted, newline-separated list
982 # of key-value pairs, and de-dup the keys if need be so that only
983 # the last instance of each arg is listed.
984 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
985
dpranke9dd5e252016-04-14 04:23:09986 args_file = vals.get('args_file', None)
987 if args_file:
988 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:38989 return gn_args
dprankefe4602312015-04-08 16:20:35990
dprankecb4a2e242016-09-19 01:13:14991 def GetIsolateCommand(self, target, vals):
kylechar50abf5a2016-11-29 16:03:07992 isolate_map = self.ReadIsolateMap()
993
Scott Graham3be4b4162017-09-12 00:41:41994 is_android = 'target_os="android"' in vals['gn_args']
Benjamin Pastene3bce864e2018-04-14 01:16:32995 is_simplechrome = vals.get('cros_passthrough', False)
Scott Graham3be4b4162017-09-12 00:41:41996 is_fuchsia = 'target_os="fuchsia"' in vals['gn_args']
Nico Weberd94b71a2018-02-22 22:00:30997 is_win = self.platform == 'win32' or 'target_os="win"' in vals['gn_args']
jbudoricke8428732016-02-02 02:17:06998
kylechar39705682017-01-19 14:37:23999 # This should be true if tests with type='windowed_test_launcher' are
1000 # expected to run using xvfb. For example, Linux Desktop, X11 CrOS and
msisovaea52732017-03-21 08:08:081001 # Ozone CrOS builds. Note that one Ozone build can be used to run differen
1002 # backends. Currently, tests are executed for the headless and X11 backends
1003 # and both can run under Xvfb.
1004 # TODO(tonikitoo,msisov,fwang): Find a way to run tests for the Wayland
1005 # backend.
Scott Graham3be4b4162017-09-12 00:41:411006 use_xvfb = self.platform == 'linux2' and not is_android and not is_fuchsia
dpranked8113582015-06-05 20:08:251007
1008 asan = 'is_asan=true' in vals['gn_args']
1009 msan = 'is_msan=true' in vals['gn_args']
1010 tsan = 'is_tsan=true' in vals['gn_args']
pcc46233c22017-06-20 22:11:411011 cfi_diag = 'use_cfi_diag=true' in vals['gn_args']
dpranked8113582015-06-05 20:08:251012
dprankecb4a2e242016-09-19 01:13:141013 test_type = isolate_map[target]['type']
dprankefe0d35e2016-02-05 02:43:591014
dprankecb4a2e242016-09-19 01:13:141015 executable = isolate_map[target].get('executable', target)
Nico Weberd94b71a2018-02-22 22:00:301016 executable_suffix = '.exe' if is_win else ''
dprankefe0d35e2016-02-05 02:43:591017
dprankea55584f12015-07-22 00:52:471018 cmdline = []
Andrii Shyshkalovc158e0102018-01-10 05:52:001019 extra_files = [
1020 '../../.vpython',
1021 '../../testing/test_env.py',
1022 ]
dpranked8113582015-06-05 20:08:251023
dprankecb4a2e242016-09-19 01:13:141024 if test_type == 'nontest':
1025 self.WriteFailureAndRaise('We should not be isolating %s.' % target,
1026 output_path=None)
1027
Scott Graham3be4b4162017-09-12 00:41:411028 if is_android and test_type != "script":
bpastenee428ea92017-02-17 02:20:321029 cmdline = [
John Budorickfb97a852017-12-20 20:10:191030 '../../testing/test_env.py',
hzl9b15df52017-03-23 23:43:041031 '../../build/android/test_wrapper/logdog_wrapper.py',
1032 '--target', target,
hzl9ae14452017-04-04 23:38:021033 '--logdog-bin-cmd', '../../bin/logdog_butler',
hzlfc66094f2017-05-18 00:50:481034 '--store-tombstones']
Scott Graham3be4b4162017-09-12 00:41:411035 elif is_fuchsia and test_type != 'script':
John Budorickfb97a852017-12-20 20:10:191036 cmdline = [
1037 '../../testing/test_env.py',
1038 os.path.join('bin', 'run_%s' % target),
1039 ]
Benjamin Pastene3bce864e2018-04-14 01:16:321040 elif is_simplechrome and test_type != 'script':
1041 cmdline = [
1042 '../../testing/test_env.py',
1043 os.path.join('bin', 'run_%s' % target),
1044 ]
kylechar39705682017-01-19 14:37:231045 elif use_xvfb and test_type == 'windowed_test_launcher':
Andrii Shyshkalovc158e0102018-01-10 05:52:001046 extra_files.append('../../testing/xvfb.py')
dprankea55584f12015-07-22 00:52:471047 cmdline = [
dprankefe0d35e2016-02-05 02:43:591048 '../../testing/xvfb.py',
dprankefe0d35e2016-02-05 02:43:591049 './' + str(executable) + executable_suffix,
1050 '--brave-new-test-launcher',
1051 '--test-launcher-bot-mode',
1052 '--asan=%d' % asan,
1053 '--msan=%d' % msan,
1054 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:411055 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:471056 ]
1057 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
dprankea55584f12015-07-22 00:52:471058 cmdline = [
1059 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:591060 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:251061 '--brave-new-test-launcher',
1062 '--test-launcher-bot-mode',
1063 '--asan=%d' % asan,
1064 '--msan=%d' % msan,
1065 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:411066 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:471067 ]
dpranke6abd8652015-08-28 03:21:111068 elif test_type == 'script':
dpranke6abd8652015-08-28 03:21:111069 cmdline = [
1070 '../../testing/test_env.py',
dprankecb4a2e242016-09-19 01:13:141071 '../../' + self.ToSrcRelPath(isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:591072 ]
Dirk Prankef24e6b22018-03-27 20:12:301073 elif test_type in ('raw', 'additional_compile_target'):
dprankea55584f12015-07-22 00:52:471074 cmdline = [
1075 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:591076 ]
dprankea55584f12015-07-22 00:52:471077 else:
1078 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
1079 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:251080
Alexander Dunaev384ba482018-03-21 17:56:121081 if is_win and asan:
1082 # Sandbox is not yet supported by ASAN for Windows.
1083 # Perhaps this is only needed for tests that use the sandbox?
1084 cmdline.append('--no-sandbox')
1085
dprankecb4a2e242016-09-19 01:13:141086 cmdline += isolate_map[target].get('args', [])
dprankefe0d35e2016-02-05 02:43:591087
dpranked8113582015-06-05 20:08:251088 return cmdline, extra_files
1089
dpranke74559b52015-06-10 21:20:391090 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:331091 return self.PathJoin(self.chromium_src_dir,
1092 self.ToSrcRelPath(build_path),
1093 *comps)
dpranked8113582015-06-05 20:08:251094
dprankeee5b51f62015-04-09 00:03:221095 def ToSrcRelPath(self, path):
1096 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:501097 if path.startswith('//'):
1098 return path[2:].replace('/', self.sep)
1099 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:351100
Dirk Pranke0fd41bcd2015-06-19 00:05:501101 def RunGNAnalyze(self, vals):
dprankecb4a2e242016-09-19 01:13:141102 # Analyze runs before 'gn gen' now, so we need to run gn gen
Dirk Pranke0fd41bcd2015-06-19 00:05:501103 # in order to ensure that we have a build directory.
Dirk Prankea3727f92017-07-17 17:30:331104 ret = self.RunGNGen(vals, compute_grit_inputs_for_analyze=True)
Dirk Pranke0fd41bcd2015-06-19 00:05:501105 if ret:
1106 return ret
1107
Dirk Prankef24e6b22018-03-27 20:12:301108 build_path = self.args.path
1109 input_path = self.args.input_path
dprankecb4a2e242016-09-19 01:13:141110 gn_input_path = input_path + '.gn'
Dirk Prankef24e6b22018-03-27 20:12:301111 output_path = self.args.output_path
dprankecb4a2e242016-09-19 01:13:141112 gn_output_path = output_path + '.gn'
1113
dpranke7837fc362015-11-19 03:54:161114 inp = self.ReadInputJSON(['files', 'test_targets',
1115 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321116 if self.args.verbose:
1117 self.Print()
1118 self.Print('analyze input:')
1119 self.PrintJSON(inp)
1120 self.Print()
1121
dpranke76734662015-04-16 02:17:501122
dpranke7c5f614d2015-07-22 23:43:391123 # This shouldn't normally happen, but could due to unusual race conditions,
1124 # like a try job that gets scheduled before a patch lands but runs after
1125 # the patch has landed.
1126 if not inp['files']:
1127 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161128 self.WriteJSON({
1129 'status': 'No dependency',
1130 'compile_targets': [],
1131 'test_targets': [],
1132 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391133 return 0
1134
dprankecb4a2e242016-09-19 01:13:141135 gn_inp = {}
dprankeb7b183f2017-04-24 23:50:161136 gn_inp['files'] = ['//' + f for f in inp['files'] if not f.startswith('//')]
dprankef61de2f2015-05-14 04:09:561137
dprankecb4a2e242016-09-19 01:13:141138 isolate_map = self.ReadIsolateMap()
1139 err, gn_inp['additional_compile_targets'] = self.MapTargetsToLabels(
1140 isolate_map, inp['additional_compile_targets'])
1141 if err:
1142 raise MBErr(err)
1143
1144 err, gn_inp['test_targets'] = self.MapTargetsToLabels(
1145 isolate_map, inp['test_targets'])
1146 if err:
1147 raise MBErr(err)
1148 labels_to_targets = {}
1149 for i, label in enumerate(gn_inp['test_targets']):
1150 labels_to_targets[label] = inp['test_targets'][i]
1151
dprankef61de2f2015-05-14 04:09:561152 try:
dprankecb4a2e242016-09-19 01:13:141153 self.WriteJSON(gn_inp, gn_input_path)
1154 cmd = self.GNCmd('analyze', build_path, gn_input_path, gn_output_path)
1155 ret, _, _ = self.Run(cmd, force_verbose=True)
1156 if ret:
1157 return ret
dpranke067d0142015-05-14 22:52:451158
dprankecb4a2e242016-09-19 01:13:141159 gn_outp_str = self.ReadFile(gn_output_path)
1160 try:
1161 gn_outp = json.loads(gn_outp_str)
1162 except Exception as e:
1163 self.Print("Failed to parse the JSON string GN returned: %s\n%s"
1164 % (repr(gn_outp_str), str(e)))
1165 raise
1166
1167 outp = {}
1168 if 'status' in gn_outp:
1169 outp['status'] = gn_outp['status']
1170 if 'error' in gn_outp:
1171 outp['error'] = gn_outp['error']
1172 if 'invalid_targets' in gn_outp:
1173 outp['invalid_targets'] = gn_outp['invalid_targets']
1174 if 'compile_targets' in gn_outp:
Dirk Pranke45165072017-11-08 04:57:491175 all_input_compile_targets = sorted(
1176 set(inp['test_targets'] + inp['additional_compile_targets']))
1177
1178 # If we're building 'all', we can throw away the rest of the targets
1179 # since they're redundant.
dpranke385a3102016-09-20 22:04:081180 if 'all' in gn_outp['compile_targets']:
1181 outp['compile_targets'] = ['all']
1182 else:
Dirk Pranke45165072017-11-08 04:57:491183 outp['compile_targets'] = gn_outp['compile_targets']
1184
1185 # crbug.com/736215: When GN returns targets back, for targets in
1186 # the default toolchain, GN will have generated a phony ninja
1187 # target matching the label, and so we can safely (and easily)
1188 # transform any GN label into the matching ninja target. For
1189 # targets in other toolchains, though, GN doesn't generate the
1190 # phony targets, and we don't know how to turn the labels into
1191 # compile targets. In this case, we also conservatively give up
1192 # and build everything. Probably the right thing to do here is
1193 # to have GN return the compile targets directly.
1194 if any("(" in target for target in outp['compile_targets']):
1195 self.Print('WARNING: targets with non-default toolchains were '
1196 'found, building everything instead.')
1197 outp['compile_targets'] = all_input_compile_targets
1198 else:
dpranke385a3102016-09-20 22:04:081199 outp['compile_targets'] = [
Dirk Pranke45165072017-11-08 04:57:491200 label.replace('//', '') for label in outp['compile_targets']]
1201
1202 # Windows has a maximum command line length of 8k; even Linux
1203 # maxes out at 128k; if analyze returns a *really long* list of
1204 # targets, we just give up and conservatively build everything instead.
1205 # Probably the right thing here is for ninja to support response
1206 # files as input on the command line
1207 # (see https://github.com/ninja-build/ninja/issues/1355).
1208 if len(' '.join(outp['compile_targets'])) > 7*1024:
1209 self.Print('WARNING: Too many compile targets were affected.')
1210 self.Print('WARNING: Building everything instead to avoid '
1211 'command-line length issues.')
1212 outp['compile_targets'] = all_input_compile_targets
1213
1214
dprankecb4a2e242016-09-19 01:13:141215 if 'test_targets' in gn_outp:
1216 outp['test_targets'] = [
1217 labels_to_targets[label] for label in gn_outp['test_targets']]
1218
1219 if self.args.verbose:
1220 self.Print()
1221 self.Print('analyze output:')
1222 self.PrintJSON(outp)
1223 self.Print()
1224
1225 self.WriteJSON(outp, output_path)
1226
dprankef61de2f2015-05-14 04:09:561227 finally:
dprankecb4a2e242016-09-19 01:13:141228 if self.Exists(gn_input_path):
1229 self.RemoveFile(gn_input_path)
1230 if self.Exists(gn_output_path):
1231 self.RemoveFile(gn_output_path)
dprankefe4602312015-04-08 16:20:351232
1233 return 0
1234
dpranked8113582015-06-05 20:08:251235 def ReadInputJSON(self, required_keys):
Dirk Prankef24e6b22018-03-27 20:12:301236 path = self.args.input_path
1237 output_path = self.args.output_path
dprankefe4602312015-04-08 16:20:351238 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321239 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351240
1241 try:
1242 inp = json.loads(self.ReadFile(path))
1243 except Exception as e:
1244 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321245 (path, e), output_path)
dpranked8113582015-06-05 20:08:251246
1247 for k in required_keys:
1248 if not k in inp:
1249 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1250 output_path)
dprankefe4602312015-04-08 16:20:351251
1252 return inp
1253
dpranked5b2b9432015-06-23 16:55:301254 def WriteFailureAndRaise(self, msg, output_path):
1255 if output_path:
dprankee0547cd2015-09-15 01:27:401256 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351257 raise MBErr(msg)
1258
dprankee0547cd2015-09-15 01:27:401259 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321260 try:
dprankee0547cd2015-09-15 01:27:401261 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1262 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321263 except Exception as e:
1264 raise MBErr('Error %s writing to the output path "%s"' %
1265 (e, path))
dprankefe4602312015-04-08 16:20:351266
aneeshmde50f472016-04-01 01:13:101267 def CheckCompile(self, master, builder):
1268 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1269 url = urllib2.quote(url_template.format(master=master, builder=builder),
1270 safe=':/()?=')
1271 try:
1272 builds = json.loads(self.Fetch(url))
1273 except Exception as e:
1274 return str(e)
1275 successes = sorted(
1276 [int(x) for x in builds.keys() if "text" in builds[x] and
1277 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1278 reverse=True)
1279 if not successes:
1280 return "no successful builds"
1281 build = builds[str(successes[0])]
1282 step_names = set([step["name"] for step in build["steps"]])
1283 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1284 if compile_indicators & step_names:
1285 return "compiles"
1286 return "does not compile"
1287
dpranke3cec199c2015-09-22 23:29:021288 def PrintCmd(self, cmd, env):
1289 if self.platform == 'win32':
1290 env_prefix = 'set '
1291 env_quoter = QuoteForSet
1292 shell_quoter = QuoteForCmd
1293 else:
1294 env_prefix = ''
1295 env_quoter = pipes.quote
1296 shell_quoter = pipes.quote
1297
1298 def print_env(var):
1299 if env and var in env:
1300 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1301
dprankeec079262016-06-07 02:21:201302 print_env('LLVM_FORCE_HEAD_REVISION')
dpranke3cec199c2015-09-22 23:29:021303
dpranke8c2cfd32015-09-17 20:12:331304 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351305 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021306 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351307
dprankecda00332015-04-11 04:18:321308 def PrintJSON(self, obj):
1309 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1310
dpranke751516a2015-10-03 01:11:341311 def Build(self, target):
Dirk Prankef24e6b22018-03-27 20:12:301312 build_dir = self.ToSrcRelPath(self.args.path)
Mike Meade9c100ff2018-03-30 23:09:381313 if self.platform == 'win32':
1314 # On Windows use the batch script since there is no exe
1315 ninja_cmd = ['autoninja.bat', '-C', build_dir]
1316 else:
1317 ninja_cmd = ['autoninja', '-C', build_dir]
dpranke751516a2015-10-03 01:11:341318 if self.args.jobs:
1319 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1320 ninja_cmd.append(target)
1321 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1322 return ret
1323
1324 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351325 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401326 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021327 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351328 if self.args.dryrun:
1329 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401330
dpranke751516a2015-10-03 01:11:341331 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401332 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341333 if ret:
1334 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351335 if out:
dprankeee5b51f62015-04-09 00:03:221336 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351337 if err:
dprankeee5b51f62015-04-09 00:03:221338 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351339 return ret, out, err
1340
dpranke751516a2015-10-03 01:11:341341 def Call(self, cmd, env=None, buffer_output=True):
1342 if buffer_output:
1343 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1344 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1345 env=env)
1346 out, err = p.communicate()
1347 else:
1348 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1349 env=env)
1350 p.wait()
1351 out = err = ''
dprankefe4602312015-04-08 16:20:351352 return p.returncode, out, err
1353
1354 def ExpandUser(self, path):
1355 # This function largely exists so it can be overridden for testing.
1356 return os.path.expanduser(path)
1357
1358 def Exists(self, path):
1359 # This function largely exists so it can be overridden for testing.
1360 return os.path.exists(path)
1361
dpranke867bcf4a2016-03-14 22:28:321362 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501363 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321364 f = urllib2.urlopen(url)
1365 contents = f.read()
1366 f.close()
1367 return contents
1368
dprankec3441d12015-06-23 23:01:351369 def MaybeMakeDirectory(self, path):
1370 try:
1371 os.makedirs(path)
1372 except OSError, e:
1373 if e.errno != errno.EEXIST:
1374 raise
1375
dpranke8c2cfd32015-09-17 20:12:331376 def PathJoin(self, *comps):
1377 # This function largely exists so it can be overriden for testing.
1378 return os.path.join(*comps)
1379
dpranke030d7a6d2016-03-26 17:23:501380 def Print(self, *args, **kwargs):
1381 # This function largely exists so it can be overridden for testing.
1382 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101383 if kwargs.get('stream', sys.stdout) == sys.stdout:
1384 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501385
dprankefe4602312015-04-08 16:20:351386 def ReadFile(self, path):
1387 # This function largely exists so it can be overriden for testing.
1388 with open(path) as fp:
1389 return fp.read()
1390
dpranke030d7a6d2016-03-26 17:23:501391 def RelPath(self, path, start='.'):
1392 # This function largely exists so it can be overriden for testing.
1393 return os.path.relpath(path, start)
1394
dprankef61de2f2015-05-14 04:09:561395 def RemoveFile(self, path):
1396 # This function largely exists so it can be overriden for testing.
1397 os.remove(path)
1398
dprankec161aa92015-09-14 20:21:131399 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331400 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131401 # In other places in chromium, we often have to retry this command
1402 # because we're worried about other processes still holding on to
1403 # file handles, but when MB is invoked, it will be early enough in the
1404 # build that their should be no other processes to interfere. We
1405 # can change this if need be.
1406 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1407 else:
1408 shutil.rmtree(abs_path, ignore_errors=True)
1409
Dirk Prankef24e6b22018-03-27 20:12:301410 def TempDir(self):
1411 # This function largely exists so it can be overriden for testing.
1412 return tempfile.mkdtemp(prefix='mb_')
1413
dprankef61de2f2015-05-14 04:09:561414 def TempFile(self, mode='w'):
1415 # This function largely exists so it can be overriden for testing.
1416 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1417
dprankee0547cd2015-09-15 01:27:401418 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351419 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401420 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301421 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351422 with open(path, 'w') as fp:
1423 return fp.write(contents)
1424
dprankef61de2f2015-05-14 04:09:561425
dprankefe4602312015-04-08 16:20:351426class MBErr(Exception):
1427 pass
1428
1429
dpranke3cec199c2015-09-22 23:29:021430# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1431# details of this next section, which handles escaping command lines
1432# so that they can be copied and pasted into a cmd window.
1433UNSAFE_FOR_SET = set('^<>&|')
1434UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1435ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1436
1437
1438def QuoteForSet(arg):
1439 if any(a in UNSAFE_FOR_SET for a in arg):
1440 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1441 return arg
1442
1443
1444def QuoteForCmd(arg):
1445 # First, escape the arg so that CommandLineToArgvW will parse it properly.
dpranke3cec199c2015-09-22 23:29:021446 if arg == '' or ' ' in arg or '"' in arg:
1447 quote_re = re.compile(r'(\\*)"')
1448 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1449
1450 # Then check to see if the arg contains any metacharacters other than
1451 # double quotes; if it does, quote everything (including the double
1452 # quotes) for safety.
1453 if any(a in UNSAFE_FOR_CMD for a in arg):
1454 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1455 return arg
1456
1457
dprankefe4602312015-04-08 16:20:351458if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591459 sys.exit(main(sys.argv[1:]))