blob: b733345166d1dab5010805d2139a19707641cd37 [file] [log] [blame]
dprankefe4602312015-04-08 16:20:351#!/usr/bin/env python
2# Copyright 2015 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""MB - the Meta-Build wrapper around GYP and GN
7
8MB is a wrapper script for GYP and GN that can be used to generate build files
9for sets of canned configurations and analyze them.
10"""
11
12from __future__ import print_function
13
14import argparse
15import ast
dprankec3441d12015-06-23 23:01:3516import errno
dprankefe4602312015-04-08 16:20:3517import json
18import os
dpranke68d1cb182015-09-17 23:30:0019import pipes
dpranked8113582015-06-05 20:08:2520import pprint
dpranke3cec199c2015-09-22 23:29:0221import re
dprankefe4602312015-04-08 16:20:3522import shutil
23import sys
24import subprocess
dprankef61de2f2015-05-14 04:09:5625import tempfile
dprankefe4602312015-04-08 16:20:3526
dprankefe4602312015-04-08 16:20:3527def main(args):
dprankeee5b51f62015-04-09 00:03:2228 mbw = MetaBuildWrapper()
29 mbw.ParseArgs(args)
30 return mbw.args.func()
dprankefe4602312015-04-08 16:20:3531
32
33class MetaBuildWrapper(object):
34 def __init__(self):
35 p = os.path
36 d = os.path.dirname
37 self.chromium_src_dir = p.normpath(d(d(d(p.abspath(__file__)))))
38 self.default_config = p.join(self.chromium_src_dir, 'tools', 'mb',
39 'mb_config.pyl')
dpranke8c2cfd32015-09-17 20:12:3340 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5141 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3342 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3543 self.args = argparse.Namespace()
44 self.configs = {}
45 self.masters = {}
46 self.mixins = {}
47 self.private_configs = []
48 self.common_dev_configs = []
49 self.unsupported_configs = []
50
51 def ParseArgs(self, argv):
52 def AddCommonOptions(subp):
53 subp.add_argument('-b', '--builder',
54 help='builder name to look up config from')
55 subp.add_argument('-m', '--master',
56 help='master name to look up config from')
57 subp.add_argument('-c', '--config',
58 help='configuration to analyze')
59 subp.add_argument('-f', '--config-file', metavar='PATH',
60 default=self.default_config,
61 help='path to config file '
62 '(default is //tools/mb/mb_config.pyl)')
63 subp.add_argument('-g', '--goma-dir', default=self.ExpandUser('~/goma'),
64 help='path to goma directory (default is %(default)s).')
65 subp.add_argument('-n', '--dryrun', action='store_true',
66 help='Do a dry run (i.e., do nothing, just print '
67 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:4068 subp.add_argument('-v', '--verbose', action='store_true',
69 help='verbose logging')
dprankefe4602312015-04-08 16:20:3570
71 parser = argparse.ArgumentParser(prog='mb')
72 subps = parser.add_subparsers()
73
74 subp = subps.add_parser('analyze',
75 help='analyze whether changes to a set of files '
76 'will cause a set of binaries to be rebuilt.')
77 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:2578 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:3579 help='path build was generated into.')
80 subp.add_argument('input_path', nargs=1,
81 help='path to a file containing the input arguments '
82 'as a JSON object.')
83 subp.add_argument('output_path', nargs=1,
84 help='path to a file containing the output arguments '
85 'as a JSON object.')
86 subp.set_defaults(func=self.CmdAnalyze)
87
88 subp = subps.add_parser('gen',
89 help='generate a new set of build files')
90 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:3991 subp.add_argument('--swarming-targets-file',
92 help='save runtime dependencies for targets listed '
93 'in file.')
dpranked8113582015-06-05 20:08:2594 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:3595 help='path to generate build into')
96 subp.set_defaults(func=self.CmdGen)
97
dpranke751516a2015-10-03 01:11:3498 subp = subps.add_parser('isolate',
99 help='generate the .isolate files for a given'
100 'binary')
101 AddCommonOptions(subp)
102 subp.add_argument('path', nargs=1,
103 help='path build was generated into')
104 subp.add_argument('target', nargs=1,
105 help='ninja target to generate the isolate for')
106 subp.set_defaults(func=self.CmdIsolate)
107
dprankefe4602312015-04-08 16:20:35108 subp = subps.add_parser('lookup',
109 help='look up the command for a given config or '
110 'builder')
111 AddCommonOptions(subp)
112 subp.set_defaults(func=self.CmdLookup)
113
dpranke751516a2015-10-03 01:11:34114 subp = subps.add_parser('run',
115 help='build and run the isolated version of a '
116 'binary')
117 AddCommonOptions(subp)
118 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
119 help='Number of jobs to pass to ninja')
120 subp.add_argument('--no-build', dest='build', default=True,
121 action='store_false',
122 help='Do not build, just isolate and run')
123 subp.add_argument('path', nargs=1,
124 help='path to generate build into')
125 subp.add_argument('target', nargs=1,
126 help='ninja target to build and run')
127 subp.set_defaults(func=self.CmdRun)
128
dprankefe4602312015-04-08 16:20:35129 subp = subps.add_parser('validate',
130 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17131 subp.add_argument('-f', '--config-file', metavar='PATH',
132 default=self.default_config,
133 help='path to config file '
134 '(default is //tools/mb/mb_config.pyl)')
dprankefe4602312015-04-08 16:20:35135 subp.set_defaults(func=self.CmdValidate)
136
137 subp = subps.add_parser('help',
138 help='Get help on a subcommand.')
139 subp.add_argument(nargs='?', action='store', dest='subcommand',
140 help='The command to get help for.')
141 subp.set_defaults(func=self.CmdHelp)
142
143 self.args = parser.parse_args(argv)
144
145 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34146 vals = self.Lookup()
dprankefe4602312015-04-08 16:20:35147 if vals['type'] == 'gn':
148 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35149 else:
dpranke751516a2015-10-03 01:11:34150 return self.RunGYPAnalyze(vals)
dprankefe4602312015-04-08 16:20:35151
152 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34153 vals = self.Lookup()
dprankec161aa92015-09-14 20:21:13154 self.ClobberIfNeeded(vals)
155
dprankefe4602312015-04-08 16:20:35156 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50157 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35158 else:
dpranke751516a2015-10-03 01:11:34159 return self.RunGYPGen(vals)
dprankefe4602312015-04-08 16:20:35160
161 def CmdHelp(self):
162 if self.args.subcommand:
163 self.ParseArgs([self.args.subcommand, '--help'])
164 else:
165 self.ParseArgs(['--help'])
166
dpranke751516a2015-10-03 01:11:34167 def CmdIsolate(self):
168 vals = self.GetConfig()
169 if not vals:
170 return 1
171
172 if vals['type'] == 'gn':
173 return self.RunGNIsolate(vals)
174 else:
175 return self.Build('%s_run' % self.args.target[0])
176
177 def CmdLookup(self):
178 vals = self.Lookup()
179 if vals['type'] == 'gn':
180 cmd = self.GNCmd('gen', '_path_', vals['gn_args'])
181 env = None
182 else:
183 cmd, env = self.GYPCmd('_path_', vals)
184
185 self.PrintCmd(cmd, env)
186 return 0
187
188 def CmdRun(self):
189 vals = self.GetConfig()
190 if not vals:
191 return 1
192
193 build_dir = self.args.path[0]
194 target = self.args.target[0]
195
196 if vals['type'] == 'gn':
197 if self.args.build:
198 ret = self.Build(target)
199 if ret:
200 return ret
201 ret = self.RunGNIsolate(vals)
202 if ret:
203 return ret
204 else:
205 ret = self.Build('%s_run' % target)
206 if ret:
207 return ret
208
209 ret, _, _ = self.Run([
210 self.executable,
211 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
212 'run',
213 '-s',
214 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
215 force_verbose=False, buffer_output=False)
216
217 return ret
218
dprankefe4602312015-04-08 16:20:35219 def CmdValidate(self):
220 errs = []
221
222 # Read the file to make sure it parses.
223 self.ReadConfigFile()
224
225 # Figure out the whole list of configs and ensure that no config is
226 # listed in more than one category.
227 all_configs = {}
228 for config in self.common_dev_configs:
229 all_configs[config] = 'common_dev_configs'
230 for config in self.private_configs:
231 if config in all_configs:
232 errs.append('config "%s" listed in "private_configs" also '
233 'listed in "%s"' % (config, all_configs['config']))
234 else:
235 all_configs[config] = 'private_configs'
236 for config in self.unsupported_configs:
237 if config in all_configs:
238 errs.append('config "%s" listed in "unsupported_configs" also '
239 'listed in "%s"' % (config, all_configs['config']))
240 else:
241 all_configs[config] = 'unsupported_configs'
242
243 for master in self.masters:
244 for builder in self.masters[master]:
245 config = self.masters[master][builder]
246 if config in all_configs and all_configs[config] not in self.masters:
247 errs.append('Config "%s" used by a bot is also listed in "%s".' %
248 (config, all_configs[config]))
249 else:
250 all_configs[config] = master
251
252 # Check that every referenced config actually exists.
253 for config, loc in all_configs.items():
254 if not config in self.configs:
255 errs.append('Unknown config "%s" referenced from "%s".' %
256 (config, loc))
257
258 # Check that every actual config is actually referenced.
259 for config in self.configs:
260 if not config in all_configs:
261 errs.append('Unused config "%s".' % config)
262
263 # Figure out the whole list of mixins, and check that every mixin
264 # listed by a config or another mixin actually exists.
265 referenced_mixins = set()
266 for config, mixins in self.configs.items():
267 for mixin in mixins:
268 if not mixin in self.mixins:
269 errs.append('Unknown mixin "%s" referenced by config "%s".' %
270 (mixin, config))
271 referenced_mixins.add(mixin)
272
273 for mixin in self.mixins:
274 for sub_mixin in self.mixins[mixin].get('mixins', []):
275 if not sub_mixin in self.mixins:
276 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
277 (sub_mixin, mixin))
278 referenced_mixins.add(sub_mixin)
279
280 # Check that every mixin defined is actually referenced somewhere.
281 for mixin in self.mixins:
282 if not mixin in referenced_mixins:
283 errs.append('Unreferenced mixin "%s".' % mixin)
284
285 if errs:
dpranke4323c80632015-08-10 22:53:54286 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17287 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35288
dprankee0547cd2015-09-15 01:27:40289 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35290 return 0
291
292 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34293 build_dir = self.args.path[0]
294
295 vals = {}
296 if self.args.builder or self.args.master or self.args.config:
297 vals = self.Lookup()
298 if vals['type'] == 'gn':
299 # Re-run gn gen in order to ensure the config is consistent with the
300 # build dir.
301 self.RunGNGen(vals)
302 return vals
303
304 # TODO: We can only get the config for GN build dirs, not GYP build dirs.
305 # GN stores the args that were used in args.gn in the build dir,
306 # but GYP doesn't store them anywhere. We should consider modifying
307 # gyp_chromium to record the arguments it runs with in a similar
308 # manner.
309
310 mb_type_path = self.PathJoin(self.ToAbsPath(build_dir), 'mb_type')
311 if not self.Exists(mb_type_path):
312 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
313 if not self.Exists(gn_args_path):
314 self.Print('Must either specify a path to an existing GN build dir '
315 'or pass in a -m/-b pair or a -c flag to specify the '
316 'configuration')
317 return {}
318 else:
319 mb_type = 'gn'
320 else:
321 mb_type = self.ReadFile(mb_type_path).strip()
322
323 if mb_type == 'gn':
324 vals = self.GNValsFromDir(build_dir)
325 else:
326 vals = {}
327 vals['type'] = mb_type
328
329 return vals
330
331 def GNValsFromDir(self, build_dir):
332 args_contents = self.ReadFile(
333 self.PathJoin(self.ToAbsPath(build_dir), 'args.gn'))
334 gn_args = []
335 for l in args_contents.splitlines():
336 fields = l.split(' ')
337 name = fields[0]
338 val = ' '.join(fields[2:])
339 gn_args.append('%s=%s' % (name, val))
340
341 return {
342 'gn_args': ' '.join(gn_args),
343 'type': 'gn',
344 }
345
346 def Lookup(self):
dprankefe4602312015-04-08 16:20:35347 self.ReadConfigFile()
348 config = self.ConfigFromArgs()
349 if not config in self.configs:
350 raise MBErr('Config "%s" not found in %s' %
351 (config, self.args.config_file))
352
dpranke751516a2015-10-03 01:11:34353 vals = self.FlattenConfig(config)
354
355 # Do some basic sanity checking on the config so that we
356 # don't have to do this in every caller.
357 assert 'type' in vals, 'No meta-build type specified in the config'
358 assert vals['type'] in ('gn', 'gyp'), (
359 'Unknown meta-build type "%s"' % vals['gn_args'])
360
361 return vals
dprankefe4602312015-04-08 16:20:35362
363 def ReadConfigFile(self):
364 if not self.Exists(self.args.config_file):
365 raise MBErr('config file not found at %s' % self.args.config_file)
366
367 try:
368 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
369 except SyntaxError as e:
370 raise MBErr('Failed to parse config file "%s": %s' %
371 (self.args.config_file, e))
372
373 self.common_dev_configs = contents['common_dev_configs']
374 self.configs = contents['configs']
375 self.masters = contents['masters']
376 self.mixins = contents['mixins']
377 self.private_configs = contents['private_configs']
378 self.unsupported_configs = contents['unsupported_configs']
379
380 def ConfigFromArgs(self):
381 if self.args.config:
382 if self.args.master or self.args.builder:
383 raise MBErr('Can not specific both -c/--config and -m/--master or '
384 '-b/--builder')
385
386 return self.args.config
387
388 if not self.args.master or not self.args.builder:
389 raise MBErr('Must specify either -c/--config or '
390 '(-m/--master and -b/--builder)')
391
392 if not self.args.master in self.masters:
393 raise MBErr('Master name "%s" not found in "%s"' %
394 (self.args.master, self.args.config_file))
395
396 if not self.args.builder in self.masters[self.args.master]:
397 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
398 (self.args.builder, self.args.master, self.args.config_file))
399
400 return self.masters[self.args.master][self.args.builder]
401
402 def FlattenConfig(self, config):
403 mixins = self.configs[config]
404 vals = {
405 'type': None,
406 'gn_args': [],
dprankec161aa92015-09-14 20:21:13407 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59408 'gyp_crosscompile': False,
dprankefe4602312015-04-08 16:20:35409 }
410
411 visited = []
412 self.FlattenMixins(mixins, vals, visited)
413 return vals
414
415 def FlattenMixins(self, mixins, vals, visited):
416 for m in mixins:
417 if m not in self.mixins:
418 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22419
420 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35421
422 visited.append(m)
423
424 mixin_vals = self.mixins[m]
425 if 'type' in mixin_vals:
426 vals['type'] = mixin_vals['type']
427 if 'gn_args' in mixin_vals:
428 if vals['gn_args']:
429 vals['gn_args'] += ' ' + mixin_vals['gn_args']
430 else:
431 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59432 if 'gyp_crosscompile' in mixin_vals:
433 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35434 if 'gyp_defines' in mixin_vals:
435 if vals['gyp_defines']:
436 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
437 else:
438 vals['gyp_defines'] = mixin_vals['gyp_defines']
439 if 'mixins' in mixin_vals:
440 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
441 return vals
442
dprankec161aa92015-09-14 20:21:13443 def ClobberIfNeeded(self, vals):
444 path = self.args.path[0]
445 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33446 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13447 needs_clobber = False
448 new_mb_type = vals['type']
449 if self.Exists(build_dir):
450 if self.Exists(mb_type_path):
451 old_mb_type = self.ReadFile(mb_type_path)
452 if old_mb_type != new_mb_type:
453 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
454 (old_mb_type, new_mb_type, path))
455 needs_clobber = True
456 else:
457 # There is no 'mb_type' file in the build directory, so this probably
458 # means that the prior build(s) were not done through mb, and we
459 # have no idea if this was a GYP build or a GN build. Clobber it
460 # to be safe.
461 self.Print("%s/mb_type missing, clobbering to be safe" % path)
462 needs_clobber = True
463
dpranke3cec199c2015-09-22 23:29:02464 if self.args.dryrun:
465 return
466
dprankec161aa92015-09-14 20:21:13467 if needs_clobber:
468 self.RemoveDirectory(build_dir)
469
470 self.MaybeMakeDirectory(build_dir)
471 self.WriteFile(mb_type_path, new_mb_type)
472
Dirk Pranke0fd41bcd2015-06-19 00:05:50473 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34474 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50475
dpranke751516a2015-10-03 01:11:34476 cmd = self.GNCmd('gen', build_dir, vals['gn_args'], extra_args=['--check'])
dpranke74559b52015-06-10 21:20:39477
478 swarming_targets = []
dpranke751516a2015-10-03 01:11:34479 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39480 # We need GN to generate the list of runtime dependencies for
481 # the compile targets listed (one per line) in the file so
482 # we can run them via swarming. We use ninja_to_gn.pyl to convert
483 # the compile targets to the matching GN labels.
484 contents = self.ReadFile(self.args.swarming_targets_file)
485 swarming_targets = contents.splitlines()
dpranke8c2cfd32015-09-17 20:12:33486 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47487 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39488 gn_labels = []
489 for target in swarming_targets:
dprankea55584f12015-07-22 00:52:47490 if not target in gn_isolate_map:
dpranke74559b52015-06-10 21:20:39491 raise MBErr('test target "%s" not found in %s' %
dprankea55584f12015-07-22 00:52:47492 (target, '//testing/buildbot/gn_isolate_map.pyl'))
493 gn_labels.append(gn_isolate_map[target]['label'])
dpranke74559b52015-06-10 21:20:39494
dpranke751516a2015-10-03 01:11:34495 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankec3441d12015-06-23 23:01:35496
497 # Since GN hasn't run yet, the build directory may not even exist.
dpranke751516a2015-10-03 01:11:34498 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
dprankec3441d12015-06-23 23:01:35499
dpranke74559b52015-06-10 21:20:39500 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
501 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
502
dprankefe4602312015-04-08 16:20:35503 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40504 if ret:
505 # If `gn gen` failed, we should exit early rather than trying to
506 # generate isolates. Run() will have already logged any error output.
507 self.Print('GN gen failed: %d' % ret)
508 return ret
dpranke74559b52015-06-10 21:20:39509
510 for target in swarming_targets:
dprankedbdd9d82015-08-12 21:18:18511 if gn_isolate_map[target]['type'] == 'gpu_browser_test':
512 runtime_deps_target = 'browser_tests'
dpranke6abd8652015-08-28 03:21:11513 elif gn_isolate_map[target]['type'] == 'script':
514 # For script targets, the build target is usually a group,
515 # for which gn generates the runtime_deps next to the stamp file
516 # for the label, which lives under the obj/ directory.
517 label = gn_isolate_map[target]['label']
518 runtime_deps_target = 'obj/%s.stamp' % label.replace(':', '/')
dpranke34bd39d2015-06-24 02:36:52519 else:
dprankedbdd9d82015-08-12 21:18:18520 runtime_deps_target = target
dpranke8c2cfd32015-09-17 20:12:33521 if self.platform == 'win32':
dpranke751516a2015-10-03 01:11:34522 deps_path = self.ToAbsPath(build_dir,
dprankedbdd9d82015-08-12 21:18:18523 runtime_deps_target + '.exe.runtime_deps')
524 else:
dpranke751516a2015-10-03 01:11:34525 deps_path = self.ToAbsPath(build_dir,
dprankedbdd9d82015-08-12 21:18:18526 runtime_deps_target + '.runtime_deps')
dpranke74559b52015-06-10 21:20:39527 if not self.Exists(deps_path):
528 raise MBErr('did not generate %s' % deps_path)
529
dprankea55584f12015-07-22 00:52:47530 command, extra_files = self.GetIsolateCommand(target, vals,
531 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30532
533 runtime_deps = self.ReadFile(deps_path).splitlines()
534
dpranke751516a2015-10-03 01:11:34535 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
536 extra_files)
dpranked5b2b9432015-06-23 16:55:30537
dpranke751516a2015-10-03 01:11:34538 return 0
539
540 def RunGNIsolate(self, vals):
541 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
542 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
543
544 build_dir = self.args.path[0]
545 target = self.args.target[0]
546 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
547
548 label = gn_isolate_map[target]['label']
549 ret, out, _ = self.Call(['gn', 'desc', build_dir, label, 'runtime_deps'])
550 if ret:
551 return ret
552
553 runtime_deps = out.splitlines()
554
555 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
556 extra_files)
557
558 ret, _, _ = self.Run([
559 self.executable,
560 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
561 'check',
562 '-i',
563 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
564 '-s',
565 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
566 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30567
dprankefe4602312015-04-08 16:20:35568 return ret
569
dpranke751516a2015-10-03 01:11:34570 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
571 extra_files):
572 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
573 self.WriteFile(isolate_path,
574 pprint.pformat({
575 'variables': {
576 'command': command,
577 'files': sorted(runtime_deps + extra_files),
578 }
579 }) + '\n')
580
581 self.WriteJSON(
582 {
583 'args': [
584 '--isolated',
585 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
586 '--isolate',
587 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
588 ],
589 'dir': self.chromium_src_dir,
590 'version': 1,
591 },
592 isolate_path + 'd.gen.json',
593 )
594
dprankeb218d912015-09-18 19:07:00595 def GNCmd(self, subcommand, path, gn_args='', extra_args=None):
dpranked1fba482015-04-14 20:54:51596 if self.platform == 'linux2':
dpranke8c2cfd32015-09-17 20:12:33597 subdir = 'linux64'
dpranked1fba482015-04-14 20:54:51598 elif self.platform == 'darwin':
dpranke8c2cfd32015-09-17 20:12:33599 subdir = 'mac'
dpranked1fba482015-04-14 20:54:51600 else:
dpranke8c2cfd32015-09-17 20:12:33601 subdir = 'win'
602 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, 'gn')
dpranked1fba482015-04-14 20:54:51603
604 cmd = [gn_path, subcommand, path]
dprankeee5b51f62015-04-09 00:03:22605 gn_args = gn_args.replace("$(goma_dir)", self.args.goma_dir)
dprankefe4602312015-04-08 16:20:35606 if gn_args:
607 cmd.append('--args=%s' % gn_args)
dprankeb218d912015-09-18 19:07:00608 if extra_args:
609 cmd.extend(extra_args)
dprankefe4602312015-04-08 16:20:35610 return cmd
611
Dirk Pranke0fd41bcd2015-06-19 00:05:50612 def RunGYPGen(self, vals):
613 path = self.args.path[0]
614
dpranke8c2cfd32015-09-17 20:12:33615 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41616 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59617 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35618 return ret
619
620 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33621 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32622 if self.args.verbose:
Dirk Pranke35330b02015-11-16 23:31:43623 inp = self.ReadInputJSON(['files'])
dprankecda00332015-04-11 04:18:32624 self.Print()
625 self.Print('analyze input:')
626 self.PrintJSON(inp)
627 self.Print()
628
dpranke38f4acb62015-09-29 23:50:41629 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33630 cmd.extend(['-f', 'analyzer',
631 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35632 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02633 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32634 if not ret and self.args.verbose:
635 outp = json.loads(self.ReadFile(self.args.output_path[0]))
636 self.Print()
637 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39638 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32639 self.Print()
640
dprankefe4602312015-04-08 16:20:35641 return ret
642
dprankea55584f12015-07-22 00:52:47643 def GetIsolateCommand(self, target, vals, gn_isolate_map):
dpranked8113582015-06-05 20:08:25644 # This needs to mirror the settings in //build/config/ui.gni:
645 # use_x11 = is_linux && !use_ozone.
646 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33647 use_x11 = (self.platform == 'linux2' and
dpranked8113582015-06-05 20:08:25648 not 'target_os="android"' in vals['gn_args'] and
649 not 'use_ozone=true' in vals['gn_args'])
650
651 asan = 'is_asan=true' in vals['gn_args']
652 msan = 'is_msan=true' in vals['gn_args']
653 tsan = 'is_tsan=true' in vals['gn_args']
654
dpranke8c2cfd32015-09-17 20:12:33655 executable_suffix = '.exe' if self.platform == 'win32' else ''
dpranked8113582015-06-05 20:08:25656
dprankea55584f12015-07-22 00:52:47657 test_type = gn_isolate_map[target]['type']
658 cmdline = []
659 extra_files = []
dpranked8113582015-06-05 20:08:25660
dprankea55584f12015-07-22 00:52:47661 if use_x11 and test_type == 'windowed_test_launcher':
662 extra_files = [
663 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25664 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47665 '../../testing/xvfb.py',
666 ]
667 cmdline = [
668 '../../testing/xvfb.py',
669 '.',
670 './' + str(target),
671 '--brave-new-test-launcher',
672 '--test-launcher-bot-mode',
673 '--asan=%d' % asan,
674 '--msan=%d' % msan,
675 '--tsan=%d' % tsan,
676 ]
677 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
678 extra_files = [
679 '../../testing/test_env.py'
680 ]
681 cmdline = [
682 '../../testing/test_env.py',
dpranked8113582015-06-05 20:08:25683 './' + str(target) + executable_suffix,
684 '--brave-new-test-launcher',
685 '--test-launcher-bot-mode',
686 '--asan=%d' % asan,
687 '--msan=%d' % msan,
688 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47689 ]
dprankedbdd9d82015-08-12 21:18:18690 elif test_type == 'gpu_browser_test':
691 extra_files = [
692 '../../testing/test_env.py'
693 ]
694 gtest_filter = gn_isolate_map[target]['gtest_filter']
695 cmdline = [
696 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:11697 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:18698 '--test-launcher-bot-mode',
699 '--enable-gpu',
700 '--test-launcher-jobs=1',
701 '--gtest_filter=%s' % gtest_filter,
702 ]
dpranke6abd8652015-08-28 03:21:11703 elif test_type == 'script':
704 extra_files = [
705 '../../testing/test_env.py'
706 ]
707 cmdline = [
708 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:39709 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
710 ] + gn_isolate_map[target].get('args', [])
dprankea55584f12015-07-22 00:52:47711 elif test_type in ('raw'):
712 extra_files = []
713 cmdline = [
714 './' + str(target) + executable_suffix,
715 ] + gn_isolate_map[target].get('args')
dpranked8113582015-06-05 20:08:25716
dprankea55584f12015-07-22 00:52:47717 else:
718 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
719 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25720
721 return cmdline, extra_files
722
dpranke74559b52015-06-10 21:20:39723 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33724 return self.PathJoin(self.chromium_src_dir,
725 self.ToSrcRelPath(build_path),
726 *comps)
dpranked8113582015-06-05 20:08:25727
dprankeee5b51f62015-04-09 00:03:22728 def ToSrcRelPath(self, path):
729 """Returns a relative path from the top of the repo."""
730 # TODO: Support normal paths in addition to source-absolute paths.
dprankefe4602312015-04-08 16:20:35731 assert(path.startswith('//'))
dpranke8c2cfd32015-09-17 20:12:33732 return path[2:].replace('/', self.sep)
dprankefe4602312015-04-08 16:20:35733
734 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:22735 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:33736 output_dir, _, _ = rpath.rpartition(self.sep)
737 return output_dir
dprankefe4602312015-04-08 16:20:35738
dpranke38f4acb62015-09-29 23:50:41739 def GYPCmd(self, output_dir, vals):
740 gyp_defines = vals['gyp_defines']
dpranke3cec199c2015-09-22 23:29:02741 goma_dir = self.args.goma_dir
742
743 # GYP uses shlex.split() to split the gyp defines into separate arguments,
744 # so we can support backslashes and and spaces in arguments by quoting
745 # them, even on Windows, where this normally wouldn't work.
746 if '\\' in goma_dir or ' ' in goma_dir:
747 goma_dir = "'%s'" % goma_dir
748 gyp_defines = gyp_defines.replace("$(goma_dir)", goma_dir)
749
dprankefe4602312015-04-08 16:20:35750 cmd = [
dpranke8c2cfd32015-09-17 20:12:33751 self.executable,
752 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:35753 '-G',
754 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:35755 ]
dpranke38f4acb62015-09-29 23:50:41756
757 # Ensure that we have an environment that only contains
758 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:02759 env = os.environ.copy()
dpranke38f4acb62015-09-29 23:50:41760 if 'GYP_CHROMIUM_NO_ACTION' in env:
761 del env['GYP_CHROMIUM_NO_ACTION']
762 if 'GYP_CROSSCOMPILE' in env:
763 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:02764 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:41765 if vals['gyp_crosscompile']:
766 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:02767 return cmd, env
dprankefe4602312015-04-08 16:20:35768
Dirk Pranke0fd41bcd2015-06-19 00:05:50769 def RunGNAnalyze(self, vals):
770 # analyze runs before 'gn gen' now, so we need to run gn gen
771 # in order to ensure that we have a build directory.
772 ret = self.RunGNGen(vals)
773 if ret:
774 return ret
775
dpranke5ab84a502015-11-13 17:35:02776 # TODO(dpranke): add 'test_targets' and 'additional_compile_targets'
777 # as required keys once the recipe has been converted over.
778 # See crbug.com/552146.
779 inp = self.ReadInputJSON(['files'])
dprankecda00332015-04-11 04:18:32780 if self.args.verbose:
781 self.Print()
782 self.Print('analyze input:')
783 self.PrintJSON(inp)
784 self.Print()
785
dpranke5ab84a502015-11-13 17:35:02786 use_new_logic = ('test_targets' in inp and
787 'additional_compile_targets' in inp)
788 if use_new_logic:
789 # TODO(crbug.com/555273) - currently GN treats targets and
790 # additional_compile_targets identically since we can't tell the
791 # difference between a target that is a group in GN and one that isn't.
792 # We should eventually fix this and treat the two types differently.
793 targets = (set(inp['test_targets']) |
794 set(inp['additional_compile_targets']))
795 else:
796 targets = set(inp['targets'])
797
dprankecda00332015-04-11 04:18:32798 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35799
800 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:02801 # what to do about it. Also, bail out early if 'all' was asked for,
802 # since we can't deal with it yet.
803 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
804 'all' in targets):
805 if use_new_logic:
806 self.WriteJSON({
807 'status': 'Found dependency (all)',
808 'compile_targets': sorted(targets),
809 'test_targets': sorted(targets & set(inp['test_targets'])),
810 }, output_path)
811 else:
812 self.WriteJSON({'status': 'Found dependency (all)'}, output_path)
dpranke76734662015-04-16 02:17:50813 return 0
814
dpranke7c5f614d2015-07-22 23:43:39815 # This shouldn't normally happen, but could due to unusual race conditions,
816 # like a try job that gets scheduled before a patch lands but runs after
817 # the patch has landed.
818 if not inp['files']:
819 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke5ab84a502015-11-13 17:35:02820 if use_new_logic:
821 self.WriteJSON({
822 'status': 'No dependency',
823 'compile_targets': [],
824 'test_targets': [],
825 }, output_path)
826 else:
827 self.WriteJSON({
828 'status': 'No dependency',
829 'targets': [],
830 'build_targets': [],
831 }, output_path)
dpranke7c5f614d2015-07-22 23:43:39832 return 0
833
Dirk Pranke12ee2db2015-04-14 23:15:32834 ret = 0
dprankef61de2f2015-05-14 04:09:56835 response_file = self.TempFile()
836 response_file.write('\n'.join(inp['files']) + '\n')
837 response_file.close()
838
dpranke5ab84a502015-11-13 17:35:02839 matching_targets = set()
dprankef61de2f2015-05-14 04:09:56840 try:
dpranked1fba482015-04-14 20:54:51841 cmd = self.GNCmd('refs', self.args.path[0]) + [
dpranke067d0142015-05-14 22:52:45842 '@%s' % response_file.name, '--all', '--as=output']
dprankee0547cd2015-09-15 01:27:40843 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:12844 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:32845 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
846 output_path)
dpranke8c2cfd32015-09-17 20:12:33847 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:56848 for output in out.splitlines():
849 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:02850 if build_output in targets:
851 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:45852
853 cmd = self.GNCmd('refs', self.args.path[0]) + [
854 '@%s' % response_file.name, '--all']
dprankee0547cd2015-09-15 01:27:40855 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:45856 if ret and not 'The input matches no targets' in out:
857 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
858 output_path)
859 for label in out.splitlines():
860 build_target = label[2:]
newt309af8f2015-08-25 22:10:20861 # We want to accept 'chrome/android:chrome_public_apk' and
862 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:45863 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:02864 for input_target in targets:
dpranke067d0142015-05-14 22:52:45865 if (input_target == build_target or
866 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:02867 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:56868 finally:
869 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:35870
dprankef61de2f2015-05-14 04:09:56871 if matching_targets:
dpranke5ab84a502015-11-13 17:35:02872 if use_new_logic:
873 self.WriteJSON({
874 'status': 'Found dependency',
875 'compile_targets': sorted(matching_targets),
876 'test_targets': sorted(matching_targets &
877 set(inp['test_targets'])),
878 }, output_path)
879 else:
880 self.WriteJSON({
881 'status': 'Found dependency',
882 'targets': sorted(matching_targets),
883 'build_targets': sorted(matching_targets),
884 }, output_path)
dprankefe4602312015-04-08 16:20:35885 else:
dpranke5ab84a502015-11-13 17:35:02886 if use_new_logic:
887 self.WriteJSON({
888 'status': 'No dependency',
889 'compile_targets': [],
890 'test_targets': [],
891 }, output_path)
892 else:
893 self.WriteJSON({
894 'status': 'No dependency',
895 'targets': [],
896 'build_targets': [],
897 }, output_path)
dprankecda00332015-04-11 04:18:32898
dprankee0547cd2015-09-15 01:27:40899 if self.args.verbose:
dprankecda00332015-04-11 04:18:32900 outp = json.loads(self.ReadFile(output_path))
901 self.Print()
902 self.Print('analyze output:')
903 self.PrintJSON(outp)
904 self.Print()
dprankefe4602312015-04-08 16:20:35905
906 return 0
907
dpranked8113582015-06-05 20:08:25908 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:35909 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:32910 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35911 if not self.Exists(path):
dprankecda00332015-04-11 04:18:32912 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:35913
914 try:
915 inp = json.loads(self.ReadFile(path))
916 except Exception as e:
917 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:32918 (path, e), output_path)
dpranked8113582015-06-05 20:08:25919
920 for k in required_keys:
921 if not k in inp:
922 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
923 output_path)
dprankefe4602312015-04-08 16:20:35924
925 return inp
926
dpranked5b2b9432015-06-23 16:55:30927 def WriteFailureAndRaise(self, msg, output_path):
928 if output_path:
dprankee0547cd2015-09-15 01:27:40929 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:35930 raise MBErr(msg)
931
dprankee0547cd2015-09-15 01:27:40932 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:32933 try:
dprankee0547cd2015-09-15 01:27:40934 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
935 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:32936 except Exception as e:
937 raise MBErr('Error %s writing to the output path "%s"' %
938 (e, path))
dprankefe4602312015-04-08 16:20:35939
dpranke3cec199c2015-09-22 23:29:02940 def PrintCmd(self, cmd, env):
941 if self.platform == 'win32':
942 env_prefix = 'set '
943 env_quoter = QuoteForSet
944 shell_quoter = QuoteForCmd
945 else:
946 env_prefix = ''
947 env_quoter = pipes.quote
948 shell_quoter = pipes.quote
949
950 def print_env(var):
951 if env and var in env:
952 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
953
954 print_env('GYP_CROSSCOMPILE')
955 print_env('GYP_DEFINES')
956
dpranke8c2cfd32015-09-17 20:12:33957 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:35958 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:02959 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:35960
dprankecda00332015-04-11 04:18:32961 def PrintJSON(self, obj):
962 self.Print(json.dumps(obj, indent=2, sort_keys=True))
963
dprankefe4602312015-04-08 16:20:35964 def Print(self, *args, **kwargs):
965 # This function largely exists so it can be overridden for testing.
966 print(*args, **kwargs)
967
dpranke751516a2015-10-03 01:11:34968 def Build(self, target):
969 build_dir = self.ToSrcRelPath(self.args.path[0])
970 ninja_cmd = ['ninja', '-C', build_dir]
971 if self.args.jobs:
972 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
973 ninja_cmd.append(target)
974 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
975 return ret
976
977 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:35978 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:40979 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:02980 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:35981 if self.args.dryrun:
982 return 0, '', ''
dprankee0547cd2015-09-15 01:27:40983
dpranke751516a2015-10-03 01:11:34984 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:40985 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:34986 if ret:
987 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:35988 if out:
dprankeee5b51f62015-04-09 00:03:22989 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:35990 if err:
dprankeee5b51f62015-04-09 00:03:22991 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:35992 return ret, out, err
993
dpranke751516a2015-10-03 01:11:34994 def Call(self, cmd, env=None, buffer_output=True):
995 if buffer_output:
996 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
997 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
998 env=env)
999 out, err = p.communicate()
1000 else:
1001 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1002 env=env)
1003 p.wait()
1004 out = err = ''
dprankefe4602312015-04-08 16:20:351005 return p.returncode, out, err
1006
1007 def ExpandUser(self, path):
1008 # This function largely exists so it can be overridden for testing.
1009 return os.path.expanduser(path)
1010
1011 def Exists(self, path):
1012 # This function largely exists so it can be overridden for testing.
1013 return os.path.exists(path)
1014
dprankec3441d12015-06-23 23:01:351015 def MaybeMakeDirectory(self, path):
1016 try:
1017 os.makedirs(path)
1018 except OSError, e:
1019 if e.errno != errno.EEXIST:
1020 raise
1021
dpranke8c2cfd32015-09-17 20:12:331022 def PathJoin(self, *comps):
1023 # This function largely exists so it can be overriden for testing.
1024 return os.path.join(*comps)
1025
dprankefe4602312015-04-08 16:20:351026 def ReadFile(self, path):
1027 # This function largely exists so it can be overriden for testing.
1028 with open(path) as fp:
1029 return fp.read()
1030
dprankef61de2f2015-05-14 04:09:561031 def RemoveFile(self, path):
1032 # This function largely exists so it can be overriden for testing.
1033 os.remove(path)
1034
dprankec161aa92015-09-14 20:21:131035 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331036 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131037 # In other places in chromium, we often have to retry this command
1038 # because we're worried about other processes still holding on to
1039 # file handles, but when MB is invoked, it will be early enough in the
1040 # build that their should be no other processes to interfere. We
1041 # can change this if need be.
1042 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1043 else:
1044 shutil.rmtree(abs_path, ignore_errors=True)
1045
dprankef61de2f2015-05-14 04:09:561046 def TempFile(self, mode='w'):
1047 # This function largely exists so it can be overriden for testing.
1048 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1049
dprankee0547cd2015-09-15 01:27:401050 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351051 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401052 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301053 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351054 with open(path, 'w') as fp:
1055 return fp.write(contents)
1056
dprankef61de2f2015-05-14 04:09:561057
dprankefe4602312015-04-08 16:20:351058class MBErr(Exception):
1059 pass
1060
1061
dpranke3cec199c2015-09-22 23:29:021062# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1063# details of this next section, which handles escaping command lines
1064# so that they can be copied and pasted into a cmd window.
1065UNSAFE_FOR_SET = set('^<>&|')
1066UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1067ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1068
1069
1070def QuoteForSet(arg):
1071 if any(a in UNSAFE_FOR_SET for a in arg):
1072 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1073 return arg
1074
1075
1076def QuoteForCmd(arg):
1077 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1078 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1079 if arg == '' or ' ' in arg or '"' in arg:
1080 quote_re = re.compile(r'(\\*)"')
1081 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1082
1083 # Then check to see if the arg contains any metacharacters other than
1084 # double quotes; if it does, quote everything (including the double
1085 # quotes) for safety.
1086 if any(a in UNSAFE_FOR_CMD for a in arg):
1087 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1088 return arg
1089
1090
dprankefe4602312015-04-08 16:20:351091if __name__ == '__main__':
1092 try:
1093 sys.exit(main(sys.argv[1:]))
1094 except MBErr as e:
1095 print(e)
1096 sys.exit(1)
1097 except KeyboardInterrupt:
1098 print("interrupted, exiting", stream=sys.stderr)
1099 sys.exit(130)