blob: 3ec07230368b8fe9b81fcb6303e632c15f106c06 [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):
dprankee0f486f2015-11-19 23:42:00347 vals = self.ReadBotConfig()
348 if not vals:
349 self.ReadConfigFile()
350 config = self.ConfigFromArgs()
351 if not config in self.configs:
352 raise MBErr('Config "%s" not found in %s' %
353 (config, self.args.config_file))
dprankefe4602312015-04-08 16:20:35354
dprankee0f486f2015-11-19 23:42:00355 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34356
357 # Do some basic sanity checking on the config so that we
358 # don't have to do this in every caller.
359 assert 'type' in vals, 'No meta-build type specified in the config'
360 assert vals['type'] in ('gn', 'gyp'), (
361 'Unknown meta-build type "%s"' % vals['gn_args'])
362
363 return vals
dprankefe4602312015-04-08 16:20:35364
dprankee0f486f2015-11-19 23:42:00365 def ReadBotConfig(self):
366 if not self.args.master or not self.args.builder:
367 return {}
368 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
369 self.args.master, self.args.builder + '.json')
370 if not self.Exists(path):
371 return {}
372
373 contents = json.loads(self.ReadFile(path))
374 gyp_vals = contents.get('GYP_DEFINES', {})
375 if isinstance(gyp_vals, dict):
376 gyp_defines = ' '.join('%s=%s' % (k, v) for k, v in gyp_vals.items())
377 else:
378 gyp_defines = ' '.join(gyp_vals)
379 gn_args = ' '.join(contents.get('gn_args', []))
380
381 return {
382 'type': contents.get('mb_type', ''),
383 'gn_args': gn_args,
384 'gyp_defines': gyp_defines,
dprankef75a3de52015-12-14 22:17:52385 'gyp_crosscompile': False,
dprankee0f486f2015-11-19 23:42:00386 }
387
dprankefe4602312015-04-08 16:20:35388 def ReadConfigFile(self):
389 if not self.Exists(self.args.config_file):
390 raise MBErr('config file not found at %s' % self.args.config_file)
391
392 try:
393 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
394 except SyntaxError as e:
395 raise MBErr('Failed to parse config file "%s": %s' %
396 (self.args.config_file, e))
397
398 self.common_dev_configs = contents['common_dev_configs']
399 self.configs = contents['configs']
400 self.masters = contents['masters']
401 self.mixins = contents['mixins']
402 self.private_configs = contents['private_configs']
403 self.unsupported_configs = contents['unsupported_configs']
404
405 def ConfigFromArgs(self):
406 if self.args.config:
407 if self.args.master or self.args.builder:
408 raise MBErr('Can not specific both -c/--config and -m/--master or '
409 '-b/--builder')
410
411 return self.args.config
412
413 if not self.args.master or not self.args.builder:
414 raise MBErr('Must specify either -c/--config or '
415 '(-m/--master and -b/--builder)')
416
417 if not self.args.master in self.masters:
418 raise MBErr('Master name "%s" not found in "%s"' %
419 (self.args.master, self.args.config_file))
420
421 if not self.args.builder in self.masters[self.args.master]:
422 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
423 (self.args.builder, self.args.master, self.args.config_file))
424
425 return self.masters[self.args.master][self.args.builder]
426
427 def FlattenConfig(self, config):
428 mixins = self.configs[config]
429 vals = {
430 'type': None,
431 'gn_args': [],
dprankec161aa92015-09-14 20:21:13432 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59433 'gyp_crosscompile': False,
dprankefe4602312015-04-08 16:20:35434 }
435
436 visited = []
437 self.FlattenMixins(mixins, vals, visited)
438 return vals
439
440 def FlattenMixins(self, mixins, vals, visited):
441 for m in mixins:
442 if m not in self.mixins:
443 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22444
445 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35446
447 visited.append(m)
448
449 mixin_vals = self.mixins[m]
450 if 'type' in mixin_vals:
451 vals['type'] = mixin_vals['type']
452 if 'gn_args' in mixin_vals:
453 if vals['gn_args']:
454 vals['gn_args'] += ' ' + mixin_vals['gn_args']
455 else:
456 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59457 if 'gyp_crosscompile' in mixin_vals:
458 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35459 if 'gyp_defines' in mixin_vals:
460 if vals['gyp_defines']:
461 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
462 else:
463 vals['gyp_defines'] = mixin_vals['gyp_defines']
464 if 'mixins' in mixin_vals:
465 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
466 return vals
467
dprankec161aa92015-09-14 20:21:13468 def ClobberIfNeeded(self, vals):
469 path = self.args.path[0]
470 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33471 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13472 needs_clobber = False
473 new_mb_type = vals['type']
474 if self.Exists(build_dir):
475 if self.Exists(mb_type_path):
476 old_mb_type = self.ReadFile(mb_type_path)
477 if old_mb_type != new_mb_type:
478 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
479 (old_mb_type, new_mb_type, path))
480 needs_clobber = True
481 else:
482 # There is no 'mb_type' file in the build directory, so this probably
483 # means that the prior build(s) were not done through mb, and we
484 # have no idea if this was a GYP build or a GN build. Clobber it
485 # to be safe.
486 self.Print("%s/mb_type missing, clobbering to be safe" % path)
487 needs_clobber = True
488
dpranke3cec199c2015-09-22 23:29:02489 if self.args.dryrun:
490 return
491
dprankec161aa92015-09-14 20:21:13492 if needs_clobber:
493 self.RemoveDirectory(build_dir)
494
495 self.MaybeMakeDirectory(build_dir)
496 self.WriteFile(mb_type_path, new_mb_type)
497
Dirk Pranke0fd41bcd2015-06-19 00:05:50498 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34499 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50500
dpranke751516a2015-10-03 01:11:34501 cmd = self.GNCmd('gen', build_dir, vals['gn_args'], extra_args=['--check'])
dpranke74559b52015-06-10 21:20:39502
503 swarming_targets = []
dpranke751516a2015-10-03 01:11:34504 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39505 # We need GN to generate the list of runtime dependencies for
506 # the compile targets listed (one per line) in the file so
507 # we can run them via swarming. We use ninja_to_gn.pyl to convert
508 # the compile targets to the matching GN labels.
509 contents = self.ReadFile(self.args.swarming_targets_file)
510 swarming_targets = contents.splitlines()
dpranke8c2cfd32015-09-17 20:12:33511 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47512 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39513 gn_labels = []
514 for target in swarming_targets:
dprankea55584f12015-07-22 00:52:47515 if not target in gn_isolate_map:
dpranke74559b52015-06-10 21:20:39516 raise MBErr('test target "%s" not found in %s' %
dprankea55584f12015-07-22 00:52:47517 (target, '//testing/buildbot/gn_isolate_map.pyl'))
518 gn_labels.append(gn_isolate_map[target]['label'])
dpranke74559b52015-06-10 21:20:39519
dpranke751516a2015-10-03 01:11:34520 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankec3441d12015-06-23 23:01:35521
522 # Since GN hasn't run yet, the build directory may not even exist.
dpranke751516a2015-10-03 01:11:34523 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
dprankec3441d12015-06-23 23:01:35524
dpranke74559b52015-06-10 21:20:39525 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
526 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
527
dprankefe4602312015-04-08 16:20:35528 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40529 if ret:
530 # If `gn gen` failed, we should exit early rather than trying to
531 # generate isolates. Run() will have already logged any error output.
532 self.Print('GN gen failed: %d' % ret)
533 return ret
dpranke74559b52015-06-10 21:20:39534
535 for target in swarming_targets:
dprankedbdd9d82015-08-12 21:18:18536 if gn_isolate_map[target]['type'] == 'gpu_browser_test':
537 runtime_deps_target = 'browser_tests'
dpranke6abd8652015-08-28 03:21:11538 elif gn_isolate_map[target]['type'] == 'script':
539 # For script targets, the build target is usually a group,
540 # for which gn generates the runtime_deps next to the stamp file
541 # for the label, which lives under the obj/ directory.
542 label = gn_isolate_map[target]['label']
543 runtime_deps_target = 'obj/%s.stamp' % label.replace(':', '/')
dpranke34bd39d2015-06-24 02:36:52544 else:
dprankedbdd9d82015-08-12 21:18:18545 runtime_deps_target = target
dpranke8c2cfd32015-09-17 20:12:33546 if self.platform == 'win32':
dpranke751516a2015-10-03 01:11:34547 deps_path = self.ToAbsPath(build_dir,
dprankedbdd9d82015-08-12 21:18:18548 runtime_deps_target + '.exe.runtime_deps')
549 else:
dpranke751516a2015-10-03 01:11:34550 deps_path = self.ToAbsPath(build_dir,
dprankedbdd9d82015-08-12 21:18:18551 runtime_deps_target + '.runtime_deps')
dpranke74559b52015-06-10 21:20:39552 if not self.Exists(deps_path):
553 raise MBErr('did not generate %s' % deps_path)
554
dprankea55584f12015-07-22 00:52:47555 command, extra_files = self.GetIsolateCommand(target, vals,
556 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30557
558 runtime_deps = self.ReadFile(deps_path).splitlines()
559
dpranke751516a2015-10-03 01:11:34560 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
561 extra_files)
dpranked5b2b9432015-06-23 16:55:30562
dpranke751516a2015-10-03 01:11:34563 return 0
564
565 def RunGNIsolate(self, vals):
566 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
567 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
568
569 build_dir = self.args.path[0]
570 target = self.args.target[0]
571 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
572
573 label = gn_isolate_map[target]['label']
574 ret, out, _ = self.Call(['gn', 'desc', build_dir, label, 'runtime_deps'])
575 if ret:
576 return ret
577
578 runtime_deps = out.splitlines()
579
580 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
581 extra_files)
582
583 ret, _, _ = self.Run([
584 self.executable,
585 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
586 'check',
587 '-i',
588 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
589 '-s',
590 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
591 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30592
dprankefe4602312015-04-08 16:20:35593 return ret
594
dpranke751516a2015-10-03 01:11:34595 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
596 extra_files):
597 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
598 self.WriteFile(isolate_path,
599 pprint.pformat({
600 'variables': {
601 'command': command,
602 'files': sorted(runtime_deps + extra_files),
603 }
604 }) + '\n')
605
606 self.WriteJSON(
607 {
608 'args': [
609 '--isolated',
610 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
611 '--isolate',
612 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
613 ],
614 'dir': self.chromium_src_dir,
615 'version': 1,
616 },
617 isolate_path + 'd.gen.json',
618 )
619
dprankeb218d912015-09-18 19:07:00620 def GNCmd(self, subcommand, path, gn_args='', extra_args=None):
dpranked1fba482015-04-14 20:54:51621 if self.platform == 'linux2':
dpranke8c2cfd32015-09-17 20:12:33622 subdir = 'linux64'
dpranked1fba482015-04-14 20:54:51623 elif self.platform == 'darwin':
dpranke8c2cfd32015-09-17 20:12:33624 subdir = 'mac'
dpranked1fba482015-04-14 20:54:51625 else:
dpranke8c2cfd32015-09-17 20:12:33626 subdir = 'win'
627 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, 'gn')
dpranked1fba482015-04-14 20:54:51628
629 cmd = [gn_path, subcommand, path]
dprankeee5b51f62015-04-09 00:03:22630 gn_args = gn_args.replace("$(goma_dir)", self.args.goma_dir)
dprankefe4602312015-04-08 16:20:35631 if gn_args:
632 cmd.append('--args=%s' % gn_args)
dprankeb218d912015-09-18 19:07:00633 if extra_args:
634 cmd.extend(extra_args)
dprankefe4602312015-04-08 16:20:35635 return cmd
636
Dirk Pranke0fd41bcd2015-06-19 00:05:50637 def RunGYPGen(self, vals):
638 path = self.args.path[0]
639
dpranke8c2cfd32015-09-17 20:12:33640 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41641 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59642 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35643 return ret
644
645 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33646 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32647 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:16648 inp = self.ReadInputJSON(['files', 'test_targets',
649 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32650 self.Print()
651 self.Print('analyze input:')
652 self.PrintJSON(inp)
653 self.Print()
654
dpranke38f4acb62015-09-29 23:50:41655 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33656 cmd.extend(['-f', 'analyzer',
657 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35658 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02659 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32660 if not ret and self.args.verbose:
661 outp = json.loads(self.ReadFile(self.args.output_path[0]))
662 self.Print()
663 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39664 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32665 self.Print()
666
dprankefe4602312015-04-08 16:20:35667 return ret
668
dprankea55584f12015-07-22 00:52:47669 def GetIsolateCommand(self, target, vals, gn_isolate_map):
dpranked8113582015-06-05 20:08:25670 # This needs to mirror the settings in //build/config/ui.gni:
671 # use_x11 = is_linux && !use_ozone.
672 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33673 use_x11 = (self.platform == 'linux2' and
dpranked8113582015-06-05 20:08:25674 not 'target_os="android"' in vals['gn_args'] and
675 not 'use_ozone=true' in vals['gn_args'])
676
677 asan = 'is_asan=true' in vals['gn_args']
678 msan = 'is_msan=true' in vals['gn_args']
679 tsan = 'is_tsan=true' in vals['gn_args']
680
dpranke8c2cfd32015-09-17 20:12:33681 executable_suffix = '.exe' if self.platform == 'win32' else ''
dpranked8113582015-06-05 20:08:25682
dprankea55584f12015-07-22 00:52:47683 test_type = gn_isolate_map[target]['type']
684 cmdline = []
685 extra_files = []
dpranked8113582015-06-05 20:08:25686
dprankea55584f12015-07-22 00:52:47687 if use_x11 and test_type == 'windowed_test_launcher':
688 extra_files = [
689 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25690 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47691 '../../testing/xvfb.py',
692 ]
693 cmdline = [
694 '../../testing/xvfb.py',
695 '.',
696 './' + str(target),
697 '--brave-new-test-launcher',
698 '--test-launcher-bot-mode',
699 '--asan=%d' % asan,
700 '--msan=%d' % msan,
701 '--tsan=%d' % tsan,
702 ]
703 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
704 extra_files = [
705 '../../testing/test_env.py'
706 ]
707 cmdline = [
708 '../../testing/test_env.py',
dpranked8113582015-06-05 20:08:25709 './' + str(target) + executable_suffix,
710 '--brave-new-test-launcher',
711 '--test-launcher-bot-mode',
712 '--asan=%d' % asan,
713 '--msan=%d' % msan,
714 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47715 ]
dprankedbdd9d82015-08-12 21:18:18716 elif test_type == 'gpu_browser_test':
717 extra_files = [
718 '../../testing/test_env.py'
719 ]
720 gtest_filter = gn_isolate_map[target]['gtest_filter']
721 cmdline = [
722 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:11723 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:18724 '--test-launcher-bot-mode',
725 '--enable-gpu',
726 '--test-launcher-jobs=1',
727 '--gtest_filter=%s' % gtest_filter,
728 ]
dpranke6abd8652015-08-28 03:21:11729 elif test_type == 'script':
730 extra_files = [
731 '../../testing/test_env.py'
732 ]
733 cmdline = [
734 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:39735 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
736 ] + gn_isolate_map[target].get('args', [])
dprankea55584f12015-07-22 00:52:47737 elif test_type in ('raw'):
738 extra_files = []
739 cmdline = [
740 './' + str(target) + executable_suffix,
741 ] + gn_isolate_map[target].get('args')
dpranked8113582015-06-05 20:08:25742
dprankea55584f12015-07-22 00:52:47743 else:
744 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
745 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25746
747 return cmdline, extra_files
748
dpranke74559b52015-06-10 21:20:39749 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33750 return self.PathJoin(self.chromium_src_dir,
751 self.ToSrcRelPath(build_path),
752 *comps)
dpranked8113582015-06-05 20:08:25753
dprankeee5b51f62015-04-09 00:03:22754 def ToSrcRelPath(self, path):
755 """Returns a relative path from the top of the repo."""
756 # TODO: Support normal paths in addition to source-absolute paths.
dprankefe4602312015-04-08 16:20:35757 assert(path.startswith('//'))
dpranke8c2cfd32015-09-17 20:12:33758 return path[2:].replace('/', self.sep)
dprankefe4602312015-04-08 16:20:35759
760 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:22761 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:33762 output_dir, _, _ = rpath.rpartition(self.sep)
763 return output_dir
dprankefe4602312015-04-08 16:20:35764
dpranke38f4acb62015-09-29 23:50:41765 def GYPCmd(self, output_dir, vals):
766 gyp_defines = vals['gyp_defines']
dpranke3cec199c2015-09-22 23:29:02767 goma_dir = self.args.goma_dir
768
769 # GYP uses shlex.split() to split the gyp defines into separate arguments,
770 # so we can support backslashes and and spaces in arguments by quoting
771 # them, even on Windows, where this normally wouldn't work.
772 if '\\' in goma_dir or ' ' in goma_dir:
773 goma_dir = "'%s'" % goma_dir
774 gyp_defines = gyp_defines.replace("$(goma_dir)", goma_dir)
775
dprankefe4602312015-04-08 16:20:35776 cmd = [
dpranke8c2cfd32015-09-17 20:12:33777 self.executable,
778 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:35779 '-G',
780 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:35781 ]
dpranke38f4acb62015-09-29 23:50:41782
783 # Ensure that we have an environment that only contains
784 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:02785 env = os.environ.copy()
dprankef75a3de52015-12-14 22:17:52786 env['GYP_GENERATORS'] = 'ninja'
dpranke38f4acb62015-09-29 23:50:41787 if 'GYP_CHROMIUM_NO_ACTION' in env:
788 del env['GYP_CHROMIUM_NO_ACTION']
789 if 'GYP_CROSSCOMPILE' in env:
790 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:02791 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:41792 if vals['gyp_crosscompile']:
793 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:02794 return cmd, env
dprankefe4602312015-04-08 16:20:35795
Dirk Pranke0fd41bcd2015-06-19 00:05:50796 def RunGNAnalyze(self, vals):
797 # analyze runs before 'gn gen' now, so we need to run gn gen
798 # in order to ensure that we have a build directory.
799 ret = self.RunGNGen(vals)
800 if ret:
801 return ret
802
dpranke7837fc362015-11-19 03:54:16803 inp = self.ReadInputJSON(['files', 'test_targets',
804 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32805 if self.args.verbose:
806 self.Print()
807 self.Print('analyze input:')
808 self.PrintJSON(inp)
809 self.Print()
810
dpranke7837fc362015-11-19 03:54:16811 # TODO(crbug.com/555273) - currently GN treats targets and
812 # additional_compile_targets identically since we can't tell the
813 # difference between a target that is a group in GN and one that isn't.
814 # We should eventually fix this and treat the two types differently.
815 targets = (set(inp['test_targets']) |
816 set(inp['additional_compile_targets']))
dpranke5ab84a502015-11-13 17:35:02817
dprankecda00332015-04-11 04:18:32818 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35819
820 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:02821 # what to do about it. Also, bail out early if 'all' was asked for,
822 # since we can't deal with it yet.
823 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
824 'all' in targets):
dpranke7837fc362015-11-19 03:54:16825 self.WriteJSON({
826 'status': 'Found dependency (all)',
827 'compile_targets': sorted(targets),
828 'test_targets': sorted(targets & set(inp['test_targets'])),
829 }, output_path)
dpranke76734662015-04-16 02:17:50830 return 0
831
dpranke7c5f614d2015-07-22 23:43:39832 # This shouldn't normally happen, but could due to unusual race conditions,
833 # like a try job that gets scheduled before a patch lands but runs after
834 # the patch has landed.
835 if not inp['files']:
836 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:16837 self.WriteJSON({
838 'status': 'No dependency',
839 'compile_targets': [],
840 'test_targets': [],
841 }, output_path)
dpranke7c5f614d2015-07-22 23:43:39842 return 0
843
Dirk Pranke12ee2db2015-04-14 23:15:32844 ret = 0
dprankef61de2f2015-05-14 04:09:56845 response_file = self.TempFile()
846 response_file.write('\n'.join(inp['files']) + '\n')
847 response_file.close()
848
dpranke5ab84a502015-11-13 17:35:02849 matching_targets = set()
dprankef61de2f2015-05-14 04:09:56850 try:
dpranked1fba482015-04-14 20:54:51851 cmd = self.GNCmd('refs', self.args.path[0]) + [
dpranke067d0142015-05-14 22:52:45852 '@%s' % response_file.name, '--all', '--as=output']
dprankee0547cd2015-09-15 01:27:40853 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:12854 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:32855 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
856 output_path)
dpranke8c2cfd32015-09-17 20:12:33857 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:56858 for output in out.splitlines():
859 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:02860 if build_output in targets:
861 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:45862
863 cmd = self.GNCmd('refs', self.args.path[0]) + [
864 '@%s' % response_file.name, '--all']
dprankee0547cd2015-09-15 01:27:40865 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:45866 if ret and not 'The input matches no targets' in out:
867 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
868 output_path)
869 for label in out.splitlines():
870 build_target = label[2:]
newt309af8f2015-08-25 22:10:20871 # We want to accept 'chrome/android:chrome_public_apk' and
872 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:45873 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:02874 for input_target in targets:
dpranke067d0142015-05-14 22:52:45875 if (input_target == build_target or
876 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:02877 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:56878 finally:
879 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:35880
dprankef61de2f2015-05-14 04:09:56881 if matching_targets:
dpranke7837fc362015-11-19 03:54:16882 self.WriteJSON({
dpranke5ab84a502015-11-13 17:35:02883 'status': 'Found dependency',
dpranke7837fc362015-11-19 03:54:16884 'compile_targets': sorted(matching_targets),
885 'test_targets': sorted(matching_targets &
886 set(inp['test_targets'])),
887 }, output_path)
dprankefe4602312015-04-08 16:20:35888 else:
dpranke7837fc362015-11-19 03:54:16889 self.WriteJSON({
890 'status': 'No dependency',
891 'compile_targets': [],
892 'test_targets': [],
893 }, output_path)
dprankecda00332015-04-11 04:18:32894
dprankee0547cd2015-09-15 01:27:40895 if self.args.verbose:
dprankecda00332015-04-11 04:18:32896 outp = json.loads(self.ReadFile(output_path))
897 self.Print()
898 self.Print('analyze output:')
899 self.PrintJSON(outp)
900 self.Print()
dprankefe4602312015-04-08 16:20:35901
902 return 0
903
dpranked8113582015-06-05 20:08:25904 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:35905 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:32906 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35907 if not self.Exists(path):
dprankecda00332015-04-11 04:18:32908 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:35909
910 try:
911 inp = json.loads(self.ReadFile(path))
912 except Exception as e:
913 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:32914 (path, e), output_path)
dpranked8113582015-06-05 20:08:25915
916 for k in required_keys:
917 if not k in inp:
918 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
919 output_path)
dprankefe4602312015-04-08 16:20:35920
921 return inp
922
dpranked5b2b9432015-06-23 16:55:30923 def WriteFailureAndRaise(self, msg, output_path):
924 if output_path:
dprankee0547cd2015-09-15 01:27:40925 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:35926 raise MBErr(msg)
927
dprankee0547cd2015-09-15 01:27:40928 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:32929 try:
dprankee0547cd2015-09-15 01:27:40930 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
931 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:32932 except Exception as e:
933 raise MBErr('Error %s writing to the output path "%s"' %
934 (e, path))
dprankefe4602312015-04-08 16:20:35935
dpranke3cec199c2015-09-22 23:29:02936 def PrintCmd(self, cmd, env):
937 if self.platform == 'win32':
938 env_prefix = 'set '
939 env_quoter = QuoteForSet
940 shell_quoter = QuoteForCmd
941 else:
942 env_prefix = ''
943 env_quoter = pipes.quote
944 shell_quoter = pipes.quote
945
946 def print_env(var):
947 if env and var in env:
948 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
949
950 print_env('GYP_CROSSCOMPILE')
951 print_env('GYP_DEFINES')
952
dpranke8c2cfd32015-09-17 20:12:33953 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:35954 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:02955 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:35956
dprankecda00332015-04-11 04:18:32957 def PrintJSON(self, obj):
958 self.Print(json.dumps(obj, indent=2, sort_keys=True))
959
dprankefe4602312015-04-08 16:20:35960 def Print(self, *args, **kwargs):
961 # This function largely exists so it can be overridden for testing.
962 print(*args, **kwargs)
963
dpranke751516a2015-10-03 01:11:34964 def Build(self, target):
965 build_dir = self.ToSrcRelPath(self.args.path[0])
966 ninja_cmd = ['ninja', '-C', build_dir]
967 if self.args.jobs:
968 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
969 ninja_cmd.append(target)
970 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
971 return ret
972
973 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:35974 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:40975 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:02976 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:35977 if self.args.dryrun:
978 return 0, '', ''
dprankee0547cd2015-09-15 01:27:40979
dpranke751516a2015-10-03 01:11:34980 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:40981 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:34982 if ret:
983 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:35984 if out:
dprankeee5b51f62015-04-09 00:03:22985 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:35986 if err:
dprankeee5b51f62015-04-09 00:03:22987 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:35988 return ret, out, err
989
dpranke751516a2015-10-03 01:11:34990 def Call(self, cmd, env=None, buffer_output=True):
991 if buffer_output:
992 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
993 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
994 env=env)
995 out, err = p.communicate()
996 else:
997 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
998 env=env)
999 p.wait()
1000 out = err = ''
dprankefe4602312015-04-08 16:20:351001 return p.returncode, out, err
1002
1003 def ExpandUser(self, path):
1004 # This function largely exists so it can be overridden for testing.
1005 return os.path.expanduser(path)
1006
1007 def Exists(self, path):
1008 # This function largely exists so it can be overridden for testing.
1009 return os.path.exists(path)
1010
dprankec3441d12015-06-23 23:01:351011 def MaybeMakeDirectory(self, path):
1012 try:
1013 os.makedirs(path)
1014 except OSError, e:
1015 if e.errno != errno.EEXIST:
1016 raise
1017
dpranke8c2cfd32015-09-17 20:12:331018 def PathJoin(self, *comps):
1019 # This function largely exists so it can be overriden for testing.
1020 return os.path.join(*comps)
1021
dprankefe4602312015-04-08 16:20:351022 def ReadFile(self, path):
1023 # This function largely exists so it can be overriden for testing.
1024 with open(path) as fp:
1025 return fp.read()
1026
dprankef61de2f2015-05-14 04:09:561027 def RemoveFile(self, path):
1028 # This function largely exists so it can be overriden for testing.
1029 os.remove(path)
1030
dprankec161aa92015-09-14 20:21:131031 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331032 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131033 # In other places in chromium, we often have to retry this command
1034 # because we're worried about other processes still holding on to
1035 # file handles, but when MB is invoked, it will be early enough in the
1036 # build that their should be no other processes to interfere. We
1037 # can change this if need be.
1038 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1039 else:
1040 shutil.rmtree(abs_path, ignore_errors=True)
1041
dprankef61de2f2015-05-14 04:09:561042 def TempFile(self, mode='w'):
1043 # This function largely exists so it can be overriden for testing.
1044 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1045
dprankee0547cd2015-09-15 01:27:401046 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351047 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401048 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301049 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351050 with open(path, 'w') as fp:
1051 return fp.write(contents)
1052
dprankef61de2f2015-05-14 04:09:561053
dprankefe4602312015-04-08 16:20:351054class MBErr(Exception):
1055 pass
1056
1057
dpranke3cec199c2015-09-22 23:29:021058# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1059# details of this next section, which handles escaping command lines
1060# so that they can be copied and pasted into a cmd window.
1061UNSAFE_FOR_SET = set('^<>&|')
1062UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1063ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1064
1065
1066def QuoteForSet(arg):
1067 if any(a in UNSAFE_FOR_SET for a in arg):
1068 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1069 return arg
1070
1071
1072def QuoteForCmd(arg):
1073 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1074 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1075 if arg == '' or ' ' in arg or '"' in arg:
1076 quote_re = re.compile(r'(\\*)"')
1077 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1078
1079 # Then check to see if the arg contains any metacharacters other than
1080 # double quotes; if it does, quote everything (including the double
1081 # quotes) for safety.
1082 if any(a in UNSAFE_FOR_CMD for a in arg):
1083 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1084 return arg
1085
1086
dprankefe4602312015-04-08 16:20:351087if __name__ == '__main__':
1088 try:
1089 sys.exit(main(sys.argv[1:]))
1090 except MBErr as e:
1091 print(e)
1092 sys.exit(1)
1093 except KeyboardInterrupt:
1094 print("interrupted, exiting", stream=sys.stderr)
1095 sys.exit(130)