#!/usr/bin/env python # Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. """MB - the Meta-Build wrapper around GN. MB is a wrapper script for GN that can be used to generate build files for sets of canned configurations and analyze them. """ from __future__ import print_function import argparse import ast import errno import json import os import pipes import pprint import re import shutil import sys import subprocess import tempfile import traceback import urllib2 from collections import OrderedDict SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) SRC_DIR = os.path.dirname(os.path.dirname(SCRIPT_DIR)) sys.path = [os.path.join(SRC_DIR, 'build')] + sys.path import gn_helpers def main(args): mbw = MetaBuildWrapper() return mbw.Main(args) class MetaBuildWrapper(object): def __init__(self): self.src_dir = SRC_DIR self.default_config = os.path.join(SCRIPT_DIR, 'mb_config.pyl') self.default_isolate_map = os.path.join(SCRIPT_DIR, 'gn_isolate_map.pyl') self.executable = sys.executable self.platform = sys.platform self.sep = os.sep self.args = argparse.Namespace() self.configs = {} self.masters = {} self.mixins = {} self.isolate_exe = 'isolate.exe' if self.platform.startswith( 'win') else 'isolate' def Main(self, args): self.ParseArgs(args) try: ret = self.args.func() if ret: self.DumpInputFiles() return ret except KeyboardInterrupt: self.Print('interrupted, exiting') return 130 except Exception: self.DumpInputFiles() s = traceback.format_exc() for l in s.splitlines(): self.Print(l) return 1 def ParseArgs(self, argv): def AddCommonOptions(subp): subp.add_argument('-b', '--builder', help='builder name to look up config from') subp.add_argument('-m', '--master', help='master name to look up config from') subp.add_argument('-c', '--config', help='configuration to analyze') subp.add_argument('--phase', help='optional phase name (used when builders ' 'do multiple compiles with different ' 'arguments in a single build)') subp.add_argument('-f', '--config-file', metavar='PATH', default=self.default_config, help='path to config file ' '(default is %(default)s)') subp.add_argument('-i', '--isolate-map-file', metavar='PATH', default=self.default_isolate_map, help='path to isolate map file ' '(default is %(default)s)') subp.add_argument('-g', '--goma-dir', help='path to goma directory') subp.add_argument('--android-version-code', help='Sets GN arg android_default_version_code') subp.add_argument('--android-version-name', help='Sets GN arg android_default_version_name') subp.add_argument('-n', '--dryrun', action='store_true', help='Do a dry run (i.e., do nothing, just print ' 'the commands that will run)') subp.add_argument('-v', '--verbose', action='store_true', help='verbose logging') parser = argparse.ArgumentParser(prog='mb') subps = parser.add_subparsers() subp = subps.add_parser('analyze', help='analyze whether changes to a set of files ' 'will cause a set of binaries to be rebuilt.') AddCommonOptions(subp) subp.add_argument('path', nargs=1, help='path build was generated into.') subp.add_argument('input_path', nargs=1, help='path to a file containing the input arguments ' 'as a JSON object.') subp.add_argument('output_path', nargs=1, help='path to a file containing the output arguments ' 'as a JSON object.') subp.add_argument('--json-output', help='Write errors to json.output') subp.set_defaults(func=self.CmdAnalyze) subp = subps.add_parser('export', help='print out the expanded configuration for' 'each builder as a JSON object') subp.add_argument('-f', '--config-file', metavar='PATH', default=self.default_config, help='path to config file (default is %(default)s)') subp.add_argument('-g', '--goma-dir', help='path to goma directory') subp.set_defaults(func=self.CmdExport) subp = subps.add_parser('gen', help='generate a new set of build files') AddCommonOptions(subp) subp.add_argument('--swarming-targets-file', help='save runtime dependencies for targets listed ' 'in file.') subp.add_argument('--json-output', help='Write errors to json.output') subp.add_argument('path', nargs=1, help='path to generate build into') subp.set_defaults(func=self.CmdGen) subp = subps.add_parser('isolate', help='generate the .isolate files for a given' 'binary') AddCommonOptions(subp) subp.add_argument('path', nargs=1, help='path build was generated into') subp.add_argument('target', nargs=1, help='ninja target to generate the isolate for') subp.set_defaults(func=self.CmdIsolate) subp = subps.add_parser('lookup', help='look up the command for a given config or ' 'builder') AddCommonOptions(subp) subp.add_argument('--quiet', default=False, action='store_true', help='Print out just the arguments, ' 'do not emulate the output of the gen subcommand.') subp.set_defaults(func=self.CmdLookup) subp = subps.add_parser( 'run', help='build and run the isolated version of a ' 'binary', formatter_class=argparse.RawDescriptionHelpFormatter) subp.description = ( 'Build, isolate, and run the given binary with the command line\n' 'listed in the isolate. You may pass extra arguments after the\n' 'target; use "--" if the extra arguments need to include switches.\n' '\n' 'Examples:\n' '\n' ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n' ' //out/Default content_browsertests\n' '\n' ' % tools/mb/mb.py run out/Default content_browsertests\n' '\n' ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n' ' --test-launcher-retry-limit=0' '\n' ) AddCommonOptions(subp) subp.add_argument('-j', '--jobs', dest='jobs', type=int, help='Number of jobs to pass to ninja') subp.add_argument('--no-build', dest='build', default=True, action='store_false', help='Do not build, just isolate and run') subp.add_argument('path', nargs=1, help=('path to generate build into (or use).' ' This can be either a regular path or a ' 'GN-style source-relative path like ' '//out/Default.')) subp.add_argument('-s', '--swarmed', action='store_true', help='Run under swarming') subp.add_argument('-d', '--dimension', default=[], action='append', nargs=2, dest='dimensions', metavar='FOO bar', help='dimension to filter on') subp.add_argument('target', nargs=1, help='ninja target to build and run') subp.add_argument('extra_args', nargs='*', help=('extra args to pass to the isolate to run. Use ' '"--" as the first arg if you need to pass ' 'switches')) subp.set_defaults(func=self.CmdRun) subp = subps.add_parser('validate', help='validate the config file') subp.add_argument('-f', '--config-file', metavar='PATH', default=self.default_config, help='path to config file (default is %(default)s)') subp.set_defaults(func=self.CmdValidate) subp = subps.add_parser('help', help='Get help on a subcommand.') subp.add_argument(nargs='?', action='store', dest='subcommand', help='The command to get help for.') subp.set_defaults(func=self.CmdHelp) self.args = parser.parse_args(argv) def DumpInputFiles(self): def DumpContentsOfFilePassedTo(arg_name, path): if path and self.Exists(path): self.Print("\n# To recreate the file passed to %s:" % arg_name) self.Print("%% cat > %s < returned %d' % ret) if out: self.Print(out, end='') if err: self.Print(err, end='', file=sys.stderr) return ret, out, err def Call(self, cmd, env=None, buffer_output=True): if buffer_output: p = subprocess.Popen(cmd, shell=False, cwd=self.src_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out, err = p.communicate() else: p = subprocess.Popen(cmd, shell=False, cwd=self.src_dir, env=env) p.wait() out = err = '' return p.returncode, out, err def ExpandUser(self, path): # This function largely exists so it can be overridden for testing. return os.path.expanduser(path) def Exists(self, path): # This function largely exists so it can be overridden for testing. return os.path.exists(path) def Fetch(self, url): # This function largely exists so it can be overridden for testing. f = urllib2.urlopen(url) contents = f.read() f.close() return contents def MaybeMakeDirectory(self, path): try: os.makedirs(path) except OSError, e: if e.errno != errno.EEXIST: raise def PathJoin(self, *comps): # This function largely exists so it can be overriden for testing. return os.path.join(*comps) def Print(self, *args, **kwargs): # This function largely exists so it can be overridden for testing. print(*args, **kwargs) if kwargs.get('stream', sys.stdout) == sys.stdout: sys.stdout.flush() def ReadFile(self, path): # This function largely exists so it can be overriden for testing. with open(path) as fp: return fp.read() def RelPath(self, path, start='.'): # This function largely exists so it can be overriden for testing. return os.path.relpath(path, start) def RemoveFile(self, path): # This function largely exists so it can be overriden for testing. os.remove(path) def RemoveDirectory(self, abs_path): if self.platform == 'win32': # In other places in chromium, we often have to retry this command # because we're worried about other processes still holding on to # file handles, but when MB is invoked, it will be early enough in the # build that their should be no other processes to interfere. We # can change this if need be. self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path]) else: shutil.rmtree(abs_path, ignore_errors=True) def TempFile(self, mode='w'): # This function largely exists so it can be overriden for testing. return tempfile.NamedTemporaryFile(mode=mode, delete=False) def WriteFile(self, path, contents, force_verbose=False): # This function largely exists so it can be overriden for testing. if self.args.dryrun or self.args.verbose or force_verbose: self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path)) with open(path, 'w') as fp: return fp.write(contents) class MBErr(Exception): pass # See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful # details of this next section, which handles escaping command lines # so that they can be copied and pasted into a cmd window. UNSAFE_FOR_SET = set('^<>&|') UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%')) ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"')) def QuoteForSet(arg): if any(a in UNSAFE_FOR_SET for a in arg): arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg) return arg def QuoteForCmd(arg): # First, escape the arg so that CommandLineToArgvW will parse it properly. if arg == '' or ' ' in arg or '"' in arg: quote_re = re.compile(r'(\\*)"') arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg)) # Then check to see if the arg contains any metacharacters other than # double quotes; if it does, quote everything (including the double # quotes) for safety. if any(a in UNSAFE_FOR_CMD for a in arg): arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg) return arg if __name__ == '__main__': sys.exit(main(sys.argv[1:]))