blob: a3fdd61804a0dbf9d7166802fafbd27bde626d1c [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,
385 }
386
dprankefe4602312015-04-08 16:20:35387 def ReadConfigFile(self):
388 if not self.Exists(self.args.config_file):
389 raise MBErr('config file not found at %s' % self.args.config_file)
390
391 try:
392 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
393 except SyntaxError as e:
394 raise MBErr('Failed to parse config file "%s": %s' %
395 (self.args.config_file, e))
396
397 self.common_dev_configs = contents['common_dev_configs']
398 self.configs = contents['configs']
399 self.masters = contents['masters']
400 self.mixins = contents['mixins']
401 self.private_configs = contents['private_configs']
402 self.unsupported_configs = contents['unsupported_configs']
403
404 def ConfigFromArgs(self):
405 if self.args.config:
406 if self.args.master or self.args.builder:
407 raise MBErr('Can not specific both -c/--config and -m/--master or '
408 '-b/--builder')
409
410 return self.args.config
411
412 if not self.args.master or not self.args.builder:
413 raise MBErr('Must specify either -c/--config or '
414 '(-m/--master and -b/--builder)')
415
416 if not self.args.master in self.masters:
417 raise MBErr('Master name "%s" not found in "%s"' %
418 (self.args.master, self.args.config_file))
419
420 if not self.args.builder in self.masters[self.args.master]:
421 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
422 (self.args.builder, self.args.master, self.args.config_file))
423
424 return self.masters[self.args.master][self.args.builder]
425
426 def FlattenConfig(self, config):
427 mixins = self.configs[config]
428 vals = {
429 'type': None,
430 'gn_args': [],
dprankec161aa92015-09-14 20:21:13431 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59432 'gyp_crosscompile': False,
dprankefe4602312015-04-08 16:20:35433 }
434
435 visited = []
436 self.FlattenMixins(mixins, vals, visited)
437 return vals
438
439 def FlattenMixins(self, mixins, vals, visited):
440 for m in mixins:
441 if m not in self.mixins:
442 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22443
444 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35445
446 visited.append(m)
447
448 mixin_vals = self.mixins[m]
449 if 'type' in mixin_vals:
450 vals['type'] = mixin_vals['type']
451 if 'gn_args' in mixin_vals:
452 if vals['gn_args']:
453 vals['gn_args'] += ' ' + mixin_vals['gn_args']
454 else:
455 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59456 if 'gyp_crosscompile' in mixin_vals:
457 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35458 if 'gyp_defines' in mixin_vals:
459 if vals['gyp_defines']:
460 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
461 else:
462 vals['gyp_defines'] = mixin_vals['gyp_defines']
463 if 'mixins' in mixin_vals:
464 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
465 return vals
466
dprankec161aa92015-09-14 20:21:13467 def ClobberIfNeeded(self, vals):
468 path = self.args.path[0]
469 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33470 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13471 needs_clobber = False
472 new_mb_type = vals['type']
473 if self.Exists(build_dir):
474 if self.Exists(mb_type_path):
475 old_mb_type = self.ReadFile(mb_type_path)
476 if old_mb_type != new_mb_type:
477 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
478 (old_mb_type, new_mb_type, path))
479 needs_clobber = True
480 else:
481 # There is no 'mb_type' file in the build directory, so this probably
482 # means that the prior build(s) were not done through mb, and we
483 # have no idea if this was a GYP build or a GN build. Clobber it
484 # to be safe.
485 self.Print("%s/mb_type missing, clobbering to be safe" % path)
486 needs_clobber = True
487
dpranke3cec199c2015-09-22 23:29:02488 if self.args.dryrun:
489 return
490
dprankec161aa92015-09-14 20:21:13491 if needs_clobber:
492 self.RemoveDirectory(build_dir)
493
494 self.MaybeMakeDirectory(build_dir)
495 self.WriteFile(mb_type_path, new_mb_type)
496
Dirk Pranke0fd41bcd2015-06-19 00:05:50497 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34498 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50499
dpranke751516a2015-10-03 01:11:34500 cmd = self.GNCmd('gen', build_dir, vals['gn_args'], extra_args=['--check'])
dpranke74559b52015-06-10 21:20:39501
502 swarming_targets = []
dpranke751516a2015-10-03 01:11:34503 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39504 # We need GN to generate the list of runtime dependencies for
505 # the compile targets listed (one per line) in the file so
506 # we can run them via swarming. We use ninja_to_gn.pyl to convert
507 # the compile targets to the matching GN labels.
508 contents = self.ReadFile(self.args.swarming_targets_file)
509 swarming_targets = contents.splitlines()
dpranke8c2cfd32015-09-17 20:12:33510 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47511 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39512 gn_labels = []
513 for target in swarming_targets:
dprankea55584f12015-07-22 00:52:47514 if not target in gn_isolate_map:
dpranke74559b52015-06-10 21:20:39515 raise MBErr('test target "%s" not found in %s' %
dprankea55584f12015-07-22 00:52:47516 (target, '//testing/buildbot/gn_isolate_map.pyl'))
517 gn_labels.append(gn_isolate_map[target]['label'])
dpranke74559b52015-06-10 21:20:39518
dpranke751516a2015-10-03 01:11:34519 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankec3441d12015-06-23 23:01:35520
521 # Since GN hasn't run yet, the build directory may not even exist.
dpranke751516a2015-10-03 01:11:34522 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
dprankec3441d12015-06-23 23:01:35523
dpranke74559b52015-06-10 21:20:39524 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
525 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
526
dprankefe4602312015-04-08 16:20:35527 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40528 if ret:
529 # If `gn gen` failed, we should exit early rather than trying to
530 # generate isolates. Run() will have already logged any error output.
531 self.Print('GN gen failed: %d' % ret)
532 return ret
dpranke74559b52015-06-10 21:20:39533
534 for target in swarming_targets:
dprankedbdd9d82015-08-12 21:18:18535 if gn_isolate_map[target]['type'] == 'gpu_browser_test':
536 runtime_deps_target = 'browser_tests'
dpranke6abd8652015-08-28 03:21:11537 elif gn_isolate_map[target]['type'] == 'script':
538 # For script targets, the build target is usually a group,
539 # for which gn generates the runtime_deps next to the stamp file
540 # for the label, which lives under the obj/ directory.
541 label = gn_isolate_map[target]['label']
542 runtime_deps_target = 'obj/%s.stamp' % label.replace(':', '/')
dpranke34bd39d2015-06-24 02:36:52543 else:
dprankedbdd9d82015-08-12 21:18:18544 runtime_deps_target = target
dpranke8c2cfd32015-09-17 20:12:33545 if self.platform == 'win32':
dpranke751516a2015-10-03 01:11:34546 deps_path = self.ToAbsPath(build_dir,
dprankedbdd9d82015-08-12 21:18:18547 runtime_deps_target + '.exe.runtime_deps')
548 else:
dpranke751516a2015-10-03 01:11:34549 deps_path = self.ToAbsPath(build_dir,
dprankedbdd9d82015-08-12 21:18:18550 runtime_deps_target + '.runtime_deps')
dpranke74559b52015-06-10 21:20:39551 if not self.Exists(deps_path):
552 raise MBErr('did not generate %s' % deps_path)
553
dprankea55584f12015-07-22 00:52:47554 command, extra_files = self.GetIsolateCommand(target, vals,
555 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30556
557 runtime_deps = self.ReadFile(deps_path).splitlines()
558
dpranke751516a2015-10-03 01:11:34559 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
560 extra_files)
dpranked5b2b9432015-06-23 16:55:30561
dpranke751516a2015-10-03 01:11:34562 return 0
563
564 def RunGNIsolate(self, vals):
565 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
566 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
567
568 build_dir = self.args.path[0]
569 target = self.args.target[0]
570 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
571
572 label = gn_isolate_map[target]['label']
573 ret, out, _ = self.Call(['gn', 'desc', build_dir, label, 'runtime_deps'])
574 if ret:
575 return ret
576
577 runtime_deps = out.splitlines()
578
579 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
580 extra_files)
581
582 ret, _, _ = self.Run([
583 self.executable,
584 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
585 'check',
586 '-i',
587 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
588 '-s',
589 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
590 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30591
dprankefe4602312015-04-08 16:20:35592 return ret
593
dpranke751516a2015-10-03 01:11:34594 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
595 extra_files):
596 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
597 self.WriteFile(isolate_path,
598 pprint.pformat({
599 'variables': {
600 'command': command,
601 'files': sorted(runtime_deps + extra_files),
602 }
603 }) + '\n')
604
605 self.WriteJSON(
606 {
607 'args': [
608 '--isolated',
609 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
610 '--isolate',
611 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
612 ],
613 'dir': self.chromium_src_dir,
614 'version': 1,
615 },
616 isolate_path + 'd.gen.json',
617 )
618
dprankeb218d912015-09-18 19:07:00619 def GNCmd(self, subcommand, path, gn_args='', extra_args=None):
dpranked1fba482015-04-14 20:54:51620 if self.platform == 'linux2':
dpranke8c2cfd32015-09-17 20:12:33621 subdir = 'linux64'
dpranked1fba482015-04-14 20:54:51622 elif self.platform == 'darwin':
dpranke8c2cfd32015-09-17 20:12:33623 subdir = 'mac'
dpranked1fba482015-04-14 20:54:51624 else:
dpranke8c2cfd32015-09-17 20:12:33625 subdir = 'win'
626 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, 'gn')
dpranked1fba482015-04-14 20:54:51627
628 cmd = [gn_path, subcommand, path]
dprankeee5b51f62015-04-09 00:03:22629 gn_args = gn_args.replace("$(goma_dir)", self.args.goma_dir)
dprankefe4602312015-04-08 16:20:35630 if gn_args:
631 cmd.append('--args=%s' % gn_args)
dprankeb218d912015-09-18 19:07:00632 if extra_args:
633 cmd.extend(extra_args)
dprankefe4602312015-04-08 16:20:35634 return cmd
635
Dirk Pranke0fd41bcd2015-06-19 00:05:50636 def RunGYPGen(self, vals):
637 path = self.args.path[0]
638
dpranke8c2cfd32015-09-17 20:12:33639 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41640 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59641 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35642 return ret
643
644 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33645 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32646 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:16647 inp = self.ReadInputJSON(['files', 'test_targets',
648 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32649 self.Print()
650 self.Print('analyze input:')
651 self.PrintJSON(inp)
652 self.Print()
653
dpranke38f4acb62015-09-29 23:50:41654 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33655 cmd.extend(['-f', 'analyzer',
656 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35657 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02658 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32659 if not ret and self.args.verbose:
660 outp = json.loads(self.ReadFile(self.args.output_path[0]))
661 self.Print()
662 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39663 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32664 self.Print()
665
dprankefe4602312015-04-08 16:20:35666 return ret
667
dprankea55584f12015-07-22 00:52:47668 def GetIsolateCommand(self, target, vals, gn_isolate_map):
dpranked8113582015-06-05 20:08:25669 # This needs to mirror the settings in //build/config/ui.gni:
670 # use_x11 = is_linux && !use_ozone.
671 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33672 use_x11 = (self.platform == 'linux2' and
dpranked8113582015-06-05 20:08:25673 not 'target_os="android"' in vals['gn_args'] and
674 not 'use_ozone=true' in vals['gn_args'])
675
676 asan = 'is_asan=true' in vals['gn_args']
677 msan = 'is_msan=true' in vals['gn_args']
678 tsan = 'is_tsan=true' in vals['gn_args']
679
dpranke8c2cfd32015-09-17 20:12:33680 executable_suffix = '.exe' if self.platform == 'win32' else ''
dpranked8113582015-06-05 20:08:25681
dprankea55584f12015-07-22 00:52:47682 test_type = gn_isolate_map[target]['type']
683 cmdline = []
684 extra_files = []
dpranked8113582015-06-05 20:08:25685
dprankea55584f12015-07-22 00:52:47686 if use_x11 and test_type == 'windowed_test_launcher':
687 extra_files = [
688 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25689 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47690 '../../testing/xvfb.py',
691 ]
692 cmdline = [
693 '../../testing/xvfb.py',
694 '.',
695 './' + str(target),
696 '--brave-new-test-launcher',
697 '--test-launcher-bot-mode',
698 '--asan=%d' % asan,
699 '--msan=%d' % msan,
700 '--tsan=%d' % tsan,
701 ]
702 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
703 extra_files = [
704 '../../testing/test_env.py'
705 ]
706 cmdline = [
707 '../../testing/test_env.py',
dpranked8113582015-06-05 20:08:25708 './' + str(target) + executable_suffix,
709 '--brave-new-test-launcher',
710 '--test-launcher-bot-mode',
711 '--asan=%d' % asan,
712 '--msan=%d' % msan,
713 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47714 ]
dprankedbdd9d82015-08-12 21:18:18715 elif test_type == 'gpu_browser_test':
716 extra_files = [
717 '../../testing/test_env.py'
718 ]
719 gtest_filter = gn_isolate_map[target]['gtest_filter']
720 cmdline = [
721 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:11722 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:18723 '--test-launcher-bot-mode',
724 '--enable-gpu',
725 '--test-launcher-jobs=1',
726 '--gtest_filter=%s' % gtest_filter,
727 ]
dpranke6abd8652015-08-28 03:21:11728 elif test_type == 'script':
729 extra_files = [
730 '../../testing/test_env.py'
731 ]
732 cmdline = [
733 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:39734 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
735 ] + gn_isolate_map[target].get('args', [])
dprankea55584f12015-07-22 00:52:47736 elif test_type in ('raw'):
737 extra_files = []
738 cmdline = [
739 './' + str(target) + executable_suffix,
740 ] + gn_isolate_map[target].get('args')
dpranked8113582015-06-05 20:08:25741
dprankea55584f12015-07-22 00:52:47742 else:
743 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
744 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25745
746 return cmdline, extra_files
747
dpranke74559b52015-06-10 21:20:39748 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33749 return self.PathJoin(self.chromium_src_dir,
750 self.ToSrcRelPath(build_path),
751 *comps)
dpranked8113582015-06-05 20:08:25752
dprankeee5b51f62015-04-09 00:03:22753 def ToSrcRelPath(self, path):
754 """Returns a relative path from the top of the repo."""
755 # TODO: Support normal paths in addition to source-absolute paths.
dprankefe4602312015-04-08 16:20:35756 assert(path.startswith('//'))
dpranke8c2cfd32015-09-17 20:12:33757 return path[2:].replace('/', self.sep)
dprankefe4602312015-04-08 16:20:35758
759 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:22760 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:33761 output_dir, _, _ = rpath.rpartition(self.sep)
762 return output_dir
dprankefe4602312015-04-08 16:20:35763
dpranke38f4acb62015-09-29 23:50:41764 def GYPCmd(self, output_dir, vals):
765 gyp_defines = vals['gyp_defines']
dpranke3cec199c2015-09-22 23:29:02766 goma_dir = self.args.goma_dir
767
768 # GYP uses shlex.split() to split the gyp defines into separate arguments,
769 # so we can support backslashes and and spaces in arguments by quoting
770 # them, even on Windows, where this normally wouldn't work.
771 if '\\' in goma_dir or ' ' in goma_dir:
772 goma_dir = "'%s'" % goma_dir
773 gyp_defines = gyp_defines.replace("$(goma_dir)", goma_dir)
774
dprankefe4602312015-04-08 16:20:35775 cmd = [
dpranke8c2cfd32015-09-17 20:12:33776 self.executable,
777 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:35778 '-G',
779 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:35780 ]
dpranke38f4acb62015-09-29 23:50:41781
782 # Ensure that we have an environment that only contains
783 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:02784 env = os.environ.copy()
dpranke38f4acb62015-09-29 23:50:41785 if 'GYP_CHROMIUM_NO_ACTION' in env:
786 del env['GYP_CHROMIUM_NO_ACTION']
787 if 'GYP_CROSSCOMPILE' in env:
788 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:02789 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:41790 if vals['gyp_crosscompile']:
791 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:02792 return cmd, env
dprankefe4602312015-04-08 16:20:35793
Dirk Pranke0fd41bcd2015-06-19 00:05:50794 def RunGNAnalyze(self, vals):
795 # analyze runs before 'gn gen' now, so we need to run gn gen
796 # in order to ensure that we have a build directory.
797 ret = self.RunGNGen(vals)
798 if ret:
799 return ret
800
dpranke7837fc362015-11-19 03:54:16801 inp = self.ReadInputJSON(['files', 'test_targets',
802 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32803 if self.args.verbose:
804 self.Print()
805 self.Print('analyze input:')
806 self.PrintJSON(inp)
807 self.Print()
808
dpranke7837fc362015-11-19 03:54:16809 # TODO(crbug.com/555273) - currently GN treats targets and
810 # additional_compile_targets identically since we can't tell the
811 # difference between a target that is a group in GN and one that isn't.
812 # We should eventually fix this and treat the two types differently.
813 targets = (set(inp['test_targets']) |
814 set(inp['additional_compile_targets']))
dpranke5ab84a502015-11-13 17:35:02815
dprankecda00332015-04-11 04:18:32816 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35817
818 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:02819 # what to do about it. Also, bail out early if 'all' was asked for,
820 # since we can't deal with it yet.
821 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
822 'all' in targets):
dpranke7837fc362015-11-19 03:54:16823 self.WriteJSON({
824 'status': 'Found dependency (all)',
825 'compile_targets': sorted(targets),
826 'test_targets': sorted(targets & set(inp['test_targets'])),
827 }, output_path)
dpranke76734662015-04-16 02:17:50828 return 0
829
dpranke7c5f614d2015-07-22 23:43:39830 # This shouldn't normally happen, but could due to unusual race conditions,
831 # like a try job that gets scheduled before a patch lands but runs after
832 # the patch has landed.
833 if not inp['files']:
834 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:16835 self.WriteJSON({
836 'status': 'No dependency',
837 'compile_targets': [],
838 'test_targets': [],
839 }, output_path)
dpranke7c5f614d2015-07-22 23:43:39840 return 0
841
Dirk Pranke12ee2db2015-04-14 23:15:32842 ret = 0
dprankef61de2f2015-05-14 04:09:56843 response_file = self.TempFile()
844 response_file.write('\n'.join(inp['files']) + '\n')
845 response_file.close()
846
dpranke5ab84a502015-11-13 17:35:02847 matching_targets = set()
dprankef61de2f2015-05-14 04:09:56848 try:
dpranked1fba482015-04-14 20:54:51849 cmd = self.GNCmd('refs', self.args.path[0]) + [
dpranke067d0142015-05-14 22:52:45850 '@%s' % response_file.name, '--all', '--as=output']
dprankee0547cd2015-09-15 01:27:40851 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:12852 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:32853 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
854 output_path)
dpranke8c2cfd32015-09-17 20:12:33855 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:56856 for output in out.splitlines():
857 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:02858 if build_output in targets:
859 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:45860
861 cmd = self.GNCmd('refs', self.args.path[0]) + [
862 '@%s' % response_file.name, '--all']
dprankee0547cd2015-09-15 01:27:40863 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:45864 if ret and not 'The input matches no targets' in out:
865 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
866 output_path)
867 for label in out.splitlines():
868 build_target = label[2:]
newt309af8f2015-08-25 22:10:20869 # We want to accept 'chrome/android:chrome_public_apk' and
870 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:45871 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:02872 for input_target in targets:
dpranke067d0142015-05-14 22:52:45873 if (input_target == build_target or
874 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:02875 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:56876 finally:
877 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:35878
dprankef61de2f2015-05-14 04:09:56879 if matching_targets:
dpranke7837fc362015-11-19 03:54:16880 self.WriteJSON({
dpranke5ab84a502015-11-13 17:35:02881 'status': 'Found dependency',
dpranke7837fc362015-11-19 03:54:16882 'compile_targets': sorted(matching_targets),
883 'test_targets': sorted(matching_targets &
884 set(inp['test_targets'])),
885 }, output_path)
dprankefe4602312015-04-08 16:20:35886 else:
dpranke7837fc362015-11-19 03:54:16887 self.WriteJSON({
888 'status': 'No dependency',
889 'compile_targets': [],
890 'test_targets': [],
891 }, output_path)
dprankecda00332015-04-11 04:18:32892
dprankee0547cd2015-09-15 01:27:40893 if self.args.verbose:
dprankecda00332015-04-11 04:18:32894 outp = json.loads(self.ReadFile(output_path))
895 self.Print()
896 self.Print('analyze output:')
897 self.PrintJSON(outp)
898 self.Print()
dprankefe4602312015-04-08 16:20:35899
900 return 0
901
dpranked8113582015-06-05 20:08:25902 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:35903 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:32904 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35905 if not self.Exists(path):
dprankecda00332015-04-11 04:18:32906 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:35907
908 try:
909 inp = json.loads(self.ReadFile(path))
910 except Exception as e:
911 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:32912 (path, e), output_path)
dpranked8113582015-06-05 20:08:25913
914 for k in required_keys:
915 if not k in inp:
916 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
917 output_path)
dprankefe4602312015-04-08 16:20:35918
919 return inp
920
dpranked5b2b9432015-06-23 16:55:30921 def WriteFailureAndRaise(self, msg, output_path):
922 if output_path:
dprankee0547cd2015-09-15 01:27:40923 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:35924 raise MBErr(msg)
925
dprankee0547cd2015-09-15 01:27:40926 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:32927 try:
dprankee0547cd2015-09-15 01:27:40928 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
929 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:32930 except Exception as e:
931 raise MBErr('Error %s writing to the output path "%s"' %
932 (e, path))
dprankefe4602312015-04-08 16:20:35933
dpranke3cec199c2015-09-22 23:29:02934 def PrintCmd(self, cmd, env):
935 if self.platform == 'win32':
936 env_prefix = 'set '
937 env_quoter = QuoteForSet
938 shell_quoter = QuoteForCmd
939 else:
940 env_prefix = ''
941 env_quoter = pipes.quote
942 shell_quoter = pipes.quote
943
944 def print_env(var):
945 if env and var in env:
946 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
947
948 print_env('GYP_CROSSCOMPILE')
949 print_env('GYP_DEFINES')
950
dpranke8c2cfd32015-09-17 20:12:33951 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:35952 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:02953 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:35954
dprankecda00332015-04-11 04:18:32955 def PrintJSON(self, obj):
956 self.Print(json.dumps(obj, indent=2, sort_keys=True))
957
dprankefe4602312015-04-08 16:20:35958 def Print(self, *args, **kwargs):
959 # This function largely exists so it can be overridden for testing.
960 print(*args, **kwargs)
961
dpranke751516a2015-10-03 01:11:34962 def Build(self, target):
963 build_dir = self.ToSrcRelPath(self.args.path[0])
964 ninja_cmd = ['ninja', '-C', build_dir]
965 if self.args.jobs:
966 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
967 ninja_cmd.append(target)
968 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
969 return ret
970
971 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:35972 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:40973 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:02974 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:35975 if self.args.dryrun:
976 return 0, '', ''
dprankee0547cd2015-09-15 01:27:40977
dpranke751516a2015-10-03 01:11:34978 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:40979 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:34980 if ret:
981 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:35982 if out:
dprankeee5b51f62015-04-09 00:03:22983 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:35984 if err:
dprankeee5b51f62015-04-09 00:03:22985 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:35986 return ret, out, err
987
dpranke751516a2015-10-03 01:11:34988 def Call(self, cmd, env=None, buffer_output=True):
989 if buffer_output:
990 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
991 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
992 env=env)
993 out, err = p.communicate()
994 else:
995 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
996 env=env)
997 p.wait()
998 out = err = ''
dprankefe4602312015-04-08 16:20:35999 return p.returncode, out, err
1000
1001 def ExpandUser(self, path):
1002 # This function largely exists so it can be overridden for testing.
1003 return os.path.expanduser(path)
1004
1005 def Exists(self, path):
1006 # This function largely exists so it can be overridden for testing.
1007 return os.path.exists(path)
1008
dprankec3441d12015-06-23 23:01:351009 def MaybeMakeDirectory(self, path):
1010 try:
1011 os.makedirs(path)
1012 except OSError, e:
1013 if e.errno != errno.EEXIST:
1014 raise
1015
dpranke8c2cfd32015-09-17 20:12:331016 def PathJoin(self, *comps):
1017 # This function largely exists so it can be overriden for testing.
1018 return os.path.join(*comps)
1019
dprankefe4602312015-04-08 16:20:351020 def ReadFile(self, path):
1021 # This function largely exists so it can be overriden for testing.
1022 with open(path) as fp:
1023 return fp.read()
1024
dprankef61de2f2015-05-14 04:09:561025 def RemoveFile(self, path):
1026 # This function largely exists so it can be overriden for testing.
1027 os.remove(path)
1028
dprankec161aa92015-09-14 20:21:131029 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331030 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131031 # In other places in chromium, we often have to retry this command
1032 # because we're worried about other processes still holding on to
1033 # file handles, but when MB is invoked, it will be early enough in the
1034 # build that their should be no other processes to interfere. We
1035 # can change this if need be.
1036 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1037 else:
1038 shutil.rmtree(abs_path, ignore_errors=True)
1039
dprankef61de2f2015-05-14 04:09:561040 def TempFile(self, mode='w'):
1041 # This function largely exists so it can be overriden for testing.
1042 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1043
dprankee0547cd2015-09-15 01:27:401044 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351045 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401046 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301047 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351048 with open(path, 'w') as fp:
1049 return fp.write(contents)
1050
dprankef61de2f2015-05-14 04:09:561051
dprankefe4602312015-04-08 16:20:351052class MBErr(Exception):
1053 pass
1054
1055
dpranke3cec199c2015-09-22 23:29:021056# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1057# details of this next section, which handles escaping command lines
1058# so that they can be copied and pasted into a cmd window.
1059UNSAFE_FOR_SET = set('^<>&|')
1060UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1061ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1062
1063
1064def QuoteForSet(arg):
1065 if any(a in UNSAFE_FOR_SET for a in arg):
1066 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1067 return arg
1068
1069
1070def QuoteForCmd(arg):
1071 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1072 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1073 if arg == '' or ' ' in arg or '"' in arg:
1074 quote_re = re.compile(r'(\\*)"')
1075 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1076
1077 # Then check to see if the arg contains any metacharacters other than
1078 # double quotes; if it does, quote everything (including the double
1079 # quotes) for safety.
1080 if any(a in UNSAFE_FOR_CMD for a in arg):
1081 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1082 return arg
1083
1084
dprankefe4602312015-04-08 16:20:351085if __name__ == '__main__':
1086 try:
1087 sys.exit(main(sys.argv[1:]))
1088 except MBErr as e:
1089 print(e)
1090 sys.exit(1)
1091 except KeyboardInterrupt:
1092 print("interrupted, exiting", stream=sys.stderr)
1093 sys.exit(130)