blob: 01f4914f3c2b6987e3e1589d498c1fc23cdbf91e [file] [log] [blame]
Christoffer Jansson4e8a7732022-02-08 09:01:12 +01001#!/usr/bin/env vpython3
2
kjellandera013a022016-11-14 05:54:22 -08003# Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
4#
5# Use of this source code is governed by a BSD-style license
6# that can be found in the LICENSE file in the root of the source
7# tree. An additional intellectual property rights grant can be found
8# in the file PATENTS. All contributing project authors may
9# be found in the AUTHORS file in the root of the source tree.
10
Oleh Prypinb708e932018-03-18 17:34:20 +010011"""MB - the Meta-Build wrapper around GN.
kjellandera013a022016-11-14 05:54:22 -080012
Oleh Prypinb708e932018-03-18 17:34:20 +010013MB is a wrapper script for GN that can be used to generate build files
kjellandera013a022016-11-14 05:54:22 -080014for sets of canned configurations and analyze them.
15"""
16
Jeremy Lecontead3f4902022-03-28 07:21:46 +000017import argparse
18import ast
19import errno
20import json
kjellandera013a022016-11-14 05:54:22 -080021import os
Jeremy Lecontead3f4902022-03-28 07:21:46 +000022import pipes
23import pprint
24import re
25import shutil
kjellandera013a022016-11-14 05:54:22 -080026import sys
Jeremy Lecontead3f4902022-03-28 07:21:46 +000027import subprocess
28import tempfile
29import traceback
30from urllib.request import urlopen
kjellandera013a022016-11-14 05:54:22 -080031
Jeremy Lecontead3f4902022-03-28 07:21:46 +000032SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
33SRC_DIR = os.path.dirname(os.path.dirname(SCRIPT_DIR))
34sys.path = [os.path.join(SRC_DIR, 'build')] + sys.path
kjellandera013a022016-11-14 05:54:22 -080035
Jeremy Lecontead3f4902022-03-28 07:21:46 +000036import gn_helpers
kjellandera013a022016-11-14 05:54:22 -080037
38
Jeremy Leconte145ff4c2022-03-28 11:32:20 +020039def _get_executable(target, platform):
40 executable_prefix = '.\\' if platform == 'win32' else './'
41 executable_suffix = '.exe' if platform == 'win32' else ''
42 return executable_prefix + target + executable_suffix
43
44
kjellandera013a022016-11-14 05:54:22 -080045def main(args):
Jeremy Lecontead3f4902022-03-28 07:21:46 +000046 mbw = MetaBuildWrapper()
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010047 return mbw.Main(args)
kjellandera013a022016-11-14 05:54:22 -080048
49
Jeremy Lecontead3f4902022-03-28 07:21:46 +000050class MetaBuildWrapper:
Jeremy Lecontef22c78b2021-12-07 19:49:48 +010051 def __init__(self):
Jeremy Lecontead3f4902022-03-28 07:21:46 +000052 self.src_dir = SRC_DIR
53 self.default_config = os.path.join(SCRIPT_DIR, 'mb_config.pyl')
54 self.default_isolate_map = os.path.join(SCRIPT_DIR, 'gn_isolate_map.pyl')
55 self.executable = sys.executable
56 self.platform = sys.platform
57 self.sep = os.sep
58 self.args = argparse.Namespace()
59 self.configs = {}
60 self.builder_groups = {}
61 self.mixins = {}
62 self.isolate_exe = 'isolate.exe' if self.platform.startswith(
63 'win') else 'isolate'
64
65 def Main(self, args):
66 self.ParseArgs(args)
67 try:
68 ret = self.args.func()
69 if ret:
70 self.DumpInputFiles()
71 return ret
72 except KeyboardInterrupt:
73 self.Print('interrupted, exiting')
74 return 130
75 except Exception:
76 self.DumpInputFiles()
77 s = traceback.format_exc()
78 for l in s.splitlines():
79 self.Print(l)
80 return 1
81
82 def ParseArgs(self, argv):
83 def AddCommonOptions(subp):
84 subp.add_argument('-b',
85 '--builder',
86 help='builder name to look up config from')
87 subp.add_argument('-m',
88 '--builder-group',
89 help='builder group name to look up config from')
90 subp.add_argument('-c', '--config', help='configuration to analyze')
91 subp.add_argument('--phase',
92 help='optional phase name (used when builders '
93 'do multiple compiles with different '
94 'arguments in a single build)')
95 subp.add_argument('-f',
96 '--config-file',
97 metavar='PATH',
98 default=self.default_config,
99 help='path to config file '
100 '(default is %(default)s)')
101 subp.add_argument('-i',
102 '--isolate-map-file',
103 metavar='PATH',
104 default=self.default_isolate_map,
105 help='path to isolate map file '
106 '(default is %(default)s)')
107 subp.add_argument('-r',
108 '--realm',
109 default='webrtc:try',
110 help='optional LUCI realm to use (for example '
111 'when triggering tasks on Swarming)')
112 subp.add_argument('-g', '--goma-dir', help='path to goma directory')
113 subp.add_argument('--android-version-code',
114 help='Sets GN arg android_default_version_code')
115 subp.add_argument('--android-version-name',
116 help='Sets GN arg android_default_version_name')
117 subp.add_argument('-n',
118 '--dryrun',
119 action='store_true',
120 help='Do a dry run (i.e., do nothing, just '
121 'print the commands that will run)')
122 subp.add_argument('-v',
123 '--verbose',
124 action='store_true',
125 help='verbose logging')
126
127 parser = argparse.ArgumentParser(prog='mb')
128 subps = parser.add_subparsers()
129
130 subp = subps.add_parser('analyze',
131 help='analyze whether changes to a set of '
132 'files will cause a set of binaries '
133 'to be rebuilt.')
134 AddCommonOptions(subp)
135 subp.add_argument('path', nargs=1, help='path build was generated into.')
136 subp.add_argument('input_path',
137 nargs=1,
138 help='path to a file containing the input '
139 'arguments as a JSON object.')
140 subp.add_argument('output_path',
141 nargs=1,
142 help='path to a file containing the output '
143 'arguments as a JSON object.')
144 subp.add_argument('--json-output', help='Write errors to json.output')
145 subp.set_defaults(func=self.CmdAnalyze)
146
147 subp = subps.add_parser('export',
148 help='print out the expanded configuration for'
149 'each builder as a JSON object')
150 subp.add_argument('-f',
151 '--config-file',
152 metavar='PATH',
153 default=self.default_config,
154 help='path to config file (default is %(default)s)')
155 subp.add_argument('-g', '--goma-dir', help='path to goma directory')
156 subp.set_defaults(func=self.CmdExport)
157
158 subp = subps.add_parser('gen', help='generate a new set of build files')
159 AddCommonOptions(subp)
160 subp.add_argument('--swarming-targets-file',
161 help='save runtime dependencies for targets listed '
162 'in file.')
163 subp.add_argument('--json-output', help='Write errors to json.output')
164 subp.add_argument('path', nargs=1, help='path to generate build into')
165 subp.set_defaults(func=self.CmdGen)
166
167 subp = subps.add_parser('isolate',
168 help='generate the .isolate files for a given'
169 'binary')
170 AddCommonOptions(subp)
171 subp.add_argument('path', nargs=1, help='path build was generated into')
172 subp.add_argument('target',
173 nargs=1,
174 help='ninja target to generate the isolate for')
175 subp.set_defaults(func=self.CmdIsolate)
176
177 subp = subps.add_parser('lookup',
178 help='look up the command for a given config '
179 'or builder')
180 AddCommonOptions(subp)
181 subp.add_argument('--quiet',
182 default=False,
183 action='store_true',
184 help='Print out just the arguments, do '
185 'not emulate the output of the gen subcommand.')
186 subp.set_defaults(func=self.CmdLookup)
187
188 subp = subps.add_parser(
189 'run',
190 help='build and run the isolated version of a '
191 'binary',
192 formatter_class=argparse.RawDescriptionHelpFormatter)
193 subp.description = (
194 'Build, isolate, and run the given binary with the command line\n'
195 'listed in the isolate. You may pass extra arguments after the\n'
196 'target; use "--" if the extra arguments need to include switches.'
197 '\n\n'
198 'Examples:\n'
199 '\n'
200 ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n'
201 ' //out/Default content_browsertests\n'
202 '\n'
203 ' % tools/mb/mb.py run out/Default content_browsertests\n'
204 '\n'
205 ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n'
206 ' --test-launcher-retry-limit=0'
207 '\n')
208 AddCommonOptions(subp)
209 subp.add_argument('-j',
210 '--jobs',
211 dest='jobs',
212 type=int,
213 help='Number of jobs to pass to ninja')
214 subp.add_argument('--no-build',
215 dest='build',
216 default=True,
217 action='store_false',
218 help='Do not build, just isolate and run')
219 subp.add_argument('path',
220 nargs=1,
221 help=('path to generate build into (or use).'
222 ' This can be either a regular path or a '
223 'GN-style source-relative path like '
224 '//out/Default.'))
225 subp.add_argument('-s',
226 '--swarmed',
227 action='store_true',
228 help='Run under swarming')
229 subp.add_argument('-d',
230 '--dimension',
231 default=[],
232 action='append',
233 nargs=2,
234 dest='dimensions',
235 metavar='FOO bar',
236 help='dimension to filter on')
237 subp.add_argument('target', nargs=1, help='ninja target to build and run')
238 subp.add_argument('extra_args',
239 nargs='*',
240 help=('extra args to pass to the isolate to run. '
241 'Use "--" as the first arg if you need to '
242 'pass switches'))
243 subp.set_defaults(func=self.CmdRun)
244
245 subp = subps.add_parser('validate', help='validate the config file')
246 subp.add_argument('-f',
247 '--config-file',
248 metavar='PATH',
249 default=self.default_config,
250 help='path to config file (default is %(default)s)')
251 subp.set_defaults(func=self.CmdValidate)
252
253 subp = subps.add_parser('help', help='Get help on a subcommand.')
254 subp.add_argument(nargs='?',
255 action='store',
256 dest='subcommand',
257 help='The command to get help for.')
258 subp.set_defaults(func=self.CmdHelp)
259
260 self.args = parser.parse_args(argv)
261
262 def DumpInputFiles(self):
263 def DumpContentsOfFilePassedTo(arg_name, path):
264 if path and self.Exists(path):
265 self.Print("\n# To recreate the file passed to %s:" % arg_name)
266 self.Print("%% cat > %s <<EOF" % path)
267 contents = self.ReadFile(path)
268 self.Print(contents)
269 self.Print("EOF\n%\n")
270
271 if getattr(self.args, 'input_path', None):
272 DumpContentsOfFilePassedTo('argv[0] (input_path)',
273 self.args.input_path[0])
274 if getattr(self.args, 'swarming_targets_file', None):
275 DumpContentsOfFilePassedTo('--swarming-targets-file',
276 self.args.swarming_targets_file)
277
278 def CmdAnalyze(self):
279 vals = self.Lookup()
280 return self.RunGNAnalyze(vals)
281
282 def CmdExport(self):
283 self.ReadConfigFile()
284 obj = {}
285 for builder_group, builders in list(self.builder_groups.items()):
286 obj[builder_group] = {}
287 for builder in builders:
288 config = self.builder_groups[builder_group][builder]
289 if not config:
290 continue
291
292 if isinstance(config, dict):
293 args = {
294 k: self.FlattenConfig(v)['gn_args']
295 for k, v in list(config.items())
296 }
297 elif config.startswith('//'):
298 args = config
299 else:
300 args = self.FlattenConfig(config)['gn_args']
301 if 'error' in args:
302 continue
303
304 obj[builder_group][builder] = args
305
306 # Dump object and trim trailing whitespace.
307 s = '\n'.join(
308 l.rstrip()
309 for l in json.dumps(obj, sort_keys=True, indent=2).splitlines())
310 self.Print(s)
311 return 0
312
313 def CmdGen(self):
314 vals = self.Lookup()
315 return self.RunGNGen(vals)
316
317 def CmdHelp(self):
318 if self.args.subcommand:
319 self.ParseArgs([self.args.subcommand, '--help'])
320 else:
321 self.ParseArgs(['--help'])
322
323 def CmdIsolate(self):
324 vals = self.GetConfig()
325 if not vals:
326 return 1
327 return self.RunGNIsolate(vals)
328
329 def CmdLookup(self):
330 vals = self.Lookup()
331 gn_args = self.GNArgs(vals)
332 if self.args.quiet:
333 self.Print(gn_args, end='')
334 else:
335 cmd = self.GNCmd('gen', '_path_')
336 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
337 env = None
338
339 self.PrintCmd(cmd, env)
340 return 0
341
342 def CmdRun(self):
343 vals = self.GetConfig()
344 if not vals:
345 return 1
346
347 build_dir = self.args.path[0]
348 target = self.args.target[0]
349
350 if self.args.build:
351 ret = self.Build(target)
352 if ret:
353 return ret
354 ret = self.RunGNIsolate(vals)
355 if ret:
356 return ret
357
358 if self.args.swarmed:
359 cmd, _ = self.GetSwarmingCommand(self.args.target[0], vals)
360 return self._RunUnderSwarming(build_dir, target, cmd)
361 return self._RunLocallyIsolated(build_dir, target)
362
363 def _RunUnderSwarming(self, build_dir, target, isolate_cmd):
364 cas_instance = 'chromium-swarm'
365 swarming_server = 'chromium-swarm.appspot.com'
366 # TODO(dpranke): Look up the information for the target in
367 # the //testing/buildbot.json file, if possible, so that we
368 # can determine the isolate target, command line, and additional
369 # swarming parameters, if possible.
370 #
371 # TODO(dpranke): Also, add support for sharding and merging results.
372 dimensions = []
373 for k, v in self.args.dimensions:
374 dimensions += ['-d', '%s=%s' % (k, v)]
375
376 archive_json_path = self.ToSrcRelPath('%s/%s.archive.json' %
377 (build_dir, target))
378 cmd = [
379 self.PathJoin(self.src_dir, 'tools', 'luci-go', self.isolate_exe),
380 'archive',
381 '-i',
382 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
383 '-cas-instance',
384 cas_instance,
385 '-dump-json',
386 archive_json_path,
387 ]
388
389 # Talking to the isolateserver may fail because we're not logged in.
390 # We trap the command explicitly and rewrite the error output so that
391 # the error message is actually correct for a Chromium check out.
392 self.PrintCmd(cmd, env=None)
393 ret, out, err = self.Run(cmd, force_verbose=False)
394 if ret:
395 self.Print(' -> returned %d' % ret)
396 if out:
397 self.Print(out, end='')
398 if err:
399 self.Print(err, end='', file=sys.stderr)
400
401 return ret
402
403 try:
404 archive_hashes = json.loads(self.ReadFile(archive_json_path))
405 except Exception:
406 self.Print('Failed to read JSON file "%s"' % archive_json_path,
407 file=sys.stderr)
408 return 1
409 try:
410 cas_digest = archive_hashes[target]
411 except Exception:
412 self.Print('Cannot find hash for "%s" in "%s", file content: %s' %
413 (target, archive_json_path, archive_hashes),
414 file=sys.stderr)
415 return 1
416
417 try:
418 json_dir = self.TempDir()
419 json_file = self.PathJoin(json_dir, 'task.json')
420
421 cmd = [
422 self.PathJoin('tools', 'luci-go', 'swarming'),
423 'trigger',
424 '-realm',
425 self.args.realm,
426 '-digest',
427 cas_digest,
428 '-server',
429 swarming_server,
430 '-tag=purpose:user-debug-mb',
431 '-relative-cwd',
432 self.ToSrcRelPath(build_dir),
433 '-dump-json',
434 json_file,
435 ] + dimensions + ['--'] + list(isolate_cmd)
436
437 if self.args.extra_args:
438 cmd += ['--'] + self.args.extra_args
439 self.Print('')
440 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
441 if ret:
442 return ret
443 task_json = self.ReadFile(json_file)
444 task_id = json.loads(task_json)["tasks"][0]['task_id']
445 finally:
446 if json_dir:
447 self.RemoveDirectory(json_dir)
448
449 cmd = [
450 self.PathJoin('tools', 'luci-go', 'swarming'),
451 'collect',
452 '-server',
453 swarming_server,
454 '-task-output-stdout=console',
455 task_id,
456 ]
457 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
458 return ret
459
460 def _RunLocallyIsolated(self, build_dir, target):
461 cmd = [
462 self.PathJoin(self.src_dir, 'tools', 'luci-go', self.isolate_exe),
463 'run',
464 '-i',
465 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
466 ]
467 if self.args.extra_args:
468 cmd += ['--'] + self.args.extra_args
469 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
470 return ret
471
472 def CmdValidate(self, print_ok=True):
473 errs = []
474
475 # Read the file to make sure it parses.
476 self.ReadConfigFile()
477
478 # Build a list of all of the configs referenced by builders.
479 all_configs = {}
480 for builder_group in self.builder_groups:
481 for config in list(self.builder_groups[builder_group].values()):
482 if isinstance(config, dict):
483 for c in list(config.values()):
484 all_configs[c] = builder_group
485 else:
486 all_configs[config] = builder_group
487
488 # Check that every referenced args file or config actually exists.
489 for config, loc in list(all_configs.items()):
490 if config.startswith('//'):
491 if not self.Exists(self.ToAbsPath(config)):
492 errs.append('Unknown args file "%s" referenced from "%s".' %
493 (config, loc))
494 elif not config in self.configs:
495 errs.append('Unknown config "%s" referenced from "%s".' % (config, loc))
496
497 # Check that every actual config is actually referenced.
498 for config in self.configs:
499 if not config in all_configs:
500 errs.append('Unused config "%s".' % config)
501
502 # Figure out the whole list of mixins, and check that every mixin
503 # listed by a config or another mixin actually exists.
504 referenced_mixins = set()
505 for config, mixins in list(self.configs.items()):
506 for mixin in mixins:
507 if not mixin in self.mixins:
508 errs.append('Unknown mixin "%s" referenced by config "%s".' %
509 (mixin, config))
510 referenced_mixins.add(mixin)
511
512 for mixin in self.mixins:
513 for sub_mixin in self.mixins[mixin].get('mixins', []):
514 if not sub_mixin in self.mixins:
515 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
516 (sub_mixin, mixin))
517 referenced_mixins.add(sub_mixin)
518
519 # Check that every mixin defined is actually referenced somewhere.
520 for mixin in self.mixins:
521 if not mixin in referenced_mixins:
522 errs.append('Unreferenced mixin "%s".' % mixin)
523
524 if errs:
525 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
526 '\n ' + '\n '.join(errs))
527
528 if print_ok:
529 self.Print('mb config file %s looks ok.' % self.args.config_file)
530 return 0
531
532 def GetConfig(self):
533 build_dir = self.args.path[0]
534
535 vals = self.DefaultVals()
536 if self.args.builder or self.args.builder_group or self.args.config:
537 vals = self.Lookup()
538 # Re-run gn gen in order to ensure the config is consistent with
539 # the build dir.
540 self.RunGNGen(vals)
541 return vals
542
543 toolchain_path = self.PathJoin(self.ToAbsPath(build_dir), 'toolchain.ninja')
544 if not self.Exists(toolchain_path):
545 self.Print('Must either specify a path to an existing GN build '
546 'dir or pass in a -m/-b pair or a -c flag to specify '
547 'the configuration')
548 return {}
549
550 vals['gn_args'] = self.GNArgsFromDir(build_dir)
551 return vals
552
553 def GNArgsFromDir(self, build_dir):
554 args_contents = ""
555 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
556 if self.Exists(gn_args_path):
557 args_contents = self.ReadFile(gn_args_path)
558 gn_args = []
559 for l in args_contents.splitlines():
560 fields = l.split(' ')
561 name = fields[0]
562 val = ' '.join(fields[2:])
563 gn_args.append('%s=%s' % (name, val))
564
565 return ' '.join(gn_args)
566
567 def Lookup(self):
568 self.ReadConfigFile()
569 config = self.ConfigFromArgs()
570 if config.startswith('//'):
571 if not self.Exists(self.ToAbsPath(config)):
572 raise MBErr('args file "%s" not found' % config)
573 vals = self.DefaultVals()
574 vals['args_file'] = config
575 else:
576 if not config in self.configs:
577 raise MBErr('Config "%s" not found in %s' %
578 (config, self.args.config_file))
579 vals = self.FlattenConfig(config)
580 return vals
581
582 def ReadConfigFile(self):
583 if not self.Exists(self.args.config_file):
584 raise MBErr('config file not found at %s' % self.args.config_file)
585
586 try:
587 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
588 except SyntaxError as e:
589 raise MBErr('Failed to parse config file "%s"' %
590 self.args.config_file) from e
591
592 self.configs = contents['configs']
593 self.builder_groups = contents['builder_groups']
594 self.mixins = contents['mixins']
595
596 def ReadIsolateMap(self):
597 isolate_map = self.args.isolate_map_file
598 if not self.Exists(isolate_map):
599 raise MBErr('isolate map file not found at %s' % isolate_map)
600 try:
601 return ast.literal_eval(self.ReadFile(isolate_map))
602 except SyntaxError as e:
603 raise MBErr('Failed to parse isolate map file "%s"' % isolate_map) from e
604
605 def ConfigFromArgs(self):
606 if self.args.config:
607 if self.args.builder_group or self.args.builder:
608 raise MBErr('Can not specific both -c/--config and '
609 '-m/--builder-group or -b/--builder')
610
611 return self.args.config
612
613 if not self.args.builder_group or not self.args.builder:
614 raise MBErr('Must specify either -c/--config or '
615 '(-m/--builder-group and -b/--builder)')
616
617 if not self.args.builder_group in self.builder_groups:
618 raise MBErr('Master name "%s" not found in "%s"' %
619 (self.args.builder_group, self.args.config_file))
620
621 if not self.args.builder in self.builder_groups[self.args.builder_group]:
622 raise MBErr(
623 'Builder name "%s" not found under builder_groups[%s] in "%s"' %
624 (self.args.builder, self.args.builder_group, self.args.config_file))
625
626 config = (self.builder_groups[self.args.builder_group][self.args.builder])
627 if isinstance(config, dict):
628 if self.args.phase is None:
629 raise MBErr('Must specify a build --phase for %s on %s' %
630 (self.args.builder, self.args.builder_group))
631 phase = str(self.args.phase)
632 if phase not in config:
633 raise MBErr('Phase %s doesn\'t exist for %s on %s' %
634 (phase, self.args.builder, self.args.builder_group))
635 return config[phase]
636
637 if self.args.phase is not None:
638 raise MBErr('Must not specify a build --phase for %s on %s' %
639 (self.args.builder, self.args.builder_group))
640 return config
641
642 def FlattenConfig(self, config):
643 mixins = self.configs[config]
644 vals = self.DefaultVals()
645
646 visited = []
647 self.FlattenMixins(mixins, vals, visited)
648 return vals
649
650 @staticmethod
651 def DefaultVals():
652 return {
653 'args_file': '',
654 'cros_passthrough': False,
655 'gn_args': '',
656 }
657
658 def FlattenMixins(self, mixins, vals, visited):
659 for m in mixins:
660 if m not in self.mixins:
661 raise MBErr('Unknown mixin "%s"' % m)
662
663 visited.append(m)
664
665 mixin_vals = self.mixins[m]
666
667 if 'cros_passthrough' in mixin_vals:
668 vals['cros_passthrough'] = mixin_vals['cros_passthrough']
669 if 'gn_args' in mixin_vals:
670 if vals['gn_args']:
671 vals['gn_args'] += ' ' + mixin_vals['gn_args']
672 else:
673 vals['gn_args'] = mixin_vals['gn_args']
674
675 if 'mixins' in mixin_vals:
676 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
677 return vals
678
679 def RunGNGen(self, vals):
680 build_dir = self.args.path[0]
681
682 cmd = self.GNCmd('gen', build_dir, '--check')
683 gn_args = self.GNArgs(vals)
684
685 # Since GN hasn't run yet, the build directory may not even exist.
686 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
687
688 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
689 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
690
691 swarming_targets = set()
692 if getattr(self.args, 'swarming_targets_file', None):
693 # We need GN to generate the list of runtime dependencies for
694 # the compile targets listed (one per line) in the file so
695 # we can run them via swarming. We use gn_isolate_map.pyl to
696 # convert the compile targets to the matching GN labels.
697 path = self.args.swarming_targets_file
698 if not self.Exists(path):
699 self.WriteFailureAndRaise('"%s" does not exist' % path,
700 output_path=None)
701 contents = self.ReadFile(path)
702 swarming_targets = set(contents.splitlines())
703
704 isolate_map = self.ReadIsolateMap()
705 err, labels = self.MapTargetsToLabels(isolate_map, swarming_targets)
706 if err:
707 raise MBErr(err)
708
709 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
710 self.WriteFile(gn_runtime_deps_path, '\n'.join(labels) + '\n')
711 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
712
713 ret, output, _ = self.Run(cmd)
714 if ret:
715 if self.args.json_output:
716 # write errors to json.output
717 self.WriteJSON({'output': output}, self.args.json_output)
718 # If `gn gen` failed, we should exit early rather than trying to
719 # generate isolates. Run() will have already logged any error
720 # output.
721 self.Print('GN gen failed: %d' % ret)
722 return ret
723
724 android = 'target_os="android"' in vals['gn_args']
725 for target in swarming_targets:
726 if android:
727 # Android targets may be either android_apk or executable. The
728 # former will result in runtime_deps associated with the stamp
729 # file, while the latter will result in runtime_deps associated
730 # with the executable.
731 label = isolate_map[target]['label']
732 runtime_deps_targets = [
733 target + '.runtime_deps',
734 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')
735 ]
736 elif isolate_map[target]['type'] == 'gpu_browser_test':
737 if self.platform == 'win32':
738 runtime_deps_targets = ['browser_tests.exe.runtime_deps']
739 else:
740 runtime_deps_targets = ['browser_tests.runtime_deps']
741 elif isolate_map[target]['type'] == 'script':
742 label = isolate_map[target]['label'].split(':')[1]
743 runtime_deps_targets = ['%s.runtime_deps' % label]
744 if self.platform == 'win32':
745 runtime_deps_targets += [label + '.exe.runtime_deps']
746 else:
747 runtime_deps_targets += [label + '.runtime_deps']
748 elif self.platform == 'win32':
749 runtime_deps_targets = [target + '.exe.runtime_deps']
750 else:
751 runtime_deps_targets = [target + '.runtime_deps']
752
753 for r in runtime_deps_targets:
754 runtime_deps_path = self.ToAbsPath(build_dir, r)
755 if self.Exists(runtime_deps_path):
756 break
757 else:
758 raise MBErr('did not generate any of %s' %
759 ', '.join(runtime_deps_targets))
760
761 command, extra_files = self.GetSwarmingCommand(target, vals)
762
763 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
764
765 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
766 extra_files)
767
768 return 0
769
770 def RunGNIsolate(self, vals):
771 target = self.args.target[0]
772 isolate_map = self.ReadIsolateMap()
773 err, labels = self.MapTargetsToLabels(isolate_map, [target])
774 if err:
775 raise MBErr(err)
776 label = labels[0]
777
778 build_dir = self.args.path[0]
779 command, extra_files = self.GetSwarmingCommand(target, vals)
780
781 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
782 ret, out, _ = self.Call(cmd)
783 if ret:
784 if out:
785 self.Print(out)
786 return ret
787
788 runtime_deps = out.splitlines()
789
790 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
791 extra_files)
792
793 ret, _, _ = self.Run([
794 self.PathJoin(self.src_dir, 'tools', 'luci-go', self.isolate_exe),
795 'check', '-i',
796 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target))
797 ],
798 buffer_output=False)
799
800 return ret
801
802 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
803 extra_files):
804 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
805 self.WriteFile(
806 isolate_path,
807 pprint.pformat({
808 'variables': {
809 'command': command,
810 'files': sorted(runtime_deps + extra_files),
811 }
812 }) + '\n')
813
814 self.WriteJSON(
815 {
816 'args': [
817 '--isolate',
818 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
819 ],
820 'dir':
821 self.src_dir,
822 'version':
823 1,
824 },
825 isolate_path + 'd.gen.json',
826 )
827
828 @staticmethod
829 def MapTargetsToLabels(isolate_map, targets):
830 labels = []
831 err = ''
832
833 def StripTestSuffixes(target):
834 for suffix in ('_apk_run', '_apk', '_run'):
835 if target.endswith(suffix):
836 return target[:-len(suffix)], suffix
837 return None, None
838
839 for target in targets:
840 if target == 'all':
841 labels.append(target)
842 elif target.startswith('//'):
843 labels.append(target)
844 else:
845 if target in isolate_map:
846 stripped_target, suffix = target, ''
847 else:
848 stripped_target, suffix = StripTestSuffixes(target)
849 if stripped_target in isolate_map:
850 if isolate_map[stripped_target]['type'] == 'unknown':
851 err += ('test target "%s" type is unknown\n' % target)
852 else:
853 labels.append(isolate_map[stripped_target]['label'] + suffix)
854 else:
855 err += ('target "%s" not found in '
856 '//testing/buildbot/gn_isolate_map.pyl\n' % target)
857
858 return err, labels
859
860 def GNCmd(self, subcommand, path, *args):
861 if self.platform.startswith('linux'):
862 subdir, exe = 'linux64', 'gn'
863 elif self.platform == 'darwin':
864 subdir, exe = 'mac', 'gn'
865 else:
866 subdir, exe = 'win', 'gn.exe'
867
868 gn_path = self.PathJoin(self.src_dir, 'buildtools', subdir, exe)
869 return [gn_path, subcommand, path] + list(args)
870
871 def GNArgs(self, vals):
872 if vals['cros_passthrough']:
873 if not 'GN_ARGS' in os.environ:
874 raise MBErr('MB is expecting GN_ARGS to be in the environment')
875 gn_args = os.environ['GN_ARGS']
876 if not re.search('target_os.*=.*"chromeos"', gn_args):
877 raise MBErr('GN_ARGS is missing target_os = "chromeos": '
878 '(GN_ARGS=%s)' % gn_args)
879 else:
880 gn_args = vals['gn_args']
881
882 if self.args.goma_dir:
883 gn_args += ' goma_dir="%s"' % self.args.goma_dir
884
885 android_version_code = self.args.android_version_code
886 if android_version_code:
887 gn_args += (' android_default_version_code="%s"' % android_version_code)
888
889 android_version_name = self.args.android_version_name
890 if android_version_name:
891 gn_args += (' android_default_version_name="%s"' % android_version_name)
892
893 # Canonicalize the arg string into a sorted, newline-separated list
894 # of key-value pairs, and de-dup the keys if need be so that only
895 # the last instance of each arg is listed.
896 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
897
898 args_file = vals.get('args_file', None)
899 if args_file:
900 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
901 return gn_args
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100902
903 def GetSwarmingCommand(self, target, vals):
904 isolate_map = self.ReadIsolateMap()
905 test_type = isolate_map[target]['type']
906
907 is_android = 'target_os="android"' in vals['gn_args']
908 is_linux = self.platform.startswith('linux') and not is_android
Jeremy Leconted15f3e12022-02-18 10:16:32 +0100909 is_ios = 'target_os="ios"' in vals['gn_args']
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100910
911 if test_type == 'nontest':
912 self.WriteFailureAndRaise('We should not be isolating %s.' % target,
913 output_path=None)
914 if test_type not in ('console_test_launcher', 'windowed_test_launcher',
915 'non_parallel_console_test_launcher', 'raw',
916 'additional_compile_target', 'junit_test', 'script'):
917 self.WriteFailureAndRaise('No command line for '
918 '%s found (test type %s).' %
919 (target, test_type),
920 output_path=None)
921
922 cmdline = []
923 extra_files = [
Mirko Bonadei5d9ae862022-01-27 20:18:16 +0100924 '../../.vpython3',
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100925 '../../testing/test_env.py',
926 ]
Mirko Bonadei5d9ae862022-01-27 20:18:16 +0100927 vpython_exe = 'vpython3'
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100928
Jeremy Leconte145ff4c2022-03-28 11:32:20 +0200929 if isolate_map[target].get('script'):
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100930 cmdline += [
931 vpython_exe,
932 '../../' + self.ToSrcRelPath(isolate_map[target]['script'])
933 ]
934 elif is_android:
935 cmdline += [
936 vpython_exe, '../../build/android/test_wrapper/logdog_wrapper.py',
937 '--target', target, '--logdog-bin-cmd', '../../bin/logdog_butler',
938 '--logcat-output-file', '${ISOLATED_OUTDIR}/logcats',
939 '--store-tombstones'
940 ]
Jeremy Leconted15f3e12022-02-18 10:16:32 +0100941 elif is_ios:
942 cmdline += [
943 vpython_exe, '../../tools_webrtc/flags_compatibility.py',
944 'bin/run_%s' % target, '--out-dir', '${ISOLATED_OUTDIR}'
945 ]
946 extra_files.append('../../tools_webrtc/flags_compatibility.py')
Jeremy Leconte145ff4c2022-03-28 11:32:20 +0200947 elif test_type == 'raw':
948 cmdline += [vpython_exe, '../../tools_webrtc/flags_compatibility.py']
949 extra_files.append('../../tools_webrtc/flags_compatibility.py')
950 cmdline.append(_get_executable(target, self.platform))
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100951 else:
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100952 if isolate_map[target].get('use_webcam', False):
953 cmdline += [
954 vpython_exe, '../../tools_webrtc/ensure_webcam_is_running.py'
955 ]
956 extra_files.append('../../tools_webrtc/ensure_webcam_is_running.py')
957
958 # is_linux uses use_ozone and x11 by default.
959 use_x11 = is_linux
960
961 xvfb = use_x11 and test_type == 'windowed_test_launcher'
962 if xvfb:
963 cmdline += [vpython_exe, '../../testing/xvfb.py']
964 extra_files.append('../../testing/xvfb.py')
965 else:
966 cmdline += [vpython_exe, '../../testing/test_env.py']
967
Jeremy Leconte145ff4c2022-03-28 11:32:20 +0200968 extra_files += [
969 '../../third_party/gtest-parallel/gtest-parallel',
970 '../../third_party/gtest-parallel/gtest_parallel.py',
971 '../../tools_webrtc/gtest-parallel-wrapper.py',
972 ]
973 sep = '\\' if self.platform == 'win32' else '/'
974 output_dir = '${ISOLATED_OUTDIR}' + sep + 'test_logs'
975 timeout = isolate_map[target].get('timeout', 900)
976 cmdline += [
977 '../../tools_webrtc/gtest-parallel-wrapper.py',
978 '--output_dir=%s' % output_dir,
979 '--gtest_color=no',
980 # We tell gtest-parallel to interrupt the test after 900
981 # seconds, so it can exit cleanly and report results,
982 # instead of being interrupted by swarming and not
983 # reporting anything.
984 '--timeout=%s' % timeout,
985 ]
986 if test_type == 'non_parallel_console_test_launcher':
987 # Still use the gtest-parallel-wrapper.py script since we
988 # need it to run tests on swarming, but don't execute tests
989 # in parallel.
990 cmdline.append('--workers=1')
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100991
992 asan = 'is_asan=true' in vals['gn_args']
993 lsan = 'is_lsan=true' in vals['gn_args']
994 msan = 'is_msan=true' in vals['gn_args']
995 tsan = 'is_tsan=true' in vals['gn_args']
996 sanitizer = asan or lsan or msan or tsan
Jeremy Leconte145ff4c2022-03-28 11:32:20 +0200997 if not sanitizer:
Jeremy Lecontef22c78b2021-12-07 19:49:48 +0100998 # Retry would hide most sanitizers detections.
999 cmdline.append('--retry_failed=3')
1000
Jeremy Leconte145ff4c2022-03-28 11:32:20 +02001001 cmdline.append(_get_executable(target, self.platform))
Jeremy Lecontef22c78b2021-12-07 19:49:48 +01001002
1003 cmdline.extend([
1004 '--asan=%d' % asan,
1005 '--lsan=%d' % lsan,
1006 '--msan=%d' % msan,
1007 '--tsan=%d' % tsan,
1008 ])
1009
1010 cmdline += isolate_map[target].get('args', [])
1011
1012 return cmdline, extra_files
1013
Jeremy Lecontead3f4902022-03-28 07:21:46 +00001014 def ToAbsPath(self, build_path, *comps):
1015 return self.PathJoin(self.src_dir, self.ToSrcRelPath(build_path), *comps)
1016
1017 def ToSrcRelPath(self, path):
1018 """Returns a relative path from the top of the repo."""
1019 if path.startswith('//'):
1020 return path[2:].replace('/', self.sep)
1021 return self.RelPath(path, self.src_dir)
1022
1023 def RunGNAnalyze(self, vals):
1024 # Analyze runs before 'gn gen' now, so we need to run gn gen
1025 # in order to ensure that we have a build directory.
1026 ret = self.RunGNGen(vals)
1027 if ret:
1028 return ret
1029
1030 build_path = self.args.path[0]
1031 input_path = self.args.input_path[0]
1032 gn_input_path = input_path + '.gn'
1033 output_path = self.args.output_path[0]
1034 gn_output_path = output_path + '.gn'
1035
1036 inp = self.ReadInputJSON(
1037 ['files', 'test_targets', 'additional_compile_targets'])
1038 if self.args.verbose:
1039 self.Print()
1040 self.Print('analyze input:')
1041 self.PrintJSON(inp)
1042 self.Print()
1043
1044 # This shouldn't normally happen, but could due to unusual race
1045 # conditions, like a try job that gets scheduled before a patch
1046 # lands but runs after the patch has landed.
1047 if not inp['files']:
1048 self.Print('Warning: No files modified in patch, bailing out early.')
1049 self.WriteJSON(
1050 {
1051 'status': 'No dependency',
1052 'compile_targets': [],
1053 'test_targets': [],
1054 }, output_path)
1055 return 0
1056
1057 gn_inp = {}
1058 gn_inp['files'] = ['//' + f for f in inp['files'] if not f.startswith('//')]
1059
1060 isolate_map = self.ReadIsolateMap()
1061 err, gn_inp['additional_compile_targets'] = self.MapTargetsToLabels(
1062 isolate_map, inp['additional_compile_targets'])
1063 if err:
1064 raise MBErr(err)
1065
1066 err, gn_inp['test_targets'] = self.MapTargetsToLabels(
1067 isolate_map, inp['test_targets'])
1068 if err:
1069 raise MBErr(err)
1070 labels_to_targets = {}
1071 for i, label in enumerate(gn_inp['test_targets']):
1072 labels_to_targets[label] = inp['test_targets'][i]
1073
1074 try:
1075 self.WriteJSON(gn_inp, gn_input_path)
1076 cmd = self.GNCmd('analyze', build_path, gn_input_path, gn_output_path)
1077 ret, output, _ = self.Run(cmd, force_verbose=True)
1078 if ret:
1079 if self.args.json_output:
1080 # write errors to json.output
1081 self.WriteJSON({'output': output}, self.args.json_output)
1082 return ret
1083
1084 gn_outp_str = self.ReadFile(gn_output_path)
1085 try:
1086 gn_outp = json.loads(gn_outp_str)
1087 except Exception as e:
1088 self.Print("Failed to parse the JSON string GN "
1089 "returned: %s\n%s" % (repr(gn_outp_str), str(e)))
1090 raise
1091
1092 outp = {}
1093 if 'status' in gn_outp:
1094 outp['status'] = gn_outp['status']
1095 if 'error' in gn_outp:
1096 outp['error'] = gn_outp['error']
1097 if 'invalid_targets' in gn_outp:
1098 outp['invalid_targets'] = gn_outp['invalid_targets']
1099 if 'compile_targets' in gn_outp:
1100 if 'all' in gn_outp['compile_targets']:
1101 outp['compile_targets'] = ['all']
1102 else:
1103 outp['compile_targets'] = [
1104 label.replace('//', '') for label in gn_outp['compile_targets']
1105 ]
1106 if 'test_targets' in gn_outp:
1107 outp['test_targets'] = [
1108 labels_to_targets[label] for label in gn_outp['test_targets']
1109 ]
1110
1111 if self.args.verbose:
1112 self.Print()
1113 self.Print('analyze output:')
1114 self.PrintJSON(outp)
1115 self.Print()
1116
1117 self.WriteJSON(outp, output_path)
1118
1119 finally:
1120 if self.Exists(gn_input_path):
1121 self.RemoveFile(gn_input_path)
1122 if self.Exists(gn_output_path):
1123 self.RemoveFile(gn_output_path)
1124
1125 return 0
1126
1127 def ReadInputJSON(self, required_keys):
1128 path = self.args.input_path[0]
1129 output_path = self.args.output_path[0]
1130 if not self.Exists(path):
1131 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
1132
1133 try:
1134 inp = json.loads(self.ReadFile(path))
1135 except Exception as e:
1136 self.WriteFailureAndRaise(
1137 'Failed to read JSON input from "%s": %s' % (path, e), output_path)
1138
1139 for k in required_keys:
1140 if not k in inp:
1141 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1142 output_path)
1143
1144 return inp
1145
1146 def WriteFailureAndRaise(self, msg, output_path):
1147 if output_path:
1148 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
1149 raise MBErr(msg)
1150
1151 def WriteJSON(self, obj, path, force_verbose=False):
1152 try:
1153 self.WriteFile(path,
1154 json.dumps(obj, indent=2, sort_keys=True) + '\n',
1155 force_verbose=force_verbose)
1156 except Exception as e:
1157 raise MBErr('Error writing to the output path "%s"' % path) from e
1158
1159 def PrintCmd(self, cmd, env):
1160 if self.platform == 'win32':
1161 env_prefix = 'set '
1162 env_quoter = QuoteForSet
1163 shell_quoter = QuoteForCmd
1164 else:
1165 env_prefix = ''
1166 env_quoter = pipes.quote
1167 shell_quoter = pipes.quote
1168
1169 var = 'LLVM_FORCE_HEAD_REVISION'
1170 if env and var in env:
1171 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1172
1173 if cmd[0] == self.executable:
1174 cmd = ['vpython3'] + cmd[1:]
1175 self.Print(*[shell_quoter(arg) for arg in cmd])
1176
1177 def PrintJSON(self, obj):
1178 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1179
1180 def Build(self, target):
1181 build_dir = self.ToSrcRelPath(self.args.path[0])
1182 ninja_cmd = ['ninja', '-C', build_dir]
1183 if self.args.jobs:
1184 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1185 ninja_cmd.append(target)
1186 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1187 return ret
1188
1189 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
1190 # This function largely exists so it can be overridden for testing.
1191 if self.args.dryrun or self.args.verbose or force_verbose:
1192 self.PrintCmd(cmd, env)
1193 if self.args.dryrun:
1194 return 0, '', ''
1195
1196 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
1197 if self.args.verbose or force_verbose:
1198 if ret:
1199 self.Print(' -> returned %d' % ret)
1200 if out:
1201 self.Print(out, end='')
1202 if err:
1203 self.Print(err, end='', file=sys.stderr)
1204 return ret, out, err
1205
1206 def Call(self, cmd, env=None, buffer_output=True):
1207 if buffer_output:
1208 p = subprocess.Popen(cmd,
1209 shell=False,
1210 cwd=self.src_dir,
1211 stdout=subprocess.PIPE,
1212 stderr=subprocess.PIPE,
1213 env=env)
1214 out, err = p.communicate()
1215 out = out.decode('utf-8')
1216 err = err.decode('utf-8')
1217 else:
1218 p = subprocess.Popen(cmd, shell=False, cwd=self.src_dir, env=env)
1219 p.wait()
1220 out = err = ''
1221 return p.returncode, out, err
1222
1223 @staticmethod
1224 def ExpandUser(path):
1225 # This function largely exists so it can be overridden for testing.
1226 return os.path.expanduser(path)
1227
1228 @staticmethod
1229 def Exists(path):
1230 # This function largely exists so it can be overridden for testing.
1231 return os.path.exists(path)
1232
1233 @staticmethod
1234 def Fetch(url):
1235 # This function largely exists so it can be overridden for testing.
1236 f = urlopen(url)
1237 contents = f.read()
1238 f.close()
1239 return contents
1240
1241 @staticmethod
1242 def MaybeMakeDirectory(path):
1243 try:
1244 os.makedirs(path)
1245 except OSError as e:
1246 if e.errno != errno.EEXIST:
1247 raise
1248
1249 @staticmethod
1250 def PathJoin(*comps):
1251 # This function largely exists so it can be overriden for testing.
1252 return os.path.join(*comps)
1253
1254 @staticmethod
1255 def Print(*args, **kwargs):
1256 # This function largely exists so it can be overridden for testing.
1257 print(*args, **kwargs)
1258 if kwargs.get('stream', sys.stdout) == sys.stdout:
1259 sys.stdout.flush()
1260
1261 @staticmethod
1262 def ReadFile(path):
1263 # This function largely exists so it can be overriden for testing.
1264 with open(path) as fp:
1265 return fp.read()
1266
1267 @staticmethod
1268 def RelPath(path, start='.'):
1269 # This function largely exists so it can be overriden for testing.
1270 return os.path.relpath(path, start)
1271
1272 @staticmethod
1273 def RemoveFile(path):
1274 # This function largely exists so it can be overriden for testing.
1275 os.remove(path)
1276
1277 def RemoveDirectory(self, abs_path):
1278 if self.platform == 'win32':
1279 # In other places in chromium, we often have to retry this command
1280 # because we're worried about other processes still holding on to
1281 # file handles, but when MB is invoked, it will be early enough in
1282 # the build that their should be no other processes to interfere.
1283 # We can change this if need be.
1284 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1285 else:
1286 shutil.rmtree(abs_path, ignore_errors=True)
1287
1288 @staticmethod
1289 def TempDir():
1290 # This function largely exists so it can be overriden for testing.
1291 return tempfile.mkdtemp(prefix='mb_')
1292
1293 @staticmethod
1294 def TempFile(mode='w'):
1295 # This function largely exists so it can be overriden for testing.
1296 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1297
1298 def WriteFile(self, path, contents, force_verbose=False):
1299 # This function largely exists so it can be overriden for testing.
1300 if self.args.dryrun or self.args.verbose or force_verbose:
1301 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
1302 with open(path, 'w') as fp:
1303 return fp.write(contents)
1304
1305
1306class MBErr(Exception):
1307 pass
1308
1309
1310# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1311# details of this next section, which handles escaping command lines
1312# so that they can be copied and pasted into a cmd window.
1313UNSAFE_FOR_SET = set('^<>&|')
1314UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1315ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1316
1317
1318def QuoteForSet(arg):
1319 if any(a in UNSAFE_FOR_SET for a in arg):
1320 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1321 return arg
1322
1323
1324def QuoteForCmd(arg):
1325 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1326 if arg == '' or ' ' in arg or '"' in arg:
1327 quote_re = re.compile(r'(\\*)"')
1328 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1329
1330 # Then check to see if the arg contains any metacharacters other than
1331 # double quotes; if it does, quote everything (including the double
1332 # quotes) for safety.
1333 if any(a in UNSAFE_FOR_CMD for a in arg):
1334 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1335 return arg
1336
1337
kjellandera013a022016-11-14 05:54:22 -08001338if __name__ == '__main__':
Jeremy Lecontef22c78b2021-12-07 19:49:48 +01001339 sys.exit(main(sys.argv[1:]))