blob: 6905bccf48848f04c983c1026f9339791449b153 [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
6"""MB - the Meta-Build wrapper around GYP and GN
7
8MB is a wrapper script for GYP and GN that can be used to generate build files
9for sets of canned configurations and analyze them.
10"""
11
thomasanderson55733612017-07-14 01:34:3112# TODO(thomasanderson): Remove this comment. It is added to
13# workaround https://crbug.com/736215 for CL
14# https://codereview.chromium.org/2974603002/
15
dprankefe4602312015-04-08 16:20:3516from __future__ import print_function
17
18import argparse
19import ast
dprankec3441d12015-06-23 23:01:3520import errno
dprankefe4602312015-04-08 16:20:3521import json
22import os
dpranke68d1cb182015-09-17 23:30:0023import pipes
dpranked8113582015-06-05 20:08:2524import pprint
dpranke3cec199c2015-09-22 23:29:0225import re
dprankefe4602312015-04-08 16:20:3526import shutil
27import sys
28import subprocess
dprankef61de2f2015-05-14 04:09:5629import tempfile
dprankebbe6d4672016-04-19 06:56:5730import traceback
dpranke867bcf4a2016-03-14 22:28:3231import urllib2
32
33from collections import OrderedDict
dprankefe4602312015-04-08 16:20:3534
dprankeeca4a782016-04-14 01:42:3835CHROMIUM_SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
36 os.path.abspath(__file__))))
37sys.path = [os.path.join(CHROMIUM_SRC_DIR, 'build')] + sys.path
38
39import gn_helpers
40
41
dprankefe4602312015-04-08 16:20:3542def main(args):
dprankeee5b51f62015-04-09 00:03:2243 mbw = MetaBuildWrapper()
dpranke255085e2016-03-16 05:23:5944 return mbw.Main(args)
dprankefe4602312015-04-08 16:20:3545
46
47class MetaBuildWrapper(object):
48 def __init__(self):
dprankeeca4a782016-04-14 01:42:3849 self.chromium_src_dir = CHROMIUM_SRC_DIR
50 self.default_config = os.path.join(self.chromium_src_dir, 'tools', 'mb',
51 'mb_config.pyl')
kjellander902bcb62016-10-26 06:20:5052 self.default_isolate_map = os.path.join(self.chromium_src_dir, 'testing',
53 'buildbot', 'gn_isolate_map.pyl')
dpranke8c2cfd32015-09-17 20:12:3354 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5155 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3356 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3557 self.args = argparse.Namespace()
58 self.configs = {}
59 self.masters = {}
60 self.mixins = {}
dprankefe4602312015-04-08 16:20:3561
dpranke255085e2016-03-16 05:23:5962 def Main(self, args):
63 self.ParseArgs(args)
64 try:
65 ret = self.args.func()
66 if ret:
67 self.DumpInputFiles()
68 return ret
69 except KeyboardInterrupt:
dprankecb4a2e242016-09-19 01:13:1470 self.Print('interrupted, exiting')
dpranke255085e2016-03-16 05:23:5971 return 130
dprankebbe6d4672016-04-19 06:56:5772 except Exception:
dpranke255085e2016-03-16 05:23:5973 self.DumpInputFiles()
dprankebbe6d4672016-04-19 06:56:5774 s = traceback.format_exc()
75 for l in s.splitlines():
76 self.Print(l)
dpranke255085e2016-03-16 05:23:5977 return 1
78
dprankefe4602312015-04-08 16:20:3579 def ParseArgs(self, argv):
80 def AddCommonOptions(subp):
81 subp.add_argument('-b', '--builder',
82 help='builder name to look up config from')
83 subp.add_argument('-m', '--master',
84 help='master name to look up config from')
85 subp.add_argument('-c', '--config',
86 help='configuration to analyze')
shenghuazhang804b21542016-10-11 02:06:4987 subp.add_argument('--phase',
88 help='optional phase name (used when builders '
89 'do multiple compiles with different '
90 'arguments in a single build)')
dprankefe4602312015-04-08 16:20:3591 subp.add_argument('-f', '--config-file', metavar='PATH',
92 default=self.default_config,
93 help='path to config file '
kjellander902bcb62016-10-26 06:20:5094 '(default is %(default)s)')
95 subp.add_argument('-i', '--isolate-map-file', metavar='PATH',
96 default=self.default_isolate_map,
97 help='path to isolate map file '
98 '(default is %(default)s)')
dpranked0c138b2016-04-13 18:28:4799 subp.add_argument('-g', '--goma-dir',
100 help='path to goma directory')
machenbach60ebf6202016-06-07 14:27:39101 subp.add_argument('--gyp-script', metavar='PATH',
102 default=self.PathJoin('build', 'gyp_chromium'),
103 help='path to gyp script relative to project root '
104 '(default is %(default)s)')
agrieve41d21a72016-04-14 18:02:26105 subp.add_argument('--android-version-code',
106 help='Sets GN arg android_default_version_code and '
107 'GYP_DEFINE app_manifest_version_code')
108 subp.add_argument('--android-version-name',
109 help='Sets GN arg android_default_version_name and '
110 'GYP_DEFINE app_manifest_version_name')
dprankefe4602312015-04-08 16:20:35111 subp.add_argument('-n', '--dryrun', action='store_true',
112 help='Do a dry run (i.e., do nothing, just print '
113 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:40114 subp.add_argument('-v', '--verbose', action='store_true',
115 help='verbose logging')
dprankefe4602312015-04-08 16:20:35116
117 parser = argparse.ArgumentParser(prog='mb')
118 subps = parser.add_subparsers()
119
120 subp = subps.add_parser('analyze',
121 help='analyze whether changes to a set of files '
122 'will cause a set of binaries to be rebuilt.')
123 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:25124 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35125 help='path build was generated into.')
126 subp.add_argument('input_path', nargs=1,
127 help='path to a file containing the input arguments '
128 'as a JSON object.')
129 subp.add_argument('output_path', nargs=1,
130 help='path to a file containing the output arguments '
131 'as a JSON object.')
132 subp.set_defaults(func=self.CmdAnalyze)
133
dprankef37aebb92016-09-23 01:14:49134 subp = subps.add_parser('export',
135 help='print out the expanded configuration for'
136 'each builder as a JSON object')
137 subp.add_argument('-f', '--config-file', metavar='PATH',
138 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50139 help='path to config file (default is %(default)s)')
dprankef37aebb92016-09-23 01:14:49140 subp.add_argument('-g', '--goma-dir',
141 help='path to goma directory')
142 subp.set_defaults(func=self.CmdExport)
143
dprankefe4602312015-04-08 16:20:35144 subp = subps.add_parser('gen',
145 help='generate a new set of build files')
146 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39147 subp.add_argument('--swarming-targets-file',
148 help='save runtime dependencies for targets listed '
149 'in file.')
dpranked8113582015-06-05 20:08:25150 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35151 help='path to generate build into')
152 subp.set_defaults(func=self.CmdGen)
153
dpranke751516a2015-10-03 01:11:34154 subp = subps.add_parser('isolate',
155 help='generate the .isolate files for a given'
156 'binary')
157 AddCommonOptions(subp)
158 subp.add_argument('path', nargs=1,
159 help='path build was generated into')
160 subp.add_argument('target', nargs=1,
161 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 )
191
dpranke751516a2015-10-03 01:11:34192 AddCommonOptions(subp)
193 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
194 help='Number of jobs to pass to ninja')
195 subp.add_argument('--no-build', dest='build', default=True,
196 action='store_false',
197 help='Do not build, just isolate and run')
198 subp.add_argument('path', nargs=1,
dpranke030d7a6d2016-03-26 17:23:50199 help=('path to generate build into (or use).'
200 ' This can be either a regular path or a '
201 'GN-style source-relative path like '
202 '//out/Default.'))
dpranke751516a2015-10-03 01:11:34203 subp.add_argument('target', nargs=1,
204 help='ninja target to build and run')
dpranke030d7a6d2016-03-26 17:23:50205 subp.add_argument('extra_args', nargs='*',
206 help=('extra args to pass to the isolate to run. Use '
207 '"--" as the first arg if you need to pass '
208 'switches'))
dpranke751516a2015-10-03 01:11:34209 subp.set_defaults(func=self.CmdRun)
210
dprankefe4602312015-04-08 16:20:35211 subp = subps.add_parser('validate',
212 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17213 subp.add_argument('-f', '--config-file', metavar='PATH',
214 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50215 help='path to config file (default is %(default)s)')
dprankefe4602312015-04-08 16:20:35216 subp.set_defaults(func=self.CmdValidate)
217
dpranke867bcf4a2016-03-14 22:28:32218 subp = subps.add_parser('audit',
219 help='Audit the config file to track progress')
220 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)')
dpranke867bcf4a2016-03-14 22:28:32223 subp.add_argument('-i', '--internal', action='store_true',
224 help='check internal masters also')
225 subp.add_argument('-m', '--master', action='append',
226 help='master to audit (default is all non-internal '
227 'masters in file)')
228 subp.add_argument('-u', '--url-template', action='store',
229 default='https://build.chromium.org/p/'
230 '{master}/json/builders',
231 help='URL scheme for JSON APIs to buildbot '
232 '(default: %(default)s) ')
aneeshmde50f472016-04-01 01:13:10233 subp.add_argument('-c', '--check-compile', action='store_true',
234 help='check whether tbd and master-only bots actually'
235 ' do compiles')
dpranke867bcf4a2016-03-14 22:28:32236 subp.set_defaults(func=self.CmdAudit)
237
dprankefe4602312015-04-08 16:20:35238 subp = subps.add_parser('help',
239 help='Get help on a subcommand.')
240 subp.add_argument(nargs='?', action='store', dest='subcommand',
241 help='The command to get help for.')
242 subp.set_defaults(func=self.CmdHelp)
243
244 self.args = parser.parse_args(argv)
245
dprankeb2be10a2016-02-22 17:11:00246 def DumpInputFiles(self):
247
dprankef7b7eb7a2016-03-28 22:42:59248 def DumpContentsOfFilePassedTo(arg_name, path):
dprankeb2be10a2016-02-22 17:11:00249 if path and self.Exists(path):
dprankef7b7eb7a2016-03-28 22:42:59250 self.Print("\n# To recreate the file passed to %s:" % arg_name)
dprankecb4a2e242016-09-19 01:13:14251 self.Print("%% cat > %s <<EOF" % path)
dprankeb2be10a2016-02-22 17:11:00252 contents = self.ReadFile(path)
dprankef7b7eb7a2016-03-28 22:42:59253 self.Print(contents)
254 self.Print("EOF\n%\n")
dprankeb2be10a2016-02-22 17:11:00255
dprankef7b7eb7a2016-03-28 22:42:59256 if getattr(self.args, 'input_path', None):
257 DumpContentsOfFilePassedTo(
258 'argv[0] (input_path)', self.args.input_path[0])
259 if getattr(self.args, 'swarming_targets_file', None):
260 DumpContentsOfFilePassedTo(
261 '--swarming-targets-file', self.args.swarming_targets_file)
dprankeb2be10a2016-02-22 17:11:00262
dprankefe4602312015-04-08 16:20:35263 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34264 vals = self.Lookup()
dprankee88057c2016-04-12 22:40:08265 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35266 if vals['type'] == 'gn':
267 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35268 else:
dpranke751516a2015-10-03 01:11:34269 return self.RunGYPAnalyze(vals)
dprankefe4602312015-04-08 16:20:35270
dprankef37aebb92016-09-23 01:14:49271 def CmdExport(self):
272 self.ReadConfigFile()
273 obj = {}
274 for master, builders in self.masters.items():
275 obj[master] = {}
276 for builder in builders:
277 config = self.masters[master][builder]
278 if not config:
279 continue
280
shenghuazhang804b21542016-10-11 02:06:49281 if isinstance(config, dict):
282 args = {k: self.FlattenConfig(v)['gn_args']
283 for k, v in config.items()}
dprankef37aebb92016-09-23 01:14:49284 elif config.startswith('//'):
285 args = config
286 else:
287 args = self.FlattenConfig(config)['gn_args']
288 if 'error' in args:
289 continue
290
291 obj[master][builder] = args
292
293 # Dump object and trim trailing whitespace.
294 s = '\n'.join(l.rstrip() for l in
295 json.dumps(obj, sort_keys=True, indent=2).splitlines())
296 self.Print(s)
297 return 0
298
dprankefe4602312015-04-08 16:20:35299 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34300 vals = self.Lookup()
dprankec161aa92015-09-14 20:21:13301 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35302 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50303 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35304 else:
dpranke751516a2015-10-03 01:11:34305 return self.RunGYPGen(vals)
dprankefe4602312015-04-08 16:20:35306
307 def CmdHelp(self):
308 if self.args.subcommand:
309 self.ParseArgs([self.args.subcommand, '--help'])
310 else:
311 self.ParseArgs(['--help'])
312
dpranke751516a2015-10-03 01:11:34313 def CmdIsolate(self):
314 vals = self.GetConfig()
315 if not vals:
316 return 1
317
318 if vals['type'] == 'gn':
319 return self.RunGNIsolate(vals)
320 else:
321 return self.Build('%s_run' % self.args.target[0])
322
323 def CmdLookup(self):
324 vals = self.Lookup()
325 if vals['type'] == 'gn':
dprankeeca4a782016-04-14 01:42:38326 cmd = self.GNCmd('gen', '_path_')
327 gn_args = self.GNArgs(vals)
328 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
dpranke751516a2015-10-03 01:11:34329 env = None
330 else:
331 cmd, env = self.GYPCmd('_path_', vals)
332
333 self.PrintCmd(cmd, env)
334 return 0
335
336 def CmdRun(self):
337 vals = self.GetConfig()
338 if not vals:
339 return 1
340
341 build_dir = self.args.path[0]
342 target = self.args.target[0]
343
344 if vals['type'] == 'gn':
345 if self.args.build:
346 ret = self.Build(target)
347 if ret:
348 return ret
349 ret = self.RunGNIsolate(vals)
350 if ret:
351 return ret
352 else:
353 ret = self.Build('%s_run' % target)
354 if ret:
355 return ret
356
dpranke030d7a6d2016-03-26 17:23:50357 cmd = [
dpranke751516a2015-10-03 01:11:34358 self.executable,
359 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
360 'run',
361 '-s',
dpranke030d7a6d2016-03-26 17:23:50362 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
363 ]
364 if self.args.extra_args:
365 cmd += ['--'] + self.args.extra_args
366
367 ret, _, _ = self.Run(cmd, force_verbose=False, buffer_output=False)
dpranke751516a2015-10-03 01:11:34368
369 return ret
370
dpranke0cafc162016-03-19 00:41:10371 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35372 errs = []
373
374 # Read the file to make sure it parses.
375 self.ReadConfigFile()
376
dpranke3be00142016-03-17 22:46:04377 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35378 all_configs = {}
dprankefe4602312015-04-08 16:20:35379 for master in self.masters:
dpranke3be00142016-03-17 22:46:04380 for config in self.masters[master].values():
shenghuazhang804b21542016-10-11 02:06:49381 if isinstance(config, dict):
382 for c in config.values():
dprankeb9380a12016-07-21 21:44:09383 all_configs[c] = master
384 else:
385 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35386
dpranke9dd5e252016-04-14 04:23:09387 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35388 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09389 if config.startswith('//'):
390 if not self.Exists(self.ToAbsPath(config)):
391 errs.append('Unknown args file "%s" referenced from "%s".' %
392 (config, loc))
393 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35394 errs.append('Unknown config "%s" referenced from "%s".' %
395 (config, loc))
396
397 # Check that every actual config is actually referenced.
398 for config in self.configs:
399 if not config in all_configs:
400 errs.append('Unused config "%s".' % config)
401
402 # Figure out the whole list of mixins, and check that every mixin
403 # listed by a config or another mixin actually exists.
404 referenced_mixins = set()
405 for config, mixins in self.configs.items():
406 for mixin in mixins:
407 if not mixin in self.mixins:
408 errs.append('Unknown mixin "%s" referenced by config "%s".' %
409 (mixin, config))
410 referenced_mixins.add(mixin)
411
412 for mixin in self.mixins:
413 for sub_mixin in self.mixins[mixin].get('mixins', []):
414 if not sub_mixin in self.mixins:
415 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
416 (sub_mixin, mixin))
417 referenced_mixins.add(sub_mixin)
418
419 # Check that every mixin defined is actually referenced somewhere.
420 for mixin in self.mixins:
421 if not mixin in referenced_mixins:
422 errs.append('Unreferenced mixin "%s".' % mixin)
423
dpranke255085e2016-03-16 05:23:59424 # If we're checking the Chromium config, check that the 'chromium' bots
425 # which build public artifacts do not include the chrome_with_codecs mixin.
426 if self.args.config_file == self.default_config:
427 if 'chromium' in self.masters:
428 for builder in self.masters['chromium']:
429 config = self.masters['chromium'][builder]
430 def RecurseMixins(current_mixin):
431 if current_mixin == 'chrome_with_codecs':
432 errs.append('Public artifact builder "%s" can not contain the '
433 '"chrome_with_codecs" mixin.' % builder)
434 return
435 if not 'mixins' in self.mixins[current_mixin]:
436 return
437 for mixin in self.mixins[current_mixin]['mixins']:
438 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41439
dpranke255085e2016-03-16 05:23:59440 for mixin in self.configs[config]:
441 RecurseMixins(mixin)
442 else:
443 errs.append('Missing "chromium" master. Please update this '
444 'proprietary codecs check with the name of the master '
445 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41446
dprankefe4602312015-04-08 16:20:35447 if errs:
dpranke4323c80632015-08-10 22:53:54448 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17449 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35450
dpranke0cafc162016-03-19 00:41:10451 if print_ok:
452 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35453 return 0
454
dpranke867bcf4a2016-03-14 22:28:32455 def CmdAudit(self):
456 """Track the progress of the GYP->GN migration on the bots."""
457
dpranke0cafc162016-03-19 00:41:10458 # First, make sure the config file is okay, but don't print anything
459 # if it is (it will throw an error if it isn't).
460 self.CmdValidate(print_ok=False)
461
dpranke867bcf4a2016-03-14 22:28:32462 stats = OrderedDict()
463 STAT_MASTER_ONLY = 'Master only'
464 STAT_CONFIG_ONLY = 'Config only'
465 STAT_TBD = 'Still TBD'
466 STAT_GYP = 'Still GYP'
467 STAT_DONE = 'Done (on GN)'
468 stats[STAT_MASTER_ONLY] = 0
469 stats[STAT_CONFIG_ONLY] = 0
470 stats[STAT_TBD] = 0
471 stats[STAT_GYP] = 0
472 stats[STAT_DONE] = 0
473
aneeshmde50f472016-04-01 01:13:10474 def PrintBuilders(heading, builders, notes):
dpranke867bcf4a2016-03-14 22:28:32475 stats.setdefault(heading, 0)
476 stats[heading] += len(builders)
477 if builders:
478 self.Print(' %s:' % heading)
479 for builder in sorted(builders):
aneeshmde50f472016-04-01 01:13:10480 self.Print(' %s%s' % (builder, notes[builder]))
dpranke867bcf4a2016-03-14 22:28:32481
482 self.ReadConfigFile()
483
484 masters = self.args.master or self.masters
485 for master in sorted(masters):
486 url = self.args.url_template.replace('{master}', master)
487
488 self.Print('Auditing %s' % master)
489
490 MASTERS_TO_SKIP = (
491 'client.skia',
492 'client.v8.fyi',
493 'tryserver.v8',
494 )
495 if master in MASTERS_TO_SKIP:
496 # Skip these bots because converting them is the responsibility of
497 # those teams and out of scope for the Chromium migration to GN.
498 self.Print(' Skipped (out of scope)')
499 self.Print('')
500 continue
501
dpranke6b6e0b82016-07-28 21:32:34502 INTERNAL_MASTERS = ('official.desktop', 'official.desktop.continuous',
503 'internal.client.kitchensync')
dpranke867bcf4a2016-03-14 22:28:32504 if master in INTERNAL_MASTERS and not self.args.internal:
505 # Skip these because the servers aren't accessible by default ...
506 self.Print(' Skipped (internal)')
507 self.Print('')
508 continue
509
510 try:
511 # Fetch the /builders contents from the buildbot master. The
512 # keys of the dict are the builder names themselves.
513 json_contents = self.Fetch(url)
514 d = json.loads(json_contents)
515 except Exception as e:
516 self.Print(str(e))
517 return 1
518
519 config_builders = set(self.masters[master])
520 master_builders = set(d.keys())
521 both = master_builders & config_builders
522 master_only = master_builders - config_builders
523 config_only = config_builders - master_builders
524 tbd = set()
525 gyp = set()
526 done = set()
aneeshmde50f472016-04-01 01:13:10527 notes = {builder: '' for builder in config_builders | master_builders}
dpranke867bcf4a2016-03-14 22:28:32528
529 for builder in both:
530 config = self.masters[master][builder]
531 if config == 'tbd':
532 tbd.add(builder)
shenghuazhang804b21542016-10-11 02:06:49533 elif isinstance(config, dict):
534 vals = self.FlattenConfig(config.values()[0])
dprankeb9380a12016-07-21 21:44:09535 if vals['type'] == 'gyp':
536 gyp.add(builder)
537 else:
538 done.add(builder)
dprankebbe6d4672016-04-19 06:56:57539 elif config.startswith('//'):
540 done.add(builder)
dpranke867bcf4a2016-03-14 22:28:32541 else:
dpranke867bcf4a2016-03-14 22:28:32542 vals = self.FlattenConfig(config)
543 if vals['type'] == 'gyp':
544 gyp.add(builder)
545 else:
546 done.add(builder)
547
aneeshmde50f472016-04-01 01:13:10548 if self.args.check_compile and (tbd or master_only):
549 either = tbd | master_only
550 for builder in either:
551 notes[builder] = ' (' + self.CheckCompile(master, builder) +')'
552
dpranke867bcf4a2016-03-14 22:28:32553 if master_only or config_only or tbd or gyp:
aneeshmde50f472016-04-01 01:13:10554 PrintBuilders(STAT_MASTER_ONLY, master_only, notes)
555 PrintBuilders(STAT_CONFIG_ONLY, config_only, notes)
556 PrintBuilders(STAT_TBD, tbd, notes)
557 PrintBuilders(STAT_GYP, gyp, notes)
dpranke867bcf4a2016-03-14 22:28:32558 else:
dprankebbe6d4672016-04-19 06:56:57559 self.Print(' All GN!')
dpranke867bcf4a2016-03-14 22:28:32560
561 stats[STAT_DONE] += len(done)
562
563 self.Print('')
564
565 fmt = '{:<27} {:>4}'
566 self.Print(fmt.format('Totals', str(sum(int(v) for v in stats.values()))))
567 self.Print(fmt.format('-' * 27, '----'))
568 for stat, count in stats.items():
569 self.Print(fmt.format(stat, str(count)))
570
571 return 0
572
dprankefe4602312015-04-08 16:20:35573 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34574 build_dir = self.args.path[0]
575
dprankef37aebb92016-09-23 01:14:49576 vals = self.DefaultVals()
dpranke751516a2015-10-03 01:11:34577 if self.args.builder or self.args.master or self.args.config:
578 vals = self.Lookup()
579 if vals['type'] == 'gn':
580 # Re-run gn gen in order to ensure the config is consistent with the
581 # build dir.
582 self.RunGNGen(vals)
583 return vals
584
dpranke751516a2015-10-03 01:11:34585 mb_type_path = self.PathJoin(self.ToAbsPath(build_dir), 'mb_type')
586 if not self.Exists(mb_type_path):
brucedawsonecc0c1cd2016-06-02 18:24:58587 toolchain_path = self.PathJoin(self.ToAbsPath(build_dir),
588 'toolchain.ninja')
589 if not self.Exists(toolchain_path):
dpranke751516a2015-10-03 01:11:34590 self.Print('Must either specify a path to an existing GN build dir '
591 'or pass in a -m/-b pair or a -c flag to specify the '
592 'configuration')
593 return {}
594 else:
595 mb_type = 'gn'
596 else:
597 mb_type = self.ReadFile(mb_type_path).strip()
598
599 if mb_type == 'gn':
dprankef37aebb92016-09-23 01:14:49600 vals['gn_args'] = self.GNArgsFromDir(build_dir)
dpranke751516a2015-10-03 01:11:34601 vals['type'] = mb_type
602
603 return vals
604
dprankef37aebb92016-09-23 01:14:49605 def GNArgsFromDir(self, build_dir):
brucedawsonecc0c1cd2016-06-02 18:24:58606 args_contents = ""
607 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
608 if self.Exists(gn_args_path):
609 args_contents = self.ReadFile(gn_args_path)
dpranke751516a2015-10-03 01:11:34610 gn_args = []
611 for l in args_contents.splitlines():
612 fields = l.split(' ')
613 name = fields[0]
614 val = ' '.join(fields[2:])
615 gn_args.append('%s=%s' % (name, val))
616
dprankef37aebb92016-09-23 01:14:49617 return ' '.join(gn_args)
dpranke751516a2015-10-03 01:11:34618
619 def Lookup(self):
dprankef37aebb92016-09-23 01:14:49620 vals = self.ReadIOSBotConfig()
dprankee0f486f2015-11-19 23:42:00621 if not vals:
622 self.ReadConfigFile()
623 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09624 if config.startswith('//'):
625 if not self.Exists(self.ToAbsPath(config)):
626 raise MBErr('args file "%s" not found' % config)
dprankef37aebb92016-09-23 01:14:49627 vals = self.DefaultVals()
628 vals['args_file'] = config
dpranke9dd5e252016-04-14 04:23:09629 else:
630 if not config in self.configs:
631 raise MBErr('Config "%s" not found in %s' %
632 (config, self.args.config_file))
633 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34634
635 # Do some basic sanity checking on the config so that we
636 # don't have to do this in every caller.
dprankef37aebb92016-09-23 01:14:49637 if 'type' not in vals:
638 vals['type'] = 'gn'
dpranke751516a2015-10-03 01:11:34639 assert vals['type'] in ('gn', 'gyp'), (
640 'Unknown meta-build type "%s"' % vals['gn_args'])
641
642 return vals
dprankefe4602312015-04-08 16:20:35643
dprankef37aebb92016-09-23 01:14:49644 def ReadIOSBotConfig(self):
dprankee0f486f2015-11-19 23:42:00645 if not self.args.master or not self.args.builder:
646 return {}
647 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
648 self.args.master, self.args.builder + '.json')
649 if not self.Exists(path):
650 return {}
651
652 contents = json.loads(self.ReadFile(path))
653 gyp_vals = contents.get('GYP_DEFINES', {})
654 if isinstance(gyp_vals, dict):
655 gyp_defines = ' '.join('%s=%s' % (k, v) for k, v in gyp_vals.items())
656 else:
657 gyp_defines = ' '.join(gyp_vals)
658 gn_args = ' '.join(contents.get('gn_args', []))
659
dprankef37aebb92016-09-23 01:14:49660 vals = self.DefaultVals()
661 vals['gn_args'] = gn_args
662 vals['gyp_defines'] = gyp_defines
663 vals['type'] = contents.get('mb_type', 'gn')
664 return vals
dprankee0f486f2015-11-19 23:42:00665
dprankefe4602312015-04-08 16:20:35666 def ReadConfigFile(self):
667 if not self.Exists(self.args.config_file):
668 raise MBErr('config file not found at %s' % self.args.config_file)
669
670 try:
671 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
672 except SyntaxError as e:
673 raise MBErr('Failed to parse config file "%s": %s' %
674 (self.args.config_file, e))
675
dprankefe4602312015-04-08 16:20:35676 self.configs = contents['configs']
677 self.masters = contents['masters']
678 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35679
dprankecb4a2e242016-09-19 01:13:14680 def ReadIsolateMap(self):
kjellander902bcb62016-10-26 06:20:50681 if not self.Exists(self.args.isolate_map_file):
682 raise MBErr('isolate map file not found at %s' %
683 self.args.isolate_map_file)
684 try:
685 return ast.literal_eval(self.ReadFile(self.args.isolate_map_file))
686 except SyntaxError as e:
687 raise MBErr('Failed to parse isolate map file "%s": %s' %
688 (self.args.isolate_map_file, e))
dprankecb4a2e242016-09-19 01:13:14689
dprankefe4602312015-04-08 16:20:35690 def ConfigFromArgs(self):
691 if self.args.config:
692 if self.args.master or self.args.builder:
693 raise MBErr('Can not specific both -c/--config and -m/--master or '
694 '-b/--builder')
695
696 return self.args.config
697
698 if not self.args.master or not self.args.builder:
699 raise MBErr('Must specify either -c/--config or '
700 '(-m/--master and -b/--builder)')
701
702 if not self.args.master in self.masters:
703 raise MBErr('Master name "%s" not found in "%s"' %
704 (self.args.master, self.args.config_file))
705
706 if not self.args.builder in self.masters[self.args.master]:
707 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
708 (self.args.builder, self.args.master, self.args.config_file))
709
dprankeb9380a12016-07-21 21:44:09710 config = self.masters[self.args.master][self.args.builder]
shenghuazhang804b21542016-10-11 02:06:49711 if isinstance(config, dict):
dprankeb9380a12016-07-21 21:44:09712 if self.args.phase is None:
713 raise MBErr('Must specify a build --phase for %s on %s' %
714 (self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49715 phase = str(self.args.phase)
716 if phase not in config:
717 raise MBErr('Phase %s doesn\'t exist for %s on %s' %
dprankeb9380a12016-07-21 21:44:09718 (phase, self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49719 return config[phase]
dprankeb9380a12016-07-21 21:44:09720
721 if self.args.phase is not None:
722 raise MBErr('Must not specify a build --phase for %s on %s' %
723 (self.args.builder, self.args.master))
724 return config
dprankefe4602312015-04-08 16:20:35725
726 def FlattenConfig(self, config):
727 mixins = self.configs[config]
dprankef37aebb92016-09-23 01:14:49728 vals = self.DefaultVals()
dprankefe4602312015-04-08 16:20:35729
730 visited = []
731 self.FlattenMixins(mixins, vals, visited)
732 return vals
733
dprankef37aebb92016-09-23 01:14:49734 def DefaultVals(self):
735 return {
736 'args_file': '',
737 'cros_passthrough': False,
738 'gn_args': '',
739 'gyp_defines': '',
740 'gyp_crosscompile': False,
741 'type': 'gn',
742 }
743
dprankefe4602312015-04-08 16:20:35744 def FlattenMixins(self, mixins, vals, visited):
745 for m in mixins:
746 if m not in self.mixins:
747 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22748
dprankefe4602312015-04-08 16:20:35749 visited.append(m)
750
751 mixin_vals = self.mixins[m]
dpranke73ed0d62016-04-25 19:18:34752
753 if 'cros_passthrough' in mixin_vals:
754 vals['cros_passthrough'] = mixin_vals['cros_passthrough']
Dirk Pranke6b99f072017-04-05 00:58:30755 if 'args_file' in mixin_vals:
756 if vals['args_file']:
757 raise MBErr('args_file specified multiple times in mixins '
758 'for %s on %s' % (self.args.builder, self.args.master))
759 vals['args_file'] = mixin_vals['args_file']
dprankefe4602312015-04-08 16:20:35760 if 'gn_args' in mixin_vals:
761 if vals['gn_args']:
762 vals['gn_args'] += ' ' + mixin_vals['gn_args']
763 else:
764 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59765 if 'gyp_crosscompile' in mixin_vals:
766 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35767 if 'gyp_defines' in mixin_vals:
768 if vals['gyp_defines']:
769 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
770 else:
771 vals['gyp_defines'] = mixin_vals['gyp_defines']
dpranke73ed0d62016-04-25 19:18:34772 if 'type' in mixin_vals:
773 vals['type'] = mixin_vals['type']
774
dprankefe4602312015-04-08 16:20:35775 if 'mixins' in mixin_vals:
776 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
777 return vals
778
dprankec161aa92015-09-14 20:21:13779 def ClobberIfNeeded(self, vals):
780 path = self.args.path[0]
781 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33782 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13783 needs_clobber = False
784 new_mb_type = vals['type']
785 if self.Exists(build_dir):
786 if self.Exists(mb_type_path):
787 old_mb_type = self.ReadFile(mb_type_path)
788 if old_mb_type != new_mb_type:
789 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
790 (old_mb_type, new_mb_type, path))
791 needs_clobber = True
792 else:
793 # There is no 'mb_type' file in the build directory, so this probably
794 # means that the prior build(s) were not done through mb, and we
795 # have no idea if this was a GYP build or a GN build. Clobber it
796 # to be safe.
797 self.Print("%s/mb_type missing, clobbering to be safe" % path)
798 needs_clobber = True
799
dpranke3cec199c2015-09-22 23:29:02800 if self.args.dryrun:
801 return
802
dprankec161aa92015-09-14 20:21:13803 if needs_clobber:
804 self.RemoveDirectory(build_dir)
805
806 self.MaybeMakeDirectory(build_dir)
807 self.WriteFile(mb_type_path, new_mb_type)
808
Dirk Prankea3727f92017-07-17 17:30:33809 def RunGNGen(self, vals, compute_grit_inputs_for_analyze=False):
dpranke751516a2015-10-03 01:11:34810 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50811
dprankeeca4a782016-04-14 01:42:38812 cmd = self.GNCmd('gen', build_dir, '--check')
813 gn_args = self.GNArgs(vals)
Dirk Prankea3727f92017-07-17 17:30:33814 if compute_grit_inputs_for_analyze:
815 gn_args += ' compute_grit_inputs_for_analyze=true'
dprankeeca4a782016-04-14 01:42:38816
817 # Since GN hasn't run yet, the build directory may not even exist.
818 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
819
820 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
dpranke4ff8b9f2016-04-15 03:07:54821 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
dpranke74559b52015-06-10 21:20:39822
823 swarming_targets = []
dpranke751516a2015-10-03 01:11:34824 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39825 # We need GN to generate the list of runtime dependencies for
826 # the compile targets listed (one per line) in the file so
dprankecb4a2e242016-09-19 01:13:14827 # we can run them via swarming. We use gn_isolate_map.pyl to convert
dpranke74559b52015-06-10 21:20:39828 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00829 path = self.args.swarming_targets_file
830 if not self.Exists(path):
831 self.WriteFailureAndRaise('"%s" does not exist' % path,
832 output_path=None)
833 contents = self.ReadFile(path)
834 swarming_targets = set(contents.splitlines())
dprankeb2be10a2016-02-22 17:11:00835
dprankecb4a2e242016-09-19 01:13:14836 isolate_map = self.ReadIsolateMap()
837 err, labels = self.MapTargetsToLabels(isolate_map, swarming_targets)
dprankeb2be10a2016-02-22 17:11:00838 if err:
dprankecb4a2e242016-09-19 01:13:14839 raise MBErr(err)
dpranke74559b52015-06-10 21:20:39840
dpranke751516a2015-10-03 01:11:34841 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankecb4a2e242016-09-19 01:13:14842 self.WriteFile(gn_runtime_deps_path, '\n'.join(labels) + '\n')
dpranke74559b52015-06-10 21:20:39843 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
844
dprankefe4602312015-04-08 16:20:35845 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40846 if ret:
847 # If `gn gen` failed, we should exit early rather than trying to
848 # generate isolates. Run() will have already logged any error output.
849 self.Print('GN gen failed: %d' % ret)
850 return ret
dpranke74559b52015-06-10 21:20:39851
jbudoricke3c4f95e2016-04-28 23:17:38852 android = 'target_os="android"' in vals['gn_args']
dpranke74559b52015-06-10 21:20:39853 for target in swarming_targets:
jbudoricke3c4f95e2016-04-28 23:17:38854 if android:
855 # Android targets may be either android_apk or executable. The former
jbudorick91c8a6012016-01-29 23:20:02856 # will result in runtime_deps associated with the stamp file, while the
857 # latter will result in runtime_deps associated with the executable.
dprankecb4a2e242016-09-19 01:13:14858 label = isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02859 runtime_deps_targets = [
dprankecb4a2e242016-09-19 01:13:14860 target + '.runtime_deps',
dpranke48ccf8f2016-03-28 23:58:28861 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
dprankecb4a2e242016-09-19 01:13:14862 elif (isolate_map[target]['type'] == 'script' or
863 isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11864 # For script targets, the build target is usually a group,
865 # for which gn generates the runtime_deps next to the stamp file
eyaich82d5ac942016-11-03 12:13:49866 # for the label, which lives under the obj/ directory, but it may
867 # also be an executable.
dprankecb4a2e242016-09-19 01:13:14868 label = isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28869 runtime_deps_targets = [
870 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
eyaich82d5ac942016-11-03 12:13:49871 if self.platform == 'win32':
872 runtime_deps_targets += [ target + '.exe.runtime_deps' ]
873 else:
874 runtime_deps_targets += [ target + '.runtime_deps' ]
dpranke48ccf8f2016-03-28 23:58:28875 elif self.platform == 'win32':
876 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52877 else:
dpranke48ccf8f2016-03-28 23:58:28878 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02879
dpranke48ccf8f2016-03-28 23:58:28880 for r in runtime_deps_targets:
881 runtime_deps_path = self.ToAbsPath(build_dir, r)
882 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02883 break
884 else:
dpranke48ccf8f2016-03-28 23:58:28885 raise MBErr('did not generate any of %s' %
886 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39887
dprankecb4a2e242016-09-19 01:13:14888 command, extra_files = self.GetIsolateCommand(target, vals)
dpranked5b2b9432015-06-23 16:55:30889
dpranke48ccf8f2016-03-28 23:58:28890 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30891
dpranke751516a2015-10-03 01:11:34892 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
893 extra_files)
dpranked5b2b9432015-06-23 16:55:30894
dpranke751516a2015-10-03 01:11:34895 return 0
896
897 def RunGNIsolate(self, vals):
dprankecb4a2e242016-09-19 01:13:14898 target = self.args.target[0]
899 isolate_map = self.ReadIsolateMap()
900 err, labels = self.MapTargetsToLabels(isolate_map, [target])
901 if err:
902 raise MBErr(err)
903 label = labels[0]
dpranke751516a2015-10-03 01:11:34904
905 build_dir = self.args.path[0]
dprankecb4a2e242016-09-19 01:13:14906 command, extra_files = self.GetIsolateCommand(target, vals)
dpranke751516a2015-10-03 01:11:34907
dprankeeca4a782016-04-14 01:42:38908 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20909 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34910 if ret:
dpranke030d7a6d2016-03-26 17:23:50911 if out:
912 self.Print(out)
dpranke751516a2015-10-03 01:11:34913 return ret
914
915 runtime_deps = out.splitlines()
916
917 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
918 extra_files)
919
920 ret, _, _ = self.Run([
921 self.executable,
922 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
923 'check',
924 '-i',
925 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
926 '-s',
927 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
928 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30929
dprankefe4602312015-04-08 16:20:35930 return ret
931
dpranke751516a2015-10-03 01:11:34932 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
933 extra_files):
934 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
935 self.WriteFile(isolate_path,
936 pprint.pformat({
937 'variables': {
938 'command': command,
939 'files': sorted(runtime_deps + extra_files),
940 }
941 }) + '\n')
942
943 self.WriteJSON(
944 {
945 'args': [
946 '--isolated',
947 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
948 '--isolate',
949 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
950 ],
951 'dir': self.chromium_src_dir,
952 'version': 1,
953 },
954 isolate_path + 'd.gen.json',
955 )
956
dprankecb4a2e242016-09-19 01:13:14957 def MapTargetsToLabels(self, isolate_map, targets):
958 labels = []
959 err = ''
960
dprankecb4a2e242016-09-19 01:13:14961 for target in targets:
962 if target == 'all':
963 labels.append(target)
964 elif target.startswith('//'):
965 labels.append(target)
966 else:
967 if target in isolate_map:
thakis024d6f32017-05-16 23:21:42968 if isolate_map[target]['type'] == 'unknown':
dprankecb4a2e242016-09-19 01:13:14969 err += ('test target "%s" type is unknown\n' % target)
970 else:
thakis024d6f32017-05-16 23:21:42971 labels.append(isolate_map[target]['label'])
dprankecb4a2e242016-09-19 01:13:14972 else:
973 err += ('target "%s" not found in '
974 '//testing/buildbot/gn_isolate_map.pyl\n' % target)
975
976 return err, labels
977
dprankeeca4a782016-04-14 01:42:38978 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51979 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20980 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51981 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20982 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51983 else:
dpranke40da0202016-02-13 05:05:20984 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38985
dpranke40da0202016-02-13 05:05:20986 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranke10118bf2016-09-16 23:16:08987 return [gn_path, subcommand, path] + list(args)
dpranke9aba8b212016-09-16 22:52:52988
dprankecb4a2e242016-09-19 01:13:14989
dprankeeca4a782016-04-14 01:42:38990 def GNArgs(self, vals):
dpranke73ed0d62016-04-25 19:18:34991 if vals['cros_passthrough']:
992 if not 'GN_ARGS' in os.environ:
993 raise MBErr('MB is expecting GN_ARGS to be in the environment')
994 gn_args = os.environ['GN_ARGS']
dpranke40260182016-04-27 04:45:16995 if not re.search('target_os.*=.*"chromeos"', gn_args):
dpranke39f3be02016-04-27 04:07:30996 raise MBErr('GN_ARGS is missing target_os = "chromeos": (GN_ARGS=%s)' %
dpranke73ed0d62016-04-25 19:18:34997 gn_args)
998 else:
999 gn_args = vals['gn_args']
1000
dpranked0c138b2016-04-13 18:28:471001 if self.args.goma_dir:
1002 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:381003
agrieve41d21a72016-04-14 18:02:261004 android_version_code = self.args.android_version_code
1005 if android_version_code:
1006 gn_args += ' android_default_version_code="%s"' % android_version_code
1007
1008 android_version_name = self.args.android_version_name
1009 if android_version_name:
1010 gn_args += ' android_default_version_name="%s"' % android_version_name
1011
dprankeeca4a782016-04-14 01:42:381012 # Canonicalize the arg string into a sorted, newline-separated list
1013 # of key-value pairs, and de-dup the keys if need be so that only
1014 # the last instance of each arg is listed.
1015 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
1016
dpranke9dd5e252016-04-14 04:23:091017 args_file = vals.get('args_file', None)
1018 if args_file:
1019 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:381020 return gn_args
dprankefe4602312015-04-08 16:20:351021
Dirk Pranke0fd41bcd2015-06-19 00:05:501022 def RunGYPGen(self, vals):
1023 path = self.args.path[0]
1024
dpranke8c2cfd32015-09-17 20:12:331025 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:411026 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:591027 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:351028 return ret
1029
1030 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:331031 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:321032 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:161033 inp = self.ReadInputJSON(['files', 'test_targets',
1034 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321035 self.Print()
1036 self.Print('analyze input:')
1037 self.PrintJSON(inp)
1038 self.Print()
1039
dpranke38f4acb62015-09-29 23:50:411040 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:331041 cmd.extend(['-f', 'analyzer',
1042 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:351043 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:021044 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:321045 if not ret and self.args.verbose:
1046 outp = json.loads(self.ReadFile(self.args.output_path[0]))
1047 self.Print()
1048 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:391049 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:321050 self.Print()
1051
dprankefe4602312015-04-08 16:20:351052 return ret
1053
dprankecb4a2e242016-09-19 01:13:141054 def GetIsolateCommand(self, target, vals):
kylechar50abf5a2016-11-29 16:03:071055 isolate_map = self.ReadIsolateMap()
1056
jbudoricke8428732016-02-02 02:17:061057 android = 'target_os="android"' in vals['gn_args']
1058
kylechar39705682017-01-19 14:37:231059 # This should be true if tests with type='windowed_test_launcher' are
1060 # expected to run using xvfb. For example, Linux Desktop, X11 CrOS and
msisovaea52732017-03-21 08:08:081061 # Ozone CrOS builds. Note that one Ozone build can be used to run differen
1062 # backends. Currently, tests are executed for the headless and X11 backends
1063 # and both can run under Xvfb.
1064 # TODO(tonikitoo,msisov,fwang): Find a way to run tests for the Wayland
1065 # backend.
dpranke7dad4682017-04-26 23:14:551066 use_xvfb = self.platform == 'linux2' and not android
dpranked8113582015-06-05 20:08:251067
1068 asan = 'is_asan=true' in vals['gn_args']
1069 msan = 'is_msan=true' in vals['gn_args']
1070 tsan = 'is_tsan=true' in vals['gn_args']
pcc46233c22017-06-20 22:11:411071 cfi_diag = 'use_cfi_diag=true' in vals['gn_args']
dpranked8113582015-06-05 20:08:251072
dprankecb4a2e242016-09-19 01:13:141073 test_type = isolate_map[target]['type']
dprankefe0d35e2016-02-05 02:43:591074
dprankecb4a2e242016-09-19 01:13:141075 executable = isolate_map[target].get('executable', target)
dprankefe0d35e2016-02-05 02:43:591076 executable_suffix = '.exe' if self.platform == 'win32' else ''
1077
dprankea55584f12015-07-22 00:52:471078 cmdline = []
1079 extra_files = []
dpranked8113582015-06-05 20:08:251080
dprankecb4a2e242016-09-19 01:13:141081 if test_type == 'nontest':
1082 self.WriteFailureAndRaise('We should not be isolating %s.' % target,
1083 output_path=None)
1084
cblumed8e58022016-05-05 03:23:551085 if android and test_type != "script":
bpastenee428ea92017-02-17 02:20:321086 cmdline = [
hzl9b15df52017-03-23 23:43:041087 '../../build/android/test_wrapper/logdog_wrapper.py',
1088 '--target', target,
hzld58d09f2017-03-15 23:15:351089 '--target-devices-file', '${SWARMING_BOT_FILE}',
hzl9ae14452017-04-04 23:38:021090 '--logdog-bin-cmd', '../../bin/logdog_butler',
hzlfc66094f2017-05-18 00:50:481091 '--logcat-output-file', '${ISOLATED_OUTDIR}/logcats',
1092 '--store-tombstones']
kylechar39705682017-01-19 14:37:231093 elif use_xvfb and test_type == 'windowed_test_launcher':
dprankea55584f12015-07-22 00:52:471094 extra_files = [
dpranked8113582015-06-05 20:08:251095 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:471096 '../../testing/xvfb.py',
1097 ]
1098 cmdline = [
dprankefe0d35e2016-02-05 02:43:591099 '../../testing/xvfb.py',
dprankefe0d35e2016-02-05 02:43:591100 './' + str(executable) + executable_suffix,
1101 '--brave-new-test-launcher',
1102 '--test-launcher-bot-mode',
1103 '--asan=%d' % asan,
1104 '--msan=%d' % msan,
1105 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:411106 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:471107 ]
1108 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
1109 extra_files = [
1110 '../../testing/test_env.py'
1111 ]
1112 cmdline = [
1113 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:591114 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:251115 '--brave-new-test-launcher',
1116 '--test-launcher-bot-mode',
1117 '--asan=%d' % asan,
1118 '--msan=%d' % msan,
1119 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:411120 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:471121 ]
dpranke6abd8652015-08-28 03:21:111122 elif test_type == 'script':
1123 extra_files = [
1124 '../../testing/test_env.py'
1125 ]
1126 cmdline = [
1127 '../../testing/test_env.py',
dprankecb4a2e242016-09-19 01:13:141128 '../../' + self.ToSrcRelPath(isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:591129 ]
dprankea55584f12015-07-22 00:52:471130 elif test_type in ('raw'):
1131 extra_files = []
1132 cmdline = [
1133 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:591134 ]
dpranked8113582015-06-05 20:08:251135
dprankea55584f12015-07-22 00:52:471136 else:
1137 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
1138 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:251139
dprankecb4a2e242016-09-19 01:13:141140 cmdline += isolate_map[target].get('args', [])
dprankefe0d35e2016-02-05 02:43:591141
dpranked8113582015-06-05 20:08:251142 return cmdline, extra_files
1143
dpranke74559b52015-06-10 21:20:391144 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:331145 return self.PathJoin(self.chromium_src_dir,
1146 self.ToSrcRelPath(build_path),
1147 *comps)
dpranked8113582015-06-05 20:08:251148
dprankeee5b51f62015-04-09 00:03:221149 def ToSrcRelPath(self, path):
1150 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:501151 if path.startswith('//'):
1152 return path[2:].replace('/', self.sep)
1153 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:351154
1155 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:221156 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:331157 output_dir, _, _ = rpath.rpartition(self.sep)
1158 return output_dir
dprankefe4602312015-04-08 16:20:351159
dpranke38f4acb62015-09-29 23:50:411160 def GYPCmd(self, output_dir, vals):
dpranke73ed0d62016-04-25 19:18:341161 if vals['cros_passthrough']:
1162 if not 'GYP_DEFINES' in os.environ:
1163 raise MBErr('MB is expecting GYP_DEFINES to be in the environment')
1164 gyp_defines = os.environ['GYP_DEFINES']
1165 if not 'chromeos=1' in gyp_defines:
1166 raise MBErr('GYP_DEFINES is missing chromeos=1: (GYP_DEFINES=%s)' %
1167 gyp_defines)
1168 else:
1169 gyp_defines = vals['gyp_defines']
1170
dpranke3cec199c2015-09-22 23:29:021171 goma_dir = self.args.goma_dir
1172
1173 # GYP uses shlex.split() to split the gyp defines into separate arguments,
1174 # so we can support backslashes and and spaces in arguments by quoting
1175 # them, even on Windows, where this normally wouldn't work.
dpranked0c138b2016-04-13 18:28:471176 if goma_dir and ('\\' in goma_dir or ' ' in goma_dir):
dpranke3cec199c2015-09-22 23:29:021177 goma_dir = "'%s'" % goma_dir
dpranked0c138b2016-04-13 18:28:471178
1179 if goma_dir:
1180 gyp_defines += ' gomadir=%s' % goma_dir
dpranke3cec199c2015-09-22 23:29:021181
agrieve41d21a72016-04-14 18:02:261182 android_version_code = self.args.android_version_code
1183 if android_version_code:
1184 gyp_defines += ' app_manifest_version_code=%s' % android_version_code
1185
1186 android_version_name = self.args.android_version_name
1187 if android_version_name:
1188 gyp_defines += ' app_manifest_version_name=%s' % android_version_name
1189
dprankefe4602312015-04-08 16:20:351190 cmd = [
dpranke8c2cfd32015-09-17 20:12:331191 self.executable,
machenbach60ebf6202016-06-07 14:27:391192 self.args.gyp_script,
dprankefe4602312015-04-08 16:20:351193 '-G',
1194 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:351195 ]
dpranke38f4acb62015-09-29 23:50:411196
1197 # Ensure that we have an environment that only contains
1198 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:021199 env = os.environ.copy()
dpranke909bad62016-04-24 23:14:521200
1201 # This is a terrible hack to work around the fact that
1202 # //tools/clang/scripts/update.py is invoked by GYP and GN but
1203 # currently relies on an environment variable to figure out
1204 # what revision to embed in the command line #defines.
1205 # For GN, we've made this work via a gn arg that will cause update.py
1206 # to get an additional command line arg, but getting that to work
1207 # via GYP_DEFINES has proven difficult, so we rewrite the GYP_DEFINES
1208 # to get rid of the arg and add the old var in, instead.
1209 # See crbug.com/582737 for more on this. This can hopefully all
1210 # go away with GYP.
dprankeec079262016-06-07 02:21:201211 m = re.search('llvm_force_head_revision=1\s*', gyp_defines)
1212 if m:
dprankebf0d5b562016-04-25 22:22:511213 env['LLVM_FORCE_HEAD_REVISION'] = '1'
dprankeec079262016-06-07 02:21:201214 gyp_defines = gyp_defines.replace(m.group(0), '')
1215
1216 # This is another terrible hack to work around the fact that
1217 # GYP sets the link concurrency to use via the GYP_LINK_CONCURRENCY
1218 # environment variable, and not via a proper GYP_DEFINE. See
1219 # crbug.com/611491 for more on this.
1220 m = re.search('gyp_link_concurrency=(\d+)(\s*)', gyp_defines)
1221 if m:
1222 env['GYP_LINK_CONCURRENCY'] = m.group(1)
1223 gyp_defines = gyp_defines.replace(m.group(0), '')
dpranke909bad62016-04-24 23:14:521224
dprankef75a3de52015-12-14 22:17:521225 env['GYP_GENERATORS'] = 'ninja'
dpranke38f4acb62015-09-29 23:50:411226 if 'GYP_CHROMIUM_NO_ACTION' in env:
1227 del env['GYP_CHROMIUM_NO_ACTION']
1228 if 'GYP_CROSSCOMPILE' in env:
1229 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:021230 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:411231 if vals['gyp_crosscompile']:
1232 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:021233 return cmd, env
dprankefe4602312015-04-08 16:20:351234
Dirk Pranke0fd41bcd2015-06-19 00:05:501235 def RunGNAnalyze(self, vals):
dprankecb4a2e242016-09-19 01:13:141236 # Analyze runs before 'gn gen' now, so we need to run gn gen
Dirk Pranke0fd41bcd2015-06-19 00:05:501237 # in order to ensure that we have a build directory.
Dirk Prankea3727f92017-07-17 17:30:331238 ret = self.RunGNGen(vals, compute_grit_inputs_for_analyze=True)
Dirk Pranke0fd41bcd2015-06-19 00:05:501239 if ret:
1240 return ret
1241
dprankecb4a2e242016-09-19 01:13:141242 build_path = self.args.path[0]
1243 input_path = self.args.input_path[0]
1244 gn_input_path = input_path + '.gn'
1245 output_path = self.args.output_path[0]
1246 gn_output_path = output_path + '.gn'
1247
dpranke7837fc362015-11-19 03:54:161248 inp = self.ReadInputJSON(['files', 'test_targets',
1249 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321250 if self.args.verbose:
1251 self.Print()
1252 self.Print('analyze input:')
1253 self.PrintJSON(inp)
1254 self.Print()
1255
dpranke76734662015-04-16 02:17:501256
dpranke7c5f614d2015-07-22 23:43:391257 # This shouldn't normally happen, but could due to unusual race conditions,
1258 # like a try job that gets scheduled before a patch lands but runs after
1259 # the patch has landed.
1260 if not inp['files']:
1261 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161262 self.WriteJSON({
1263 'status': 'No dependency',
1264 'compile_targets': [],
1265 'test_targets': [],
1266 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391267 return 0
1268
dprankecb4a2e242016-09-19 01:13:141269 gn_inp = {}
dprankeb7b183f2017-04-24 23:50:161270 gn_inp['files'] = ['//' + f for f in inp['files'] if not f.startswith('//')]
dprankef61de2f2015-05-14 04:09:561271
dprankecb4a2e242016-09-19 01:13:141272 isolate_map = self.ReadIsolateMap()
1273 err, gn_inp['additional_compile_targets'] = self.MapTargetsToLabels(
1274 isolate_map, inp['additional_compile_targets'])
dprankecb4a2e242016-09-19 01:13:141275 if err:
1276 raise MBErr(err)
1277
1278 err, gn_inp['test_targets'] = self.MapTargetsToLabels(
1279 isolate_map, inp['test_targets'])
dprankecb4a2e242016-09-19 01:13:141280 if err:
1281 raise MBErr(err)
1282 labels_to_targets = {}
1283 for i, label in enumerate(gn_inp['test_targets']):
1284 labels_to_targets[label] = inp['test_targets'][i]
1285
dprankef61de2f2015-05-14 04:09:561286 try:
dprankecb4a2e242016-09-19 01:13:141287 self.WriteJSON(gn_inp, gn_input_path)
1288 cmd = self.GNCmd('analyze', build_path, gn_input_path, gn_output_path)
1289 ret, _, _ = self.Run(cmd, force_verbose=True)
1290 if ret:
1291 return ret
dpranke067d0142015-05-14 22:52:451292
dprankecb4a2e242016-09-19 01:13:141293 gn_outp_str = self.ReadFile(gn_output_path)
1294 try:
1295 gn_outp = json.loads(gn_outp_str)
1296 except Exception as e:
1297 self.Print("Failed to parse the JSON string GN returned: %s\n%s"
1298 % (repr(gn_outp_str), str(e)))
1299 raise
1300
1301 outp = {}
1302 if 'status' in gn_outp:
1303 outp['status'] = gn_outp['status']
1304 if 'error' in gn_outp:
1305 outp['error'] = gn_outp['error']
1306 if 'invalid_targets' in gn_outp:
1307 outp['invalid_targets'] = gn_outp['invalid_targets']
1308 if 'compile_targets' in gn_outp:
dpranke385a3102016-09-20 22:04:081309 if 'all' in gn_outp['compile_targets']:
1310 outp['compile_targets'] = ['all']
1311 else:
1312 outp['compile_targets'] = [
1313 label.replace('//', '') for label in gn_outp['compile_targets']]
dprankecb4a2e242016-09-19 01:13:141314 if 'test_targets' in gn_outp:
1315 outp['test_targets'] = [
1316 labels_to_targets[label] for label in gn_outp['test_targets']]
1317
1318 if self.args.verbose:
1319 self.Print()
1320 self.Print('analyze output:')
1321 self.PrintJSON(outp)
1322 self.Print()
1323
1324 self.WriteJSON(outp, output_path)
1325
dprankef61de2f2015-05-14 04:09:561326 finally:
dprankecb4a2e242016-09-19 01:13:141327 if self.Exists(gn_input_path):
1328 self.RemoveFile(gn_input_path)
1329 if self.Exists(gn_output_path):
1330 self.RemoveFile(gn_output_path)
dprankefe4602312015-04-08 16:20:351331
1332 return 0
1333
dpranked8113582015-06-05 20:08:251334 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351335 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321336 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351337 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321338 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351339
1340 try:
1341 inp = json.loads(self.ReadFile(path))
1342 except Exception as e:
1343 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321344 (path, e), output_path)
dpranked8113582015-06-05 20:08:251345
1346 for k in required_keys:
1347 if not k in inp:
1348 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1349 output_path)
dprankefe4602312015-04-08 16:20:351350
1351 return inp
1352
dpranked5b2b9432015-06-23 16:55:301353 def WriteFailureAndRaise(self, msg, output_path):
1354 if output_path:
dprankee0547cd2015-09-15 01:27:401355 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351356 raise MBErr(msg)
1357
dprankee0547cd2015-09-15 01:27:401358 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321359 try:
dprankee0547cd2015-09-15 01:27:401360 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1361 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321362 except Exception as e:
1363 raise MBErr('Error %s writing to the output path "%s"' %
1364 (e, path))
dprankefe4602312015-04-08 16:20:351365
aneeshmde50f472016-04-01 01:13:101366 def CheckCompile(self, master, builder):
1367 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1368 url = urllib2.quote(url_template.format(master=master, builder=builder),
1369 safe=':/()?=')
1370 try:
1371 builds = json.loads(self.Fetch(url))
1372 except Exception as e:
1373 return str(e)
1374 successes = sorted(
1375 [int(x) for x in builds.keys() if "text" in builds[x] and
1376 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1377 reverse=True)
1378 if not successes:
1379 return "no successful builds"
1380 build = builds[str(successes[0])]
1381 step_names = set([step["name"] for step in build["steps"]])
1382 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1383 if compile_indicators & step_names:
1384 return "compiles"
1385 return "does not compile"
1386
dpranke3cec199c2015-09-22 23:29:021387 def PrintCmd(self, cmd, env):
1388 if self.platform == 'win32':
1389 env_prefix = 'set '
1390 env_quoter = QuoteForSet
1391 shell_quoter = QuoteForCmd
1392 else:
1393 env_prefix = ''
1394 env_quoter = pipes.quote
1395 shell_quoter = pipes.quote
1396
1397 def print_env(var):
1398 if env and var in env:
1399 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1400
1401 print_env('GYP_CROSSCOMPILE')
1402 print_env('GYP_DEFINES')
dprankeec079262016-06-07 02:21:201403 print_env('GYP_LINK_CONCURRENCY')
1404 print_env('LLVM_FORCE_HEAD_REVISION')
dpranke3cec199c2015-09-22 23:29:021405
dpranke8c2cfd32015-09-17 20:12:331406 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351407 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021408 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351409
dprankecda00332015-04-11 04:18:321410 def PrintJSON(self, obj):
1411 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1412
dpranke751516a2015-10-03 01:11:341413 def Build(self, target):
1414 build_dir = self.ToSrcRelPath(self.args.path[0])
1415 ninja_cmd = ['ninja', '-C', build_dir]
1416 if self.args.jobs:
1417 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1418 ninja_cmd.append(target)
1419 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1420 return ret
1421
1422 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351423 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401424 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021425 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351426 if self.args.dryrun:
1427 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401428
dpranke751516a2015-10-03 01:11:341429 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401430 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341431 if ret:
1432 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351433 if out:
dprankeee5b51f62015-04-09 00:03:221434 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351435 if err:
dprankeee5b51f62015-04-09 00:03:221436 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351437 return ret, out, err
1438
dpranke751516a2015-10-03 01:11:341439 def Call(self, cmd, env=None, buffer_output=True):
1440 if buffer_output:
1441 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1442 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1443 env=env)
1444 out, err = p.communicate()
1445 else:
1446 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1447 env=env)
1448 p.wait()
1449 out = err = ''
dprankefe4602312015-04-08 16:20:351450 return p.returncode, out, err
1451
1452 def ExpandUser(self, path):
1453 # This function largely exists so it can be overridden for testing.
1454 return os.path.expanduser(path)
1455
1456 def Exists(self, path):
1457 # This function largely exists so it can be overridden for testing.
1458 return os.path.exists(path)
1459
dpranke867bcf4a2016-03-14 22:28:321460 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501461 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321462 f = urllib2.urlopen(url)
1463 contents = f.read()
1464 f.close()
1465 return contents
1466
dprankec3441d12015-06-23 23:01:351467 def MaybeMakeDirectory(self, path):
1468 try:
1469 os.makedirs(path)
1470 except OSError, e:
1471 if e.errno != errno.EEXIST:
1472 raise
1473
dpranke8c2cfd32015-09-17 20:12:331474 def PathJoin(self, *comps):
1475 # This function largely exists so it can be overriden for testing.
1476 return os.path.join(*comps)
1477
dpranke030d7a6d2016-03-26 17:23:501478 def Print(self, *args, **kwargs):
1479 # This function largely exists so it can be overridden for testing.
1480 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101481 if kwargs.get('stream', sys.stdout) == sys.stdout:
1482 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501483
dprankefe4602312015-04-08 16:20:351484 def ReadFile(self, path):
1485 # This function largely exists so it can be overriden for testing.
1486 with open(path) as fp:
1487 return fp.read()
1488
dpranke030d7a6d2016-03-26 17:23:501489 def RelPath(self, path, start='.'):
1490 # This function largely exists so it can be overriden for testing.
1491 return os.path.relpath(path, start)
1492
dprankef61de2f2015-05-14 04:09:561493 def RemoveFile(self, path):
1494 # This function largely exists so it can be overriden for testing.
1495 os.remove(path)
1496
dprankec161aa92015-09-14 20:21:131497 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331498 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131499 # In other places in chromium, we often have to retry this command
1500 # because we're worried about other processes still holding on to
1501 # file handles, but when MB is invoked, it will be early enough in the
1502 # build that their should be no other processes to interfere. We
1503 # can change this if need be.
1504 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1505 else:
1506 shutil.rmtree(abs_path, ignore_errors=True)
1507
dprankef61de2f2015-05-14 04:09:561508 def TempFile(self, mode='w'):
1509 # This function largely exists so it can be overriden for testing.
1510 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1511
dprankee0547cd2015-09-15 01:27:401512 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351513 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401514 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301515 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351516 with open(path, 'w') as fp:
1517 return fp.write(contents)
1518
dprankef61de2f2015-05-14 04:09:561519
dprankefe4602312015-04-08 16:20:351520class MBErr(Exception):
1521 pass
1522
1523
dpranke3cec199c2015-09-22 23:29:021524# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1525# details of this next section, which handles escaping command lines
1526# so that they can be copied and pasted into a cmd window.
1527UNSAFE_FOR_SET = set('^<>&|')
1528UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1529ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1530
1531
1532def QuoteForSet(arg):
1533 if any(a in UNSAFE_FOR_SET for a in arg):
1534 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1535 return arg
1536
1537
1538def QuoteForCmd(arg):
1539 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1540 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1541 if arg == '' or ' ' in arg or '"' in arg:
1542 quote_re = re.compile(r'(\\*)"')
1543 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1544
1545 # Then check to see if the arg contains any metacharacters other than
1546 # double quotes; if it does, quote everything (including the double
1547 # quotes) for safety.
1548 if any(a in UNSAFE_FOR_CMD for a in arg):
1549 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1550 return arg
1551
1552
dprankefe4602312015-04-08 16:20:351553if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591554 sys.exit(main(sys.argv[1:]))