blob: a3e8e3734d1834aecffc5080421d8dff6cb8e43a [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
dprankefe4602312015-04-08 16:20:3526
dprankefe4602312015-04-08 16:20:3527def main(args):
dprankeee5b51f62015-04-09 00:03:2228 mbw = MetaBuildWrapper()
29 mbw.ParseArgs(args)
30 return mbw.args.func()
dprankefe4602312015-04-08 16:20:3531
32
33class MetaBuildWrapper(object):
34 def __init__(self):
35 p = os.path
36 d = os.path.dirname
37 self.chromium_src_dir = p.normpath(d(d(d(p.abspath(__file__)))))
38 self.default_config = p.join(self.chromium_src_dir, 'tools', 'mb',
39 'mb_config.pyl')
dpranke8c2cfd32015-09-17 20:12:3340 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5141 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3342 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3543 self.args = argparse.Namespace()
44 self.configs = {}
45 self.masters = {}
46 self.mixins = {}
47 self.private_configs = []
48 self.common_dev_configs = []
49 self.unsupported_configs = []
50
51 def ParseArgs(self, argv):
52 def AddCommonOptions(subp):
53 subp.add_argument('-b', '--builder',
54 help='builder name to look up config from')
55 subp.add_argument('-m', '--master',
56 help='master name to look up config from')
57 subp.add_argument('-c', '--config',
58 help='configuration to analyze')
59 subp.add_argument('-f', '--config-file', metavar='PATH',
60 default=self.default_config,
61 help='path to config file '
62 '(default is //tools/mb/mb_config.pyl)')
63 subp.add_argument('-g', '--goma-dir', default=self.ExpandUser('~/goma'),
64 help='path to goma directory (default is %(default)s).')
65 subp.add_argument('-n', '--dryrun', action='store_true',
66 help='Do a dry run (i.e., do nothing, just print '
67 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:4068 subp.add_argument('-v', '--verbose', action='store_true',
69 help='verbose logging')
dprankefe4602312015-04-08 16:20:3570
71 parser = argparse.ArgumentParser(prog='mb')
72 subps = parser.add_subparsers()
73
74 subp = subps.add_parser('analyze',
75 help='analyze whether changes to a set of files '
76 'will cause a set of binaries to be rebuilt.')
77 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:2578 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:3579 help='path build was generated into.')
80 subp.add_argument('input_path', nargs=1,
81 help='path to a file containing the input arguments '
82 'as a JSON object.')
83 subp.add_argument('output_path', nargs=1,
84 help='path to a file containing the output arguments '
85 'as a JSON object.')
86 subp.set_defaults(func=self.CmdAnalyze)
87
88 subp = subps.add_parser('gen',
89 help='generate a new set of build files')
90 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:3991 subp.add_argument('--swarming-targets-file',
92 help='save runtime dependencies for targets listed '
93 'in file.')
dpranked8113582015-06-05 20:08:2594 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:3595 help='path to generate build into')
96 subp.set_defaults(func=self.CmdGen)
97
dpranke751516a2015-10-03 01:11:3498 subp = subps.add_parser('isolate',
99 help='generate the .isolate files for a given'
100 'binary')
101 AddCommonOptions(subp)
102 subp.add_argument('path', nargs=1,
103 help='path build was generated into')
104 subp.add_argument('target', nargs=1,
105 help='ninja target to generate the isolate for')
106 subp.set_defaults(func=self.CmdIsolate)
107
dprankefe4602312015-04-08 16:20:35108 subp = subps.add_parser('lookup',
109 help='look up the command for a given config or '
110 'builder')
111 AddCommonOptions(subp)
112 subp.set_defaults(func=self.CmdLookup)
113
dpranke751516a2015-10-03 01:11:34114 subp = subps.add_parser('run',
115 help='build and run the isolated version of a '
116 'binary')
117 AddCommonOptions(subp)
118 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
119 help='Number of jobs to pass to ninja')
120 subp.add_argument('--no-build', dest='build', default=True,
121 action='store_false',
122 help='Do not build, just isolate and run')
123 subp.add_argument('path', nargs=1,
124 help='path to generate build into')
125 subp.add_argument('target', nargs=1,
126 help='ninja target to build and run')
127 subp.set_defaults(func=self.CmdRun)
128
dprankefe4602312015-04-08 16:20:35129 subp = subps.add_parser('validate',
130 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17131 subp.add_argument('-f', '--config-file', metavar='PATH',
132 default=self.default_config,
133 help='path to config file '
134 '(default is //tools/mb/mb_config.pyl)')
dprankefe4602312015-04-08 16:20:35135 subp.set_defaults(func=self.CmdValidate)
136
137 subp = subps.add_parser('help',
138 help='Get help on a subcommand.')
139 subp.add_argument(nargs='?', action='store', dest='subcommand',
140 help='The command to get help for.')
141 subp.set_defaults(func=self.CmdHelp)
142
143 self.args = parser.parse_args(argv)
144
145 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34146 vals = self.Lookup()
dprankefe4602312015-04-08 16:20:35147 if vals['type'] == 'gn':
148 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35149 else:
dpranke751516a2015-10-03 01:11:34150 return self.RunGYPAnalyze(vals)
dprankefe4602312015-04-08 16:20:35151
152 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34153 vals = self.Lookup()
dprankec161aa92015-09-14 20:21:13154 self.ClobberIfNeeded(vals)
155
dprankefe4602312015-04-08 16:20:35156 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50157 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35158 else:
dpranke751516a2015-10-03 01:11:34159 return self.RunGYPGen(vals)
dprankefe4602312015-04-08 16:20:35160
161 def CmdHelp(self):
162 if self.args.subcommand:
163 self.ParseArgs([self.args.subcommand, '--help'])
164 else:
165 self.ParseArgs(['--help'])
166
dpranke751516a2015-10-03 01:11:34167 def CmdIsolate(self):
168 vals = self.GetConfig()
169 if not vals:
170 return 1
171
172 if vals['type'] == 'gn':
173 return self.RunGNIsolate(vals)
174 else:
175 return self.Build('%s_run' % self.args.target[0])
176
177 def CmdLookup(self):
178 vals = self.Lookup()
179 if vals['type'] == 'gn':
180 cmd = self.GNCmd('gen', '_path_', vals['gn_args'])
181 env = None
182 else:
183 cmd, env = self.GYPCmd('_path_', vals)
184
185 self.PrintCmd(cmd, env)
186 return 0
187
188 def CmdRun(self):
189 vals = self.GetConfig()
190 if not vals:
191 return 1
192
193 build_dir = self.args.path[0]
194 target = self.args.target[0]
195
196 if vals['type'] == 'gn':
197 if self.args.build:
198 ret = self.Build(target)
199 if ret:
200 return ret
201 ret = self.RunGNIsolate(vals)
202 if ret:
203 return ret
204 else:
205 ret = self.Build('%s_run' % target)
206 if ret:
207 return ret
208
209 ret, _, _ = self.Run([
210 self.executable,
211 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
212 'run',
213 '-s',
214 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
215 force_verbose=False, buffer_output=False)
216
217 return ret
218
dprankefe4602312015-04-08 16:20:35219 def CmdValidate(self):
220 errs = []
221
222 # Read the file to make sure it parses.
223 self.ReadConfigFile()
224
225 # Figure out the whole list of configs and ensure that no config is
226 # listed in more than one category.
227 all_configs = {}
228 for config in self.common_dev_configs:
229 all_configs[config] = 'common_dev_configs'
230 for config in self.private_configs:
231 if config in all_configs:
232 errs.append('config "%s" listed in "private_configs" also '
233 'listed in "%s"' % (config, all_configs['config']))
234 else:
235 all_configs[config] = 'private_configs'
236 for config in self.unsupported_configs:
237 if config in all_configs:
238 errs.append('config "%s" listed in "unsupported_configs" also '
239 'listed in "%s"' % (config, all_configs['config']))
240 else:
241 all_configs[config] = 'unsupported_configs'
242
243 for master in self.masters:
244 for builder in self.masters[master]:
245 config = self.masters[master][builder]
246 if config in all_configs and all_configs[config] not in self.masters:
247 errs.append('Config "%s" used by a bot is also listed in "%s".' %
248 (config, all_configs[config]))
249 else:
250 all_configs[config] = master
251
252 # Check that every referenced config actually exists.
253 for config, loc in all_configs.items():
254 if not config in self.configs:
255 errs.append('Unknown config "%s" referenced from "%s".' %
256 (config, loc))
257
258 # Check that every actual config is actually referenced.
259 for config in self.configs:
260 if not config in all_configs:
261 errs.append('Unused config "%s".' % config)
262
263 # Figure out the whole list of mixins, and check that every mixin
264 # listed by a config or another mixin actually exists.
265 referenced_mixins = set()
266 for config, mixins in self.configs.items():
267 for mixin in mixins:
268 if not mixin in self.mixins:
269 errs.append('Unknown mixin "%s" referenced by config "%s".' %
270 (mixin, config))
271 referenced_mixins.add(mixin)
272
273 for mixin in self.mixins:
274 for sub_mixin in self.mixins[mixin].get('mixins', []):
275 if not sub_mixin in self.mixins:
276 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
277 (sub_mixin, mixin))
278 referenced_mixins.add(sub_mixin)
279
280 # Check that every mixin defined is actually referenced somewhere.
281 for mixin in self.mixins:
282 if not mixin in referenced_mixins:
283 errs.append('Unreferenced mixin "%s".' % mixin)
284
285 if errs:
dpranke4323c80632015-08-10 22:53:54286 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17287 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35288
dprankee0547cd2015-09-15 01:27:40289 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35290 return 0
291
292 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34293 build_dir = self.args.path[0]
294
295 vals = {}
296 if self.args.builder or self.args.master or self.args.config:
297 vals = self.Lookup()
298 if vals['type'] == 'gn':
299 # Re-run gn gen in order to ensure the config is consistent with the
300 # build dir.
301 self.RunGNGen(vals)
302 return vals
303
304 # TODO: We can only get the config for GN build dirs, not GYP build dirs.
305 # GN stores the args that were used in args.gn in the build dir,
306 # but GYP doesn't store them anywhere. We should consider modifying
307 # gyp_chromium to record the arguments it runs with in a similar
308 # manner.
309
310 mb_type_path = self.PathJoin(self.ToAbsPath(build_dir), 'mb_type')
311 if not self.Exists(mb_type_path):
312 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
313 if not self.Exists(gn_args_path):
314 self.Print('Must either specify a path to an existing GN build dir '
315 'or pass in a -m/-b pair or a -c flag to specify the '
316 'configuration')
317 return {}
318 else:
319 mb_type = 'gn'
320 else:
321 mb_type = self.ReadFile(mb_type_path).strip()
322
323 if mb_type == 'gn':
324 vals = self.GNValsFromDir(build_dir)
325 else:
326 vals = {}
327 vals['type'] = mb_type
328
329 return vals
330
331 def GNValsFromDir(self, build_dir):
332 args_contents = self.ReadFile(
333 self.PathJoin(self.ToAbsPath(build_dir), 'args.gn'))
334 gn_args = []
335 for l in args_contents.splitlines():
336 fields = l.split(' ')
337 name = fields[0]
338 val = ' '.join(fields[2:])
339 gn_args.append('%s=%s' % (name, val))
340
341 return {
342 'gn_args': ' '.join(gn_args),
343 'type': 'gn',
344 }
345
346 def Lookup(self):
dprankefe4602312015-04-08 16:20:35347 self.ReadConfigFile()
348 config = self.ConfigFromArgs()
349 if not config in self.configs:
350 raise MBErr('Config "%s" not found in %s' %
351 (config, self.args.config_file))
352
dpranke751516a2015-10-03 01:11:34353 vals = self.FlattenConfig(config)
354
355 # Do some basic sanity checking on the config so that we
356 # don't have to do this in every caller.
357 assert 'type' in vals, 'No meta-build type specified in the config'
358 assert vals['type'] in ('gn', 'gyp'), (
359 'Unknown meta-build type "%s"' % vals['gn_args'])
360
361 return vals
dprankefe4602312015-04-08 16:20:35362
363 def ReadConfigFile(self):
364 if not self.Exists(self.args.config_file):
365 raise MBErr('config file not found at %s' % self.args.config_file)
366
367 try:
368 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
369 except SyntaxError as e:
370 raise MBErr('Failed to parse config file "%s": %s' %
371 (self.args.config_file, e))
372
373 self.common_dev_configs = contents['common_dev_configs']
374 self.configs = contents['configs']
375 self.masters = contents['masters']
376 self.mixins = contents['mixins']
377 self.private_configs = contents['private_configs']
378 self.unsupported_configs = contents['unsupported_configs']
379
380 def ConfigFromArgs(self):
381 if self.args.config:
382 if self.args.master or self.args.builder:
383 raise MBErr('Can not specific both -c/--config and -m/--master or '
384 '-b/--builder')
385
386 return self.args.config
387
388 if not self.args.master or not self.args.builder:
389 raise MBErr('Must specify either -c/--config or '
390 '(-m/--master and -b/--builder)')
391
392 if not self.args.master in self.masters:
393 raise MBErr('Master name "%s" not found in "%s"' %
394 (self.args.master, self.args.config_file))
395
396 if not self.args.builder in self.masters[self.args.master]:
397 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
398 (self.args.builder, self.args.master, self.args.config_file))
399
400 return self.masters[self.args.master][self.args.builder]
401
402 def FlattenConfig(self, config):
403 mixins = self.configs[config]
404 vals = {
405 'type': None,
406 'gn_args': [],
dprankec161aa92015-09-14 20:21:13407 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59408 'gyp_crosscompile': False,
dprankefe4602312015-04-08 16:20:35409 }
410
411 visited = []
412 self.FlattenMixins(mixins, vals, visited)
413 return vals
414
415 def FlattenMixins(self, mixins, vals, visited):
416 for m in mixins:
417 if m not in self.mixins:
418 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22419
420 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35421
422 visited.append(m)
423
424 mixin_vals = self.mixins[m]
425 if 'type' in mixin_vals:
426 vals['type'] = mixin_vals['type']
427 if 'gn_args' in mixin_vals:
428 if vals['gn_args']:
429 vals['gn_args'] += ' ' + mixin_vals['gn_args']
430 else:
431 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59432 if 'gyp_crosscompile' in mixin_vals:
433 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35434 if 'gyp_defines' in mixin_vals:
435 if vals['gyp_defines']:
436 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
437 else:
438 vals['gyp_defines'] = mixin_vals['gyp_defines']
439 if 'mixins' in mixin_vals:
440 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
441 return vals
442
dprankec161aa92015-09-14 20:21:13443 def ClobberIfNeeded(self, vals):
444 path = self.args.path[0]
445 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33446 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13447 needs_clobber = False
448 new_mb_type = vals['type']
449 if self.Exists(build_dir):
450 if self.Exists(mb_type_path):
451 old_mb_type = self.ReadFile(mb_type_path)
452 if old_mb_type != new_mb_type:
453 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
454 (old_mb_type, new_mb_type, path))
455 needs_clobber = True
456 else:
457 # There is no 'mb_type' file in the build directory, so this probably
458 # means that the prior build(s) were not done through mb, and we
459 # have no idea if this was a GYP build or a GN build. Clobber it
460 # to be safe.
461 self.Print("%s/mb_type missing, clobbering to be safe" % path)
462 needs_clobber = True
463
dpranke3cec199c2015-09-22 23:29:02464 if self.args.dryrun:
465 return
466
dprankec161aa92015-09-14 20:21:13467 if needs_clobber:
468 self.RemoveDirectory(build_dir)
469
470 self.MaybeMakeDirectory(build_dir)
471 self.WriteFile(mb_type_path, new_mb_type)
472
Dirk Pranke0fd41bcd2015-06-19 00:05:50473 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34474 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50475
dpranke751516a2015-10-03 01:11:34476 cmd = self.GNCmd('gen', build_dir, vals['gn_args'], extra_args=['--check'])
dpranke74559b52015-06-10 21:20:39477
478 swarming_targets = []
dpranke751516a2015-10-03 01:11:34479 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39480 # We need GN to generate the list of runtime dependencies for
481 # the compile targets listed (one per line) in the file so
482 # we can run them via swarming. We use ninja_to_gn.pyl to convert
483 # the compile targets to the matching GN labels.
484 contents = self.ReadFile(self.args.swarming_targets_file)
485 swarming_targets = contents.splitlines()
dpranke8c2cfd32015-09-17 20:12:33486 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47487 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39488 gn_labels = []
489 for target in swarming_targets:
dprankea55584f12015-07-22 00:52:47490 if not target in gn_isolate_map:
dpranke74559b52015-06-10 21:20:39491 raise MBErr('test target "%s" not found in %s' %
dprankea55584f12015-07-22 00:52:47492 (target, '//testing/buildbot/gn_isolate_map.pyl'))
493 gn_labels.append(gn_isolate_map[target]['label'])
dpranke74559b52015-06-10 21:20:39494
dpranke751516a2015-10-03 01:11:34495 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankec3441d12015-06-23 23:01:35496
497 # Since GN hasn't run yet, the build directory may not even exist.
dpranke751516a2015-10-03 01:11:34498 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
dprankec3441d12015-06-23 23:01:35499
dpranke74559b52015-06-10 21:20:39500 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
501 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
502
dprankefe4602312015-04-08 16:20:35503 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40504 if ret:
505 # If `gn gen` failed, we should exit early rather than trying to
506 # generate isolates. Run() will have already logged any error output.
507 self.Print('GN gen failed: %d' % ret)
508 return ret
dpranke74559b52015-06-10 21:20:39509
510 for target in swarming_targets:
dprankedbdd9d82015-08-12 21:18:18511 if gn_isolate_map[target]['type'] == 'gpu_browser_test':
512 runtime_deps_target = 'browser_tests'
dpranke6abd8652015-08-28 03:21:11513 elif gn_isolate_map[target]['type'] == 'script':
514 # For script targets, the build target is usually a group,
515 # for which gn generates the runtime_deps next to the stamp file
516 # for the label, which lives under the obj/ directory.
517 label = gn_isolate_map[target]['label']
518 runtime_deps_target = 'obj/%s.stamp' % label.replace(':', '/')
dpranke34bd39d2015-06-24 02:36:52519 else:
dprankedbdd9d82015-08-12 21:18:18520 runtime_deps_target = target
dpranke8c2cfd32015-09-17 20:12:33521 if self.platform == 'win32':
dpranke751516a2015-10-03 01:11:34522 deps_path = self.ToAbsPath(build_dir,
dprankedbdd9d82015-08-12 21:18:18523 runtime_deps_target + '.exe.runtime_deps')
524 else:
dpranke751516a2015-10-03 01:11:34525 deps_path = self.ToAbsPath(build_dir,
dprankedbdd9d82015-08-12 21:18:18526 runtime_deps_target + '.runtime_deps')
dpranke74559b52015-06-10 21:20:39527 if not self.Exists(deps_path):
528 raise MBErr('did not generate %s' % deps_path)
529
dprankea55584f12015-07-22 00:52:47530 command, extra_files = self.GetIsolateCommand(target, vals,
531 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30532
533 runtime_deps = self.ReadFile(deps_path).splitlines()
534
dpranke751516a2015-10-03 01:11:34535 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
536 extra_files)
dpranked5b2b9432015-06-23 16:55:30537
dpranke751516a2015-10-03 01:11:34538 return 0
539
540 def RunGNIsolate(self, vals):
541 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
542 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
543
544 build_dir = self.args.path[0]
545 target = self.args.target[0]
546 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
547
548 label = gn_isolate_map[target]['label']
549 ret, out, _ = self.Call(['gn', 'desc', build_dir, label, 'runtime_deps'])
550 if ret:
551 return ret
552
553 runtime_deps = out.splitlines()
554
555 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
556 extra_files)
557
558 ret, _, _ = self.Run([
559 self.executable,
560 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
561 'check',
562 '-i',
563 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
564 '-s',
565 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
566 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30567
dprankefe4602312015-04-08 16:20:35568 return ret
569
dpranke751516a2015-10-03 01:11:34570 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
571 extra_files):
572 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
573 self.WriteFile(isolate_path,
574 pprint.pformat({
575 'variables': {
576 'command': command,
577 'files': sorted(runtime_deps + extra_files),
578 }
579 }) + '\n')
580
581 self.WriteJSON(
582 {
583 'args': [
584 '--isolated',
585 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
586 '--isolate',
587 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
588 ],
589 'dir': self.chromium_src_dir,
590 'version': 1,
591 },
592 isolate_path + 'd.gen.json',
593 )
594
dprankeb218d912015-09-18 19:07:00595 def GNCmd(self, subcommand, path, gn_args='', extra_args=None):
dpranked1fba482015-04-14 20:54:51596 if self.platform == 'linux2':
dpranke8c2cfd32015-09-17 20:12:33597 subdir = 'linux64'
dpranked1fba482015-04-14 20:54:51598 elif self.platform == 'darwin':
dpranke8c2cfd32015-09-17 20:12:33599 subdir = 'mac'
dpranked1fba482015-04-14 20:54:51600 else:
dpranke8c2cfd32015-09-17 20:12:33601 subdir = 'win'
602 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, 'gn')
dpranked1fba482015-04-14 20:54:51603
604 cmd = [gn_path, subcommand, path]
dprankeee5b51f62015-04-09 00:03:22605 gn_args = gn_args.replace("$(goma_dir)", self.args.goma_dir)
dprankefe4602312015-04-08 16:20:35606 if gn_args:
607 cmd.append('--args=%s' % gn_args)
dprankeb218d912015-09-18 19:07:00608 if extra_args:
609 cmd.extend(extra_args)
dprankefe4602312015-04-08 16:20:35610 return cmd
611
Dirk Pranke0fd41bcd2015-06-19 00:05:50612 def RunGYPGen(self, vals):
613 path = self.args.path[0]
614
dpranke8c2cfd32015-09-17 20:12:33615 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41616 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59617 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35618 return ret
619
620 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33621 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32622 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:16623 inp = self.ReadInputJSON(['files', 'test_targets',
624 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32625 self.Print()
626 self.Print('analyze input:')
627 self.PrintJSON(inp)
628 self.Print()
629
dpranke38f4acb62015-09-29 23:50:41630 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33631 cmd.extend(['-f', 'analyzer',
632 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35633 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02634 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32635 if not ret and self.args.verbose:
636 outp = json.loads(self.ReadFile(self.args.output_path[0]))
637 self.Print()
638 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39639 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32640 self.Print()
641
dprankefe4602312015-04-08 16:20:35642 return ret
643
dprankea55584f12015-07-22 00:52:47644 def GetIsolateCommand(self, target, vals, gn_isolate_map):
dpranked8113582015-06-05 20:08:25645 # This needs to mirror the settings in //build/config/ui.gni:
646 # use_x11 = is_linux && !use_ozone.
647 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33648 use_x11 = (self.platform == 'linux2' and
dpranked8113582015-06-05 20:08:25649 not 'target_os="android"' in vals['gn_args'] and
650 not 'use_ozone=true' in vals['gn_args'])
651
652 asan = 'is_asan=true' in vals['gn_args']
653 msan = 'is_msan=true' in vals['gn_args']
654 tsan = 'is_tsan=true' in vals['gn_args']
655
dpranke8c2cfd32015-09-17 20:12:33656 executable_suffix = '.exe' if self.platform == 'win32' else ''
dpranked8113582015-06-05 20:08:25657
dprankea55584f12015-07-22 00:52:47658 test_type = gn_isolate_map[target]['type']
659 cmdline = []
660 extra_files = []
dpranked8113582015-06-05 20:08:25661
dprankea55584f12015-07-22 00:52:47662 if use_x11 and test_type == 'windowed_test_launcher':
663 extra_files = [
664 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25665 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47666 '../../testing/xvfb.py',
667 ]
668 cmdline = [
669 '../../testing/xvfb.py',
670 '.',
671 './' + str(target),
672 '--brave-new-test-launcher',
673 '--test-launcher-bot-mode',
674 '--asan=%d' % asan,
675 '--msan=%d' % msan,
676 '--tsan=%d' % tsan,
677 ]
678 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
679 extra_files = [
680 '../../testing/test_env.py'
681 ]
682 cmdline = [
683 '../../testing/test_env.py',
dpranked8113582015-06-05 20:08:25684 './' + str(target) + executable_suffix,
685 '--brave-new-test-launcher',
686 '--test-launcher-bot-mode',
687 '--asan=%d' % asan,
688 '--msan=%d' % msan,
689 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47690 ]
dprankedbdd9d82015-08-12 21:18:18691 elif test_type == 'gpu_browser_test':
692 extra_files = [
693 '../../testing/test_env.py'
694 ]
695 gtest_filter = gn_isolate_map[target]['gtest_filter']
696 cmdline = [
697 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:11698 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:18699 '--test-launcher-bot-mode',
700 '--enable-gpu',
701 '--test-launcher-jobs=1',
702 '--gtest_filter=%s' % gtest_filter,
703 ]
dpranke6abd8652015-08-28 03:21:11704 elif test_type == 'script':
705 extra_files = [
706 '../../testing/test_env.py'
707 ]
708 cmdline = [
709 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:39710 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
711 ] + gn_isolate_map[target].get('args', [])
dprankea55584f12015-07-22 00:52:47712 elif test_type in ('raw'):
713 extra_files = []
714 cmdline = [
715 './' + str(target) + executable_suffix,
716 ] + gn_isolate_map[target].get('args')
dpranked8113582015-06-05 20:08:25717
dprankea55584f12015-07-22 00:52:47718 else:
719 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
720 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25721
722 return cmdline, extra_files
723
dpranke74559b52015-06-10 21:20:39724 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33725 return self.PathJoin(self.chromium_src_dir,
726 self.ToSrcRelPath(build_path),
727 *comps)
dpranked8113582015-06-05 20:08:25728
dprankeee5b51f62015-04-09 00:03:22729 def ToSrcRelPath(self, path):
730 """Returns a relative path from the top of the repo."""
731 # TODO: Support normal paths in addition to source-absolute paths.
dprankefe4602312015-04-08 16:20:35732 assert(path.startswith('//'))
dpranke8c2cfd32015-09-17 20:12:33733 return path[2:].replace('/', self.sep)
dprankefe4602312015-04-08 16:20:35734
735 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:22736 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:33737 output_dir, _, _ = rpath.rpartition(self.sep)
738 return output_dir
dprankefe4602312015-04-08 16:20:35739
dpranke38f4acb62015-09-29 23:50:41740 def GYPCmd(self, output_dir, vals):
741 gyp_defines = vals['gyp_defines']
dpranke3cec199c2015-09-22 23:29:02742 goma_dir = self.args.goma_dir
743
744 # GYP uses shlex.split() to split the gyp defines into separate arguments,
745 # so we can support backslashes and and spaces in arguments by quoting
746 # them, even on Windows, where this normally wouldn't work.
747 if '\\' in goma_dir or ' ' in goma_dir:
748 goma_dir = "'%s'" % goma_dir
749 gyp_defines = gyp_defines.replace("$(goma_dir)", goma_dir)
750
dprankefe4602312015-04-08 16:20:35751 cmd = [
dpranke8c2cfd32015-09-17 20:12:33752 self.executable,
753 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:35754 '-G',
755 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:35756 ]
dpranke38f4acb62015-09-29 23:50:41757
758 # Ensure that we have an environment that only contains
759 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:02760 env = os.environ.copy()
dpranke38f4acb62015-09-29 23:50:41761 if 'GYP_CHROMIUM_NO_ACTION' in env:
762 del env['GYP_CHROMIUM_NO_ACTION']
763 if 'GYP_CROSSCOMPILE' in env:
764 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:02765 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:41766 if vals['gyp_crosscompile']:
767 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:02768 return cmd, env
dprankefe4602312015-04-08 16:20:35769
Dirk Pranke0fd41bcd2015-06-19 00:05:50770 def RunGNAnalyze(self, vals):
771 # analyze runs before 'gn gen' now, so we need to run gn gen
772 # in order to ensure that we have a build directory.
773 ret = self.RunGNGen(vals)
774 if ret:
775 return ret
776
dpranke7837fc362015-11-19 03:54:16777 inp = self.ReadInputJSON(['files', 'test_targets',
778 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32779 if self.args.verbose:
780 self.Print()
781 self.Print('analyze input:')
782 self.PrintJSON(inp)
783 self.Print()
784
dpranke7837fc362015-11-19 03:54:16785 # TODO(crbug.com/555273) - currently GN treats targets and
786 # additional_compile_targets identically since we can't tell the
787 # difference between a target that is a group in GN and one that isn't.
788 # We should eventually fix this and treat the two types differently.
789 targets = (set(inp['test_targets']) |
790 set(inp['additional_compile_targets']))
dpranke5ab84a502015-11-13 17:35:02791
dprankecda00332015-04-11 04:18:32792 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35793
794 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:02795 # what to do about it. Also, bail out early if 'all' was asked for,
796 # since we can't deal with it yet.
797 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
798 'all' in targets):
dpranke7837fc362015-11-19 03:54:16799 self.WriteJSON({
800 'status': 'Found dependency (all)',
801 'compile_targets': sorted(targets),
802 'test_targets': sorted(targets & set(inp['test_targets'])),
803 }, output_path)
dpranke76734662015-04-16 02:17:50804 return 0
805
dpranke7c5f614d2015-07-22 23:43:39806 # This shouldn't normally happen, but could due to unusual race conditions,
807 # like a try job that gets scheduled before a patch lands but runs after
808 # the patch has landed.
809 if not inp['files']:
810 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:16811 self.WriteJSON({
812 'status': 'No dependency',
813 'compile_targets': [],
814 'test_targets': [],
815 }, output_path)
dpranke7c5f614d2015-07-22 23:43:39816 return 0
817
Dirk Pranke12ee2db2015-04-14 23:15:32818 ret = 0
dprankef61de2f2015-05-14 04:09:56819 response_file = self.TempFile()
820 response_file.write('\n'.join(inp['files']) + '\n')
821 response_file.close()
822
dpranke5ab84a502015-11-13 17:35:02823 matching_targets = set()
dprankef61de2f2015-05-14 04:09:56824 try:
dpranked1fba482015-04-14 20:54:51825 cmd = self.GNCmd('refs', self.args.path[0]) + [
dpranke067d0142015-05-14 22:52:45826 '@%s' % response_file.name, '--all', '--as=output']
dprankee0547cd2015-09-15 01:27:40827 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:12828 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:32829 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
830 output_path)
dpranke8c2cfd32015-09-17 20:12:33831 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:56832 for output in out.splitlines():
833 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:02834 if build_output in targets:
835 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:45836
837 cmd = self.GNCmd('refs', self.args.path[0]) + [
838 '@%s' % response_file.name, '--all']
dprankee0547cd2015-09-15 01:27:40839 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:45840 if ret and not 'The input matches no targets' in out:
841 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
842 output_path)
843 for label in out.splitlines():
844 build_target = label[2:]
newt309af8f2015-08-25 22:10:20845 # We want to accept 'chrome/android:chrome_public_apk' and
846 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:45847 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:02848 for input_target in targets:
dpranke067d0142015-05-14 22:52:45849 if (input_target == build_target or
850 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:02851 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:56852 finally:
853 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:35854
dprankef61de2f2015-05-14 04:09:56855 if matching_targets:
dpranke7837fc362015-11-19 03:54:16856 self.WriteJSON({
dpranke5ab84a502015-11-13 17:35:02857 'status': 'Found dependency',
dpranke7837fc362015-11-19 03:54:16858 'compile_targets': sorted(matching_targets),
859 'test_targets': sorted(matching_targets &
860 set(inp['test_targets'])),
861 }, output_path)
dprankefe4602312015-04-08 16:20:35862 else:
dpranke7837fc362015-11-19 03:54:16863 self.WriteJSON({
864 'status': 'No dependency',
865 'compile_targets': [],
866 'test_targets': [],
867 }, output_path)
dprankecda00332015-04-11 04:18:32868
dprankee0547cd2015-09-15 01:27:40869 if self.args.verbose:
dprankecda00332015-04-11 04:18:32870 outp = json.loads(self.ReadFile(output_path))
871 self.Print()
872 self.Print('analyze output:')
873 self.PrintJSON(outp)
874 self.Print()
dprankefe4602312015-04-08 16:20:35875
876 return 0
877
dpranked8113582015-06-05 20:08:25878 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:35879 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:32880 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35881 if not self.Exists(path):
dprankecda00332015-04-11 04:18:32882 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:35883
884 try:
885 inp = json.loads(self.ReadFile(path))
886 except Exception as e:
887 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:32888 (path, e), output_path)
dpranked8113582015-06-05 20:08:25889
890 for k in required_keys:
891 if not k in inp:
892 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
893 output_path)
dprankefe4602312015-04-08 16:20:35894
895 return inp
896
dpranked5b2b9432015-06-23 16:55:30897 def WriteFailureAndRaise(self, msg, output_path):
898 if output_path:
dprankee0547cd2015-09-15 01:27:40899 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:35900 raise MBErr(msg)
901
dprankee0547cd2015-09-15 01:27:40902 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:32903 try:
dprankee0547cd2015-09-15 01:27:40904 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
905 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:32906 except Exception as e:
907 raise MBErr('Error %s writing to the output path "%s"' %
908 (e, path))
dprankefe4602312015-04-08 16:20:35909
dpranke3cec199c2015-09-22 23:29:02910 def PrintCmd(self, cmd, env):
911 if self.platform == 'win32':
912 env_prefix = 'set '
913 env_quoter = QuoteForSet
914 shell_quoter = QuoteForCmd
915 else:
916 env_prefix = ''
917 env_quoter = pipes.quote
918 shell_quoter = pipes.quote
919
920 def print_env(var):
921 if env and var in env:
922 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
923
924 print_env('GYP_CROSSCOMPILE')
925 print_env('GYP_DEFINES')
926
dpranke8c2cfd32015-09-17 20:12:33927 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:35928 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:02929 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:35930
dprankecda00332015-04-11 04:18:32931 def PrintJSON(self, obj):
932 self.Print(json.dumps(obj, indent=2, sort_keys=True))
933
dprankefe4602312015-04-08 16:20:35934 def Print(self, *args, **kwargs):
935 # This function largely exists so it can be overridden for testing.
936 print(*args, **kwargs)
937
dpranke751516a2015-10-03 01:11:34938 def Build(self, target):
939 build_dir = self.ToSrcRelPath(self.args.path[0])
940 ninja_cmd = ['ninja', '-C', build_dir]
941 if self.args.jobs:
942 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
943 ninja_cmd.append(target)
944 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
945 return ret
946
947 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:35948 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:40949 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:02950 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:35951 if self.args.dryrun:
952 return 0, '', ''
dprankee0547cd2015-09-15 01:27:40953
dpranke751516a2015-10-03 01:11:34954 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:40955 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:34956 if ret:
957 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:35958 if out:
dprankeee5b51f62015-04-09 00:03:22959 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:35960 if err:
dprankeee5b51f62015-04-09 00:03:22961 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:35962 return ret, out, err
963
dpranke751516a2015-10-03 01:11:34964 def Call(self, cmd, env=None, buffer_output=True):
965 if buffer_output:
966 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
967 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
968 env=env)
969 out, err = p.communicate()
970 else:
971 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
972 env=env)
973 p.wait()
974 out = err = ''
dprankefe4602312015-04-08 16:20:35975 return p.returncode, out, err
976
977 def ExpandUser(self, path):
978 # This function largely exists so it can be overridden for testing.
979 return os.path.expanduser(path)
980
981 def Exists(self, path):
982 # This function largely exists so it can be overridden for testing.
983 return os.path.exists(path)
984
dprankec3441d12015-06-23 23:01:35985 def MaybeMakeDirectory(self, path):
986 try:
987 os.makedirs(path)
988 except OSError, e:
989 if e.errno != errno.EEXIST:
990 raise
991
dpranke8c2cfd32015-09-17 20:12:33992 def PathJoin(self, *comps):
993 # This function largely exists so it can be overriden for testing.
994 return os.path.join(*comps)
995
dprankefe4602312015-04-08 16:20:35996 def ReadFile(self, path):
997 # This function largely exists so it can be overriden for testing.
998 with open(path) as fp:
999 return fp.read()
1000
dprankef61de2f2015-05-14 04:09:561001 def RemoveFile(self, path):
1002 # This function largely exists so it can be overriden for testing.
1003 os.remove(path)
1004
dprankec161aa92015-09-14 20:21:131005 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331006 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131007 # In other places in chromium, we often have to retry this command
1008 # because we're worried about other processes still holding on to
1009 # file handles, but when MB is invoked, it will be early enough in the
1010 # build that their should be no other processes to interfere. We
1011 # can change this if need be.
1012 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1013 else:
1014 shutil.rmtree(abs_path, ignore_errors=True)
1015
dprankef61de2f2015-05-14 04:09:561016 def TempFile(self, mode='w'):
1017 # This function largely exists so it can be overriden for testing.
1018 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1019
dprankee0547cd2015-09-15 01:27:401020 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351021 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401022 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301023 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351024 with open(path, 'w') as fp:
1025 return fp.write(contents)
1026
dprankef61de2f2015-05-14 04:09:561027
dprankefe4602312015-04-08 16:20:351028class MBErr(Exception):
1029 pass
1030
1031
dpranke3cec199c2015-09-22 23:29:021032# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1033# details of this next section, which handles escaping command lines
1034# so that they can be copied and pasted into a cmd window.
1035UNSAFE_FOR_SET = set('^<>&|')
1036UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1037ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1038
1039
1040def QuoteForSet(arg):
1041 if any(a in UNSAFE_FOR_SET for a in arg):
1042 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1043 return arg
1044
1045
1046def QuoteForCmd(arg):
1047 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1048 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1049 if arg == '' or ' ' in arg or '"' in arg:
1050 quote_re = re.compile(r'(\\*)"')
1051 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1052
1053 # Then check to see if the arg contains any metacharacters other than
1054 # double quotes; if it does, quote everything (including the double
1055 # quotes) for safety.
1056 if any(a in UNSAFE_FOR_CMD for a in arg):
1057 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1058 return arg
1059
1060
dprankefe4602312015-04-08 16:20:351061if __name__ == '__main__':
1062 try:
1063 sys.exit(main(sys.argv[1:]))
1064 except MBErr as e:
1065 print(e)
1066 sys.exit(1)
1067 except KeyboardInterrupt:
1068 print("interrupted, exiting", stream=sys.stderr)
1069 sys.exit(130)