blob: d76ab5aeb0950270a2f574ed41419074ee1f492b [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
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
dpranked8113582015-06-05 20:08:2520import pprint
dpranke3cec199c2015-09-22 23:29:0221import re
dprankefe4602312015-04-08 16:20:3522import shutil
23import sys
24import subprocess
dprankef61de2f2015-05-14 04:09:5625import tempfile
dpranke867bcf4a2016-03-14 22:28:3226import urllib2
27
28from collections import OrderedDict
dprankefe4602312015-04-08 16:20:3529
dprankefe4602312015-04-08 16:20:3530def main(args):
dprankeee5b51f62015-04-09 00:03:2231 mbw = MetaBuildWrapper()
dpranke255085e2016-03-16 05:23:5932 return mbw.Main(args)
dprankefe4602312015-04-08 16:20:3533
34
35class MetaBuildWrapper(object):
36 def __init__(self):
37 p = os.path
38 d = os.path.dirname
39 self.chromium_src_dir = p.normpath(d(d(d(p.abspath(__file__)))))
40 self.default_config = p.join(self.chromium_src_dir, 'tools', 'mb',
41 'mb_config.pyl')
dpranke8c2cfd32015-09-17 20:12:3342 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5143 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3344 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3545 self.args = argparse.Namespace()
46 self.configs = {}
47 self.masters = {}
48 self.mixins = {}
dprankefe4602312015-04-08 16:20:3549
dpranke255085e2016-03-16 05:23:5950 def Main(self, args):
51 self.ParseArgs(args)
52 try:
53 ret = self.args.func()
54 if ret:
55 self.DumpInputFiles()
56 return ret
57 except KeyboardInterrupt:
58 self.Print('interrupted, exiting', stream=sys.stderr)
59 return 130
60 except Exception as e:
61 self.DumpInputFiles()
62 self.Print(str(e))
63 return 1
64
dprankefe4602312015-04-08 16:20:3565 def ParseArgs(self, argv):
66 def AddCommonOptions(subp):
67 subp.add_argument('-b', '--builder',
68 help='builder name to look up config from')
69 subp.add_argument('-m', '--master',
70 help='master name to look up config from')
71 subp.add_argument('-c', '--config',
72 help='configuration to analyze')
73 subp.add_argument('-f', '--config-file', metavar='PATH',
74 default=self.default_config,
75 help='path to config file '
76 '(default is //tools/mb/mb_config.pyl)')
77 subp.add_argument('-g', '--goma-dir', default=self.ExpandUser('~/goma'),
78 help='path to goma directory (default is %(default)s).')
79 subp.add_argument('-n', '--dryrun', action='store_true',
80 help='Do a dry run (i.e., do nothing, just print '
81 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:4082 subp.add_argument('-v', '--verbose', action='store_true',
83 help='verbose logging')
dprankefe4602312015-04-08 16:20:3584
85 parser = argparse.ArgumentParser(prog='mb')
86 subps = parser.add_subparsers()
87
88 subp = subps.add_parser('analyze',
89 help='analyze whether changes to a set of files '
90 'will cause a set of binaries to be rebuilt.')
91 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:2592 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:3593 help='path build was generated into.')
94 subp.add_argument('input_path', nargs=1,
95 help='path to a file containing the input arguments '
96 'as a JSON object.')
97 subp.add_argument('output_path', nargs=1,
98 help='path to a file containing the output arguments '
99 'as a JSON object.')
100 subp.set_defaults(func=self.CmdAnalyze)
101
102 subp = subps.add_parser('gen',
103 help='generate a new set of build files')
104 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39105 subp.add_argument('--swarming-targets-file',
106 help='save runtime dependencies for targets listed '
107 'in file.')
dpranked8113582015-06-05 20:08:25108 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35109 help='path to generate build into')
110 subp.set_defaults(func=self.CmdGen)
111
dpranke751516a2015-10-03 01:11:34112 subp = subps.add_parser('isolate',
113 help='generate the .isolate files for a given'
114 'binary')
115 AddCommonOptions(subp)
116 subp.add_argument('path', nargs=1,
117 help='path build was generated into')
118 subp.add_argument('target', nargs=1,
119 help='ninja target to generate the isolate for')
120 subp.set_defaults(func=self.CmdIsolate)
121
dprankefe4602312015-04-08 16:20:35122 subp = subps.add_parser('lookup',
123 help='look up the command for a given config or '
124 'builder')
125 AddCommonOptions(subp)
126 subp.set_defaults(func=self.CmdLookup)
127
dpranke751516a2015-10-03 01:11:34128 subp = subps.add_parser('run',
129 help='build and run the isolated version of a '
130 'binary')
131 AddCommonOptions(subp)
132 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
133 help='Number of jobs to pass to ninja')
134 subp.add_argument('--no-build', dest='build', default=True,
135 action='store_false',
136 help='Do not build, just isolate and run')
137 subp.add_argument('path', nargs=1,
138 help='path to generate build into')
139 subp.add_argument('target', nargs=1,
140 help='ninja target to build and run')
141 subp.set_defaults(func=self.CmdRun)
142
dprankefe4602312015-04-08 16:20:35143 subp = subps.add_parser('validate',
144 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17145 subp.add_argument('-f', '--config-file', metavar='PATH',
146 default=self.default_config,
147 help='path to config file '
148 '(default is //tools/mb/mb_config.pyl)')
dprankefe4602312015-04-08 16:20:35149 subp.set_defaults(func=self.CmdValidate)
150
dpranke867bcf4a2016-03-14 22:28:32151 subp = subps.add_parser('audit',
152 help='Audit the config file to track progress')
153 subp.add_argument('-f', '--config-file', metavar='PATH',
154 default=self.default_config,
155 help='path to config file '
156 '(default is //tools/mb/mb_config.pyl)')
157 subp.add_argument('-i', '--internal', action='store_true',
158 help='check internal masters also')
159 subp.add_argument('-m', '--master', action='append',
160 help='master to audit (default is all non-internal '
161 'masters in file)')
162 subp.add_argument('-u', '--url-template', action='store',
163 default='https://build.chromium.org/p/'
164 '{master}/json/builders',
165 help='URL scheme for JSON APIs to buildbot '
166 '(default: %(default)s) ')
167 subp.set_defaults(func=self.CmdAudit)
168
dprankefe4602312015-04-08 16:20:35169 subp = subps.add_parser('help',
170 help='Get help on a subcommand.')
171 subp.add_argument(nargs='?', action='store', dest='subcommand',
172 help='The command to get help for.')
173 subp.set_defaults(func=self.CmdHelp)
174
175 self.args = parser.parse_args(argv)
176
dprankeb2be10a2016-02-22 17:11:00177 def DumpInputFiles(self):
178
179 def DumpContentsOfFilePassedTo(arg):
180 attr = arg.replace('--', '').replace('-', '_')
181 path = getattr(self.args, attr, '')
182 if path and self.Exists(path):
183 print("\n# To recreate the file passed to %s:" % arg)
184 print("%% cat > %s <<EOF)" % path)
185 contents = self.ReadFile(path)
186 print(contents)
187 print("EOF\n%\n")
188
189 DumpContentsOfFilePassedTo('input_path')
190 DumpContentsOfFilePassedTo('--swarming-targets-file')
191
dprankefe4602312015-04-08 16:20:35192 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34193 vals = self.Lookup()
dprankefe4602312015-04-08 16:20:35194 if vals['type'] == 'gn':
195 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35196 else:
dpranke751516a2015-10-03 01:11:34197 return self.RunGYPAnalyze(vals)
dprankefe4602312015-04-08 16:20:35198
199 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34200 vals = self.Lookup()
dprankec161aa92015-09-14 20:21:13201 self.ClobberIfNeeded(vals)
202
dprankefe4602312015-04-08 16:20:35203 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50204 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35205 else:
dpranke751516a2015-10-03 01:11:34206 return self.RunGYPGen(vals)
dprankefe4602312015-04-08 16:20:35207
208 def CmdHelp(self):
209 if self.args.subcommand:
210 self.ParseArgs([self.args.subcommand, '--help'])
211 else:
212 self.ParseArgs(['--help'])
213
dpranke751516a2015-10-03 01:11:34214 def CmdIsolate(self):
215 vals = self.GetConfig()
216 if not vals:
217 return 1
218
219 if vals['type'] == 'gn':
220 return self.RunGNIsolate(vals)
221 else:
222 return self.Build('%s_run' % self.args.target[0])
223
224 def CmdLookup(self):
225 vals = self.Lookup()
226 if vals['type'] == 'gn':
227 cmd = self.GNCmd('gen', '_path_', vals['gn_args'])
228 env = None
229 else:
230 cmd, env = self.GYPCmd('_path_', vals)
231
232 self.PrintCmd(cmd, env)
233 return 0
234
235 def CmdRun(self):
236 vals = self.GetConfig()
237 if not vals:
238 return 1
239
240 build_dir = self.args.path[0]
241 target = self.args.target[0]
242
243 if vals['type'] == 'gn':
244 if self.args.build:
245 ret = self.Build(target)
246 if ret:
247 return ret
248 ret = self.RunGNIsolate(vals)
249 if ret:
250 return ret
251 else:
252 ret = self.Build('%s_run' % target)
253 if ret:
254 return ret
255
256 ret, _, _ = self.Run([
257 self.executable,
258 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
259 'run',
260 '-s',
261 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
262 force_verbose=False, buffer_output=False)
263
264 return ret
265
dpranke0cafc162016-03-19 00:41:10266 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35267 errs = []
268
269 # Read the file to make sure it parses.
270 self.ReadConfigFile()
271
dpranke3be00142016-03-17 22:46:04272 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35273 all_configs = {}
dprankefe4602312015-04-08 16:20:35274 for master in self.masters:
dpranke3be00142016-03-17 22:46:04275 for config in self.masters[master].values():
276 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35277
278 # Check that every referenced config actually exists.
279 for config, loc in all_configs.items():
280 if not config in self.configs:
281 errs.append('Unknown config "%s" referenced from "%s".' %
282 (config, loc))
283
284 # Check that every actual config is actually referenced.
285 for config in self.configs:
286 if not config in all_configs:
287 errs.append('Unused config "%s".' % config)
288
289 # Figure out the whole list of mixins, and check that every mixin
290 # listed by a config or another mixin actually exists.
291 referenced_mixins = set()
292 for config, mixins in self.configs.items():
293 for mixin in mixins:
294 if not mixin in self.mixins:
295 errs.append('Unknown mixin "%s" referenced by config "%s".' %
296 (mixin, config))
297 referenced_mixins.add(mixin)
298
299 for mixin in self.mixins:
300 for sub_mixin in self.mixins[mixin].get('mixins', []):
301 if not sub_mixin in self.mixins:
302 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
303 (sub_mixin, mixin))
304 referenced_mixins.add(sub_mixin)
305
306 # Check that every mixin defined is actually referenced somewhere.
307 for mixin in self.mixins:
308 if not mixin in referenced_mixins:
309 errs.append('Unreferenced mixin "%s".' % mixin)
310
dpranke255085e2016-03-16 05:23:59311 # If we're checking the Chromium config, check that the 'chromium' bots
312 # which build public artifacts do not include the chrome_with_codecs mixin.
313 if self.args.config_file == self.default_config:
314 if 'chromium' in self.masters:
315 for builder in self.masters['chromium']:
316 config = self.masters['chromium'][builder]
317 def RecurseMixins(current_mixin):
318 if current_mixin == 'chrome_with_codecs':
319 errs.append('Public artifact builder "%s" can not contain the '
320 '"chrome_with_codecs" mixin.' % builder)
321 return
322 if not 'mixins' in self.mixins[current_mixin]:
323 return
324 for mixin in self.mixins[current_mixin]['mixins']:
325 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41326
dpranke255085e2016-03-16 05:23:59327 for mixin in self.configs[config]:
328 RecurseMixins(mixin)
329 else:
330 errs.append('Missing "chromium" master. Please update this '
331 'proprietary codecs check with the name of the master '
332 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41333
dprankefe4602312015-04-08 16:20:35334 if errs:
dpranke4323c80632015-08-10 22:53:54335 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17336 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35337
dpranke0cafc162016-03-19 00:41:10338 if print_ok:
339 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35340 return 0
341
dpranke867bcf4a2016-03-14 22:28:32342 def CmdAudit(self):
343 """Track the progress of the GYP->GN migration on the bots."""
344
dpranke0cafc162016-03-19 00:41:10345 # First, make sure the config file is okay, but don't print anything
346 # if it is (it will throw an error if it isn't).
347 self.CmdValidate(print_ok=False)
348
dpranke867bcf4a2016-03-14 22:28:32349 stats = OrderedDict()
350 STAT_MASTER_ONLY = 'Master only'
351 STAT_CONFIG_ONLY = 'Config only'
352 STAT_TBD = 'Still TBD'
353 STAT_GYP = 'Still GYP'
354 STAT_DONE = 'Done (on GN)'
355 stats[STAT_MASTER_ONLY] = 0
356 stats[STAT_CONFIG_ONLY] = 0
357 stats[STAT_TBD] = 0
358 stats[STAT_GYP] = 0
359 stats[STAT_DONE] = 0
360
361 def PrintBuilders(heading, builders):
362 stats.setdefault(heading, 0)
363 stats[heading] += len(builders)
364 if builders:
365 self.Print(' %s:' % heading)
366 for builder in sorted(builders):
367 self.Print(' %s' % builder)
368
369 self.ReadConfigFile()
370
371 masters = self.args.master or self.masters
372 for master in sorted(masters):
373 url = self.args.url_template.replace('{master}', master)
374
375 self.Print('Auditing %s' % master)
376
377 MASTERS_TO_SKIP = (
378 'client.skia',
379 'client.v8.fyi',
380 'tryserver.v8',
381 )
382 if master in MASTERS_TO_SKIP:
383 # Skip these bots because converting them is the responsibility of
384 # those teams and out of scope for the Chromium migration to GN.
385 self.Print(' Skipped (out of scope)')
386 self.Print('')
387 continue
388
dprankeeafba352016-03-15 19:34:53389 INTERNAL_MASTERS = ('official.desktop', 'official.desktop.continuous')
dpranke867bcf4a2016-03-14 22:28:32390 if master in INTERNAL_MASTERS and not self.args.internal:
391 # Skip these because the servers aren't accessible by default ...
392 self.Print(' Skipped (internal)')
393 self.Print('')
394 continue
395
396 try:
397 # Fetch the /builders contents from the buildbot master. The
398 # keys of the dict are the builder names themselves.
399 json_contents = self.Fetch(url)
400 d = json.loads(json_contents)
401 except Exception as e:
402 self.Print(str(e))
403 return 1
404
405 config_builders = set(self.masters[master])
406 master_builders = set(d.keys())
407 both = master_builders & config_builders
408 master_only = master_builders - config_builders
409 config_only = config_builders - master_builders
410 tbd = set()
411 gyp = set()
412 done = set()
413
414 for builder in both:
415 config = self.masters[master][builder]
416 if config == 'tbd':
417 tbd.add(builder)
418 else:
419 # TODO(dpranke): Check if MB is actually running?
420 vals = self.FlattenConfig(config)
421 if vals['type'] == 'gyp':
422 gyp.add(builder)
423 else:
424 done.add(builder)
425
426 if master_only or config_only or tbd or gyp:
427 PrintBuilders(STAT_MASTER_ONLY, master_only)
428 PrintBuilders(STAT_CONFIG_ONLY, config_only)
429 PrintBuilders(STAT_TBD, tbd)
430 PrintBuilders(STAT_GYP, gyp)
431 else:
dprankeeafba352016-03-15 19:34:53432 self.Print(' ... done')
dpranke867bcf4a2016-03-14 22:28:32433
434 stats[STAT_DONE] += len(done)
435
436 self.Print('')
437
438 fmt = '{:<27} {:>4}'
439 self.Print(fmt.format('Totals', str(sum(int(v) for v in stats.values()))))
440 self.Print(fmt.format('-' * 27, '----'))
441 for stat, count in stats.items():
442 self.Print(fmt.format(stat, str(count)))
443
444 return 0
445
dprankefe4602312015-04-08 16:20:35446 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34447 build_dir = self.args.path[0]
448
449 vals = {}
450 if self.args.builder or self.args.master or self.args.config:
451 vals = self.Lookup()
452 if vals['type'] == 'gn':
453 # Re-run gn gen in order to ensure the config is consistent with the
454 # build dir.
455 self.RunGNGen(vals)
456 return vals
457
458 # TODO: We can only get the config for GN build dirs, not GYP build dirs.
459 # GN stores the args that were used in args.gn in the build dir,
460 # but GYP doesn't store them anywhere. We should consider modifying
461 # gyp_chromium to record the arguments it runs with in a similar
462 # manner.
463
464 mb_type_path = self.PathJoin(self.ToAbsPath(build_dir), 'mb_type')
465 if not self.Exists(mb_type_path):
466 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
467 if not self.Exists(gn_args_path):
468 self.Print('Must either specify a path to an existing GN build dir '
469 'or pass in a -m/-b pair or a -c flag to specify the '
470 'configuration')
471 return {}
472 else:
473 mb_type = 'gn'
474 else:
475 mb_type = self.ReadFile(mb_type_path).strip()
476
477 if mb_type == 'gn':
478 vals = self.GNValsFromDir(build_dir)
479 else:
480 vals = {}
481 vals['type'] = mb_type
482
483 return vals
484
485 def GNValsFromDir(self, build_dir):
486 args_contents = self.ReadFile(
487 self.PathJoin(self.ToAbsPath(build_dir), 'args.gn'))
488 gn_args = []
489 for l in args_contents.splitlines():
490 fields = l.split(' ')
491 name = fields[0]
492 val = ' '.join(fields[2:])
493 gn_args.append('%s=%s' % (name, val))
494
495 return {
496 'gn_args': ' '.join(gn_args),
497 'type': 'gn',
498 }
499
500 def Lookup(self):
dprankee0f486f2015-11-19 23:42:00501 vals = self.ReadBotConfig()
502 if not vals:
503 self.ReadConfigFile()
504 config = self.ConfigFromArgs()
505 if not config in self.configs:
506 raise MBErr('Config "%s" not found in %s' %
507 (config, self.args.config_file))
dprankefe4602312015-04-08 16:20:35508
dprankee0f486f2015-11-19 23:42:00509 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34510
511 # Do some basic sanity checking on the config so that we
512 # don't have to do this in every caller.
513 assert 'type' in vals, 'No meta-build type specified in the config'
514 assert vals['type'] in ('gn', 'gyp'), (
515 'Unknown meta-build type "%s"' % vals['gn_args'])
516
517 return vals
dprankefe4602312015-04-08 16:20:35518
dprankee0f486f2015-11-19 23:42:00519 def ReadBotConfig(self):
520 if not self.args.master or not self.args.builder:
521 return {}
522 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
523 self.args.master, self.args.builder + '.json')
524 if not self.Exists(path):
525 return {}
526
527 contents = json.loads(self.ReadFile(path))
528 gyp_vals = contents.get('GYP_DEFINES', {})
529 if isinstance(gyp_vals, dict):
530 gyp_defines = ' '.join('%s=%s' % (k, v) for k, v in gyp_vals.items())
531 else:
532 gyp_defines = ' '.join(gyp_vals)
533 gn_args = ' '.join(contents.get('gn_args', []))
534
535 return {
536 'type': contents.get('mb_type', ''),
537 'gn_args': gn_args,
538 'gyp_defines': gyp_defines,
dprankef75a3de52015-12-14 22:17:52539 'gyp_crosscompile': False,
dprankee0f486f2015-11-19 23:42:00540 }
541
dprankefe4602312015-04-08 16:20:35542 def ReadConfigFile(self):
543 if not self.Exists(self.args.config_file):
544 raise MBErr('config file not found at %s' % self.args.config_file)
545
546 try:
547 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
548 except SyntaxError as e:
549 raise MBErr('Failed to parse config file "%s": %s' %
550 (self.args.config_file, e))
551
dprankefe4602312015-04-08 16:20:35552 self.configs = contents['configs']
553 self.masters = contents['masters']
554 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35555
556 def ConfigFromArgs(self):
557 if self.args.config:
558 if self.args.master or self.args.builder:
559 raise MBErr('Can not specific both -c/--config and -m/--master or '
560 '-b/--builder')
561
562 return self.args.config
563
564 if not self.args.master or not self.args.builder:
565 raise MBErr('Must specify either -c/--config or '
566 '(-m/--master and -b/--builder)')
567
568 if not self.args.master in self.masters:
569 raise MBErr('Master name "%s" not found in "%s"' %
570 (self.args.master, self.args.config_file))
571
572 if not self.args.builder in self.masters[self.args.master]:
573 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
574 (self.args.builder, self.args.master, self.args.config_file))
575
576 return self.masters[self.args.master][self.args.builder]
577
578 def FlattenConfig(self, config):
579 mixins = self.configs[config]
580 vals = {
581 'type': None,
582 'gn_args': [],
dprankec161aa92015-09-14 20:21:13583 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59584 'gyp_crosscompile': False,
dprankefe4602312015-04-08 16:20:35585 }
586
587 visited = []
588 self.FlattenMixins(mixins, vals, visited)
589 return vals
590
591 def FlattenMixins(self, mixins, vals, visited):
592 for m in mixins:
593 if m not in self.mixins:
594 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22595
596 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35597
598 visited.append(m)
599
600 mixin_vals = self.mixins[m]
601 if 'type' in mixin_vals:
602 vals['type'] = mixin_vals['type']
603 if 'gn_args' in mixin_vals:
604 if vals['gn_args']:
605 vals['gn_args'] += ' ' + mixin_vals['gn_args']
606 else:
607 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59608 if 'gyp_crosscompile' in mixin_vals:
609 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35610 if 'gyp_defines' in mixin_vals:
611 if vals['gyp_defines']:
612 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
613 else:
614 vals['gyp_defines'] = mixin_vals['gyp_defines']
615 if 'mixins' in mixin_vals:
616 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
617 return vals
618
dprankec161aa92015-09-14 20:21:13619 def ClobberIfNeeded(self, vals):
620 path = self.args.path[0]
621 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33622 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13623 needs_clobber = False
624 new_mb_type = vals['type']
625 if self.Exists(build_dir):
626 if self.Exists(mb_type_path):
627 old_mb_type = self.ReadFile(mb_type_path)
628 if old_mb_type != new_mb_type:
629 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
630 (old_mb_type, new_mb_type, path))
631 needs_clobber = True
632 else:
633 # There is no 'mb_type' file in the build directory, so this probably
634 # means that the prior build(s) were not done through mb, and we
635 # have no idea if this was a GYP build or a GN build. Clobber it
636 # to be safe.
637 self.Print("%s/mb_type missing, clobbering to be safe" % path)
638 needs_clobber = True
639
dpranke3cec199c2015-09-22 23:29:02640 if self.args.dryrun:
641 return
642
dprankec161aa92015-09-14 20:21:13643 if needs_clobber:
644 self.RemoveDirectory(build_dir)
645
646 self.MaybeMakeDirectory(build_dir)
647 self.WriteFile(mb_type_path, new_mb_type)
648
Dirk Pranke0fd41bcd2015-06-19 00:05:50649 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34650 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50651
dpranke751516a2015-10-03 01:11:34652 cmd = self.GNCmd('gen', build_dir, vals['gn_args'], extra_args=['--check'])
dpranke74559b52015-06-10 21:20:39653
654 swarming_targets = []
dpranke751516a2015-10-03 01:11:34655 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39656 # We need GN to generate the list of runtime dependencies for
657 # the compile targets listed (one per line) in the file so
658 # we can run them via swarming. We use ninja_to_gn.pyl to convert
659 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00660 path = self.args.swarming_targets_file
661 if not self.Exists(path):
662 self.WriteFailureAndRaise('"%s" does not exist' % path,
663 output_path=None)
664 contents = self.ReadFile(path)
665 swarming_targets = set(contents.splitlines())
dpranke8c2cfd32015-09-17 20:12:33666 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47667 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39668 gn_labels = []
dprankeb2be10a2016-02-22 17:11:00669 err = ''
dpranke74559b52015-06-10 21:20:39670 for target in swarming_targets:
jbudorickdcff99982016-02-03 19:38:07671 target_name = self.GNTargetName(target)
672 if not target_name in gn_isolate_map:
dprankeb2be10a2016-02-22 17:11:00673 err += ('test target "%s" not found\n' % target_name)
674 elif gn_isolate_map[target_name]['type'] == 'unknown':
675 err += ('test target "%s" type is unknown\n' % target_name)
676 else:
677 gn_labels.append(gn_isolate_map[target_name]['label'])
678
679 if err:
680 raise MBErr('Error: Failed to match swarming targets to %s:\n%s' %
681 ('//testing/buildbot/gn_isolate_map.pyl', err))
dpranke74559b52015-06-10 21:20:39682
dpranke751516a2015-10-03 01:11:34683 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankec3441d12015-06-23 23:01:35684
685 # Since GN hasn't run yet, the build directory may not even exist.
dpranke751516a2015-10-03 01:11:34686 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
dprankec3441d12015-06-23 23:01:35687
dpranke74559b52015-06-10 21:20:39688 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
689 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
690
dprankefe4602312015-04-08 16:20:35691 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40692 if ret:
693 # If `gn gen` failed, we should exit early rather than trying to
694 # generate isolates. Run() will have already logged any error output.
695 self.Print('GN gen failed: %d' % ret)
696 return ret
dpranke74559b52015-06-10 21:20:39697
698 for target in swarming_targets:
jbudorick91c8a6012016-01-29 23:20:02699 if target.endswith('_apk'):
700 # "_apk" targets may be either android_apk or executable. The former
701 # will result in runtime_deps associated with the stamp file, while the
702 # latter will result in runtime_deps associated with the executable.
jbudorickdcff99982016-02-03 19:38:07703 target_name = self.GNTargetName(target)
704 label = gn_isolate_map[target_name]['label']
jbudorick91c8a6012016-01-29 23:20:02705 runtime_deps_targets = [
jbudorickdcff99982016-02-03 19:38:07706 target_name,
jbudorick91c8a6012016-01-29 23:20:02707 'obj/%s.stamp' % label.replace(':', '/')]
708 elif gn_isolate_map[target]['type'] == 'gpu_browser_test':
709 runtime_deps_targets = ['browser_tests']
dprankefe0d35e2016-02-05 02:43:59710 elif (gn_isolate_map[target]['type'] == 'script' or
711 gn_isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11712 # For script targets, the build target is usually a group,
713 # for which gn generates the runtime_deps next to the stamp file
714 # for the label, which lives under the obj/ directory.
715 label = gn_isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02716 runtime_deps_targets = ['obj/%s.stamp' % label.replace(':', '/')]
dpranke34bd39d2015-06-24 02:36:52717 else:
jbudorick91c8a6012016-01-29 23:20:02718 runtime_deps_targets = [target]
719
dpranke8c2cfd32015-09-17 20:12:33720 if self.platform == 'win32':
jbudorick91c8a6012016-01-29 23:20:02721 deps_paths = [
722 self.ToAbsPath(build_dir, r + '.exe.runtime_deps')
723 for r in runtime_deps_targets]
dprankedbdd9d82015-08-12 21:18:18724 else:
jbudorick91c8a6012016-01-29 23:20:02725 deps_paths = [
726 self.ToAbsPath(build_dir, r + '.runtime_deps')
727 for r in runtime_deps_targets]
728
729 for d in deps_paths:
730 if self.Exists(d):
731 deps_path = d
732 break
733 else:
jbudoricke8428732016-02-02 02:17:06734 raise MBErr('did not generate any of %s' % ', '.join(deps_paths))
dpranke74559b52015-06-10 21:20:39735
dprankea55584f12015-07-22 00:52:47736 command, extra_files = self.GetIsolateCommand(target, vals,
737 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30738
739 runtime_deps = self.ReadFile(deps_path).splitlines()
740
dpranke751516a2015-10-03 01:11:34741 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
742 extra_files)
dpranked5b2b9432015-06-23 16:55:30743
dpranke751516a2015-10-03 01:11:34744 return 0
745
746 def RunGNIsolate(self, vals):
747 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
748 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
749
750 build_dir = self.args.path[0]
751 target = self.args.target[0]
jbudorickdcff99982016-02-03 19:38:07752 target_name = self.GNTargetName(target)
dpranke751516a2015-10-03 01:11:34753 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
754
jbudorickdcff99982016-02-03 19:38:07755 label = gn_isolate_map[target_name]['label']
dpranke40da0202016-02-13 05:05:20756 cmd = self.GNCmd('desc', build_dir, extra_args=[label, 'runtime_deps'])
757 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34758 if ret:
759 return ret
760
761 runtime_deps = out.splitlines()
762
763 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
764 extra_files)
765
766 ret, _, _ = self.Run([
767 self.executable,
768 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
769 'check',
770 '-i',
771 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
772 '-s',
773 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
774 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30775
dprankefe4602312015-04-08 16:20:35776 return ret
777
dpranke751516a2015-10-03 01:11:34778 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
779 extra_files):
780 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
781 self.WriteFile(isolate_path,
782 pprint.pformat({
783 'variables': {
784 'command': command,
785 'files': sorted(runtime_deps + extra_files),
786 }
787 }) + '\n')
788
789 self.WriteJSON(
790 {
791 'args': [
792 '--isolated',
793 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
794 '--isolate',
795 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
796 ],
797 'dir': self.chromium_src_dir,
798 'version': 1,
799 },
800 isolate_path + 'd.gen.json',
801 )
802
dprankeb218d912015-09-18 19:07:00803 def GNCmd(self, subcommand, path, gn_args='', extra_args=None):
dpranked1fba482015-04-14 20:54:51804 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20805 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51806 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20807 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51808 else:
dpranke40da0202016-02-13 05:05:20809 subdir, exe = 'win', 'gn.exe'
810 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranked1fba482015-04-14 20:54:51811
812 cmd = [gn_path, subcommand, path]
dprankeee5b51f62015-04-09 00:03:22813 gn_args = gn_args.replace("$(goma_dir)", self.args.goma_dir)
dprankefe4602312015-04-08 16:20:35814 if gn_args:
815 cmd.append('--args=%s' % gn_args)
dprankeb218d912015-09-18 19:07:00816 if extra_args:
817 cmd.extend(extra_args)
dprankefe4602312015-04-08 16:20:35818 return cmd
819
Dirk Pranke0fd41bcd2015-06-19 00:05:50820 def RunGYPGen(self, vals):
821 path = self.args.path[0]
822
dpranke8c2cfd32015-09-17 20:12:33823 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41824 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59825 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35826 return ret
827
828 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33829 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32830 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:16831 inp = self.ReadInputJSON(['files', 'test_targets',
832 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32833 self.Print()
834 self.Print('analyze input:')
835 self.PrintJSON(inp)
836 self.Print()
837
dpranke38f4acb62015-09-29 23:50:41838 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33839 cmd.extend(['-f', 'analyzer',
840 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35841 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02842 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32843 if not ret and self.args.verbose:
844 outp = json.loads(self.ReadFile(self.args.output_path[0]))
845 self.Print()
846 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39847 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32848 self.Print()
849
dprankefe4602312015-04-08 16:20:35850 return ret
851
dprankea55584f12015-07-22 00:52:47852 def GetIsolateCommand(self, target, vals, gn_isolate_map):
jbudoricke8428732016-02-02 02:17:06853 android = 'target_os="android"' in vals['gn_args']
854
dpranked8113582015-06-05 20:08:25855 # This needs to mirror the settings in //build/config/ui.gni:
856 # use_x11 = is_linux && !use_ozone.
857 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33858 use_x11 = (self.platform == 'linux2' and
jbudoricke8428732016-02-02 02:17:06859 not android and
dpranked8113582015-06-05 20:08:25860 not 'use_ozone=true' in vals['gn_args'])
861
862 asan = 'is_asan=true' in vals['gn_args']
863 msan = 'is_msan=true' in vals['gn_args']
864 tsan = 'is_tsan=true' in vals['gn_args']
865
jbudorickdcff99982016-02-03 19:38:07866 target_name = self.GNTargetName(target)
867 test_type = gn_isolate_map[target_name]['type']
dprankefe0d35e2016-02-05 02:43:59868
869 executable = gn_isolate_map[target_name].get('executable', target_name)
870 executable_suffix = '.exe' if self.platform == 'win32' else ''
871
dprankea55584f12015-07-22 00:52:47872 cmdline = []
873 extra_files = []
dpranked8113582015-06-05 20:08:25874
jbudoricke8428732016-02-02 02:17:06875 if android:
876 # TODO(jbudorick): This won't work with instrumentation test targets.
877 # Revisit this logic when those are added to gn_isolate_map.pyl.
jbudorickdcff99982016-02-03 19:38:07878 cmdline = [self.PathJoin('bin', 'run_%s' % target_name)]
jbudoricke8428732016-02-02 02:17:06879 elif use_x11 and test_type == 'windowed_test_launcher':
dprankea55584f12015-07-22 00:52:47880 extra_files = [
881 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25882 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47883 '../../testing/xvfb.py',
884 ]
885 cmdline = [
dprankefe0d35e2016-02-05 02:43:59886 '../../testing/xvfb.py',
887 '.',
888 './' + str(executable) + executable_suffix,
889 '--brave-new-test-launcher',
890 '--test-launcher-bot-mode',
891 '--asan=%d' % asan,
892 '--msan=%d' % msan,
893 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47894 ]
895 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
896 extra_files = [
897 '../../testing/test_env.py'
898 ]
899 cmdline = [
900 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:59901 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:25902 '--brave-new-test-launcher',
903 '--test-launcher-bot-mode',
904 '--asan=%d' % asan,
905 '--msan=%d' % msan,
906 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47907 ]
dprankedbdd9d82015-08-12 21:18:18908 elif test_type == 'gpu_browser_test':
909 extra_files = [
910 '../../testing/test_env.py'
911 ]
912 gtest_filter = gn_isolate_map[target]['gtest_filter']
913 cmdline = [
914 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:11915 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:18916 '--test-launcher-bot-mode',
917 '--enable-gpu',
918 '--test-launcher-jobs=1',
919 '--gtest_filter=%s' % gtest_filter,
920 ]
dpranke6abd8652015-08-28 03:21:11921 elif test_type == 'script':
922 extra_files = [
923 '../../testing/test_env.py'
924 ]
925 cmdline = [
926 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:39927 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:59928 ]
dprankea55584f12015-07-22 00:52:47929 elif test_type in ('raw'):
930 extra_files = []
931 cmdline = [
932 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:59933 ]
dpranked8113582015-06-05 20:08:25934
dprankea55584f12015-07-22 00:52:47935 else:
936 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
937 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25938
jbudorick8a0560422016-02-05 06:07:17939 cmdline += gn_isolate_map[target_name].get('args', [])
dprankefe0d35e2016-02-05 02:43:59940
dpranked8113582015-06-05 20:08:25941 return cmdline, extra_files
942
dpranke74559b52015-06-10 21:20:39943 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33944 return self.PathJoin(self.chromium_src_dir,
945 self.ToSrcRelPath(build_path),
946 *comps)
dpranked8113582015-06-05 20:08:25947
dprankeee5b51f62015-04-09 00:03:22948 def ToSrcRelPath(self, path):
949 """Returns a relative path from the top of the repo."""
950 # TODO: Support normal paths in addition to source-absolute paths.
dprankefe4602312015-04-08 16:20:35951 assert(path.startswith('//'))
dpranke8c2cfd32015-09-17 20:12:33952 return path[2:].replace('/', self.sep)
dprankefe4602312015-04-08 16:20:35953
954 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:22955 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:33956 output_dir, _, _ = rpath.rpartition(self.sep)
957 return output_dir
dprankefe4602312015-04-08 16:20:35958
dpranke38f4acb62015-09-29 23:50:41959 def GYPCmd(self, output_dir, vals):
960 gyp_defines = vals['gyp_defines']
dpranke3cec199c2015-09-22 23:29:02961 goma_dir = self.args.goma_dir
962
963 # GYP uses shlex.split() to split the gyp defines into separate arguments,
964 # so we can support backslashes and and spaces in arguments by quoting
965 # them, even on Windows, where this normally wouldn't work.
966 if '\\' in goma_dir or ' ' in goma_dir:
967 goma_dir = "'%s'" % goma_dir
968 gyp_defines = gyp_defines.replace("$(goma_dir)", goma_dir)
969
dprankefe4602312015-04-08 16:20:35970 cmd = [
dpranke8c2cfd32015-09-17 20:12:33971 self.executable,
972 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:35973 '-G',
974 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:35975 ]
dpranke38f4acb62015-09-29 23:50:41976
977 # Ensure that we have an environment that only contains
978 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:02979 env = os.environ.copy()
dprankef75a3de52015-12-14 22:17:52980 env['GYP_GENERATORS'] = 'ninja'
dpranke38f4acb62015-09-29 23:50:41981 if 'GYP_CHROMIUM_NO_ACTION' in env:
982 del env['GYP_CHROMIUM_NO_ACTION']
983 if 'GYP_CROSSCOMPILE' in env:
984 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:02985 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:41986 if vals['gyp_crosscompile']:
987 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:02988 return cmd, env
dprankefe4602312015-04-08 16:20:35989
Dirk Pranke0fd41bcd2015-06-19 00:05:50990 def RunGNAnalyze(self, vals):
991 # analyze runs before 'gn gen' now, so we need to run gn gen
992 # in order to ensure that we have a build directory.
993 ret = self.RunGNGen(vals)
994 if ret:
995 return ret
996
dpranke7837fc362015-11-19 03:54:16997 inp = self.ReadInputJSON(['files', 'test_targets',
998 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32999 if self.args.verbose:
1000 self.Print()
1001 self.Print('analyze input:')
1002 self.PrintJSON(inp)
1003 self.Print()
1004
dpranke7837fc362015-11-19 03:54:161005 # TODO(crbug.com/555273) - currently GN treats targets and
1006 # additional_compile_targets identically since we can't tell the
1007 # difference between a target that is a group in GN and one that isn't.
1008 # We should eventually fix this and treat the two types differently.
1009 targets = (set(inp['test_targets']) |
1010 set(inp['additional_compile_targets']))
dpranke5ab84a502015-11-13 17:35:021011
dprankecda00332015-04-11 04:18:321012 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351013
1014 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:021015 # what to do about it. Also, bail out early if 'all' was asked for,
1016 # since we can't deal with it yet.
1017 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
1018 'all' in targets):
dpranke7837fc362015-11-19 03:54:161019 self.WriteJSON({
1020 'status': 'Found dependency (all)',
1021 'compile_targets': sorted(targets),
1022 'test_targets': sorted(targets & set(inp['test_targets'])),
1023 }, output_path)
dpranke76734662015-04-16 02:17:501024 return 0
1025
dpranke7c5f614d2015-07-22 23:43:391026 # This shouldn't normally happen, but could due to unusual race conditions,
1027 # like a try job that gets scheduled before a patch lands but runs after
1028 # the patch has landed.
1029 if not inp['files']:
1030 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161031 self.WriteJSON({
1032 'status': 'No dependency',
1033 'compile_targets': [],
1034 'test_targets': [],
1035 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391036 return 0
1037
Dirk Pranke12ee2db2015-04-14 23:15:321038 ret = 0
dprankef61de2f2015-05-14 04:09:561039 response_file = self.TempFile()
1040 response_file.write('\n'.join(inp['files']) + '\n')
1041 response_file.close()
1042
dpranke5ab84a502015-11-13 17:35:021043 matching_targets = set()
dprankef61de2f2015-05-14 04:09:561044 try:
dpranked1fba482015-04-14 20:54:511045 cmd = self.GNCmd('refs', self.args.path[0]) + [
dpranke067d0142015-05-14 22:52:451046 '@%s' % response_file.name, '--all', '--as=output']
dprankee0547cd2015-09-15 01:27:401047 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:121048 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:321049 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
1050 output_path)
dpranke8c2cfd32015-09-17 20:12:331051 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:561052 for output in out.splitlines():
1053 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:021054 if build_output in targets:
1055 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:451056
1057 cmd = self.GNCmd('refs', self.args.path[0]) + [
1058 '@%s' % response_file.name, '--all']
dprankee0547cd2015-09-15 01:27:401059 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:451060 if ret and not 'The input matches no targets' in out:
1061 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
1062 output_path)
1063 for label in out.splitlines():
1064 build_target = label[2:]
newt309af8f2015-08-25 22:10:201065 # We want to accept 'chrome/android:chrome_public_apk' and
1066 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:451067 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:021068 for input_target in targets:
dpranke067d0142015-05-14 22:52:451069 if (input_target == build_target or
1070 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:021071 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:561072 finally:
1073 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:351074
dprankef61de2f2015-05-14 04:09:561075 if matching_targets:
dpranke7837fc362015-11-19 03:54:161076 self.WriteJSON({
dpranke5ab84a502015-11-13 17:35:021077 'status': 'Found dependency',
dpranke7837fc362015-11-19 03:54:161078 'compile_targets': sorted(matching_targets),
1079 'test_targets': sorted(matching_targets &
1080 set(inp['test_targets'])),
1081 }, output_path)
dprankefe4602312015-04-08 16:20:351082 else:
dpranke7837fc362015-11-19 03:54:161083 self.WriteJSON({
1084 'status': 'No dependency',
1085 'compile_targets': [],
1086 'test_targets': [],
1087 }, output_path)
dprankecda00332015-04-11 04:18:321088
dprankee0547cd2015-09-15 01:27:401089 if self.args.verbose:
dprankecda00332015-04-11 04:18:321090 outp = json.loads(self.ReadFile(output_path))
1091 self.Print()
1092 self.Print('analyze output:')
1093 self.PrintJSON(outp)
1094 self.Print()
dprankefe4602312015-04-08 16:20:351095
1096 return 0
1097
dpranked8113582015-06-05 20:08:251098 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351099 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321100 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351101 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321102 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351103
1104 try:
1105 inp = json.loads(self.ReadFile(path))
1106 except Exception as e:
1107 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321108 (path, e), output_path)
dpranked8113582015-06-05 20:08:251109
1110 for k in required_keys:
1111 if not k in inp:
1112 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1113 output_path)
dprankefe4602312015-04-08 16:20:351114
1115 return inp
1116
dpranked5b2b9432015-06-23 16:55:301117 def WriteFailureAndRaise(self, msg, output_path):
1118 if output_path:
dprankee0547cd2015-09-15 01:27:401119 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351120 raise MBErr(msg)
1121
dprankee0547cd2015-09-15 01:27:401122 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321123 try:
dprankee0547cd2015-09-15 01:27:401124 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1125 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321126 except Exception as e:
1127 raise MBErr('Error %s writing to the output path "%s"' %
1128 (e, path))
dprankefe4602312015-04-08 16:20:351129
dpranke3cec199c2015-09-22 23:29:021130 def PrintCmd(self, cmd, env):
1131 if self.platform == 'win32':
1132 env_prefix = 'set '
1133 env_quoter = QuoteForSet
1134 shell_quoter = QuoteForCmd
1135 else:
1136 env_prefix = ''
1137 env_quoter = pipes.quote
1138 shell_quoter = pipes.quote
1139
1140 def print_env(var):
1141 if env and var in env:
1142 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1143
1144 print_env('GYP_CROSSCOMPILE')
1145 print_env('GYP_DEFINES')
1146
dpranke8c2cfd32015-09-17 20:12:331147 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351148 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021149 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351150
dprankecda00332015-04-11 04:18:321151 def PrintJSON(self, obj):
1152 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1153
dprankefe4602312015-04-08 16:20:351154 def Print(self, *args, **kwargs):
1155 # This function largely exists so it can be overridden for testing.
1156 print(*args, **kwargs)
1157
dpranke751516a2015-10-03 01:11:341158 def Build(self, target):
1159 build_dir = self.ToSrcRelPath(self.args.path[0])
1160 ninja_cmd = ['ninja', '-C', build_dir]
1161 if self.args.jobs:
1162 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1163 ninja_cmd.append(target)
1164 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1165 return ret
1166
1167 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351168 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401169 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021170 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351171 if self.args.dryrun:
1172 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401173
dpranke751516a2015-10-03 01:11:341174 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401175 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341176 if ret:
1177 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351178 if out:
dprankeee5b51f62015-04-09 00:03:221179 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351180 if err:
dprankeee5b51f62015-04-09 00:03:221181 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351182 return ret, out, err
1183
dpranke751516a2015-10-03 01:11:341184 def Call(self, cmd, env=None, buffer_output=True):
1185 if buffer_output:
1186 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1187 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1188 env=env)
1189 out, err = p.communicate()
1190 else:
1191 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1192 env=env)
1193 p.wait()
1194 out = err = ''
dprankefe4602312015-04-08 16:20:351195 return p.returncode, out, err
1196
1197 def ExpandUser(self, path):
1198 # This function largely exists so it can be overridden for testing.
1199 return os.path.expanduser(path)
1200
1201 def Exists(self, path):
1202 # This function largely exists so it can be overridden for testing.
1203 return os.path.exists(path)
1204
dpranke867bcf4a2016-03-14 22:28:321205 def Fetch(self, url):
1206
1207 f = urllib2.urlopen(url)
1208 contents = f.read()
1209 f.close()
1210 return contents
1211
jbudorickdcff99982016-02-03 19:38:071212 def GNTargetName(self, target):
1213 return target[:-len('_apk')] if target.endswith('_apk') else target
1214
dprankec3441d12015-06-23 23:01:351215 def MaybeMakeDirectory(self, path):
1216 try:
1217 os.makedirs(path)
1218 except OSError, e:
1219 if e.errno != errno.EEXIST:
1220 raise
1221
dpranke8c2cfd32015-09-17 20:12:331222 def PathJoin(self, *comps):
1223 # This function largely exists so it can be overriden for testing.
1224 return os.path.join(*comps)
1225
dprankefe4602312015-04-08 16:20:351226 def ReadFile(self, path):
1227 # This function largely exists so it can be overriden for testing.
1228 with open(path) as fp:
1229 return fp.read()
1230
dprankef61de2f2015-05-14 04:09:561231 def RemoveFile(self, path):
1232 # This function largely exists so it can be overriden for testing.
1233 os.remove(path)
1234
dprankec161aa92015-09-14 20:21:131235 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331236 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131237 # In other places in chromium, we often have to retry this command
1238 # because we're worried about other processes still holding on to
1239 # file handles, but when MB is invoked, it will be early enough in the
1240 # build that their should be no other processes to interfere. We
1241 # can change this if need be.
1242 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1243 else:
1244 shutil.rmtree(abs_path, ignore_errors=True)
1245
dprankef61de2f2015-05-14 04:09:561246 def TempFile(self, mode='w'):
1247 # This function largely exists so it can be overriden for testing.
1248 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1249
dprankee0547cd2015-09-15 01:27:401250 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351251 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401252 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301253 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351254 with open(path, 'w') as fp:
1255 return fp.write(contents)
1256
dprankef61de2f2015-05-14 04:09:561257
dprankefe4602312015-04-08 16:20:351258class MBErr(Exception):
1259 pass
1260
1261
dpranke3cec199c2015-09-22 23:29:021262# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1263# details of this next section, which handles escaping command lines
1264# so that they can be copied and pasted into a cmd window.
1265UNSAFE_FOR_SET = set('^<>&|')
1266UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1267ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1268
1269
1270def QuoteForSet(arg):
1271 if any(a in UNSAFE_FOR_SET for a in arg):
1272 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1273 return arg
1274
1275
1276def QuoteForCmd(arg):
1277 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1278 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1279 if arg == '' or ' ' in arg or '"' in arg:
1280 quote_re = re.compile(r'(\\*)"')
1281 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1282
1283 # Then check to see if the arg contains any metacharacters other than
1284 # double quotes; if it does, quote everything (including the double
1285 # quotes) for safety.
1286 if any(a in UNSAFE_FOR_CMD for a in arg):
1287 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1288 return arg
1289
1290
dprankefe4602312015-04-08 16:20:351291if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591292 sys.exit(main(sys.argv[1:]))