blob: 239720141cba2fd52ad1d5129ac54f6806f0c568 [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
dprankebbe6d4672016-04-19 06:56:5726import traceback
dpranke867bcf4a2016-03-14 22:28:3227import urllib2
28
29from collections import OrderedDict
dprankefe4602312015-04-08 16:20:3530
dprankeeca4a782016-04-14 01:42:3831CHROMIUM_SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
32 os.path.abspath(__file__))))
33sys.path = [os.path.join(CHROMIUM_SRC_DIR, 'build')] + sys.path
34
35import gn_helpers
36
37
dprankefe4602312015-04-08 16:20:3538def main(args):
dprankeee5b51f62015-04-09 00:03:2239 mbw = MetaBuildWrapper()
dpranke255085e2016-03-16 05:23:5940 return mbw.Main(args)
dprankefe4602312015-04-08 16:20:3541
42
43class MetaBuildWrapper(object):
44 def __init__(self):
dprankeeca4a782016-04-14 01:42:3845 self.chromium_src_dir = CHROMIUM_SRC_DIR
46 self.default_config = os.path.join(self.chromium_src_dir, 'tools', 'mb',
47 'mb_config.pyl')
kjellander902bcb62016-10-26 06:20:5048 self.default_isolate_map = os.path.join(self.chromium_src_dir, 'testing',
49 'buildbot', 'gn_isolate_map.pyl')
dpranke8c2cfd32015-09-17 20:12:3350 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5151 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3352 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3553 self.args = argparse.Namespace()
54 self.configs = {}
55 self.masters = {}
56 self.mixins = {}
dprankefe4602312015-04-08 16:20:3557
dpranke255085e2016-03-16 05:23:5958 def Main(self, args):
59 self.ParseArgs(args)
60 try:
61 ret = self.args.func()
62 if ret:
63 self.DumpInputFiles()
64 return ret
65 except KeyboardInterrupt:
dprankecb4a2e242016-09-19 01:13:1466 self.Print('interrupted, exiting')
dpranke255085e2016-03-16 05:23:5967 return 130
dprankebbe6d4672016-04-19 06:56:5768 except Exception:
dpranke255085e2016-03-16 05:23:5969 self.DumpInputFiles()
dprankebbe6d4672016-04-19 06:56:5770 s = traceback.format_exc()
71 for l in s.splitlines():
72 self.Print(l)
dpranke255085e2016-03-16 05:23:5973 return 1
74
dprankefe4602312015-04-08 16:20:3575 def ParseArgs(self, argv):
76 def AddCommonOptions(subp):
77 subp.add_argument('-b', '--builder',
78 help='builder name to look up config from')
79 subp.add_argument('-m', '--master',
80 help='master name to look up config from')
81 subp.add_argument('-c', '--config',
82 help='configuration to analyze')
shenghuazhang804b21542016-10-11 02:06:4983 subp.add_argument('--phase',
84 help='optional phase name (used when builders '
85 'do multiple compiles with different '
86 'arguments in a single build)')
dprankefe4602312015-04-08 16:20:3587 subp.add_argument('-f', '--config-file', metavar='PATH',
88 default=self.default_config,
89 help='path to config file '
kjellander902bcb62016-10-26 06:20:5090 '(default is %(default)s)')
91 subp.add_argument('-i', '--isolate-map-file', metavar='PATH',
92 default=self.default_isolate_map,
93 help='path to isolate map file '
94 '(default is %(default)s)')
dpranked0c138b2016-04-13 18:28:4795 subp.add_argument('-g', '--goma-dir',
96 help='path to goma directory')
machenbach60ebf6202016-06-07 14:27:3997 subp.add_argument('--gyp-script', metavar='PATH',
98 default=self.PathJoin('build', 'gyp_chromium'),
99 help='path to gyp script relative to project root '
100 '(default is %(default)s)')
agrieve41d21a72016-04-14 18:02:26101 subp.add_argument('--android-version-code',
102 help='Sets GN arg android_default_version_code and '
103 'GYP_DEFINE app_manifest_version_code')
104 subp.add_argument('--android-version-name',
105 help='Sets GN arg android_default_version_name and '
106 'GYP_DEFINE app_manifest_version_name')
dprankefe4602312015-04-08 16:20:35107 subp.add_argument('-n', '--dryrun', action='store_true',
108 help='Do a dry run (i.e., do nothing, just print '
109 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:40110 subp.add_argument('-v', '--verbose', action='store_true',
111 help='verbose logging')
dprankefe4602312015-04-08 16:20:35112
113 parser = argparse.ArgumentParser(prog='mb')
114 subps = parser.add_subparsers()
115
116 subp = subps.add_parser('analyze',
117 help='analyze whether changes to a set of files '
118 'will cause a set of binaries to be rebuilt.')
119 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:25120 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35121 help='path build was generated into.')
122 subp.add_argument('input_path', nargs=1,
123 help='path to a file containing the input arguments '
124 'as a JSON object.')
125 subp.add_argument('output_path', nargs=1,
126 help='path to a file containing the output arguments '
127 'as a JSON object.')
128 subp.set_defaults(func=self.CmdAnalyze)
129
dprankef37aebb92016-09-23 01:14:49130 subp = subps.add_parser('export',
131 help='print out the expanded configuration for'
132 'each builder as a JSON object')
133 subp.add_argument('-f', '--config-file', metavar='PATH',
134 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50135 help='path to config file (default is %(default)s)')
dprankef37aebb92016-09-23 01:14:49136 subp.add_argument('-g', '--goma-dir',
137 help='path to goma directory')
138 subp.set_defaults(func=self.CmdExport)
139
dprankefe4602312015-04-08 16:20:35140 subp = subps.add_parser('gen',
141 help='generate a new set of build files')
142 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39143 subp.add_argument('--swarming-targets-file',
144 help='save runtime dependencies for targets listed '
145 'in file.')
dpranked8113582015-06-05 20:08:25146 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35147 help='path to generate build into')
148 subp.set_defaults(func=self.CmdGen)
149
dpranke751516a2015-10-03 01:11:34150 subp = subps.add_parser('isolate',
151 help='generate the .isolate files for a given'
152 'binary')
153 AddCommonOptions(subp)
154 subp.add_argument('path', nargs=1,
155 help='path build was generated into')
156 subp.add_argument('target', nargs=1,
157 help='ninja target to generate the isolate for')
158 subp.set_defaults(func=self.CmdIsolate)
159
dprankefe4602312015-04-08 16:20:35160 subp = subps.add_parser('lookup',
161 help='look up the command for a given config or '
162 'builder')
163 AddCommonOptions(subp)
164 subp.set_defaults(func=self.CmdLookup)
165
dpranke030d7a6d2016-03-26 17:23:50166 subp = subps.add_parser(
167 'run',
168 help='build and run the isolated version of a '
169 'binary',
170 formatter_class=argparse.RawDescriptionHelpFormatter)
171 subp.description = (
172 'Build, isolate, and run the given binary with the command line\n'
173 'listed in the isolate. You may pass extra arguments after the\n'
174 'target; use "--" if the extra arguments need to include switches.\n'
175 '\n'
176 'Examples:\n'
177 '\n'
178 ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n'
179 ' //out/Default content_browsertests\n'
180 '\n'
181 ' % tools/mb/mb.py run out/Default content_browsertests\n'
182 '\n'
183 ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n'
184 ' --test-launcher-retry-limit=0'
185 '\n'
186 )
187
dpranke751516a2015-10-03 01:11:34188 AddCommonOptions(subp)
189 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
190 help='Number of jobs to pass to ninja')
191 subp.add_argument('--no-build', dest='build', default=True,
192 action='store_false',
193 help='Do not build, just isolate and run')
194 subp.add_argument('path', nargs=1,
dpranke030d7a6d2016-03-26 17:23:50195 help=('path to generate build into (or use).'
196 ' This can be either a regular path or a '
197 'GN-style source-relative path like '
198 '//out/Default.'))
dpranke751516a2015-10-03 01:11:34199 subp.add_argument('target', nargs=1,
200 help='ninja target to build and run')
dpranke030d7a6d2016-03-26 17:23:50201 subp.add_argument('extra_args', nargs='*',
202 help=('extra args to pass to the isolate to run. Use '
203 '"--" as the first arg if you need to pass '
204 'switches'))
dpranke751516a2015-10-03 01:11:34205 subp.set_defaults(func=self.CmdRun)
206
dprankefe4602312015-04-08 16:20:35207 subp = subps.add_parser('validate',
208 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17209 subp.add_argument('-f', '--config-file', metavar='PATH',
210 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50211 help='path to config file (default is %(default)s)')
dprankefe4602312015-04-08 16:20:35212 subp.set_defaults(func=self.CmdValidate)
213
dpranke867bcf4a2016-03-14 22:28:32214 subp = subps.add_parser('audit',
215 help='Audit the config file to track progress')
216 subp.add_argument('-f', '--config-file', metavar='PATH',
217 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50218 help='path to config file (default is %(default)s)')
dpranke867bcf4a2016-03-14 22:28:32219 subp.add_argument('-i', '--internal', action='store_true',
220 help='check internal masters also')
221 subp.add_argument('-m', '--master', action='append',
222 help='master to audit (default is all non-internal '
223 'masters in file)')
224 subp.add_argument('-u', '--url-template', action='store',
225 default='https://build.chromium.org/p/'
226 '{master}/json/builders',
227 help='URL scheme for JSON APIs to buildbot '
228 '(default: %(default)s) ')
aneeshmde50f472016-04-01 01:13:10229 subp.add_argument('-c', '--check-compile', action='store_true',
230 help='check whether tbd and master-only bots actually'
231 ' do compiles')
dpranke867bcf4a2016-03-14 22:28:32232 subp.set_defaults(func=self.CmdAudit)
233
dprankefe4602312015-04-08 16:20:35234 subp = subps.add_parser('help',
235 help='Get help on a subcommand.')
236 subp.add_argument(nargs='?', action='store', dest='subcommand',
237 help='The command to get help for.')
238 subp.set_defaults(func=self.CmdHelp)
239
240 self.args = parser.parse_args(argv)
241
dprankeb2be10a2016-02-22 17:11:00242 def DumpInputFiles(self):
243
dprankef7b7eb7a2016-03-28 22:42:59244 def DumpContentsOfFilePassedTo(arg_name, path):
dprankeb2be10a2016-02-22 17:11:00245 if path and self.Exists(path):
dprankef7b7eb7a2016-03-28 22:42:59246 self.Print("\n# To recreate the file passed to %s:" % arg_name)
dprankecb4a2e242016-09-19 01:13:14247 self.Print("%% cat > %s <<EOF" % path)
dprankeb2be10a2016-02-22 17:11:00248 contents = self.ReadFile(path)
dprankef7b7eb7a2016-03-28 22:42:59249 self.Print(contents)
250 self.Print("EOF\n%\n")
dprankeb2be10a2016-02-22 17:11:00251
dprankef7b7eb7a2016-03-28 22:42:59252 if getattr(self.args, 'input_path', None):
253 DumpContentsOfFilePassedTo(
254 'argv[0] (input_path)', self.args.input_path[0])
255 if getattr(self.args, 'swarming_targets_file', None):
256 DumpContentsOfFilePassedTo(
257 '--swarming-targets-file', self.args.swarming_targets_file)
dprankeb2be10a2016-02-22 17:11:00258
dprankefe4602312015-04-08 16:20:35259 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34260 vals = self.Lookup()
dprankee88057c2016-04-12 22:40:08261 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35262 if vals['type'] == 'gn':
263 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35264 else:
dpranke751516a2015-10-03 01:11:34265 return self.RunGYPAnalyze(vals)
dprankefe4602312015-04-08 16:20:35266
dprankef37aebb92016-09-23 01:14:49267 def CmdExport(self):
268 self.ReadConfigFile()
269 obj = {}
270 for master, builders in self.masters.items():
271 obj[master] = {}
272 for builder in builders:
273 config = self.masters[master][builder]
274 if not config:
275 continue
276
shenghuazhang804b21542016-10-11 02:06:49277 if isinstance(config, dict):
278 args = {k: self.FlattenConfig(v)['gn_args']
279 for k, v in config.items()}
dprankef37aebb92016-09-23 01:14:49280 elif config.startswith('//'):
281 args = config
282 else:
283 args = self.FlattenConfig(config)['gn_args']
284 if 'error' in args:
285 continue
286
287 obj[master][builder] = args
288
289 # Dump object and trim trailing whitespace.
290 s = '\n'.join(l.rstrip() for l in
291 json.dumps(obj, sort_keys=True, indent=2).splitlines())
292 self.Print(s)
293 return 0
294
dprankefe4602312015-04-08 16:20:35295 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34296 vals = self.Lookup()
dprankec161aa92015-09-14 20:21:13297 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35298 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50299 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35300 else:
dpranke751516a2015-10-03 01:11:34301 return self.RunGYPGen(vals)
dprankefe4602312015-04-08 16:20:35302
303 def CmdHelp(self):
304 if self.args.subcommand:
305 self.ParseArgs([self.args.subcommand, '--help'])
306 else:
307 self.ParseArgs(['--help'])
308
dpranke751516a2015-10-03 01:11:34309 def CmdIsolate(self):
310 vals = self.GetConfig()
311 if not vals:
312 return 1
313
314 if vals['type'] == 'gn':
315 return self.RunGNIsolate(vals)
316 else:
317 return self.Build('%s_run' % self.args.target[0])
318
319 def CmdLookup(self):
320 vals = self.Lookup()
321 if vals['type'] == 'gn':
dprankeeca4a782016-04-14 01:42:38322 cmd = self.GNCmd('gen', '_path_')
323 gn_args = self.GNArgs(vals)
324 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
dpranke751516a2015-10-03 01:11:34325 env = None
326 else:
327 cmd, env = self.GYPCmd('_path_', vals)
328
329 self.PrintCmd(cmd, env)
330 return 0
331
332 def CmdRun(self):
333 vals = self.GetConfig()
334 if not vals:
335 return 1
336
337 build_dir = self.args.path[0]
338 target = self.args.target[0]
339
340 if vals['type'] == 'gn':
341 if self.args.build:
342 ret = self.Build(target)
343 if ret:
344 return ret
345 ret = self.RunGNIsolate(vals)
346 if ret:
347 return ret
348 else:
349 ret = self.Build('%s_run' % target)
350 if ret:
351 return ret
352
dpranke030d7a6d2016-03-26 17:23:50353 cmd = [
dpranke751516a2015-10-03 01:11:34354 self.executable,
355 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
356 'run',
357 '-s',
dpranke030d7a6d2016-03-26 17:23:50358 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
359 ]
360 if self.args.extra_args:
361 cmd += ['--'] + self.args.extra_args
362
363 ret, _, _ = self.Run(cmd, force_verbose=False, buffer_output=False)
dpranke751516a2015-10-03 01:11:34364
365 return ret
366
dpranke0cafc162016-03-19 00:41:10367 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35368 errs = []
369
370 # Read the file to make sure it parses.
371 self.ReadConfigFile()
372
dpranke3be00142016-03-17 22:46:04373 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35374 all_configs = {}
dprankefe4602312015-04-08 16:20:35375 for master in self.masters:
dpranke3be00142016-03-17 22:46:04376 for config in self.masters[master].values():
shenghuazhang804b21542016-10-11 02:06:49377 if isinstance(config, dict):
378 for c in config.values():
dprankeb9380a12016-07-21 21:44:09379 all_configs[c] = master
380 else:
381 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35382
dpranke9dd5e252016-04-14 04:23:09383 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35384 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09385 if config.startswith('//'):
386 if not self.Exists(self.ToAbsPath(config)):
387 errs.append('Unknown args file "%s" referenced from "%s".' %
388 (config, loc))
389 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35390 errs.append('Unknown config "%s" referenced from "%s".' %
391 (config, loc))
392
393 # Check that every actual config is actually referenced.
394 for config in self.configs:
395 if not config in all_configs:
396 errs.append('Unused config "%s".' % config)
397
398 # Figure out the whole list of mixins, and check that every mixin
399 # listed by a config or another mixin actually exists.
400 referenced_mixins = set()
401 for config, mixins in self.configs.items():
402 for mixin in mixins:
403 if not mixin in self.mixins:
404 errs.append('Unknown mixin "%s" referenced by config "%s".' %
405 (mixin, config))
406 referenced_mixins.add(mixin)
407
408 for mixin in self.mixins:
409 for sub_mixin in self.mixins[mixin].get('mixins', []):
410 if not sub_mixin in self.mixins:
411 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
412 (sub_mixin, mixin))
413 referenced_mixins.add(sub_mixin)
414
415 # Check that every mixin defined is actually referenced somewhere.
416 for mixin in self.mixins:
417 if not mixin in referenced_mixins:
418 errs.append('Unreferenced mixin "%s".' % mixin)
419
dpranke255085e2016-03-16 05:23:59420 # If we're checking the Chromium config, check that the 'chromium' bots
421 # which build public artifacts do not include the chrome_with_codecs mixin.
422 if self.args.config_file == self.default_config:
423 if 'chromium' in self.masters:
424 for builder in self.masters['chromium']:
425 config = self.masters['chromium'][builder]
426 def RecurseMixins(current_mixin):
427 if current_mixin == 'chrome_with_codecs':
428 errs.append('Public artifact builder "%s" can not contain the '
429 '"chrome_with_codecs" mixin.' % builder)
430 return
431 if not 'mixins' in self.mixins[current_mixin]:
432 return
433 for mixin in self.mixins[current_mixin]['mixins']:
434 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41435
dpranke255085e2016-03-16 05:23:59436 for mixin in self.configs[config]:
437 RecurseMixins(mixin)
438 else:
439 errs.append('Missing "chromium" master. Please update this '
440 'proprietary codecs check with the name of the master '
441 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41442
dprankefe4602312015-04-08 16:20:35443 if errs:
dpranke4323c80632015-08-10 22:53:54444 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17445 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35446
dpranke0cafc162016-03-19 00:41:10447 if print_ok:
448 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35449 return 0
450
dpranke867bcf4a2016-03-14 22:28:32451 def CmdAudit(self):
452 """Track the progress of the GYP->GN migration on the bots."""
453
dpranke0cafc162016-03-19 00:41:10454 # First, make sure the config file is okay, but don't print anything
455 # if it is (it will throw an error if it isn't).
456 self.CmdValidate(print_ok=False)
457
dpranke867bcf4a2016-03-14 22:28:32458 stats = OrderedDict()
459 STAT_MASTER_ONLY = 'Master only'
460 STAT_CONFIG_ONLY = 'Config only'
461 STAT_TBD = 'Still TBD'
462 STAT_GYP = 'Still GYP'
463 STAT_DONE = 'Done (on GN)'
464 stats[STAT_MASTER_ONLY] = 0
465 stats[STAT_CONFIG_ONLY] = 0
466 stats[STAT_TBD] = 0
467 stats[STAT_GYP] = 0
468 stats[STAT_DONE] = 0
469
aneeshmde50f472016-04-01 01:13:10470 def PrintBuilders(heading, builders, notes):
dpranke867bcf4a2016-03-14 22:28:32471 stats.setdefault(heading, 0)
472 stats[heading] += len(builders)
473 if builders:
474 self.Print(' %s:' % heading)
475 for builder in sorted(builders):
aneeshmde50f472016-04-01 01:13:10476 self.Print(' %s%s' % (builder, notes[builder]))
dpranke867bcf4a2016-03-14 22:28:32477
478 self.ReadConfigFile()
479
480 masters = self.args.master or self.masters
481 for master in sorted(masters):
482 url = self.args.url_template.replace('{master}', master)
483
484 self.Print('Auditing %s' % master)
485
486 MASTERS_TO_SKIP = (
487 'client.skia',
488 'client.v8.fyi',
489 'tryserver.v8',
490 )
491 if master in MASTERS_TO_SKIP:
492 # Skip these bots because converting them is the responsibility of
493 # those teams and out of scope for the Chromium migration to GN.
494 self.Print(' Skipped (out of scope)')
495 self.Print('')
496 continue
497
dpranke6b6e0b82016-07-28 21:32:34498 INTERNAL_MASTERS = ('official.desktop', 'official.desktop.continuous',
499 'internal.client.kitchensync')
dpranke867bcf4a2016-03-14 22:28:32500 if master in INTERNAL_MASTERS and not self.args.internal:
501 # Skip these because the servers aren't accessible by default ...
502 self.Print(' Skipped (internal)')
503 self.Print('')
504 continue
505
506 try:
507 # Fetch the /builders contents from the buildbot master. The
508 # keys of the dict are the builder names themselves.
509 json_contents = self.Fetch(url)
510 d = json.loads(json_contents)
511 except Exception as e:
512 self.Print(str(e))
513 return 1
514
515 config_builders = set(self.masters[master])
516 master_builders = set(d.keys())
517 both = master_builders & config_builders
518 master_only = master_builders - config_builders
519 config_only = config_builders - master_builders
520 tbd = set()
521 gyp = set()
522 done = set()
aneeshmde50f472016-04-01 01:13:10523 notes = {builder: '' for builder in config_builders | master_builders}
dpranke867bcf4a2016-03-14 22:28:32524
525 for builder in both:
526 config = self.masters[master][builder]
527 if config == 'tbd':
528 tbd.add(builder)
shenghuazhang804b21542016-10-11 02:06:49529 elif isinstance(config, dict):
530 vals = self.FlattenConfig(config.values()[0])
dprankeb9380a12016-07-21 21:44:09531 if vals['type'] == 'gyp':
532 gyp.add(builder)
533 else:
534 done.add(builder)
dprankebbe6d4672016-04-19 06:56:57535 elif config.startswith('//'):
536 done.add(builder)
dpranke867bcf4a2016-03-14 22:28:32537 else:
dpranke867bcf4a2016-03-14 22:28:32538 vals = self.FlattenConfig(config)
539 if vals['type'] == 'gyp':
540 gyp.add(builder)
541 else:
542 done.add(builder)
543
aneeshmde50f472016-04-01 01:13:10544 if self.args.check_compile and (tbd or master_only):
545 either = tbd | master_only
546 for builder in either:
547 notes[builder] = ' (' + self.CheckCompile(master, builder) +')'
548
dpranke867bcf4a2016-03-14 22:28:32549 if master_only or config_only or tbd or gyp:
aneeshmde50f472016-04-01 01:13:10550 PrintBuilders(STAT_MASTER_ONLY, master_only, notes)
551 PrintBuilders(STAT_CONFIG_ONLY, config_only, notes)
552 PrintBuilders(STAT_TBD, tbd, notes)
553 PrintBuilders(STAT_GYP, gyp, notes)
dpranke867bcf4a2016-03-14 22:28:32554 else:
dprankebbe6d4672016-04-19 06:56:57555 self.Print(' All GN!')
dpranke867bcf4a2016-03-14 22:28:32556
557 stats[STAT_DONE] += len(done)
558
559 self.Print('')
560
561 fmt = '{:<27} {:>4}'
562 self.Print(fmt.format('Totals', str(sum(int(v) for v in stats.values()))))
563 self.Print(fmt.format('-' * 27, '----'))
564 for stat, count in stats.items():
565 self.Print(fmt.format(stat, str(count)))
566
567 return 0
568
dprankefe4602312015-04-08 16:20:35569 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34570 build_dir = self.args.path[0]
571
dprankef37aebb92016-09-23 01:14:49572 vals = self.DefaultVals()
dpranke751516a2015-10-03 01:11:34573 if self.args.builder or self.args.master or self.args.config:
574 vals = self.Lookup()
575 if vals['type'] == 'gn':
576 # Re-run gn gen in order to ensure the config is consistent with the
577 # build dir.
578 self.RunGNGen(vals)
579 return vals
580
dpranke751516a2015-10-03 01:11:34581 mb_type_path = self.PathJoin(self.ToAbsPath(build_dir), 'mb_type')
582 if not self.Exists(mb_type_path):
brucedawsonecc0c1cd2016-06-02 18:24:58583 toolchain_path = self.PathJoin(self.ToAbsPath(build_dir),
584 'toolchain.ninja')
585 if not self.Exists(toolchain_path):
dpranke751516a2015-10-03 01:11:34586 self.Print('Must either specify a path to an existing GN build dir '
587 'or pass in a -m/-b pair or a -c flag to specify the '
588 'configuration')
589 return {}
590 else:
591 mb_type = 'gn'
592 else:
593 mb_type = self.ReadFile(mb_type_path).strip()
594
595 if mb_type == 'gn':
dprankef37aebb92016-09-23 01:14:49596 vals['gn_args'] = self.GNArgsFromDir(build_dir)
dpranke751516a2015-10-03 01:11:34597 vals['type'] = mb_type
598
599 return vals
600
dprankef37aebb92016-09-23 01:14:49601 def GNArgsFromDir(self, build_dir):
brucedawsonecc0c1cd2016-06-02 18:24:58602 args_contents = ""
603 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
604 if self.Exists(gn_args_path):
605 args_contents = self.ReadFile(gn_args_path)
dpranke751516a2015-10-03 01:11:34606 gn_args = []
607 for l in args_contents.splitlines():
608 fields = l.split(' ')
609 name = fields[0]
610 val = ' '.join(fields[2:])
611 gn_args.append('%s=%s' % (name, val))
612
dprankef37aebb92016-09-23 01:14:49613 return ' '.join(gn_args)
dpranke751516a2015-10-03 01:11:34614
615 def Lookup(self):
dprankef37aebb92016-09-23 01:14:49616 vals = self.ReadIOSBotConfig()
dprankee0f486f2015-11-19 23:42:00617 if not vals:
618 self.ReadConfigFile()
619 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09620 if config.startswith('//'):
621 if not self.Exists(self.ToAbsPath(config)):
622 raise MBErr('args file "%s" not found' % config)
dprankef37aebb92016-09-23 01:14:49623 vals = self.DefaultVals()
624 vals['args_file'] = config
dpranke9dd5e252016-04-14 04:23:09625 else:
626 if not config in self.configs:
627 raise MBErr('Config "%s" not found in %s' %
628 (config, self.args.config_file))
629 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34630
631 # Do some basic sanity checking on the config so that we
632 # don't have to do this in every caller.
dprankef37aebb92016-09-23 01:14:49633 if 'type' not in vals:
634 vals['type'] = 'gn'
dpranke751516a2015-10-03 01:11:34635 assert vals['type'] in ('gn', 'gyp'), (
636 'Unknown meta-build type "%s"' % vals['gn_args'])
637
638 return vals
dprankefe4602312015-04-08 16:20:35639
dprankef37aebb92016-09-23 01:14:49640 def ReadIOSBotConfig(self):
dprankee0f486f2015-11-19 23:42:00641 if not self.args.master or not self.args.builder:
642 return {}
643 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
644 self.args.master, self.args.builder + '.json')
645 if not self.Exists(path):
646 return {}
647
648 contents = json.loads(self.ReadFile(path))
649 gyp_vals = contents.get('GYP_DEFINES', {})
650 if isinstance(gyp_vals, dict):
651 gyp_defines = ' '.join('%s=%s' % (k, v) for k, v in gyp_vals.items())
652 else:
653 gyp_defines = ' '.join(gyp_vals)
654 gn_args = ' '.join(contents.get('gn_args', []))
655
dprankef37aebb92016-09-23 01:14:49656 vals = self.DefaultVals()
657 vals['gn_args'] = gn_args
658 vals['gyp_defines'] = gyp_defines
659 vals['type'] = contents.get('mb_type', 'gn')
660 return vals
dprankee0f486f2015-11-19 23:42:00661
dprankefe4602312015-04-08 16:20:35662 def ReadConfigFile(self):
663 if not self.Exists(self.args.config_file):
664 raise MBErr('config file not found at %s' % self.args.config_file)
665
666 try:
667 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
668 except SyntaxError as e:
669 raise MBErr('Failed to parse config file "%s": %s' %
670 (self.args.config_file, e))
671
dprankefe4602312015-04-08 16:20:35672 self.configs = contents['configs']
673 self.masters = contents['masters']
674 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35675
dprankecb4a2e242016-09-19 01:13:14676 def ReadIsolateMap(self):
kjellander902bcb62016-10-26 06:20:50677 if not self.Exists(self.args.isolate_map_file):
678 raise MBErr('isolate map file not found at %s' %
679 self.args.isolate_map_file)
680 try:
681 return ast.literal_eval(self.ReadFile(self.args.isolate_map_file))
682 except SyntaxError as e:
683 raise MBErr('Failed to parse isolate map file "%s": %s' %
684 (self.args.isolate_map_file, e))
dprankecb4a2e242016-09-19 01:13:14685
dprankefe4602312015-04-08 16:20:35686 def ConfigFromArgs(self):
687 if self.args.config:
688 if self.args.master or self.args.builder:
689 raise MBErr('Can not specific both -c/--config and -m/--master or '
690 '-b/--builder')
691
692 return self.args.config
693
694 if not self.args.master or not self.args.builder:
695 raise MBErr('Must specify either -c/--config or '
696 '(-m/--master and -b/--builder)')
697
698 if not self.args.master in self.masters:
699 raise MBErr('Master name "%s" not found in "%s"' %
700 (self.args.master, self.args.config_file))
701
702 if not self.args.builder in self.masters[self.args.master]:
703 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
704 (self.args.builder, self.args.master, self.args.config_file))
705
dprankeb9380a12016-07-21 21:44:09706 config = self.masters[self.args.master][self.args.builder]
shenghuazhang804b21542016-10-11 02:06:49707 if isinstance(config, dict):
dprankeb9380a12016-07-21 21:44:09708 if self.args.phase is None:
709 raise MBErr('Must specify a build --phase for %s on %s' %
710 (self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49711 phase = str(self.args.phase)
712 if phase not in config:
713 raise MBErr('Phase %s doesn\'t exist for %s on %s' %
dprankeb9380a12016-07-21 21:44:09714 (phase, self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49715 return config[phase]
dprankeb9380a12016-07-21 21:44:09716
717 if self.args.phase is not None:
718 raise MBErr('Must not specify a build --phase for %s on %s' %
719 (self.args.builder, self.args.master))
720 return config
dprankefe4602312015-04-08 16:20:35721
722 def FlattenConfig(self, config):
723 mixins = self.configs[config]
dprankef37aebb92016-09-23 01:14:49724 vals = self.DefaultVals()
dprankefe4602312015-04-08 16:20:35725
726 visited = []
727 self.FlattenMixins(mixins, vals, visited)
728 return vals
729
dprankef37aebb92016-09-23 01:14:49730 def DefaultVals(self):
731 return {
732 'args_file': '',
733 'cros_passthrough': False,
734 'gn_args': '',
735 'gyp_defines': '',
736 'gyp_crosscompile': False,
737 'type': 'gn',
738 }
739
dprankefe4602312015-04-08 16:20:35740 def FlattenMixins(self, mixins, vals, visited):
741 for m in mixins:
742 if m not in self.mixins:
743 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22744
dprankefe4602312015-04-08 16:20:35745 visited.append(m)
746
747 mixin_vals = self.mixins[m]
dpranke73ed0d62016-04-25 19:18:34748
749 if 'cros_passthrough' in mixin_vals:
750 vals['cros_passthrough'] = mixin_vals['cros_passthrough']
Dirk Pranke6b99f072017-04-05 00:58:30751 if 'args_file' in mixin_vals:
752 if vals['args_file']:
753 raise MBErr('args_file specified multiple times in mixins '
754 'for %s on %s' % (self.args.builder, self.args.master))
755 vals['args_file'] = mixin_vals['args_file']
dprankefe4602312015-04-08 16:20:35756 if 'gn_args' in mixin_vals:
757 if vals['gn_args']:
758 vals['gn_args'] += ' ' + mixin_vals['gn_args']
759 else:
760 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59761 if 'gyp_crosscompile' in mixin_vals:
762 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35763 if 'gyp_defines' in mixin_vals:
764 if vals['gyp_defines']:
765 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
766 else:
767 vals['gyp_defines'] = mixin_vals['gyp_defines']
dpranke73ed0d62016-04-25 19:18:34768 if 'type' in mixin_vals:
769 vals['type'] = mixin_vals['type']
770
dprankefe4602312015-04-08 16:20:35771 if 'mixins' in mixin_vals:
772 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
773 return vals
774
dprankec161aa92015-09-14 20:21:13775 def ClobberIfNeeded(self, vals):
776 path = self.args.path[0]
777 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33778 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13779 needs_clobber = False
780 new_mb_type = vals['type']
781 if self.Exists(build_dir):
782 if self.Exists(mb_type_path):
783 old_mb_type = self.ReadFile(mb_type_path)
784 if old_mb_type != new_mb_type:
785 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
786 (old_mb_type, new_mb_type, path))
787 needs_clobber = True
788 else:
789 # There is no 'mb_type' file in the build directory, so this probably
790 # means that the prior build(s) were not done through mb, and we
791 # have no idea if this was a GYP build or a GN build. Clobber it
792 # to be safe.
793 self.Print("%s/mb_type missing, clobbering to be safe" % path)
794 needs_clobber = True
795
dpranke3cec199c2015-09-22 23:29:02796 if self.args.dryrun:
797 return
798
dprankec161aa92015-09-14 20:21:13799 if needs_clobber:
800 self.RemoveDirectory(build_dir)
801
802 self.MaybeMakeDirectory(build_dir)
803 self.WriteFile(mb_type_path, new_mb_type)
804
Dirk Pranke0fd41bcd2015-06-19 00:05:50805 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34806 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50807
dprankeeca4a782016-04-14 01:42:38808 cmd = self.GNCmd('gen', build_dir, '--check')
809 gn_args = self.GNArgs(vals)
810
811 # Since GN hasn't run yet, the build directory may not even exist.
812 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
813
814 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
dpranke4ff8b9f2016-04-15 03:07:54815 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
dpranke74559b52015-06-10 21:20:39816
817 swarming_targets = []
dpranke751516a2015-10-03 01:11:34818 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39819 # We need GN to generate the list of runtime dependencies for
820 # the compile targets listed (one per line) in the file so
dprankecb4a2e242016-09-19 01:13:14821 # we can run them via swarming. We use gn_isolate_map.pyl to convert
dpranke74559b52015-06-10 21:20:39822 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00823 path = self.args.swarming_targets_file
824 if not self.Exists(path):
825 self.WriteFailureAndRaise('"%s" does not exist' % path,
826 output_path=None)
827 contents = self.ReadFile(path)
828 swarming_targets = set(contents.splitlines())
dprankeb2be10a2016-02-22 17:11:00829
dprankecb4a2e242016-09-19 01:13:14830 isolate_map = self.ReadIsolateMap()
831 err, labels = self.MapTargetsToLabels(isolate_map, swarming_targets)
dprankeb2be10a2016-02-22 17:11:00832 if err:
dprankecb4a2e242016-09-19 01:13:14833 raise MBErr(err)
dpranke74559b52015-06-10 21:20:39834
dpranke751516a2015-10-03 01:11:34835 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankecb4a2e242016-09-19 01:13:14836 self.WriteFile(gn_runtime_deps_path, '\n'.join(labels) + '\n')
dpranke74559b52015-06-10 21:20:39837 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
838
dprankefe4602312015-04-08 16:20:35839 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40840 if ret:
841 # If `gn gen` failed, we should exit early rather than trying to
842 # generate isolates. Run() will have already logged any error output.
843 self.Print('GN gen failed: %d' % ret)
844 return ret
dpranke74559b52015-06-10 21:20:39845
jbudoricke3c4f95e2016-04-28 23:17:38846 android = 'target_os="android"' in vals['gn_args']
dpranke74559b52015-06-10 21:20:39847 for target in swarming_targets:
jbudoricke3c4f95e2016-04-28 23:17:38848 if android:
849 # Android targets may be either android_apk or executable. The former
jbudorick91c8a6012016-01-29 23:20:02850 # will result in runtime_deps associated with the stamp file, while the
851 # latter will result in runtime_deps associated with the executable.
dprankecb4a2e242016-09-19 01:13:14852 label = isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02853 runtime_deps_targets = [
dprankecb4a2e242016-09-19 01:13:14854 target + '.runtime_deps',
dpranke48ccf8f2016-03-28 23:58:28855 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
dprankecb4a2e242016-09-19 01:13:14856 elif (isolate_map[target]['type'] == 'script' or
857 isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11858 # For script targets, the build target is usually a group,
859 # for which gn generates the runtime_deps next to the stamp file
eyaich82d5ac942016-11-03 12:13:49860 # for the label, which lives under the obj/ directory, but it may
861 # also be an executable.
dprankecb4a2e242016-09-19 01:13:14862 label = isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28863 runtime_deps_targets = [
864 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
eyaich82d5ac942016-11-03 12:13:49865 if self.platform == 'win32':
866 runtime_deps_targets += [ target + '.exe.runtime_deps' ]
867 else:
868 runtime_deps_targets += [ target + '.runtime_deps' ]
dpranke48ccf8f2016-03-28 23:58:28869 elif self.platform == 'win32':
870 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52871 else:
dpranke48ccf8f2016-03-28 23:58:28872 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02873
dpranke48ccf8f2016-03-28 23:58:28874 for r in runtime_deps_targets:
875 runtime_deps_path = self.ToAbsPath(build_dir, r)
876 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02877 break
878 else:
dpranke48ccf8f2016-03-28 23:58:28879 raise MBErr('did not generate any of %s' %
880 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39881
dprankecb4a2e242016-09-19 01:13:14882 command, extra_files = self.GetIsolateCommand(target, vals)
dpranked5b2b9432015-06-23 16:55:30883
dpranke48ccf8f2016-03-28 23:58:28884 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30885
dpranke751516a2015-10-03 01:11:34886 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
887 extra_files)
dpranked5b2b9432015-06-23 16:55:30888
dpranke751516a2015-10-03 01:11:34889 return 0
890
891 def RunGNIsolate(self, vals):
dprankecb4a2e242016-09-19 01:13:14892 target = self.args.target[0]
893 isolate_map = self.ReadIsolateMap()
894 err, labels = self.MapTargetsToLabels(isolate_map, [target])
895 if err:
896 raise MBErr(err)
897 label = labels[0]
dpranke751516a2015-10-03 01:11:34898
899 build_dir = self.args.path[0]
dprankecb4a2e242016-09-19 01:13:14900 command, extra_files = self.GetIsolateCommand(target, vals)
dpranke751516a2015-10-03 01:11:34901
dprankeeca4a782016-04-14 01:42:38902 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20903 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34904 if ret:
dpranke030d7a6d2016-03-26 17:23:50905 if out:
906 self.Print(out)
dpranke751516a2015-10-03 01:11:34907 return ret
908
909 runtime_deps = out.splitlines()
910
911 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
912 extra_files)
913
914 ret, _, _ = self.Run([
915 self.executable,
916 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
917 'check',
918 '-i',
919 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
920 '-s',
921 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
922 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30923
dprankefe4602312015-04-08 16:20:35924 return ret
925
dpranke751516a2015-10-03 01:11:34926 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
927 extra_files):
928 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
929 self.WriteFile(isolate_path,
930 pprint.pformat({
931 'variables': {
932 'command': command,
933 'files': sorted(runtime_deps + extra_files),
934 }
935 }) + '\n')
936
937 self.WriteJSON(
938 {
939 'args': [
940 '--isolated',
941 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
942 '--isolate',
943 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
944 ],
945 'dir': self.chromium_src_dir,
946 'version': 1,
947 },
948 isolate_path + 'd.gen.json',
949 )
950
dprankecb4a2e242016-09-19 01:13:14951 def MapTargetsToLabels(self, isolate_map, targets):
952 labels = []
953 err = ''
954
dprankecb4a2e242016-09-19 01:13:14955 for target in targets:
956 if target == 'all':
957 labels.append(target)
958 elif target.startswith('//'):
959 labels.append(target)
960 else:
961 if target in isolate_map:
thakis024d6f32017-05-16 23:21:42962 if isolate_map[target]['type'] == 'unknown':
dprankecb4a2e242016-09-19 01:13:14963 err += ('test target "%s" type is unknown\n' % target)
964 else:
thakis024d6f32017-05-16 23:21:42965 labels.append(isolate_map[target]['label'])
dprankecb4a2e242016-09-19 01:13:14966 else:
967 err += ('target "%s" not found in '
968 '//testing/buildbot/gn_isolate_map.pyl\n' % target)
969
970 return err, labels
971
dprankeeca4a782016-04-14 01:42:38972 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51973 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20974 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51975 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20976 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51977 else:
dpranke40da0202016-02-13 05:05:20978 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38979
dpranke40da0202016-02-13 05:05:20980 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranke10118bf2016-09-16 23:16:08981 return [gn_path, subcommand, path] + list(args)
dpranke9aba8b212016-09-16 22:52:52982
dprankecb4a2e242016-09-19 01:13:14983
dprankeeca4a782016-04-14 01:42:38984 def GNArgs(self, vals):
dpranke73ed0d62016-04-25 19:18:34985 if vals['cros_passthrough']:
986 if not 'GN_ARGS' in os.environ:
987 raise MBErr('MB is expecting GN_ARGS to be in the environment')
988 gn_args = os.environ['GN_ARGS']
dpranke40260182016-04-27 04:45:16989 if not re.search('target_os.*=.*"chromeos"', gn_args):
dpranke39f3be02016-04-27 04:07:30990 raise MBErr('GN_ARGS is missing target_os = "chromeos": (GN_ARGS=%s)' %
dpranke73ed0d62016-04-25 19:18:34991 gn_args)
992 else:
993 gn_args = vals['gn_args']
994
dpranked0c138b2016-04-13 18:28:47995 if self.args.goma_dir:
996 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38997
agrieve41d21a72016-04-14 18:02:26998 android_version_code = self.args.android_version_code
999 if android_version_code:
1000 gn_args += ' android_default_version_code="%s"' % android_version_code
1001
1002 android_version_name = self.args.android_version_name
1003 if android_version_name:
1004 gn_args += ' android_default_version_name="%s"' % android_version_name
1005
dprankeeca4a782016-04-14 01:42:381006 # Canonicalize the arg string into a sorted, newline-separated list
1007 # of key-value pairs, and de-dup the keys if need be so that only
1008 # the last instance of each arg is listed.
1009 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
1010
dpranke9dd5e252016-04-14 04:23:091011 args_file = vals.get('args_file', None)
1012 if args_file:
1013 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:381014 return gn_args
dprankefe4602312015-04-08 16:20:351015
Dirk Pranke0fd41bcd2015-06-19 00:05:501016 def RunGYPGen(self, vals):
1017 path = self.args.path[0]
1018
dpranke8c2cfd32015-09-17 20:12:331019 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:411020 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:591021 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:351022 return ret
1023
1024 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:331025 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:321026 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:161027 inp = self.ReadInputJSON(['files', 'test_targets',
1028 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321029 self.Print()
1030 self.Print('analyze input:')
1031 self.PrintJSON(inp)
1032 self.Print()
1033
dpranke38f4acb62015-09-29 23:50:411034 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:331035 cmd.extend(['-f', 'analyzer',
1036 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:351037 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:021038 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:321039 if not ret and self.args.verbose:
1040 outp = json.loads(self.ReadFile(self.args.output_path[0]))
1041 self.Print()
1042 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:391043 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:321044 self.Print()
1045
dprankefe4602312015-04-08 16:20:351046 return ret
1047
dprankecb4a2e242016-09-19 01:13:141048 def GetIsolateCommand(self, target, vals):
kylechar50abf5a2016-11-29 16:03:071049 isolate_map = self.ReadIsolateMap()
1050
jbudoricke8428732016-02-02 02:17:061051 android = 'target_os="android"' in vals['gn_args']
1052
kylechar39705682017-01-19 14:37:231053 # This should be true if tests with type='windowed_test_launcher' are
1054 # expected to run using xvfb. For example, Linux Desktop, X11 CrOS and
msisovaea52732017-03-21 08:08:081055 # Ozone CrOS builds. Note that one Ozone build can be used to run differen
1056 # backends. Currently, tests are executed for the headless and X11 backends
1057 # and both can run under Xvfb.
1058 # TODO(tonikitoo,msisov,fwang): Find a way to run tests for the Wayland
1059 # backend.
dpranke7dad4682017-04-26 23:14:551060 use_xvfb = self.platform == 'linux2' and not android
dpranked8113582015-06-05 20:08:251061
1062 asan = 'is_asan=true' in vals['gn_args']
1063 msan = 'is_msan=true' in vals['gn_args']
1064 tsan = 'is_tsan=true' in vals['gn_args']
pcc46233c22017-06-20 22:11:411065 cfi_diag = 'use_cfi_diag=true' in vals['gn_args']
dpranked8113582015-06-05 20:08:251066
dprankecb4a2e242016-09-19 01:13:141067 test_type = isolate_map[target]['type']
dprankefe0d35e2016-02-05 02:43:591068
dprankecb4a2e242016-09-19 01:13:141069 executable = isolate_map[target].get('executable', target)
dprankefe0d35e2016-02-05 02:43:591070 executable_suffix = '.exe' if self.platform == 'win32' else ''
1071
dprankea55584f12015-07-22 00:52:471072 cmdline = []
1073 extra_files = []
dpranked8113582015-06-05 20:08:251074
dprankecb4a2e242016-09-19 01:13:141075 if test_type == 'nontest':
1076 self.WriteFailureAndRaise('We should not be isolating %s.' % target,
1077 output_path=None)
1078
cblumed8e58022016-05-05 03:23:551079 if android and test_type != "script":
bpastenee428ea92017-02-17 02:20:321080 cmdline = [
hzl9b15df52017-03-23 23:43:041081 '../../build/android/test_wrapper/logdog_wrapper.py',
1082 '--target', target,
hzld58d09f2017-03-15 23:15:351083 '--target-devices-file', '${SWARMING_BOT_FILE}',
hzl9ae14452017-04-04 23:38:021084 '--logdog-bin-cmd', '../../bin/logdog_butler',
hzlfc66094f2017-05-18 00:50:481085 '--logcat-output-file', '${ISOLATED_OUTDIR}/logcats',
1086 '--store-tombstones']
kylechar39705682017-01-19 14:37:231087 elif use_xvfb and test_type == 'windowed_test_launcher':
dprankea55584f12015-07-22 00:52:471088 extra_files = [
dpranked8113582015-06-05 20:08:251089 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:471090 '../../testing/xvfb.py',
1091 ]
1092 cmdline = [
dprankefe0d35e2016-02-05 02:43:591093 '../../testing/xvfb.py',
dprankefe0d35e2016-02-05 02:43:591094 './' + str(executable) + executable_suffix,
1095 '--brave-new-test-launcher',
1096 '--test-launcher-bot-mode',
1097 '--asan=%d' % asan,
1098 '--msan=%d' % msan,
1099 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:411100 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:471101 ]
1102 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
1103 extra_files = [
1104 '../../testing/test_env.py'
1105 ]
1106 cmdline = [
1107 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:591108 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:251109 '--brave-new-test-launcher',
1110 '--test-launcher-bot-mode',
1111 '--asan=%d' % asan,
1112 '--msan=%d' % msan,
1113 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:411114 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:471115 ]
dpranke6abd8652015-08-28 03:21:111116 elif test_type == 'script':
1117 extra_files = [
1118 '../../testing/test_env.py'
1119 ]
1120 cmdline = [
1121 '../../testing/test_env.py',
dprankecb4a2e242016-09-19 01:13:141122 '../../' + self.ToSrcRelPath(isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:591123 ]
dprankea55584f12015-07-22 00:52:471124 elif test_type in ('raw'):
1125 extra_files = []
1126 cmdline = [
1127 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:591128 ]
dpranked8113582015-06-05 20:08:251129
dprankea55584f12015-07-22 00:52:471130 else:
1131 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
1132 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:251133
dprankecb4a2e242016-09-19 01:13:141134 cmdline += isolate_map[target].get('args', [])
dprankefe0d35e2016-02-05 02:43:591135
dpranked8113582015-06-05 20:08:251136 return cmdline, extra_files
1137
dpranke74559b52015-06-10 21:20:391138 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:331139 return self.PathJoin(self.chromium_src_dir,
1140 self.ToSrcRelPath(build_path),
1141 *comps)
dpranked8113582015-06-05 20:08:251142
dprankeee5b51f62015-04-09 00:03:221143 def ToSrcRelPath(self, path):
1144 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:501145 if path.startswith('//'):
1146 return path[2:].replace('/', self.sep)
1147 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:351148
1149 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:221150 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:331151 output_dir, _, _ = rpath.rpartition(self.sep)
1152 return output_dir
dprankefe4602312015-04-08 16:20:351153
dpranke38f4acb62015-09-29 23:50:411154 def GYPCmd(self, output_dir, vals):
dpranke73ed0d62016-04-25 19:18:341155 if vals['cros_passthrough']:
1156 if not 'GYP_DEFINES' in os.environ:
1157 raise MBErr('MB is expecting GYP_DEFINES to be in the environment')
1158 gyp_defines = os.environ['GYP_DEFINES']
1159 if not 'chromeos=1' in gyp_defines:
1160 raise MBErr('GYP_DEFINES is missing chromeos=1: (GYP_DEFINES=%s)' %
1161 gyp_defines)
1162 else:
1163 gyp_defines = vals['gyp_defines']
1164
dpranke3cec199c2015-09-22 23:29:021165 goma_dir = self.args.goma_dir
1166
1167 # GYP uses shlex.split() to split the gyp defines into separate arguments,
1168 # so we can support backslashes and and spaces in arguments by quoting
1169 # them, even on Windows, where this normally wouldn't work.
dpranked0c138b2016-04-13 18:28:471170 if goma_dir and ('\\' in goma_dir or ' ' in goma_dir):
dpranke3cec199c2015-09-22 23:29:021171 goma_dir = "'%s'" % goma_dir
dpranked0c138b2016-04-13 18:28:471172
1173 if goma_dir:
1174 gyp_defines += ' gomadir=%s' % goma_dir
dpranke3cec199c2015-09-22 23:29:021175
agrieve41d21a72016-04-14 18:02:261176 android_version_code = self.args.android_version_code
1177 if android_version_code:
1178 gyp_defines += ' app_manifest_version_code=%s' % android_version_code
1179
1180 android_version_name = self.args.android_version_name
1181 if android_version_name:
1182 gyp_defines += ' app_manifest_version_name=%s' % android_version_name
1183
dprankefe4602312015-04-08 16:20:351184 cmd = [
dpranke8c2cfd32015-09-17 20:12:331185 self.executable,
machenbach60ebf6202016-06-07 14:27:391186 self.args.gyp_script,
dprankefe4602312015-04-08 16:20:351187 '-G',
1188 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:351189 ]
dpranke38f4acb62015-09-29 23:50:411190
1191 # Ensure that we have an environment that only contains
1192 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:021193 env = os.environ.copy()
dpranke909bad62016-04-24 23:14:521194
1195 # This is a terrible hack to work around the fact that
1196 # //tools/clang/scripts/update.py is invoked by GYP and GN but
1197 # currently relies on an environment variable to figure out
1198 # what revision to embed in the command line #defines.
1199 # For GN, we've made this work via a gn arg that will cause update.py
1200 # to get an additional command line arg, but getting that to work
1201 # via GYP_DEFINES has proven difficult, so we rewrite the GYP_DEFINES
1202 # to get rid of the arg and add the old var in, instead.
1203 # See crbug.com/582737 for more on this. This can hopefully all
1204 # go away with GYP.
dprankeec079262016-06-07 02:21:201205 m = re.search('llvm_force_head_revision=1\s*', gyp_defines)
1206 if m:
dprankebf0d5b562016-04-25 22:22:511207 env['LLVM_FORCE_HEAD_REVISION'] = '1'
dprankeec079262016-06-07 02:21:201208 gyp_defines = gyp_defines.replace(m.group(0), '')
1209
1210 # This is another terrible hack to work around the fact that
1211 # GYP sets the link concurrency to use via the GYP_LINK_CONCURRENCY
1212 # environment variable, and not via a proper GYP_DEFINE. See
1213 # crbug.com/611491 for more on this.
1214 m = re.search('gyp_link_concurrency=(\d+)(\s*)', gyp_defines)
1215 if m:
1216 env['GYP_LINK_CONCURRENCY'] = m.group(1)
1217 gyp_defines = gyp_defines.replace(m.group(0), '')
dpranke909bad62016-04-24 23:14:521218
dprankef75a3de52015-12-14 22:17:521219 env['GYP_GENERATORS'] = 'ninja'
dpranke38f4acb62015-09-29 23:50:411220 if 'GYP_CHROMIUM_NO_ACTION' in env:
1221 del env['GYP_CHROMIUM_NO_ACTION']
1222 if 'GYP_CROSSCOMPILE' in env:
1223 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:021224 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:411225 if vals['gyp_crosscompile']:
1226 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:021227 return cmd, env
dprankefe4602312015-04-08 16:20:351228
Dirk Pranke0fd41bcd2015-06-19 00:05:501229 def RunGNAnalyze(self, vals):
dprankecb4a2e242016-09-19 01:13:141230 # Analyze runs before 'gn gen' now, so we need to run gn gen
Dirk Pranke0fd41bcd2015-06-19 00:05:501231 # in order to ensure that we have a build directory.
1232 ret = self.RunGNGen(vals)
1233 if ret:
1234 return ret
1235
dprankecb4a2e242016-09-19 01:13:141236 build_path = self.args.path[0]
1237 input_path = self.args.input_path[0]
1238 gn_input_path = input_path + '.gn'
1239 output_path = self.args.output_path[0]
1240 gn_output_path = output_path + '.gn'
1241
dpranke7837fc362015-11-19 03:54:161242 inp = self.ReadInputJSON(['files', 'test_targets',
1243 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321244 if self.args.verbose:
1245 self.Print()
1246 self.Print('analyze input:')
1247 self.PrintJSON(inp)
1248 self.Print()
1249
dpranke76734662015-04-16 02:17:501250
dpranke7c5f614d2015-07-22 23:43:391251 # This shouldn't normally happen, but could due to unusual race conditions,
1252 # like a try job that gets scheduled before a patch lands but runs after
1253 # the patch has landed.
1254 if not inp['files']:
1255 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161256 self.WriteJSON({
1257 'status': 'No dependency',
1258 'compile_targets': [],
1259 'test_targets': [],
1260 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391261 return 0
1262
dprankecb4a2e242016-09-19 01:13:141263 gn_inp = {}
dprankeb7b183f2017-04-24 23:50:161264 gn_inp['files'] = ['//' + f for f in inp['files'] if not f.startswith('//')]
dprankef61de2f2015-05-14 04:09:561265
dprankecb4a2e242016-09-19 01:13:141266 isolate_map = self.ReadIsolateMap()
1267 err, gn_inp['additional_compile_targets'] = self.MapTargetsToLabels(
1268 isolate_map, inp['additional_compile_targets'])
dprankecb4a2e242016-09-19 01:13:141269 if err:
1270 raise MBErr(err)
1271
1272 err, gn_inp['test_targets'] = self.MapTargetsToLabels(
1273 isolate_map, inp['test_targets'])
dprankecb4a2e242016-09-19 01:13:141274 if err:
1275 raise MBErr(err)
1276 labels_to_targets = {}
1277 for i, label in enumerate(gn_inp['test_targets']):
1278 labels_to_targets[label] = inp['test_targets'][i]
1279
dprankef61de2f2015-05-14 04:09:561280 try:
dprankecb4a2e242016-09-19 01:13:141281 self.WriteJSON(gn_inp, gn_input_path)
1282 cmd = self.GNCmd('analyze', build_path, gn_input_path, gn_output_path)
1283 ret, _, _ = self.Run(cmd, force_verbose=True)
1284 if ret:
1285 return ret
dpranke067d0142015-05-14 22:52:451286
dprankecb4a2e242016-09-19 01:13:141287 gn_outp_str = self.ReadFile(gn_output_path)
1288 try:
1289 gn_outp = json.loads(gn_outp_str)
1290 except Exception as e:
1291 self.Print("Failed to parse the JSON string GN returned: %s\n%s"
1292 % (repr(gn_outp_str), str(e)))
1293 raise
1294
1295 outp = {}
1296 if 'status' in gn_outp:
1297 outp['status'] = gn_outp['status']
1298 if 'error' in gn_outp:
1299 outp['error'] = gn_outp['error']
1300 if 'invalid_targets' in gn_outp:
1301 outp['invalid_targets'] = gn_outp['invalid_targets']
1302 if 'compile_targets' in gn_outp:
dpranke385a3102016-09-20 22:04:081303 if 'all' in gn_outp['compile_targets']:
1304 outp['compile_targets'] = ['all']
1305 else:
1306 outp['compile_targets'] = [
1307 label.replace('//', '') for label in gn_outp['compile_targets']]
dprankecb4a2e242016-09-19 01:13:141308 if 'test_targets' in gn_outp:
1309 outp['test_targets'] = [
1310 labels_to_targets[label] for label in gn_outp['test_targets']]
1311
1312 if self.args.verbose:
1313 self.Print()
1314 self.Print('analyze output:')
1315 self.PrintJSON(outp)
1316 self.Print()
1317
1318 self.WriteJSON(outp, output_path)
1319
dprankef61de2f2015-05-14 04:09:561320 finally:
dprankecb4a2e242016-09-19 01:13:141321 if self.Exists(gn_input_path):
1322 self.RemoveFile(gn_input_path)
1323 if self.Exists(gn_output_path):
1324 self.RemoveFile(gn_output_path)
dprankefe4602312015-04-08 16:20:351325
1326 return 0
1327
dpranked8113582015-06-05 20:08:251328 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351329 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321330 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351331 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321332 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351333
1334 try:
1335 inp = json.loads(self.ReadFile(path))
1336 except Exception as e:
1337 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321338 (path, e), output_path)
dpranked8113582015-06-05 20:08:251339
1340 for k in required_keys:
1341 if not k in inp:
1342 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1343 output_path)
dprankefe4602312015-04-08 16:20:351344
1345 return inp
1346
dpranked5b2b9432015-06-23 16:55:301347 def WriteFailureAndRaise(self, msg, output_path):
1348 if output_path:
dprankee0547cd2015-09-15 01:27:401349 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351350 raise MBErr(msg)
1351
dprankee0547cd2015-09-15 01:27:401352 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321353 try:
dprankee0547cd2015-09-15 01:27:401354 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1355 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321356 except Exception as e:
1357 raise MBErr('Error %s writing to the output path "%s"' %
1358 (e, path))
dprankefe4602312015-04-08 16:20:351359
aneeshmde50f472016-04-01 01:13:101360 def CheckCompile(self, master, builder):
1361 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1362 url = urllib2.quote(url_template.format(master=master, builder=builder),
1363 safe=':/()?=')
1364 try:
1365 builds = json.loads(self.Fetch(url))
1366 except Exception as e:
1367 return str(e)
1368 successes = sorted(
1369 [int(x) for x in builds.keys() if "text" in builds[x] and
1370 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1371 reverse=True)
1372 if not successes:
1373 return "no successful builds"
1374 build = builds[str(successes[0])]
1375 step_names = set([step["name"] for step in build["steps"]])
1376 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1377 if compile_indicators & step_names:
1378 return "compiles"
1379 return "does not compile"
1380
dpranke3cec199c2015-09-22 23:29:021381 def PrintCmd(self, cmd, env):
1382 if self.platform == 'win32':
1383 env_prefix = 'set '
1384 env_quoter = QuoteForSet
1385 shell_quoter = QuoteForCmd
1386 else:
1387 env_prefix = ''
1388 env_quoter = pipes.quote
1389 shell_quoter = pipes.quote
1390
1391 def print_env(var):
1392 if env and var in env:
1393 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1394
1395 print_env('GYP_CROSSCOMPILE')
1396 print_env('GYP_DEFINES')
dprankeec079262016-06-07 02:21:201397 print_env('GYP_LINK_CONCURRENCY')
1398 print_env('LLVM_FORCE_HEAD_REVISION')
dpranke3cec199c2015-09-22 23:29:021399
dpranke8c2cfd32015-09-17 20:12:331400 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351401 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021402 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351403
dprankecda00332015-04-11 04:18:321404 def PrintJSON(self, obj):
1405 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1406
dpranke751516a2015-10-03 01:11:341407 def Build(self, target):
1408 build_dir = self.ToSrcRelPath(self.args.path[0])
1409 ninja_cmd = ['ninja', '-C', build_dir]
1410 if self.args.jobs:
1411 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1412 ninja_cmd.append(target)
1413 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1414 return ret
1415
1416 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351417 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401418 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021419 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351420 if self.args.dryrun:
1421 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401422
dpranke751516a2015-10-03 01:11:341423 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401424 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341425 if ret:
1426 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351427 if out:
dprankeee5b51f62015-04-09 00:03:221428 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351429 if err:
dprankeee5b51f62015-04-09 00:03:221430 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351431 return ret, out, err
1432
dpranke751516a2015-10-03 01:11:341433 def Call(self, cmd, env=None, buffer_output=True):
1434 if buffer_output:
1435 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1436 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1437 env=env)
1438 out, err = p.communicate()
1439 else:
1440 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1441 env=env)
1442 p.wait()
1443 out = err = ''
dprankefe4602312015-04-08 16:20:351444 return p.returncode, out, err
1445
1446 def ExpandUser(self, path):
1447 # This function largely exists so it can be overridden for testing.
1448 return os.path.expanduser(path)
1449
1450 def Exists(self, path):
1451 # This function largely exists so it can be overridden for testing.
1452 return os.path.exists(path)
1453
dpranke867bcf4a2016-03-14 22:28:321454 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501455 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321456 f = urllib2.urlopen(url)
1457 contents = f.read()
1458 f.close()
1459 return contents
1460
dprankec3441d12015-06-23 23:01:351461 def MaybeMakeDirectory(self, path):
1462 try:
1463 os.makedirs(path)
1464 except OSError, e:
1465 if e.errno != errno.EEXIST:
1466 raise
1467
dpranke8c2cfd32015-09-17 20:12:331468 def PathJoin(self, *comps):
1469 # This function largely exists so it can be overriden for testing.
1470 return os.path.join(*comps)
1471
dpranke030d7a6d2016-03-26 17:23:501472 def Print(self, *args, **kwargs):
1473 # This function largely exists so it can be overridden for testing.
1474 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101475 if kwargs.get('stream', sys.stdout) == sys.stdout:
1476 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501477
dprankefe4602312015-04-08 16:20:351478 def ReadFile(self, path):
1479 # This function largely exists so it can be overriden for testing.
1480 with open(path) as fp:
1481 return fp.read()
1482
dpranke030d7a6d2016-03-26 17:23:501483 def RelPath(self, path, start='.'):
1484 # This function largely exists so it can be overriden for testing.
1485 return os.path.relpath(path, start)
1486
dprankef61de2f2015-05-14 04:09:561487 def RemoveFile(self, path):
1488 # This function largely exists so it can be overriden for testing.
1489 os.remove(path)
1490
dprankec161aa92015-09-14 20:21:131491 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331492 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131493 # In other places in chromium, we often have to retry this command
1494 # because we're worried about other processes still holding on to
1495 # file handles, but when MB is invoked, it will be early enough in the
1496 # build that their should be no other processes to interfere. We
1497 # can change this if need be.
1498 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1499 else:
1500 shutil.rmtree(abs_path, ignore_errors=True)
1501
dprankef61de2f2015-05-14 04:09:561502 def TempFile(self, mode='w'):
1503 # This function largely exists so it can be overriden for testing.
1504 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1505
dprankee0547cd2015-09-15 01:27:401506 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351507 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401508 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301509 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351510 with open(path, 'w') as fp:
1511 return fp.write(contents)
1512
dprankef61de2f2015-05-14 04:09:561513
dprankefe4602312015-04-08 16:20:351514class MBErr(Exception):
1515 pass
1516
1517
dpranke3cec199c2015-09-22 23:29:021518# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1519# details of this next section, which handles escaping command lines
1520# so that they can be copied and pasted into a cmd window.
1521UNSAFE_FOR_SET = set('^<>&|')
1522UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1523ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1524
1525
1526def QuoteForSet(arg):
1527 if any(a in UNSAFE_FOR_SET for a in arg):
1528 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1529 return arg
1530
1531
1532def QuoteForCmd(arg):
1533 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1534 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1535 if arg == '' or ' ' in arg or '"' in arg:
1536 quote_re = re.compile(r'(\\*)"')
1537 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1538
1539 # Then check to see if the arg contains any metacharacters other than
1540 # double quotes; if it does, quote everything (including the double
1541 # quotes) for safety.
1542 if any(a in UNSAFE_FOR_CMD for a in arg):
1543 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1544 return arg
1545
1546
dprankefe4602312015-04-08 16:20:351547if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591548 sys.exit(main(sys.argv[1:]))