blob: b03f03a7a4648eeee6afa97f529a2575bddc8fd6 [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
dprankebbe6d4672016-04-19 06:56:5726import traceback
dpranke867bcf4a2016-03-14 22:28:3227import urllib2
28
29from collections import OrderedDict
dprankefe4602312015-04-08 16:20:3530
dprankeeca4a782016-04-14 01:42:3831CHROMIUM_SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
32 os.path.abspath(__file__))))
33sys.path = [os.path.join(CHROMIUM_SRC_DIR, 'build')] + sys.path
34
35import gn_helpers
36
37
dprankefe4602312015-04-08 16:20:3538def main(args):
dprankeee5b51f62015-04-09 00:03:2239 mbw = MetaBuildWrapper()
dpranke255085e2016-03-16 05:23:5940 return mbw.Main(args)
dprankefe4602312015-04-08 16:20:3541
42
43class MetaBuildWrapper(object):
44 def __init__(self):
dprankeeca4a782016-04-14 01:42:3845 self.chromium_src_dir = CHROMIUM_SRC_DIR
46 self.default_config = os.path.join(self.chromium_src_dir, 'tools', 'mb',
47 'mb_config.pyl')
dpranke8c2cfd32015-09-17 20:12:3348 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5149 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3350 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3551 self.args = argparse.Namespace()
52 self.configs = {}
53 self.masters = {}
54 self.mixins = {}
dprankefe4602312015-04-08 16:20:3555
dpranke255085e2016-03-16 05:23:5956 def Main(self, args):
57 self.ParseArgs(args)
58 try:
59 ret = self.args.func()
60 if ret:
61 self.DumpInputFiles()
62 return ret
63 except KeyboardInterrupt:
64 self.Print('interrupted, exiting', stream=sys.stderr)
65 return 130
dprankebbe6d4672016-04-19 06:56:5766 except Exception:
dpranke255085e2016-03-16 05:23:5967 self.DumpInputFiles()
dprankebbe6d4672016-04-19 06:56:5768 s = traceback.format_exc()
69 for l in s.splitlines():
70 self.Print(l)
dpranke255085e2016-03-16 05:23:5971 return 1
72
dprankefe4602312015-04-08 16:20:3573 def ParseArgs(self, argv):
74 def AddCommonOptions(subp):
75 subp.add_argument('-b', '--builder',
76 help='builder name to look up config from')
77 subp.add_argument('-m', '--master',
78 help='master name to look up config from')
79 subp.add_argument('-c', '--config',
80 help='configuration to analyze')
81 subp.add_argument('-f', '--config-file', metavar='PATH',
82 default=self.default_config,
83 help='path to config file '
84 '(default is //tools/mb/mb_config.pyl)')
dpranked0c138b2016-04-13 18:28:4785 subp.add_argument('-g', '--goma-dir',
86 help='path to goma directory')
agrieve41d21a72016-04-14 18:02:2687 subp.add_argument('--android-version-code',
88 help='Sets GN arg android_default_version_code and '
89 'GYP_DEFINE app_manifest_version_code')
90 subp.add_argument('--android-version-name',
91 help='Sets GN arg android_default_version_name and '
92 'GYP_DEFINE app_manifest_version_name')
dprankefe4602312015-04-08 16:20:3593 subp.add_argument('-n', '--dryrun', action='store_true',
94 help='Do a dry run (i.e., do nothing, just print '
95 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:4096 subp.add_argument('-v', '--verbose', action='store_true',
97 help='verbose logging')
dprankefe4602312015-04-08 16:20:3598
99 parser = argparse.ArgumentParser(prog='mb')
100 subps = parser.add_subparsers()
101
102 subp = subps.add_parser('analyze',
103 help='analyze whether changes to a set of files '
104 'will cause a set of binaries to be rebuilt.')
105 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:25106 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35107 help='path build was generated into.')
108 subp.add_argument('input_path', nargs=1,
109 help='path to a file containing the input arguments '
110 'as a JSON object.')
111 subp.add_argument('output_path', nargs=1,
112 help='path to a file containing the output arguments '
113 'as a JSON object.')
114 subp.set_defaults(func=self.CmdAnalyze)
115
116 subp = subps.add_parser('gen',
117 help='generate a new set of build files')
118 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39119 subp.add_argument('--swarming-targets-file',
120 help='save runtime dependencies for targets listed '
121 'in file.')
dpranked8113582015-06-05 20:08:25122 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35123 help='path to generate build into')
124 subp.set_defaults(func=self.CmdGen)
125
dpranke751516a2015-10-03 01:11:34126 subp = subps.add_parser('isolate',
127 help='generate the .isolate files for a given'
128 'binary')
129 AddCommonOptions(subp)
130 subp.add_argument('path', nargs=1,
131 help='path build was generated into')
132 subp.add_argument('target', nargs=1,
133 help='ninja target to generate the isolate for')
134 subp.set_defaults(func=self.CmdIsolate)
135
dprankefe4602312015-04-08 16:20:35136 subp = subps.add_parser('lookup',
137 help='look up the command for a given config or '
138 'builder')
139 AddCommonOptions(subp)
140 subp.set_defaults(func=self.CmdLookup)
141
dpranke030d7a6d2016-03-26 17:23:50142 subp = subps.add_parser(
143 'run',
144 help='build and run the isolated version of a '
145 'binary',
146 formatter_class=argparse.RawDescriptionHelpFormatter)
147 subp.description = (
148 'Build, isolate, and run the given binary with the command line\n'
149 'listed in the isolate. You may pass extra arguments after the\n'
150 'target; use "--" if the extra arguments need to include switches.\n'
151 '\n'
152 'Examples:\n'
153 '\n'
154 ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n'
155 ' //out/Default content_browsertests\n'
156 '\n'
157 ' % tools/mb/mb.py run out/Default content_browsertests\n'
158 '\n'
159 ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n'
160 ' --test-launcher-retry-limit=0'
161 '\n'
162 )
163
dpranke751516a2015-10-03 01:11:34164 AddCommonOptions(subp)
165 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
166 help='Number of jobs to pass to ninja')
167 subp.add_argument('--no-build', dest='build', default=True,
168 action='store_false',
169 help='Do not build, just isolate and run')
170 subp.add_argument('path', nargs=1,
dpranke030d7a6d2016-03-26 17:23:50171 help=('path to generate build into (or use).'
172 ' This can be either a regular path or a '
173 'GN-style source-relative path like '
174 '//out/Default.'))
dpranke751516a2015-10-03 01:11:34175 subp.add_argument('target', nargs=1,
176 help='ninja target to build and run')
dpranke030d7a6d2016-03-26 17:23:50177 subp.add_argument('extra_args', nargs='*',
178 help=('extra args to pass to the isolate to run. Use '
179 '"--" as the first arg if you need to pass '
180 'switches'))
dpranke751516a2015-10-03 01:11:34181 subp.set_defaults(func=self.CmdRun)
182
dprankefe4602312015-04-08 16:20:35183 subp = subps.add_parser('validate',
184 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17185 subp.add_argument('-f', '--config-file', metavar='PATH',
186 default=self.default_config,
187 help='path to config file '
188 '(default is //tools/mb/mb_config.pyl)')
dprankefe4602312015-04-08 16:20:35189 subp.set_defaults(func=self.CmdValidate)
190
dpranke867bcf4a2016-03-14 22:28:32191 subp = subps.add_parser('audit',
192 help='Audit the config file to track progress')
193 subp.add_argument('-f', '--config-file', metavar='PATH',
194 default=self.default_config,
195 help='path to config file '
196 '(default is //tools/mb/mb_config.pyl)')
197 subp.add_argument('-i', '--internal', action='store_true',
198 help='check internal masters also')
199 subp.add_argument('-m', '--master', action='append',
200 help='master to audit (default is all non-internal '
201 'masters in file)')
202 subp.add_argument('-u', '--url-template', action='store',
203 default='https://build.chromium.org/p/'
204 '{master}/json/builders',
205 help='URL scheme for JSON APIs to buildbot '
206 '(default: %(default)s) ')
aneeshmde50f472016-04-01 01:13:10207 subp.add_argument('-c', '--check-compile', action='store_true',
208 help='check whether tbd and master-only bots actually'
209 ' do compiles')
dpranke867bcf4a2016-03-14 22:28:32210 subp.set_defaults(func=self.CmdAudit)
211
dprankefe4602312015-04-08 16:20:35212 subp = subps.add_parser('help',
213 help='Get help on a subcommand.')
214 subp.add_argument(nargs='?', action='store', dest='subcommand',
215 help='The command to get help for.')
216 subp.set_defaults(func=self.CmdHelp)
217
218 self.args = parser.parse_args(argv)
219
dprankeb2be10a2016-02-22 17:11:00220 def DumpInputFiles(self):
221
dprankef7b7eb7a2016-03-28 22:42:59222 def DumpContentsOfFilePassedTo(arg_name, path):
dprankeb2be10a2016-02-22 17:11:00223 if path and self.Exists(path):
dprankef7b7eb7a2016-03-28 22:42:59224 self.Print("\n# To recreate the file passed to %s:" % arg_name)
225 self.Print("%% cat > %s <<EOF)" % path)
dprankeb2be10a2016-02-22 17:11:00226 contents = self.ReadFile(path)
dprankef7b7eb7a2016-03-28 22:42:59227 self.Print(contents)
228 self.Print("EOF\n%\n")
dprankeb2be10a2016-02-22 17:11:00229
dprankef7b7eb7a2016-03-28 22:42:59230 if getattr(self.args, 'input_path', None):
231 DumpContentsOfFilePassedTo(
232 'argv[0] (input_path)', self.args.input_path[0])
233 if getattr(self.args, 'swarming_targets_file', None):
234 DumpContentsOfFilePassedTo(
235 '--swarming-targets-file', self.args.swarming_targets_file)
dprankeb2be10a2016-02-22 17:11:00236
dprankefe4602312015-04-08 16:20:35237 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34238 vals = self.Lookup()
dprankee88057c2016-04-12 22:40:08239 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35240 if vals['type'] == 'gn':
241 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35242 else:
dpranke751516a2015-10-03 01:11:34243 return self.RunGYPAnalyze(vals)
dprankefe4602312015-04-08 16:20:35244
245 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34246 vals = self.Lookup()
dprankec161aa92015-09-14 20:21:13247 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35248 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50249 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35250 else:
dpranke751516a2015-10-03 01:11:34251 return self.RunGYPGen(vals)
dprankefe4602312015-04-08 16:20:35252
253 def CmdHelp(self):
254 if self.args.subcommand:
255 self.ParseArgs([self.args.subcommand, '--help'])
256 else:
257 self.ParseArgs(['--help'])
258
dpranke751516a2015-10-03 01:11:34259 def CmdIsolate(self):
260 vals = self.GetConfig()
261 if not vals:
262 return 1
263
264 if vals['type'] == 'gn':
265 return self.RunGNIsolate(vals)
266 else:
267 return self.Build('%s_run' % self.args.target[0])
268
269 def CmdLookup(self):
270 vals = self.Lookup()
271 if vals['type'] == 'gn':
dprankeeca4a782016-04-14 01:42:38272 cmd = self.GNCmd('gen', '_path_')
273 gn_args = self.GNArgs(vals)
274 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
dpranke751516a2015-10-03 01:11:34275 env = None
276 else:
277 cmd, env = self.GYPCmd('_path_', vals)
278
279 self.PrintCmd(cmd, env)
280 return 0
281
282 def CmdRun(self):
283 vals = self.GetConfig()
284 if not vals:
285 return 1
286
287 build_dir = self.args.path[0]
288 target = self.args.target[0]
289
290 if vals['type'] == 'gn':
291 if self.args.build:
292 ret = self.Build(target)
293 if ret:
294 return ret
295 ret = self.RunGNIsolate(vals)
296 if ret:
297 return ret
298 else:
299 ret = self.Build('%s_run' % target)
300 if ret:
301 return ret
302
dpranke030d7a6d2016-03-26 17:23:50303 cmd = [
dpranke751516a2015-10-03 01:11:34304 self.executable,
305 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
306 'run',
307 '-s',
dpranke030d7a6d2016-03-26 17:23:50308 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
309 ]
310 if self.args.extra_args:
311 cmd += ['--'] + self.args.extra_args
312
313 ret, _, _ = self.Run(cmd, force_verbose=False, buffer_output=False)
dpranke751516a2015-10-03 01:11:34314
315 return ret
316
dpranke0cafc162016-03-19 00:41:10317 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35318 errs = []
319
320 # Read the file to make sure it parses.
321 self.ReadConfigFile()
322
dpranke3be00142016-03-17 22:46:04323 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35324 all_configs = {}
dprankefe4602312015-04-08 16:20:35325 for master in self.masters:
dpranke3be00142016-03-17 22:46:04326 for config in self.masters[master].values():
327 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35328
dpranke9dd5e252016-04-14 04:23:09329 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35330 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09331 if config.startswith('//'):
332 if not self.Exists(self.ToAbsPath(config)):
333 errs.append('Unknown args file "%s" referenced from "%s".' %
334 (config, loc))
335 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35336 errs.append('Unknown config "%s" referenced from "%s".' %
337 (config, loc))
338
339 # Check that every actual config is actually referenced.
340 for config in self.configs:
341 if not config in all_configs:
342 errs.append('Unused config "%s".' % config)
343
344 # Figure out the whole list of mixins, and check that every mixin
345 # listed by a config or another mixin actually exists.
346 referenced_mixins = set()
347 for config, mixins in self.configs.items():
348 for mixin in mixins:
349 if not mixin in self.mixins:
350 errs.append('Unknown mixin "%s" referenced by config "%s".' %
351 (mixin, config))
352 referenced_mixins.add(mixin)
353
354 for mixin in self.mixins:
355 for sub_mixin in self.mixins[mixin].get('mixins', []):
356 if not sub_mixin in self.mixins:
357 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
358 (sub_mixin, mixin))
359 referenced_mixins.add(sub_mixin)
360
361 # Check that every mixin defined is actually referenced somewhere.
362 for mixin in self.mixins:
363 if not mixin in referenced_mixins:
364 errs.append('Unreferenced mixin "%s".' % mixin)
365
dpranke255085e2016-03-16 05:23:59366 # If we're checking the Chromium config, check that the 'chromium' bots
367 # which build public artifacts do not include the chrome_with_codecs mixin.
368 if self.args.config_file == self.default_config:
369 if 'chromium' in self.masters:
370 for builder in self.masters['chromium']:
371 config = self.masters['chromium'][builder]
372 def RecurseMixins(current_mixin):
373 if current_mixin == 'chrome_with_codecs':
374 errs.append('Public artifact builder "%s" can not contain the '
375 '"chrome_with_codecs" mixin.' % builder)
376 return
377 if not 'mixins' in self.mixins[current_mixin]:
378 return
379 for mixin in self.mixins[current_mixin]['mixins']:
380 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41381
dpranke255085e2016-03-16 05:23:59382 for mixin in self.configs[config]:
383 RecurseMixins(mixin)
384 else:
385 errs.append('Missing "chromium" master. Please update this '
386 'proprietary codecs check with the name of the master '
387 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41388
dprankefe4602312015-04-08 16:20:35389 if errs:
dpranke4323c80632015-08-10 22:53:54390 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17391 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35392
dpranke0cafc162016-03-19 00:41:10393 if print_ok:
394 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35395 return 0
396
dpranke867bcf4a2016-03-14 22:28:32397 def CmdAudit(self):
398 """Track the progress of the GYP->GN migration on the bots."""
399
dpranke0cafc162016-03-19 00:41:10400 # First, make sure the config file is okay, but don't print anything
401 # if it is (it will throw an error if it isn't).
402 self.CmdValidate(print_ok=False)
403
dpranke867bcf4a2016-03-14 22:28:32404 stats = OrderedDict()
405 STAT_MASTER_ONLY = 'Master only'
406 STAT_CONFIG_ONLY = 'Config only'
407 STAT_TBD = 'Still TBD'
408 STAT_GYP = 'Still GYP'
409 STAT_DONE = 'Done (on GN)'
410 stats[STAT_MASTER_ONLY] = 0
411 stats[STAT_CONFIG_ONLY] = 0
412 stats[STAT_TBD] = 0
413 stats[STAT_GYP] = 0
414 stats[STAT_DONE] = 0
415
aneeshmde50f472016-04-01 01:13:10416 def PrintBuilders(heading, builders, notes):
dpranke867bcf4a2016-03-14 22:28:32417 stats.setdefault(heading, 0)
418 stats[heading] += len(builders)
419 if builders:
420 self.Print(' %s:' % heading)
421 for builder in sorted(builders):
aneeshmde50f472016-04-01 01:13:10422 self.Print(' %s%s' % (builder, notes[builder]))
dpranke867bcf4a2016-03-14 22:28:32423
424 self.ReadConfigFile()
425
426 masters = self.args.master or self.masters
427 for master in sorted(masters):
428 url = self.args.url_template.replace('{master}', master)
429
430 self.Print('Auditing %s' % master)
431
432 MASTERS_TO_SKIP = (
433 'client.skia',
434 'client.v8.fyi',
435 'tryserver.v8',
436 )
437 if master in MASTERS_TO_SKIP:
438 # Skip these bots because converting them is the responsibility of
439 # those teams and out of scope for the Chromium migration to GN.
440 self.Print(' Skipped (out of scope)')
441 self.Print('')
442 continue
443
dprankeeafba352016-03-15 19:34:53444 INTERNAL_MASTERS = ('official.desktop', 'official.desktop.continuous')
dpranke867bcf4a2016-03-14 22:28:32445 if master in INTERNAL_MASTERS and not self.args.internal:
446 # Skip these because the servers aren't accessible by default ...
447 self.Print(' Skipped (internal)')
448 self.Print('')
449 continue
450
451 try:
452 # Fetch the /builders contents from the buildbot master. The
453 # keys of the dict are the builder names themselves.
454 json_contents = self.Fetch(url)
455 d = json.loads(json_contents)
456 except Exception as e:
457 self.Print(str(e))
458 return 1
459
460 config_builders = set(self.masters[master])
461 master_builders = set(d.keys())
462 both = master_builders & config_builders
463 master_only = master_builders - config_builders
464 config_only = config_builders - master_builders
465 tbd = set()
466 gyp = set()
467 done = set()
aneeshmde50f472016-04-01 01:13:10468 notes = {builder: '' for builder in config_builders | master_builders}
dpranke867bcf4a2016-03-14 22:28:32469
470 for builder in both:
471 config = self.masters[master][builder]
472 if config == 'tbd':
473 tbd.add(builder)
dprankebbe6d4672016-04-19 06:56:57474 elif config.startswith('//'):
475 done.add(builder)
dpranke867bcf4a2016-03-14 22:28:32476 else:
477 # TODO(dpranke): Check if MB is actually running?
478 vals = self.FlattenConfig(config)
479 if vals['type'] == 'gyp':
480 gyp.add(builder)
481 else:
482 done.add(builder)
483
aneeshmde50f472016-04-01 01:13:10484 if self.args.check_compile and (tbd or master_only):
485 either = tbd | master_only
486 for builder in either:
487 notes[builder] = ' (' + self.CheckCompile(master, builder) +')'
488
dpranke867bcf4a2016-03-14 22:28:32489 if master_only or config_only or tbd or gyp:
aneeshmde50f472016-04-01 01:13:10490 PrintBuilders(STAT_MASTER_ONLY, master_only, notes)
491 PrintBuilders(STAT_CONFIG_ONLY, config_only, notes)
492 PrintBuilders(STAT_TBD, tbd, notes)
493 PrintBuilders(STAT_GYP, gyp, notes)
dpranke867bcf4a2016-03-14 22:28:32494 else:
dprankebbe6d4672016-04-19 06:56:57495 self.Print(' All GN!')
dpranke867bcf4a2016-03-14 22:28:32496
497 stats[STAT_DONE] += len(done)
498
499 self.Print('')
500
501 fmt = '{:<27} {:>4}'
502 self.Print(fmt.format('Totals', str(sum(int(v) for v in stats.values()))))
503 self.Print(fmt.format('-' * 27, '----'))
504 for stat, count in stats.items():
505 self.Print(fmt.format(stat, str(count)))
506
507 return 0
508
dprankefe4602312015-04-08 16:20:35509 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34510 build_dir = self.args.path[0]
511
512 vals = {}
513 if self.args.builder or self.args.master or self.args.config:
514 vals = self.Lookup()
515 if vals['type'] == 'gn':
516 # Re-run gn gen in order to ensure the config is consistent with the
517 # build dir.
518 self.RunGNGen(vals)
519 return vals
520
521 # TODO: We can only get the config for GN build dirs, not GYP build dirs.
522 # GN stores the args that were used in args.gn in the build dir,
523 # but GYP doesn't store them anywhere. We should consider modifying
524 # gyp_chromium to record the arguments it runs with in a similar
525 # manner.
526
527 mb_type_path = self.PathJoin(self.ToAbsPath(build_dir), 'mb_type')
528 if not self.Exists(mb_type_path):
529 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
530 if not self.Exists(gn_args_path):
531 self.Print('Must either specify a path to an existing GN build dir '
532 'or pass in a -m/-b pair or a -c flag to specify the '
533 'configuration')
534 return {}
535 else:
536 mb_type = 'gn'
537 else:
538 mb_type = self.ReadFile(mb_type_path).strip()
539
540 if mb_type == 'gn':
541 vals = self.GNValsFromDir(build_dir)
542 else:
543 vals = {}
544 vals['type'] = mb_type
545
546 return vals
547
548 def GNValsFromDir(self, build_dir):
549 args_contents = self.ReadFile(
550 self.PathJoin(self.ToAbsPath(build_dir), 'args.gn'))
551 gn_args = []
552 for l in args_contents.splitlines():
553 fields = l.split(' ')
554 name = fields[0]
555 val = ' '.join(fields[2:])
556 gn_args.append('%s=%s' % (name, val))
557
558 return {
559 'gn_args': ' '.join(gn_args),
560 'type': 'gn',
561 }
562
563 def Lookup(self):
dprankee0f486f2015-11-19 23:42:00564 vals = self.ReadBotConfig()
565 if not vals:
566 self.ReadConfigFile()
567 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09568 if config.startswith('//'):
569 if not self.Exists(self.ToAbsPath(config)):
570 raise MBErr('args file "%s" not found' % config)
571 vals = {
dpranke9dd5e252016-04-14 04:23:09572 'args_file': config,
dpranke73ed0d62016-04-25 19:18:34573 'cros_passthrough': False,
dpranke9dd5e252016-04-14 04:23:09574 'gn_args': '',
dpranke73ed0d62016-04-25 19:18:34575 'gyp_crosscompile': False,
576 'gyp_defines': '',
577 'type': 'gn',
dpranke9dd5e252016-04-14 04:23:09578 }
579 else:
580 if not config in self.configs:
581 raise MBErr('Config "%s" not found in %s' %
582 (config, self.args.config_file))
583 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34584
585 # Do some basic sanity checking on the config so that we
586 # don't have to do this in every caller.
587 assert 'type' in vals, 'No meta-build type specified in the config'
588 assert vals['type'] in ('gn', 'gyp'), (
589 'Unknown meta-build type "%s"' % vals['gn_args'])
590
591 return vals
dprankefe4602312015-04-08 16:20:35592
dprankee0f486f2015-11-19 23:42:00593 def ReadBotConfig(self):
594 if not self.args.master or not self.args.builder:
595 return {}
596 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
597 self.args.master, self.args.builder + '.json')
598 if not self.Exists(path):
599 return {}
600
601 contents = json.loads(self.ReadFile(path))
602 gyp_vals = contents.get('GYP_DEFINES', {})
603 if isinstance(gyp_vals, dict):
604 gyp_defines = ' '.join('%s=%s' % (k, v) for k, v in gyp_vals.items())
605 else:
606 gyp_defines = ' '.join(gyp_vals)
607 gn_args = ' '.join(contents.get('gn_args', []))
608
609 return {
dpranke73ed0d62016-04-25 19:18:34610 'args_file': '',
611 'cros_passthrough': False,
dprankee0f486f2015-11-19 23:42:00612 'gn_args': gn_args,
dprankef75a3de52015-12-14 22:17:52613 'gyp_crosscompile': False,
dpranke73ed0d62016-04-25 19:18:34614 'gyp_defines': gyp_defines,
615 'type': contents.get('mb_type', ''),
dprankee0f486f2015-11-19 23:42:00616 }
617
dprankefe4602312015-04-08 16:20:35618 def ReadConfigFile(self):
619 if not self.Exists(self.args.config_file):
620 raise MBErr('config file not found at %s' % self.args.config_file)
621
622 try:
623 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
624 except SyntaxError as e:
625 raise MBErr('Failed to parse config file "%s": %s' %
626 (self.args.config_file, e))
627
dprankefe4602312015-04-08 16:20:35628 self.configs = contents['configs']
629 self.masters = contents['masters']
630 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35631
632 def ConfigFromArgs(self):
633 if self.args.config:
634 if self.args.master or self.args.builder:
635 raise MBErr('Can not specific both -c/--config and -m/--master or '
636 '-b/--builder')
637
638 return self.args.config
639
640 if not self.args.master or not self.args.builder:
641 raise MBErr('Must specify either -c/--config or '
642 '(-m/--master and -b/--builder)')
643
644 if not self.args.master in self.masters:
645 raise MBErr('Master name "%s" not found in "%s"' %
646 (self.args.master, self.args.config_file))
647
648 if not self.args.builder in self.masters[self.args.master]:
649 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
650 (self.args.builder, self.args.master, self.args.config_file))
651
652 return self.masters[self.args.master][self.args.builder]
653
654 def FlattenConfig(self, config):
655 mixins = self.configs[config]
dpranke73ed0d62016-04-25 19:18:34656 # TODO(dpranke): We really should provide a constructor for the
657 # default set of values.
dprankefe4602312015-04-08 16:20:35658 vals = {
dpranke73ed0d62016-04-25 19:18:34659 'args_file': '',
660 'cros_passthrough': False,
dprankefe4602312015-04-08 16:20:35661 'gn_args': [],
dprankec161aa92015-09-14 20:21:13662 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59663 'gyp_crosscompile': False,
dpranke73ed0d62016-04-25 19:18:34664 'type': None,
dprankefe4602312015-04-08 16:20:35665 }
666
667 visited = []
668 self.FlattenMixins(mixins, vals, visited)
669 return vals
670
671 def FlattenMixins(self, mixins, vals, visited):
672 for m in mixins:
673 if m not in self.mixins:
674 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22675
676 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35677
678 visited.append(m)
679
680 mixin_vals = self.mixins[m]
dpranke73ed0d62016-04-25 19:18:34681
682 if 'cros_passthrough' in mixin_vals:
683 vals['cros_passthrough'] = mixin_vals['cros_passthrough']
dprankefe4602312015-04-08 16:20:35684 if 'gn_args' in mixin_vals:
685 if vals['gn_args']:
686 vals['gn_args'] += ' ' + mixin_vals['gn_args']
687 else:
688 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59689 if 'gyp_crosscompile' in mixin_vals:
690 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35691 if 'gyp_defines' in mixin_vals:
692 if vals['gyp_defines']:
693 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
694 else:
695 vals['gyp_defines'] = mixin_vals['gyp_defines']
dpranke73ed0d62016-04-25 19:18:34696 if 'type' in mixin_vals:
697 vals['type'] = mixin_vals['type']
698
dprankefe4602312015-04-08 16:20:35699 if 'mixins' in mixin_vals:
700 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
701 return vals
702
dprankec161aa92015-09-14 20:21:13703 def ClobberIfNeeded(self, vals):
704 path = self.args.path[0]
705 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33706 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13707 needs_clobber = False
708 new_mb_type = vals['type']
709 if self.Exists(build_dir):
710 if self.Exists(mb_type_path):
711 old_mb_type = self.ReadFile(mb_type_path)
712 if old_mb_type != new_mb_type:
713 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
714 (old_mb_type, new_mb_type, path))
715 needs_clobber = True
716 else:
717 # There is no 'mb_type' file in the build directory, so this probably
718 # means that the prior build(s) were not done through mb, and we
719 # have no idea if this was a GYP build or a GN build. Clobber it
720 # to be safe.
721 self.Print("%s/mb_type missing, clobbering to be safe" % path)
722 needs_clobber = True
723
dpranke3cec199c2015-09-22 23:29:02724 if self.args.dryrun:
725 return
726
dprankec161aa92015-09-14 20:21:13727 if needs_clobber:
728 self.RemoveDirectory(build_dir)
729
730 self.MaybeMakeDirectory(build_dir)
731 self.WriteFile(mb_type_path, new_mb_type)
732
Dirk Pranke0fd41bcd2015-06-19 00:05:50733 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34734 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50735
dprankeeca4a782016-04-14 01:42:38736 cmd = self.GNCmd('gen', build_dir, '--check')
737 gn_args = self.GNArgs(vals)
738
739 # Since GN hasn't run yet, the build directory may not even exist.
740 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
741
742 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
dpranke4ff8b9f2016-04-15 03:07:54743 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
dpranke74559b52015-06-10 21:20:39744
745 swarming_targets = []
dpranke751516a2015-10-03 01:11:34746 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39747 # We need GN to generate the list of runtime dependencies for
748 # the compile targets listed (one per line) in the file so
749 # we can run them via swarming. We use ninja_to_gn.pyl to convert
750 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00751 path = self.args.swarming_targets_file
752 if not self.Exists(path):
753 self.WriteFailureAndRaise('"%s" does not exist' % path,
754 output_path=None)
755 contents = self.ReadFile(path)
756 swarming_targets = set(contents.splitlines())
dpranke8c2cfd32015-09-17 20:12:33757 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47758 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39759 gn_labels = []
dprankeb2be10a2016-02-22 17:11:00760 err = ''
dpranke74559b52015-06-10 21:20:39761 for target in swarming_targets:
jbudorickdcff99982016-02-03 19:38:07762 target_name = self.GNTargetName(target)
763 if not target_name in gn_isolate_map:
dprankeb2be10a2016-02-22 17:11:00764 err += ('test target "%s" not found\n' % target_name)
765 elif gn_isolate_map[target_name]['type'] == 'unknown':
766 err += ('test target "%s" type is unknown\n' % target_name)
767 else:
768 gn_labels.append(gn_isolate_map[target_name]['label'])
769
770 if err:
771 raise MBErr('Error: Failed to match swarming targets to %s:\n%s' %
772 ('//testing/buildbot/gn_isolate_map.pyl', err))
dpranke74559b52015-06-10 21:20:39773
dpranke751516a2015-10-03 01:11:34774 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dpranke74559b52015-06-10 21:20:39775 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
776 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
777
dprankefe4602312015-04-08 16:20:35778 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40779 if ret:
780 # If `gn gen` failed, we should exit early rather than trying to
781 # generate isolates. Run() will have already logged any error output.
782 self.Print('GN gen failed: %d' % ret)
783 return ret
dpranke74559b52015-06-10 21:20:39784
785 for target in swarming_targets:
jbudorick91c8a6012016-01-29 23:20:02786 if target.endswith('_apk'):
787 # "_apk" targets may be either android_apk or executable. The former
788 # will result in runtime_deps associated with the stamp file, while the
789 # latter will result in runtime_deps associated with the executable.
jbudorickdcff99982016-02-03 19:38:07790 target_name = self.GNTargetName(target)
791 label = gn_isolate_map[target_name]['label']
jbudorick91c8a6012016-01-29 23:20:02792 runtime_deps_targets = [
dpranke48ccf8f2016-03-28 23:58:28793 target_name + '.runtime_deps',
794 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
jbudorick91c8a6012016-01-29 23:20:02795 elif gn_isolate_map[target]['type'] == 'gpu_browser_test':
dpranke48ccf8f2016-03-28 23:58:28796 if self.platform == 'win32':
797 runtime_deps_targets = ['browser_tests.exe.runtime_deps']
798 else:
799 runtime_deps_targets = ['browser_tests.runtime_deps']
dprankefe0d35e2016-02-05 02:43:59800 elif (gn_isolate_map[target]['type'] == 'script' or
801 gn_isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11802 # For script targets, the build target is usually a group,
803 # for which gn generates the runtime_deps next to the stamp file
804 # for the label, which lives under the obj/ directory.
805 label = gn_isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28806 runtime_deps_targets = [
807 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
808 elif self.platform == 'win32':
809 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52810 else:
dpranke48ccf8f2016-03-28 23:58:28811 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02812
dpranke48ccf8f2016-03-28 23:58:28813 for r in runtime_deps_targets:
814 runtime_deps_path = self.ToAbsPath(build_dir, r)
815 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02816 break
817 else:
dpranke48ccf8f2016-03-28 23:58:28818 raise MBErr('did not generate any of %s' %
819 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39820
dprankea55584f12015-07-22 00:52:47821 command, extra_files = self.GetIsolateCommand(target, vals,
822 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30823
dpranke48ccf8f2016-03-28 23:58:28824 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30825
dpranke751516a2015-10-03 01:11:34826 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
827 extra_files)
dpranked5b2b9432015-06-23 16:55:30828
dpranke751516a2015-10-03 01:11:34829 return 0
830
831 def RunGNIsolate(self, vals):
832 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
833 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
834
835 build_dir = self.args.path[0]
836 target = self.args.target[0]
jbudorickdcff99982016-02-03 19:38:07837 target_name = self.GNTargetName(target)
dpranke751516a2015-10-03 01:11:34838 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
839
jbudorickdcff99982016-02-03 19:38:07840 label = gn_isolate_map[target_name]['label']
dprankeeca4a782016-04-14 01:42:38841 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20842 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34843 if ret:
dpranke030d7a6d2016-03-26 17:23:50844 if out:
845 self.Print(out)
dpranke751516a2015-10-03 01:11:34846 return ret
847
848 runtime_deps = out.splitlines()
849
850 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
851 extra_files)
852
853 ret, _, _ = self.Run([
854 self.executable,
855 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
856 'check',
857 '-i',
858 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
859 '-s',
860 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
861 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30862
dprankefe4602312015-04-08 16:20:35863 return ret
864
dpranke751516a2015-10-03 01:11:34865 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
866 extra_files):
867 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
868 self.WriteFile(isolate_path,
869 pprint.pformat({
870 'variables': {
871 'command': command,
872 'files': sorted(runtime_deps + extra_files),
873 }
874 }) + '\n')
875
876 self.WriteJSON(
877 {
878 'args': [
879 '--isolated',
880 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
881 '--isolate',
882 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
883 ],
884 'dir': self.chromium_src_dir,
885 'version': 1,
886 },
887 isolate_path + 'd.gen.json',
888 )
889
dprankeeca4a782016-04-14 01:42:38890 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51891 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20892 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51893 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20894 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51895 else:
dpranke40da0202016-02-13 05:05:20896 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38897
dpranke40da0202016-02-13 05:05:20898 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranked1fba482015-04-14 20:54:51899
dprankeeca4a782016-04-14 01:42:38900 return [gn_path, subcommand, path] + list(args)
901
902 def GNArgs(self, vals):
dpranke73ed0d62016-04-25 19:18:34903 if vals['cros_passthrough']:
904 if not 'GN_ARGS' in os.environ:
905 raise MBErr('MB is expecting GN_ARGS to be in the environment')
906 gn_args = os.environ['GN_ARGS']
dpranke40260182016-04-27 04:45:16907 if not re.search('target_os.*=.*"chromeos"', gn_args):
dpranke39f3be02016-04-27 04:07:30908 raise MBErr('GN_ARGS is missing target_os = "chromeos": (GN_ARGS=%s)' %
dpranke73ed0d62016-04-25 19:18:34909 gn_args)
910 else:
911 gn_args = vals['gn_args']
912
dpranked0c138b2016-04-13 18:28:47913 if self.args.goma_dir:
914 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38915
agrieve41d21a72016-04-14 18:02:26916 android_version_code = self.args.android_version_code
917 if android_version_code:
918 gn_args += ' android_default_version_code="%s"' % android_version_code
919
920 android_version_name = self.args.android_version_name
921 if android_version_name:
922 gn_args += ' android_default_version_name="%s"' % android_version_name
923
dprankeeca4a782016-04-14 01:42:38924 # Canonicalize the arg string into a sorted, newline-separated list
925 # of key-value pairs, and de-dup the keys if need be so that only
926 # the last instance of each arg is listed.
927 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
928
dpranke9dd5e252016-04-14 04:23:09929 args_file = vals.get('args_file', None)
930 if args_file:
931 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:38932 return gn_args
dprankefe4602312015-04-08 16:20:35933
Dirk Pranke0fd41bcd2015-06-19 00:05:50934 def RunGYPGen(self, vals):
935 path = self.args.path[0]
936
dpranke8c2cfd32015-09-17 20:12:33937 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41938 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59939 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35940 return ret
941
942 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33943 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32944 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:16945 inp = self.ReadInputJSON(['files', 'test_targets',
946 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32947 self.Print()
948 self.Print('analyze input:')
949 self.PrintJSON(inp)
950 self.Print()
951
dpranke38f4acb62015-09-29 23:50:41952 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33953 cmd.extend(['-f', 'analyzer',
954 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35955 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02956 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32957 if not ret and self.args.verbose:
958 outp = json.loads(self.ReadFile(self.args.output_path[0]))
959 self.Print()
960 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39961 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32962 self.Print()
963
dprankefe4602312015-04-08 16:20:35964 return ret
965
dprankea55584f12015-07-22 00:52:47966 def GetIsolateCommand(self, target, vals, gn_isolate_map):
jbudoricke8428732016-02-02 02:17:06967 android = 'target_os="android"' in vals['gn_args']
968
dpranked8113582015-06-05 20:08:25969 # This needs to mirror the settings in //build/config/ui.gni:
970 # use_x11 = is_linux && !use_ozone.
971 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33972 use_x11 = (self.platform == 'linux2' and
jbudoricke8428732016-02-02 02:17:06973 not android and
dpranked8113582015-06-05 20:08:25974 not 'use_ozone=true' in vals['gn_args'])
975
976 asan = 'is_asan=true' in vals['gn_args']
977 msan = 'is_msan=true' in vals['gn_args']
978 tsan = 'is_tsan=true' in vals['gn_args']
979
jbudorickdcff99982016-02-03 19:38:07980 target_name = self.GNTargetName(target)
981 test_type = gn_isolate_map[target_name]['type']
dprankefe0d35e2016-02-05 02:43:59982
983 executable = gn_isolate_map[target_name].get('executable', target_name)
984 executable_suffix = '.exe' if self.platform == 'win32' else ''
985
dprankea55584f12015-07-22 00:52:47986 cmdline = []
987 extra_files = []
dpranked8113582015-06-05 20:08:25988
jbudoricke8428732016-02-02 02:17:06989 if android:
990 # TODO(jbudorick): This won't work with instrumentation test targets.
991 # Revisit this logic when those are added to gn_isolate_map.pyl.
jbudorickdcff99982016-02-03 19:38:07992 cmdline = [self.PathJoin('bin', 'run_%s' % target_name)]
jbudoricke8428732016-02-02 02:17:06993 elif use_x11 and test_type == 'windowed_test_launcher':
dprankea55584f12015-07-22 00:52:47994 extra_files = [
995 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25996 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47997 '../../testing/xvfb.py',
998 ]
999 cmdline = [
dprankefe0d35e2016-02-05 02:43:591000 '../../testing/xvfb.py',
1001 '.',
1002 './' + str(executable) + executable_suffix,
1003 '--brave-new-test-launcher',
1004 '--test-launcher-bot-mode',
1005 '--asan=%d' % asan,
1006 '--msan=%d' % msan,
1007 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:471008 ]
1009 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
1010 extra_files = [
1011 '../../testing/test_env.py'
1012 ]
1013 cmdline = [
1014 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:591015 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:251016 '--brave-new-test-launcher',
1017 '--test-launcher-bot-mode',
1018 '--asan=%d' % asan,
1019 '--msan=%d' % msan,
1020 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:471021 ]
dprankedbdd9d82015-08-12 21:18:181022 elif test_type == 'gpu_browser_test':
1023 extra_files = [
1024 '../../testing/test_env.py'
1025 ]
1026 gtest_filter = gn_isolate_map[target]['gtest_filter']
1027 cmdline = [
1028 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:111029 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:181030 '--test-launcher-bot-mode',
1031 '--enable-gpu',
1032 '--test-launcher-jobs=1',
1033 '--gtest_filter=%s' % gtest_filter,
1034 ]
dpranke6abd8652015-08-28 03:21:111035 elif test_type == 'script':
1036 extra_files = [
1037 '../../testing/test_env.py'
1038 ]
1039 cmdline = [
1040 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:391041 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:591042 ]
dprankea55584f12015-07-22 00:52:471043 elif test_type in ('raw'):
1044 extra_files = []
1045 cmdline = [
1046 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:591047 ]
dpranked8113582015-06-05 20:08:251048
dprankea55584f12015-07-22 00:52:471049 else:
1050 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
1051 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:251052
jbudorick8a0560422016-02-05 06:07:171053 cmdline += gn_isolate_map[target_name].get('args', [])
dprankefe0d35e2016-02-05 02:43:591054
dpranked8113582015-06-05 20:08:251055 return cmdline, extra_files
1056
dpranke74559b52015-06-10 21:20:391057 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:331058 return self.PathJoin(self.chromium_src_dir,
1059 self.ToSrcRelPath(build_path),
1060 *comps)
dpranked8113582015-06-05 20:08:251061
dprankeee5b51f62015-04-09 00:03:221062 def ToSrcRelPath(self, path):
1063 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:501064 if path.startswith('//'):
1065 return path[2:].replace('/', self.sep)
1066 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:351067
1068 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:221069 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:331070 output_dir, _, _ = rpath.rpartition(self.sep)
1071 return output_dir
dprankefe4602312015-04-08 16:20:351072
dpranke38f4acb62015-09-29 23:50:411073 def GYPCmd(self, output_dir, vals):
dpranke73ed0d62016-04-25 19:18:341074 if vals['cros_passthrough']:
1075 if not 'GYP_DEFINES' in os.environ:
1076 raise MBErr('MB is expecting GYP_DEFINES to be in the environment')
1077 gyp_defines = os.environ['GYP_DEFINES']
1078 if not 'chromeos=1' in gyp_defines:
1079 raise MBErr('GYP_DEFINES is missing chromeos=1: (GYP_DEFINES=%s)' %
1080 gyp_defines)
1081 else:
1082 gyp_defines = vals['gyp_defines']
1083
dpranke3cec199c2015-09-22 23:29:021084 goma_dir = self.args.goma_dir
1085
1086 # GYP uses shlex.split() to split the gyp defines into separate arguments,
1087 # so we can support backslashes and and spaces in arguments by quoting
1088 # them, even on Windows, where this normally wouldn't work.
dpranked0c138b2016-04-13 18:28:471089 if goma_dir and ('\\' in goma_dir or ' ' in goma_dir):
dpranke3cec199c2015-09-22 23:29:021090 goma_dir = "'%s'" % goma_dir
dpranked0c138b2016-04-13 18:28:471091
1092 if goma_dir:
1093 gyp_defines += ' gomadir=%s' % goma_dir
dpranke3cec199c2015-09-22 23:29:021094
agrieve41d21a72016-04-14 18:02:261095 android_version_code = self.args.android_version_code
1096 if android_version_code:
1097 gyp_defines += ' app_manifest_version_code=%s' % android_version_code
1098
1099 android_version_name = self.args.android_version_name
1100 if android_version_name:
1101 gyp_defines += ' app_manifest_version_name=%s' % android_version_name
1102
dprankefe4602312015-04-08 16:20:351103 cmd = [
dpranke8c2cfd32015-09-17 20:12:331104 self.executable,
1105 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:351106 '-G',
1107 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:351108 ]
dpranke38f4acb62015-09-29 23:50:411109
1110 # Ensure that we have an environment that only contains
1111 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:021112 env = os.environ.copy()
dpranke909bad62016-04-24 23:14:521113
1114 # This is a terrible hack to work around the fact that
1115 # //tools/clang/scripts/update.py is invoked by GYP and GN but
1116 # currently relies on an environment variable to figure out
1117 # what revision to embed in the command line #defines.
1118 # For GN, we've made this work via a gn arg that will cause update.py
1119 # to get an additional command line arg, but getting that to work
1120 # via GYP_DEFINES has proven difficult, so we rewrite the GYP_DEFINES
1121 # to get rid of the arg and add the old var in, instead.
1122 # See crbug.com/582737 for more on this. This can hopefully all
1123 # go away with GYP.
1124 if 'llvm_force_head_revision=1' in gyp_defines:
dprankebf0d5b562016-04-25 22:22:511125 env['LLVM_FORCE_HEAD_REVISION'] = '1'
dpranke909bad62016-04-24 23:14:521126 gyp_defines = gyp_defines.replace('llvm_force_head_revision=1', '')
1127
dprankef75a3de52015-12-14 22:17:521128 env['GYP_GENERATORS'] = 'ninja'
dpranke38f4acb62015-09-29 23:50:411129 if 'GYP_CHROMIUM_NO_ACTION' in env:
1130 del env['GYP_CHROMIUM_NO_ACTION']
1131 if 'GYP_CROSSCOMPILE' in env:
1132 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:021133 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:411134 if vals['gyp_crosscompile']:
1135 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:021136 return cmd, env
dprankefe4602312015-04-08 16:20:351137
Dirk Pranke0fd41bcd2015-06-19 00:05:501138 def RunGNAnalyze(self, vals):
1139 # analyze runs before 'gn gen' now, so we need to run gn gen
1140 # in order to ensure that we have a build directory.
1141 ret = self.RunGNGen(vals)
1142 if ret:
1143 return ret
1144
dpranke7837fc362015-11-19 03:54:161145 inp = self.ReadInputJSON(['files', 'test_targets',
1146 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321147 if self.args.verbose:
1148 self.Print()
1149 self.Print('analyze input:')
1150 self.PrintJSON(inp)
1151 self.Print()
1152
dpranke7837fc362015-11-19 03:54:161153 # TODO(crbug.com/555273) - currently GN treats targets and
1154 # additional_compile_targets identically since we can't tell the
1155 # difference between a target that is a group in GN and one that isn't.
1156 # We should eventually fix this and treat the two types differently.
1157 targets = (set(inp['test_targets']) |
1158 set(inp['additional_compile_targets']))
dpranke5ab84a502015-11-13 17:35:021159
dprankecda00332015-04-11 04:18:321160 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351161
1162 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:021163 # what to do about it. Also, bail out early if 'all' was asked for,
1164 # since we can't deal with it yet.
1165 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
1166 'all' in targets):
dpranke7837fc362015-11-19 03:54:161167 self.WriteJSON({
1168 'status': 'Found dependency (all)',
1169 'compile_targets': sorted(targets),
1170 'test_targets': sorted(targets & set(inp['test_targets'])),
1171 }, output_path)
dpranke76734662015-04-16 02:17:501172 return 0
1173
dpranke7c5f614d2015-07-22 23:43:391174 # This shouldn't normally happen, but could due to unusual race conditions,
1175 # like a try job that gets scheduled before a patch lands but runs after
1176 # the patch has landed.
1177 if not inp['files']:
1178 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161179 self.WriteJSON({
1180 'status': 'No dependency',
1181 'compile_targets': [],
1182 'test_targets': [],
1183 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391184 return 0
1185
Dirk Pranke12ee2db2015-04-14 23:15:321186 ret = 0
dprankef61de2f2015-05-14 04:09:561187 response_file = self.TempFile()
1188 response_file.write('\n'.join(inp['files']) + '\n')
1189 response_file.close()
1190
dpranke5ab84a502015-11-13 17:35:021191 matching_targets = set()
dprankef61de2f2015-05-14 04:09:561192 try:
dprankeeca4a782016-04-14 01:42:381193 cmd = self.GNCmd('refs',
1194 self.args.path[0],
1195 '@%s' % response_file.name,
1196 '--all',
1197 '--as=output')
dprankee0547cd2015-09-15 01:27:401198 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:121199 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:321200 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
1201 output_path)
dpranke8c2cfd32015-09-17 20:12:331202 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:561203 for output in out.splitlines():
1204 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:021205 if build_output in targets:
1206 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:451207
dprankeeca4a782016-04-14 01:42:381208 cmd = self.GNCmd('refs',
1209 self.args.path[0],
1210 '@%s' % response_file.name,
1211 '--all')
dprankee0547cd2015-09-15 01:27:401212 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:451213 if ret and not 'The input matches no targets' in out:
1214 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
1215 output_path)
1216 for label in out.splitlines():
1217 build_target = label[2:]
newt309af8f2015-08-25 22:10:201218 # We want to accept 'chrome/android:chrome_public_apk' and
1219 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:451220 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:021221 for input_target in targets:
dpranke067d0142015-05-14 22:52:451222 if (input_target == build_target or
1223 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:021224 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:561225 finally:
1226 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:351227
dprankef61de2f2015-05-14 04:09:561228 if matching_targets:
dpranke7837fc362015-11-19 03:54:161229 self.WriteJSON({
dpranke5ab84a502015-11-13 17:35:021230 'status': 'Found dependency',
dpranke7837fc362015-11-19 03:54:161231 'compile_targets': sorted(matching_targets),
1232 'test_targets': sorted(matching_targets &
1233 set(inp['test_targets'])),
1234 }, output_path)
dprankefe4602312015-04-08 16:20:351235 else:
dpranke7837fc362015-11-19 03:54:161236 self.WriteJSON({
1237 'status': 'No dependency',
1238 'compile_targets': [],
1239 'test_targets': [],
1240 }, output_path)
dprankecda00332015-04-11 04:18:321241
dprankee0547cd2015-09-15 01:27:401242 if self.args.verbose:
dprankecda00332015-04-11 04:18:321243 outp = json.loads(self.ReadFile(output_path))
1244 self.Print()
1245 self.Print('analyze output:')
1246 self.PrintJSON(outp)
1247 self.Print()
dprankefe4602312015-04-08 16:20:351248
1249 return 0
1250
dpranked8113582015-06-05 20:08:251251 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351252 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321253 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351254 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321255 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351256
1257 try:
1258 inp = json.loads(self.ReadFile(path))
1259 except Exception as e:
1260 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321261 (path, e), output_path)
dpranked8113582015-06-05 20:08:251262
1263 for k in required_keys:
1264 if not k in inp:
1265 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1266 output_path)
dprankefe4602312015-04-08 16:20:351267
1268 return inp
1269
dpranked5b2b9432015-06-23 16:55:301270 def WriteFailureAndRaise(self, msg, output_path):
1271 if output_path:
dprankee0547cd2015-09-15 01:27:401272 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351273 raise MBErr(msg)
1274
dprankee0547cd2015-09-15 01:27:401275 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321276 try:
dprankee0547cd2015-09-15 01:27:401277 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1278 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321279 except Exception as e:
1280 raise MBErr('Error %s writing to the output path "%s"' %
1281 (e, path))
dprankefe4602312015-04-08 16:20:351282
aneeshmde50f472016-04-01 01:13:101283 def CheckCompile(self, master, builder):
1284 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1285 url = urllib2.quote(url_template.format(master=master, builder=builder),
1286 safe=':/()?=')
1287 try:
1288 builds = json.loads(self.Fetch(url))
1289 except Exception as e:
1290 return str(e)
1291 successes = sorted(
1292 [int(x) for x in builds.keys() if "text" in builds[x] and
1293 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1294 reverse=True)
1295 if not successes:
1296 return "no successful builds"
1297 build = builds[str(successes[0])]
1298 step_names = set([step["name"] for step in build["steps"]])
1299 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1300 if compile_indicators & step_names:
1301 return "compiles"
1302 return "does not compile"
1303
dpranke3cec199c2015-09-22 23:29:021304 def PrintCmd(self, cmd, env):
1305 if self.platform == 'win32':
1306 env_prefix = 'set '
1307 env_quoter = QuoteForSet
1308 shell_quoter = QuoteForCmd
1309 else:
1310 env_prefix = ''
1311 env_quoter = pipes.quote
1312 shell_quoter = pipes.quote
1313
1314 def print_env(var):
1315 if env and var in env:
1316 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1317
1318 print_env('GYP_CROSSCOMPILE')
1319 print_env('GYP_DEFINES')
1320
dpranke8c2cfd32015-09-17 20:12:331321 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351322 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021323 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351324
dprankecda00332015-04-11 04:18:321325 def PrintJSON(self, obj):
1326 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1327
dpranke030d7a6d2016-03-26 17:23:501328 def GNTargetName(self, target):
1329 return target[:-len('_apk')] if target.endswith('_apk') else target
dprankefe4602312015-04-08 16:20:351330
dpranke751516a2015-10-03 01:11:341331 def Build(self, target):
1332 build_dir = self.ToSrcRelPath(self.args.path[0])
1333 ninja_cmd = ['ninja', '-C', build_dir]
1334 if self.args.jobs:
1335 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1336 ninja_cmd.append(target)
1337 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1338 return ret
1339
1340 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351341 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401342 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021343 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351344 if self.args.dryrun:
1345 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401346
dpranke751516a2015-10-03 01:11:341347 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401348 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341349 if ret:
1350 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351351 if out:
dprankeee5b51f62015-04-09 00:03:221352 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351353 if err:
dprankeee5b51f62015-04-09 00:03:221354 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351355 return ret, out, err
1356
dpranke751516a2015-10-03 01:11:341357 def Call(self, cmd, env=None, buffer_output=True):
1358 if buffer_output:
1359 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1360 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1361 env=env)
1362 out, err = p.communicate()
1363 else:
1364 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1365 env=env)
1366 p.wait()
1367 out = err = ''
dprankefe4602312015-04-08 16:20:351368 return p.returncode, out, err
1369
1370 def ExpandUser(self, path):
1371 # This function largely exists so it can be overridden for testing.
1372 return os.path.expanduser(path)
1373
1374 def Exists(self, path):
1375 # This function largely exists so it can be overridden for testing.
1376 return os.path.exists(path)
1377
dpranke867bcf4a2016-03-14 22:28:321378 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501379 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321380 f = urllib2.urlopen(url)
1381 contents = f.read()
1382 f.close()
1383 return contents
1384
dprankec3441d12015-06-23 23:01:351385 def MaybeMakeDirectory(self, path):
1386 try:
1387 os.makedirs(path)
1388 except OSError, e:
1389 if e.errno != errno.EEXIST:
1390 raise
1391
dpranke8c2cfd32015-09-17 20:12:331392 def PathJoin(self, *comps):
1393 # This function largely exists so it can be overriden for testing.
1394 return os.path.join(*comps)
1395
dpranke030d7a6d2016-03-26 17:23:501396 def Print(self, *args, **kwargs):
1397 # This function largely exists so it can be overridden for testing.
1398 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101399 if kwargs.get('stream', sys.stdout) == sys.stdout:
1400 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501401
dprankefe4602312015-04-08 16:20:351402 def ReadFile(self, path):
1403 # This function largely exists so it can be overriden for testing.
1404 with open(path) as fp:
1405 return fp.read()
1406
dpranke030d7a6d2016-03-26 17:23:501407 def RelPath(self, path, start='.'):
1408 # This function largely exists so it can be overriden for testing.
1409 return os.path.relpath(path, start)
1410
dprankef61de2f2015-05-14 04:09:561411 def RemoveFile(self, path):
1412 # This function largely exists so it can be overriden for testing.
1413 os.remove(path)
1414
dprankec161aa92015-09-14 20:21:131415 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331416 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131417 # In other places in chromium, we often have to retry this command
1418 # because we're worried about other processes still holding on to
1419 # file handles, but when MB is invoked, it will be early enough in the
1420 # build that their should be no other processes to interfere. We
1421 # can change this if need be.
1422 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1423 else:
1424 shutil.rmtree(abs_path, ignore_errors=True)
1425
dprankef61de2f2015-05-14 04:09:561426 def TempFile(self, mode='w'):
1427 # This function largely exists so it can be overriden for testing.
1428 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1429
dprankee0547cd2015-09-15 01:27:401430 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351431 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401432 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301433 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351434 with open(path, 'w') as fp:
1435 return fp.write(contents)
1436
dprankef61de2f2015-05-14 04:09:561437
dprankefe4602312015-04-08 16:20:351438class MBErr(Exception):
1439 pass
1440
1441
dpranke3cec199c2015-09-22 23:29:021442# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1443# details of this next section, which handles escaping command lines
1444# so that they can be copied and pasted into a cmd window.
1445UNSAFE_FOR_SET = set('^<>&|')
1446UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1447ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1448
1449
1450def QuoteForSet(arg):
1451 if any(a in UNSAFE_FOR_SET for a in arg):
1452 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1453 return arg
1454
1455
1456def QuoteForCmd(arg):
1457 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1458 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1459 if arg == '' or ' ' in arg or '"' in arg:
1460 quote_re = re.compile(r'(\\*)"')
1461 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1462
1463 # Then check to see if the arg contains any metacharacters other than
1464 # double quotes; if it does, quote everything (including the double
1465 # quotes) for safety.
1466 if any(a in UNSAFE_FOR_CMD for a in arg):
1467 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1468 return arg
1469
1470
dprankefe4602312015-04-08 16:20:351471if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591472 sys.exit(main(sys.argv[1:]))