blob: d80d9caf5251235644e13f82503bf2fcd515ae39 [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:
jbudorick91c8a6012016-01-29 23:20:02515 if target.endswith('_apk'):
516 target = target[:-len('_apk')]
dprankea55584f12015-07-22 00:52:47517 if not target in gn_isolate_map:
dpranke74559b52015-06-10 21:20:39518 raise MBErr('test target "%s" not found in %s' %
dprankea55584f12015-07-22 00:52:47519 (target, '//testing/buildbot/gn_isolate_map.pyl'))
520 gn_labels.append(gn_isolate_map[target]['label'])
dpranke74559b52015-06-10 21:20:39521
dpranke751516a2015-10-03 01:11:34522 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankec3441d12015-06-23 23:01:35523
524 # Since GN hasn't run yet, the build directory may not even exist.
dpranke751516a2015-10-03 01:11:34525 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
dprankec3441d12015-06-23 23:01:35526
dpranke74559b52015-06-10 21:20:39527 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
528 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
529
dprankefe4602312015-04-08 16:20:35530 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40531 if ret:
532 # If `gn gen` failed, we should exit early rather than trying to
533 # generate isolates. Run() will have already logged any error output.
534 self.Print('GN gen failed: %d' % ret)
535 return ret
dpranke74559b52015-06-10 21:20:39536
537 for target in swarming_targets:
jbudorick91c8a6012016-01-29 23:20:02538 if target.endswith('_apk'):
539 # "_apk" targets may be either android_apk or executable. The former
540 # will result in runtime_deps associated with the stamp file, while the
541 # latter will result in runtime_deps associated with the executable.
542 target = target[:-len('_apk')]
543 label = gn_isolate_map[target]['label']
544 runtime_deps_targets = [
545 target,
546 'obj/%s.stamp' % label.replace(':', '/')]
547 elif gn_isolate_map[target]['type'] == 'gpu_browser_test':
548 runtime_deps_targets = ['browser_tests']
dpranke6abd8652015-08-28 03:21:11549 elif gn_isolate_map[target]['type'] == 'script':
550 # For script targets, the build target is usually a group,
551 # for which gn generates the runtime_deps next to the stamp file
552 # for the label, which lives under the obj/ directory.
553 label = gn_isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02554 runtime_deps_targets = ['obj/%s.stamp' % label.replace(':', '/')]
dpranke34bd39d2015-06-24 02:36:52555 else:
jbudorick91c8a6012016-01-29 23:20:02556 runtime_deps_targets = [target]
557
dpranke8c2cfd32015-09-17 20:12:33558 if self.platform == 'win32':
jbudorick91c8a6012016-01-29 23:20:02559 deps_paths = [
560 self.ToAbsPath(build_dir, r + '.exe.runtime_deps')
561 for r in runtime_deps_targets]
dprankedbdd9d82015-08-12 21:18:18562 else:
jbudorick91c8a6012016-01-29 23:20:02563 deps_paths = [
564 self.ToAbsPath(build_dir, r + '.runtime_deps')
565 for r in runtime_deps_targets]
566
567 for d in deps_paths:
568 if self.Exists(d):
569 deps_path = d
570 break
571 else:
jbudoricke8428732016-02-02 02:17:06572 raise MBErr('did not generate any of %s' % ', '.join(deps_paths))
dpranke74559b52015-06-10 21:20:39573
dprankea55584f12015-07-22 00:52:47574 command, extra_files = self.GetIsolateCommand(target, vals,
575 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30576
577 runtime_deps = self.ReadFile(deps_path).splitlines()
578
dpranke751516a2015-10-03 01:11:34579 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
580 extra_files)
dpranked5b2b9432015-06-23 16:55:30581
dpranke751516a2015-10-03 01:11:34582 return 0
583
584 def RunGNIsolate(self, vals):
585 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
586 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
587
588 build_dir = self.args.path[0]
589 target = self.args.target[0]
590 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
591
592 label = gn_isolate_map[target]['label']
593 ret, out, _ = self.Call(['gn', 'desc', build_dir, label, 'runtime_deps'])
594 if ret:
595 return ret
596
597 runtime_deps = out.splitlines()
598
599 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
600 extra_files)
601
602 ret, _, _ = self.Run([
603 self.executable,
604 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
605 'check',
606 '-i',
607 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
608 '-s',
609 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
610 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30611
dprankefe4602312015-04-08 16:20:35612 return ret
613
dpranke751516a2015-10-03 01:11:34614 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
615 extra_files):
616 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
617 self.WriteFile(isolate_path,
618 pprint.pformat({
619 'variables': {
620 'command': command,
621 'files': sorted(runtime_deps + extra_files),
622 }
623 }) + '\n')
624
625 self.WriteJSON(
626 {
627 'args': [
628 '--isolated',
629 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
630 '--isolate',
631 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
632 ],
633 'dir': self.chromium_src_dir,
634 'version': 1,
635 },
636 isolate_path + 'd.gen.json',
637 )
638
dprankeb218d912015-09-18 19:07:00639 def GNCmd(self, subcommand, path, gn_args='', extra_args=None):
dpranked1fba482015-04-14 20:54:51640 if self.platform == 'linux2':
dpranke8c2cfd32015-09-17 20:12:33641 subdir = 'linux64'
dpranked1fba482015-04-14 20:54:51642 elif self.platform == 'darwin':
dpranke8c2cfd32015-09-17 20:12:33643 subdir = 'mac'
dpranked1fba482015-04-14 20:54:51644 else:
dpranke8c2cfd32015-09-17 20:12:33645 subdir = 'win'
646 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, 'gn')
dpranked1fba482015-04-14 20:54:51647
648 cmd = [gn_path, subcommand, path]
dprankeee5b51f62015-04-09 00:03:22649 gn_args = gn_args.replace("$(goma_dir)", self.args.goma_dir)
dprankefe4602312015-04-08 16:20:35650 if gn_args:
651 cmd.append('--args=%s' % gn_args)
dprankeb218d912015-09-18 19:07:00652 if extra_args:
653 cmd.extend(extra_args)
dprankefe4602312015-04-08 16:20:35654 return cmd
655
Dirk Pranke0fd41bcd2015-06-19 00:05:50656 def RunGYPGen(self, vals):
657 path = self.args.path[0]
658
dpranke8c2cfd32015-09-17 20:12:33659 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41660 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59661 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35662 return ret
663
664 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33665 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32666 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:16667 inp = self.ReadInputJSON(['files', 'test_targets',
668 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32669 self.Print()
670 self.Print('analyze input:')
671 self.PrintJSON(inp)
672 self.Print()
673
dpranke38f4acb62015-09-29 23:50:41674 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33675 cmd.extend(['-f', 'analyzer',
676 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35677 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02678 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32679 if not ret and self.args.verbose:
680 outp = json.loads(self.ReadFile(self.args.output_path[0]))
681 self.Print()
682 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39683 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32684 self.Print()
685
dprankefe4602312015-04-08 16:20:35686 return ret
687
dprankea55584f12015-07-22 00:52:47688 def GetIsolateCommand(self, target, vals, gn_isolate_map):
jbudoricke8428732016-02-02 02:17:06689 android = 'target_os="android"' in vals['gn_args']
690
dpranked8113582015-06-05 20:08:25691 # This needs to mirror the settings in //build/config/ui.gni:
692 # use_x11 = is_linux && !use_ozone.
693 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33694 use_x11 = (self.platform == 'linux2' and
jbudoricke8428732016-02-02 02:17:06695 not android and
dpranked8113582015-06-05 20:08:25696 not 'use_ozone=true' in vals['gn_args'])
697
698 asan = 'is_asan=true' in vals['gn_args']
699 msan = 'is_msan=true' in vals['gn_args']
700 tsan = 'is_tsan=true' in vals['gn_args']
701
dpranke8c2cfd32015-09-17 20:12:33702 executable_suffix = '.exe' if self.platform == 'win32' else ''
dpranked8113582015-06-05 20:08:25703
dprankea55584f12015-07-22 00:52:47704 test_type = gn_isolate_map[target]['type']
705 cmdline = []
706 extra_files = []
dpranked8113582015-06-05 20:08:25707
jbudoricke8428732016-02-02 02:17:06708 if android:
709 # TODO(jbudorick): This won't work with instrumentation test targets.
710 # Revisit this logic when those are added to gn_isolate_map.pyl.
711 cmdline = [self.PathJoin('bin', 'run_%s' % target)]
712 elif use_x11 and test_type == 'windowed_test_launcher':
dprankea55584f12015-07-22 00:52:47713 extra_files = [
714 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25715 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47716 '../../testing/xvfb.py',
717 ]
718 cmdline = [
jbudoricke8428732016-02-02 02:17:06719 '../../testing/xvfb.py',
720 '.',
721 './' + str(target),
722 '--brave-new-test-launcher',
723 '--test-launcher-bot-mode',
724 '--asan=%d' % asan,
725 '--msan=%d' % msan,
726 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47727 ]
728 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
729 extra_files = [
730 '../../testing/test_env.py'
731 ]
732 cmdline = [
733 '../../testing/test_env.py',
dpranked8113582015-06-05 20:08:25734 './' + str(target) + executable_suffix,
735 '--brave-new-test-launcher',
736 '--test-launcher-bot-mode',
737 '--asan=%d' % asan,
738 '--msan=%d' % msan,
739 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47740 ]
dprankedbdd9d82015-08-12 21:18:18741 elif test_type == 'gpu_browser_test':
742 extra_files = [
743 '../../testing/test_env.py'
744 ]
745 gtest_filter = gn_isolate_map[target]['gtest_filter']
746 cmdline = [
747 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:11748 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:18749 '--test-launcher-bot-mode',
750 '--enable-gpu',
751 '--test-launcher-jobs=1',
752 '--gtest_filter=%s' % gtest_filter,
753 ]
dpranke6abd8652015-08-28 03:21:11754 elif test_type == 'script':
755 extra_files = [
756 '../../testing/test_env.py'
757 ]
758 cmdline = [
759 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:39760 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
761 ] + gn_isolate_map[target].get('args', [])
dprankea55584f12015-07-22 00:52:47762 elif test_type in ('raw'):
763 extra_files = []
764 cmdline = [
765 './' + str(target) + executable_suffix,
766 ] + gn_isolate_map[target].get('args')
dpranked8113582015-06-05 20:08:25767
dprankea55584f12015-07-22 00:52:47768 else:
769 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
770 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25771
772 return cmdline, extra_files
773
dpranke74559b52015-06-10 21:20:39774 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33775 return self.PathJoin(self.chromium_src_dir,
776 self.ToSrcRelPath(build_path),
777 *comps)
dpranked8113582015-06-05 20:08:25778
dprankeee5b51f62015-04-09 00:03:22779 def ToSrcRelPath(self, path):
780 """Returns a relative path from the top of the repo."""
781 # TODO: Support normal paths in addition to source-absolute paths.
dprankefe4602312015-04-08 16:20:35782 assert(path.startswith('//'))
dpranke8c2cfd32015-09-17 20:12:33783 return path[2:].replace('/', self.sep)
dprankefe4602312015-04-08 16:20:35784
785 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:22786 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:33787 output_dir, _, _ = rpath.rpartition(self.sep)
788 return output_dir
dprankefe4602312015-04-08 16:20:35789
dpranke38f4acb62015-09-29 23:50:41790 def GYPCmd(self, output_dir, vals):
791 gyp_defines = vals['gyp_defines']
dpranke3cec199c2015-09-22 23:29:02792 goma_dir = self.args.goma_dir
793
794 # GYP uses shlex.split() to split the gyp defines into separate arguments,
795 # so we can support backslashes and and spaces in arguments by quoting
796 # them, even on Windows, where this normally wouldn't work.
797 if '\\' in goma_dir or ' ' in goma_dir:
798 goma_dir = "'%s'" % goma_dir
799 gyp_defines = gyp_defines.replace("$(goma_dir)", goma_dir)
800
dprankefe4602312015-04-08 16:20:35801 cmd = [
dpranke8c2cfd32015-09-17 20:12:33802 self.executable,
803 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:35804 '-G',
805 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:35806 ]
dpranke38f4acb62015-09-29 23:50:41807
808 # Ensure that we have an environment that only contains
809 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:02810 env = os.environ.copy()
dprankef75a3de52015-12-14 22:17:52811 env['GYP_GENERATORS'] = 'ninja'
dpranke38f4acb62015-09-29 23:50:41812 if 'GYP_CHROMIUM_NO_ACTION' in env:
813 del env['GYP_CHROMIUM_NO_ACTION']
814 if 'GYP_CROSSCOMPILE' in env:
815 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:02816 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:41817 if vals['gyp_crosscompile']:
818 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:02819 return cmd, env
dprankefe4602312015-04-08 16:20:35820
Dirk Pranke0fd41bcd2015-06-19 00:05:50821 def RunGNAnalyze(self, vals):
822 # analyze runs before 'gn gen' now, so we need to run gn gen
823 # in order to ensure that we have a build directory.
824 ret = self.RunGNGen(vals)
825 if ret:
826 return ret
827
dpranke7837fc362015-11-19 03:54:16828 inp = self.ReadInputJSON(['files', 'test_targets',
829 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32830 if self.args.verbose:
831 self.Print()
832 self.Print('analyze input:')
833 self.PrintJSON(inp)
834 self.Print()
835
dpranke7837fc362015-11-19 03:54:16836 # TODO(crbug.com/555273) - currently GN treats targets and
837 # additional_compile_targets identically since we can't tell the
838 # difference between a target that is a group in GN and one that isn't.
839 # We should eventually fix this and treat the two types differently.
840 targets = (set(inp['test_targets']) |
841 set(inp['additional_compile_targets']))
dpranke5ab84a502015-11-13 17:35:02842
dprankecda00332015-04-11 04:18:32843 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35844
845 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:02846 # what to do about it. Also, bail out early if 'all' was asked for,
847 # since we can't deal with it yet.
848 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
849 'all' in targets):
dpranke7837fc362015-11-19 03:54:16850 self.WriteJSON({
851 'status': 'Found dependency (all)',
852 'compile_targets': sorted(targets),
853 'test_targets': sorted(targets & set(inp['test_targets'])),
854 }, output_path)
dpranke76734662015-04-16 02:17:50855 return 0
856
dpranke7c5f614d2015-07-22 23:43:39857 # This shouldn't normally happen, but could due to unusual race conditions,
858 # like a try job that gets scheduled before a patch lands but runs after
859 # the patch has landed.
860 if not inp['files']:
861 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:16862 self.WriteJSON({
863 'status': 'No dependency',
864 'compile_targets': [],
865 'test_targets': [],
866 }, output_path)
dpranke7c5f614d2015-07-22 23:43:39867 return 0
868
Dirk Pranke12ee2db2015-04-14 23:15:32869 ret = 0
dprankef61de2f2015-05-14 04:09:56870 response_file = self.TempFile()
871 response_file.write('\n'.join(inp['files']) + '\n')
872 response_file.close()
873
dpranke5ab84a502015-11-13 17:35:02874 matching_targets = set()
dprankef61de2f2015-05-14 04:09:56875 try:
dpranked1fba482015-04-14 20:54:51876 cmd = self.GNCmd('refs', self.args.path[0]) + [
dpranke067d0142015-05-14 22:52:45877 '@%s' % response_file.name, '--all', '--as=output']
dprankee0547cd2015-09-15 01:27:40878 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:12879 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:32880 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
881 output_path)
dpranke8c2cfd32015-09-17 20:12:33882 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:56883 for output in out.splitlines():
884 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:02885 if build_output in targets:
886 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:45887
888 cmd = self.GNCmd('refs', self.args.path[0]) + [
889 '@%s' % response_file.name, '--all']
dprankee0547cd2015-09-15 01:27:40890 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:45891 if ret and not 'The input matches no targets' in out:
892 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
893 output_path)
894 for label in out.splitlines():
895 build_target = label[2:]
newt309af8f2015-08-25 22:10:20896 # We want to accept 'chrome/android:chrome_public_apk' and
897 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:45898 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:02899 for input_target in targets:
dpranke067d0142015-05-14 22:52:45900 if (input_target == build_target or
901 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:02902 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:56903 finally:
904 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:35905
dprankef61de2f2015-05-14 04:09:56906 if matching_targets:
dpranke7837fc362015-11-19 03:54:16907 self.WriteJSON({
dpranke5ab84a502015-11-13 17:35:02908 'status': 'Found dependency',
dpranke7837fc362015-11-19 03:54:16909 'compile_targets': sorted(matching_targets),
910 'test_targets': sorted(matching_targets &
911 set(inp['test_targets'])),
912 }, output_path)
dprankefe4602312015-04-08 16:20:35913 else:
dpranke7837fc362015-11-19 03:54:16914 self.WriteJSON({
915 'status': 'No dependency',
916 'compile_targets': [],
917 'test_targets': [],
918 }, output_path)
dprankecda00332015-04-11 04:18:32919
dprankee0547cd2015-09-15 01:27:40920 if self.args.verbose:
dprankecda00332015-04-11 04:18:32921 outp = json.loads(self.ReadFile(output_path))
922 self.Print()
923 self.Print('analyze output:')
924 self.PrintJSON(outp)
925 self.Print()
dprankefe4602312015-04-08 16:20:35926
927 return 0
928
dpranked8113582015-06-05 20:08:25929 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:35930 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:32931 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35932 if not self.Exists(path):
dprankecda00332015-04-11 04:18:32933 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:35934
935 try:
936 inp = json.loads(self.ReadFile(path))
937 except Exception as e:
938 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:32939 (path, e), output_path)
dpranked8113582015-06-05 20:08:25940
941 for k in required_keys:
942 if not k in inp:
943 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
944 output_path)
dprankefe4602312015-04-08 16:20:35945
946 return inp
947
dpranked5b2b9432015-06-23 16:55:30948 def WriteFailureAndRaise(self, msg, output_path):
949 if output_path:
dprankee0547cd2015-09-15 01:27:40950 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:35951 raise MBErr(msg)
952
dprankee0547cd2015-09-15 01:27:40953 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:32954 try:
dprankee0547cd2015-09-15 01:27:40955 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
956 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:32957 except Exception as e:
958 raise MBErr('Error %s writing to the output path "%s"' %
959 (e, path))
dprankefe4602312015-04-08 16:20:35960
dpranke3cec199c2015-09-22 23:29:02961 def PrintCmd(self, cmd, env):
962 if self.platform == 'win32':
963 env_prefix = 'set '
964 env_quoter = QuoteForSet
965 shell_quoter = QuoteForCmd
966 else:
967 env_prefix = ''
968 env_quoter = pipes.quote
969 shell_quoter = pipes.quote
970
971 def print_env(var):
972 if env and var in env:
973 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
974
975 print_env('GYP_CROSSCOMPILE')
976 print_env('GYP_DEFINES')
977
dpranke8c2cfd32015-09-17 20:12:33978 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:35979 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:02980 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:35981
dprankecda00332015-04-11 04:18:32982 def PrintJSON(self, obj):
983 self.Print(json.dumps(obj, indent=2, sort_keys=True))
984
dprankefe4602312015-04-08 16:20:35985 def Print(self, *args, **kwargs):
986 # This function largely exists so it can be overridden for testing.
987 print(*args, **kwargs)
988
dpranke751516a2015-10-03 01:11:34989 def Build(self, target):
990 build_dir = self.ToSrcRelPath(self.args.path[0])
991 ninja_cmd = ['ninja', '-C', build_dir]
992 if self.args.jobs:
993 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
994 ninja_cmd.append(target)
995 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
996 return ret
997
998 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:35999 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401000 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021001 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351002 if self.args.dryrun:
1003 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401004
dpranke751516a2015-10-03 01:11:341005 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401006 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341007 if ret:
1008 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351009 if out:
dprankeee5b51f62015-04-09 00:03:221010 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351011 if err:
dprankeee5b51f62015-04-09 00:03:221012 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351013 return ret, out, err
1014
dpranke751516a2015-10-03 01:11:341015 def Call(self, cmd, env=None, buffer_output=True):
1016 if buffer_output:
1017 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1018 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1019 env=env)
1020 out, err = p.communicate()
1021 else:
1022 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1023 env=env)
1024 p.wait()
1025 out = err = ''
dprankefe4602312015-04-08 16:20:351026 return p.returncode, out, err
1027
1028 def ExpandUser(self, path):
1029 # This function largely exists so it can be overridden for testing.
1030 return os.path.expanduser(path)
1031
1032 def Exists(self, path):
1033 # This function largely exists so it can be overridden for testing.
1034 return os.path.exists(path)
1035
dprankec3441d12015-06-23 23:01:351036 def MaybeMakeDirectory(self, path):
1037 try:
1038 os.makedirs(path)
1039 except OSError, e:
1040 if e.errno != errno.EEXIST:
1041 raise
1042
dpranke8c2cfd32015-09-17 20:12:331043 def PathJoin(self, *comps):
1044 # This function largely exists so it can be overriden for testing.
1045 return os.path.join(*comps)
1046
dprankefe4602312015-04-08 16:20:351047 def ReadFile(self, path):
1048 # This function largely exists so it can be overriden for testing.
1049 with open(path) as fp:
1050 return fp.read()
1051
dprankef61de2f2015-05-14 04:09:561052 def RemoveFile(self, path):
1053 # This function largely exists so it can be overriden for testing.
1054 os.remove(path)
1055
dprankec161aa92015-09-14 20:21:131056 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331057 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131058 # In other places in chromium, we often have to retry this command
1059 # because we're worried about other processes still holding on to
1060 # file handles, but when MB is invoked, it will be early enough in the
1061 # build that their should be no other processes to interfere. We
1062 # can change this if need be.
1063 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1064 else:
1065 shutil.rmtree(abs_path, ignore_errors=True)
1066
dprankef61de2f2015-05-14 04:09:561067 def TempFile(self, mode='w'):
1068 # This function largely exists so it can be overriden for testing.
1069 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1070
dprankee0547cd2015-09-15 01:27:401071 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351072 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401073 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301074 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351075 with open(path, 'w') as fp:
1076 return fp.write(contents)
1077
dprankef61de2f2015-05-14 04:09:561078
dprankefe4602312015-04-08 16:20:351079class MBErr(Exception):
1080 pass
1081
1082
dpranke3cec199c2015-09-22 23:29:021083# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1084# details of this next section, which handles escaping command lines
1085# so that they can be copied and pasted into a cmd window.
1086UNSAFE_FOR_SET = set('^<>&|')
1087UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1088ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1089
1090
1091def QuoteForSet(arg):
1092 if any(a in UNSAFE_FOR_SET for a in arg):
1093 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1094 return arg
1095
1096
1097def QuoteForCmd(arg):
1098 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1099 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1100 if arg == '' or ' ' in arg or '"' in arg:
1101 quote_re = re.compile(r'(\\*)"')
1102 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1103
1104 # Then check to see if the arg contains any metacharacters other than
1105 # double quotes; if it does, quote everything (including the double
1106 # quotes) for safety.
1107 if any(a in UNSAFE_FOR_CMD for a in arg):
1108 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1109 return arg
1110
1111
dprankefe4602312015-04-08 16:20:351112if __name__ == '__main__':
1113 try:
1114 sys.exit(main(sys.argv[1:]))
1115 except MBErr as e:
1116 print(e)
1117 sys.exit(1)
1118 except KeyboardInterrupt:
1119 print("interrupted, exiting", stream=sys.stderr)
1120 sys.exit(130)