diff options
author | Jocelyn Turcotte <jocelyn.turcotte@digia.com> | 2014-08-08 14:30:41 +0200 |
---|---|---|
committer | Jocelyn Turcotte <jocelyn.turcotte@digia.com> | 2014-08-12 13:49:54 +0200 |
commit | ab0a50979b9eb4dfa3320eff7e187e41efedf7a9 (patch) | |
tree | 498dfb8a97ff3361a9f7486863a52bb4e26bb898 /chromium/tools/cr/cr | |
parent | 4ce69f7403811819800e7c5ae1318b2647e778d1 (diff) |
Update Chromium to beta version 37.0.2062.68
Change-Id: I188e3b5aff1bec75566014291b654eb19f5bc8ca
Reviewed-by: Andras Becsi <andras.becsi@digia.com>
Diffstat (limited to 'chromium/tools/cr/cr')
49 files changed, 0 insertions, 3693 deletions
diff --git a/chromium/tools/cr/cr/__init__.py b/chromium/tools/cr/cr/__init__.py deleted file mode 100644 index 928e08bb790..00000000000 --- a/chromium/tools/cr/cr/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Chromium cr tool module. - -This is the root module of all the cr code. -Commonly accessed elements, including all plugins, are promoted into this -module. -""" -import sys - -from cr.config import Config -from cr.loader import AutoExport -import cr.plugin diff --git a/chromium/tools/cr/cr/actions/__init__.py b/chromium/tools/cr/cr/actions/__init__.py deleted file mode 100644 index 5f818b39a2b..00000000000 --- a/chromium/tools/cr/cr/actions/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A package to hold all the actions for the cr tool. - -This package holds the standard actions used by the commands in the cr tool. -These actions are the things that actually perform the work, they are generally -run in sequences by commands. -""" diff --git a/chromium/tools/cr/cr/actions/action.py b/chromium/tools/cr/cr/actions/action.py deleted file mode 100644 index b812aaea1a2..00000000000 --- a/chromium/tools/cr/cr/actions/action.py +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the Action plugin base class.""" - -import cr - - -class Action(cr.Plugin): - """Base class for cr actions. - - This provides the standard interface used to add actions to commands, - including support for selecting the right implementation of an action and - handling command line arguments for the action. - """ - - @classmethod - def AddArguments(cls, command, parser): - cls.AddSelectorArg(command, parser) - - @classmethod - def AddSelectorArg(cls, command, parser): - parser.add_argument( - cls.SELECTOR_ARG, dest=cls.SELECTOR, - choices=cls.Choices(), - default=None, - help=cls.SELECTOR_HELP + 'Overrides ' + cls.SELECTOR - ) - - @cr.Plugin.activemethod - def Skipping(self, context): - """A method that is used to detect void or skip implementations. - - Most actions have a skip version that you can select to indicate that you - want to not perform the action at all. - It is important that commands can detect this so they can modify the action - sequence if there are other changes that depend on it (for instance not - performing actions that were only there to produce the inputs of an action - that is being skipped). - - Args: - context: the cr context to test within. - Returns: - True if this implementation is a skip action. - """ - return self.name == 'skip' - - diff --git a/chromium/tools/cr/cr/actions/adb.py b/chromium/tools/cr/cr/actions/adb.py deleted file mode 100644 index 25117c74ec4..00000000000 --- a/chromium/tools/cr/cr/actions/adb.py +++ /dev/null @@ -1,144 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module to hold adb specific action implementations.""" - -import re - -import cr - - -class Adb(object): - """Exposes the functionality of the adb tool to the rest of cr. - - This is intended as the only class in the cr that needs to understand the - adb command line, and expose it in neutral form to the rest of the code. - """ - - # Tracks the set of killed target names, so we don't keep issuing kill - # commands that are not going to have any effect. - _kills = {} - - @classmethod - def GetPids(cls, target): - """Gets the set of running PIDs that match the specified target.""" - pids = [] - output = cr.Host.Capture(target, '{CR_ADB}', 'shell', 'ps') - pattern = re.compile(r'\S+\s+(\d+)\s+.*{CR_PROCESS}') - for line in output.split('\n'): - match = re.match(pattern, line) - if match: - pids.append(match.group(1)) - return pids - - @classmethod - def Run(cls, target, arguments): - """Invoke a target binary on the device.""" - cr.Host.Execute( - target, - '{CR_ADB}', 'shell', 'am', 'start', - '-a', '{CR_ACTION}', - '-n', '{CR_INTENT}', - '{CR_RUN_ARGUMENTS}', - *arguments - ) - - @classmethod - def Kill(cls, target, _): - """Kill all running processes for a target.""" - target_name = target.build_target - if target_name in cls._kills: - # already killed this target, do nothing - return - pids = cls.GetPids(target) - if pids: - cr.Host.Execute(target, '{CR_ADB}', 'shell', 'kill', *pids) - elif target.verbose: - print target.Substitute('{CR_TARGET_NAME} not running') - cls._kills[target_name] = True - - @classmethod - def Uninstall(cls, target, arguments): - cr.Host.Execute( - target, - '{CR_ADB}', 'uninstall', - '{CR_PACKAGE}', - *arguments - ) - - @classmethod - def Install(cls, target, arguments): - cr.Host.Execute( - target, - '{CR_ADB}', 'install', - '{CR_BINARY}', - *arguments - ) - - @classmethod - def Reinstall(cls, target, arguments): - cr.Host.Execute( - target, - '{CR_ADB}', 'install', - '-r', - '-d', - '{CR_BINARY}', - *arguments - ) - - @classmethod - def AttachGdb(cls, target, arguments): - cr.Host.Execute( - target, - '{CR_ADB_GDB}', - '--adb={CR_ADB}', - '--symbol-dir=${CR_BUILD_DIR}/lib', - '--program-name={CR_TARGET_NAME}', - '--package-name={CR_PACKAGE}', - *arguments - ) - - -class AdbRunner(cr.Runner): - """An implementation of cr.Runner for the android platform.""" - - @property - def enabled(self): - return cr.AndroidPlatform.GetInstance().is_active - - def Kill(self, context, targets, arguments): - for target in targets: - Adb.Kill(target, arguments) - - def Run(self, context, target, arguments): - Adb.Run(target, arguments) - - def Test(self, context, target, arguments): - cr.Host.Execute( - target, - '{CR_TEST_RUNNER}', '{CR_TEST_TYPE}', - '-s', '{CR_TARGET_NAME}', - '--{CR_TEST_MODE}', - *arguments - ) - - -class AdbInstaller(cr.Installer): - """An implementation of cr.Installer for the android platform.""" - - @property - def enabled(self): - return cr.AndroidPlatform.GetInstance().is_active - - def Uninstall(self, context, targets, arguments): - for target in targets: - Adb.Uninstall(target, arguments) - - def Install(self, context, targets, arguments): - for target in targets: - Adb.Install(target, arguments) - - def Reinstall(self, context, targets, arguments): - for target in targets: - Adb.Reinstall(target, arguments) diff --git a/chromium/tools/cr/cr/actions/builder.py b/chromium/tools/cr/cr/actions/builder.py deleted file mode 100644 index 74959afe627..00000000000 --- a/chromium/tools/cr/cr/actions/builder.py +++ /dev/null @@ -1,72 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the Builder base class.""" - -import cr - - -class Builder(cr.Action, cr.Plugin.Type): - """Base class for implementing builders. - - Builder implementations must override the Build and Clean methods at a - minimum to build a target and clean up back to a pristine state respectively. - They can also override Rebuild if they are able to handle it in a more - efficient way that a Clean Build sequence. - They should override the GetTargets method to return the set of valid targets - the build system knows about, and override IsTarget if they can implement it - more efficiently than checking from presents in the result of GetTargets. - """ - - SELECTOR_ARG = '--builder' - SELECTOR = 'CR_BUILDER' - SELECTOR_HELP = 'Sets the builder to use to update dependencies.' - - @cr.Plugin.activemethod - def Build(self, context, targets, arguments): - raise NotImplementedError('Must be overridden.') - - @cr.Plugin.activemethod - def Clean(self, context, targets, arguments): - """Clean temporary files built by a target.""" - raise NotImplementedError('Must be overridden.') - - @cr.Plugin.activemethod - def Rebuild(self, context, targets, arguments): - """Make a target build even if it is up to date. - - Default implementation is to do a Clean and Build sequence. - Do not call the base version if you implement a more efficient one. - """ - self.Clean(context, targets, []) - self.Build(context, targets, arguments) - - @cr.Plugin.activemethod - def GetTargets(self, context): - """Gets the full set of targets supported by this builder. - - Used in automatic target name transformations, and also in offering the - user choices. - """ - return [] - - @cr.Plugin.activemethod - def IsTarget(self, context, target_name): - """Check if a target name is on the builder knows about.""" - return target_name in self.GetTargets(context) - - -class SkipBuilder(Builder): - """The "skip" version of a Builder, causes the build step to be skipped.""" - - @property - def priority(self): - return super(SkipBuilder, self).priority - 1 - - def Build(self, context, targets, arguments): - pass - - def Clean(self, context, targets, arguments): - pass - diff --git a/chromium/tools/cr/cr/actions/debugger.py b/chromium/tools/cr/cr/actions/debugger.py deleted file mode 100644 index a634ab22038..00000000000 --- a/chromium/tools/cr/cr/actions/debugger.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the Debugger base class.""" - -import cr - - -class Debugger(cr.Action, cr.Plugin.Type): - """Base class for implementing debuggers. - - Implementations must override the Invoke and Attach methods. - """ - - SELECTOR_ARG = '--debugger' - SELECTOR = 'CR_DEBUGGER' - SELECTOR_HELP = 'Sets the debugger to use for debug commands.' - - @classmethod - def AddArguments(cls, command, parser): - cr.Runner.AddSelectorArg(command, parser) - - @classmethod - def ShouldInvoke(cls, context): - """Checks if the debugger is attaching or launching.""" - return not cr.Runner.Skipping(context) - - @cr.Plugin.activemethod - def Restart(self, context, targets, arguments): - """Ask the debugger to restart. - - Defaults to a Kill Invoke sequence. - """ - self.Kill(context, targets, []) - self.Invoke(context, targets, arguments) - - @cr.Plugin.activemethod - def Kill(self, context, targets, arguments): - """Kill the running debugger.""" - cr.Runner.Kill(context, targets, arguments) - - @cr.Plugin.activemethod - def Invoke(self, context, targets, arguments): - """Invoke the program within a debugger.""" - raise NotImplementedError('Must be overridden.') - - @cr.Plugin.activemethod - def Attach(self, context, targets, arguments): - """Attach a debugger to a running program.""" - raise NotImplementedError('Must be overridden.') diff --git a/chromium/tools/cr/cr/actions/gdb.py b/chromium/tools/cr/cr/actions/gdb.py deleted file mode 100644 index d93fe27eb90..00000000000 --- a/chromium/tools/cr/cr/actions/gdb.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import os - -import cr - - -class GdbDebugger(cr.Debugger): - """An implementation of cr.Debugger that launches gdb.""" - - DETECTED = cr.Config('DETECTED') - - @property - def enabled(self): - return (cr.LinuxPlatform.GetInstance().is_active and - self.DETECTED.Find('CR_GDB')) - - def Invoke(self, context, targets, arguments): - for target in targets: - cr.Host.Execute( - target, - '{CR_GDB}', '--eval-command=run', '--args', - '{CR_BINARY}', - '{CR_RUN_ARGUMENTS}', - *arguments - ) - - def Attach(self, context, targets, arguments): - raise NotImplementedError('Attach not currently supported for gdb.') - - -def _DetectGdb(): - """Attempts to find a valid gdb on the path.""" - gdb_binaries = cr.Host.SearchPath('gdb') - if gdb_binaries: - GdbDebugger.DETECTED.Set(CR_GDB=gdb_binaries[0]) - -_DetectGdb() diff --git a/chromium/tools/cr/cr/actions/gyp.py b/chromium/tools/cr/cr/actions/gyp.py deleted file mode 100644 index b3492bbefd0..00000000000 --- a/chromium/tools/cr/cr/actions/gyp.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module to add gyp support to cr.""" - -import cr - - -class GypPrepareOut(cr.PrepareOut): - """A prepare action that runs gyp whenever you select an output directory.""" - - ENABLED = cr.Config.From( - GYP_GENERATORS='ninja', - GYP_GENERATOR_FLAGS='output_dir={CR_OUT_BASE} config={CR_BUILDTYPE}', - ) - - def Prepare(self, context): - if context.verbose >= 1: - print context.Substitute('Invoking gyp with {GYP_GENERATOR_FLAGS}') - cr.Host.Execute( - context, - '{CR_SRC}/build/gyp_chromium', - '--depth={CR_SRC}', - '--check' - ) diff --git a/chromium/tools/cr/cr/actions/installer.py b/chromium/tools/cr/cr/actions/installer.py deleted file mode 100644 index 0dd432df653..00000000000 --- a/chromium/tools/cr/cr/actions/installer.py +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the Installer base class.""" - -import cr - - -class Installer(cr.Action, cr.Plugin.Type): - """Base class for implementing installers. - - Installer implementations must implement the Uninstall and Install methods. - If the location into which targets are built is find for running them, then - they do not actually have to do anything. - """ - - SELECTOR_ARG = '--installer' - SELECTOR = 'CR_INSTALLER' - SELECTOR_HELP = 'Sets the installer to use.' - - @cr.Plugin.activemethod - def Uninstall(self, context, targets, arguments): - """Removes a target from it's installed location.""" - - raise NotImplementedError('Must be overridden.') - - @cr.Plugin.activemethod - def Install(self, context, targets, arguments): - """Installs a target somewhere so that it is ready to run.""" - raise NotImplementedError('Must be overridden.') - - @cr.Plugin.activemethod - def Reinstall(self, context, targets, arguments): - """Force a target to install even if already installed. - - Default implementation is to do an Uninstall Install sequence. - Do not call the base version if you implement a more efficient one. - """ - self.Uninstall(context, targets, []) - self.Install(context, targets, arguments) - - -class SkipInstaller(Installer): - """An Installer the user chooses to bypass the install step of a command.""" - - @property - def priority(self): - return super(SkipInstaller, self).priority - 1 - - def Uninstall(self, context, targets, arguments): - pass - - def Install(self, context, targets, arguments): - pass diff --git a/chromium/tools/cr/cr/actions/linux.py b/chromium/tools/cr/cr/actions/linux.py deleted file mode 100644 index adcdb31abd6..00000000000 --- a/chromium/tools/cr/cr/actions/linux.py +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module to hold linux specific action implementations.""" - -import cr - - -class LinuxRunner(cr.Runner): - """An implementation of cr.Runner for the linux platform. - - This supports directly executing the binaries from the output directory. - """ - - @property - def enabled(self): - return cr.LinuxPlatform.GetInstance().is_active - - def Kill(self, context, targets, arguments): - # TODO(iancottrell): Think about how to implement this, or even if we should - print '**WARNING** Kill not yet implemented on linux' - - def Run(self, context, target, arguments): - cr.Host.Execute(target, '{CR_BINARY}', '{CR_RUN_ARGUMENTS}', *arguments) - - def Test(self, context, target, arguments): - self.Run(context, target, arguments) - - -class LinuxInstaller(cr.Installer): - """An implementation of cr.Installer for the linux platform. - - This does nothing, the linux runner works from the output directory, there - is no need to install anywhere. - """ - - @property - def enabled(self): - return cr.LinuxPlatform.GetInstance().is_active - - def Uninstall(self, context, targets, arguments): - pass - - def Install(self, context, targets, arguments): - pass - - def Reinstall(self, context, targets, arguments): - pass - diff --git a/chromium/tools/cr/cr/actions/ninja.py b/chromium/tools/cr/cr/actions/ninja.py deleted file mode 100644 index 404e6caea26..00000000000 --- a/chromium/tools/cr/cr/actions/ninja.py +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module to add ninja support to cr.""" - -import os - -import cr - -_PHONY_SUFFIX = ': phony' -_LINK_SUFFIX = ': link' - - -class NinjaBuilder(cr.Builder): - """An implementation of Builder that uses ninja to do the actual build.""" - - # Some basic configuration installed if we are enabled. - ENABLED = cr.Config.From( - NINJA_BINARY=os.path.join('{DEPOT_TOOLS}', 'ninja'), - NINJA_JOBS=200, - NINJA_PROCESSORS=12, - GOMA_DIR=os.path.join('{GOOGLE_CODE}', 'goma'), - ) - # A placeholder for the system detected configuration - DETECTED = cr.Config('DETECTED') - - def __init__(self): - super(NinjaBuilder, self).__init__() - self._targets = [] - - def Build(self, context, targets, arguments): - build_arguments = [target.build_target for target in targets] - build_arguments.extend(arguments) - cr.Host.Execute( - context, - '{NINJA_BINARY}', - '-C{CR_BUILD_DIR}', - '-j{NINJA_JOBS}', - '-l{NINJA_PROCESSORS}', - *build_arguments - ) - - def Clean(self, context, targets, arguments): - build_arguments = [target.build_target for target in targets] - build_arguments.extend(arguments) - cr.Host.Execute( - context, - '{NINJA_BINARY}', - '-C{CR_BUILD_DIR}', - '-tclean', - *build_arguments - ) - - def GetTargets(self, context): - """Overridden from Builder.GetTargets.""" - if not self._targets: - try: - context.Get('CR_BUILD_DIR', raise_errors=True) - except KeyError: - return self._targets - output = cr.Host.Capture( - context, - '{NINJA_BINARY}', - '-C{CR_BUILD_DIR}', - '-ttargets', - 'all' - ) - for line in output.split('\n'): - line = line.strip() - if line.endswith(_PHONY_SUFFIX): - target = line[:-len(_PHONY_SUFFIX)].strip() - self._targets.append(target) - elif line.endswith(_LINK_SUFFIX): - target = line[:-len(_LINK_SUFFIX)].strip() - self._targets.append(target) - return self._targets - - @classmethod - def DetectNinja(cls): - # TODO(iancottrell): If we can't detect ninja, we should be disabled. - ninja_binaries = cr.Host.SearchPath('ninja') - if ninja_binaries: - cls.DETECTED.Set(NINJA_BINARY=ninja_binaries[0]) - -NinjaBuilder.DetectNinja() diff --git a/chromium/tools/cr/cr/actions/runner.py b/chromium/tools/cr/cr/actions/runner.py deleted file mode 100644 index 72590fc35e0..00000000000 --- a/chromium/tools/cr/cr/actions/runner.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the Runner base class.""" - -import cr - - -class Runner(cr.Action, cr.Plugin.Type): - """Base class for implementing target runners. - - Runner implementations must implement the Kill, Run and Test methods. - - """ - - SELECTOR_ARG = '--runner' - SELECTOR = 'CR_RUNNER' - SELECTOR_HELP = 'Sets the runner to use to execute the target.' - - @classmethod - def AddArguments(cls, command, parser): - parser.add_argument( - '--test', dest='CR_TEST_TYPE', - choices=cr.Target.TEST_TYPES, - default=None, - help=""" - Sets the test type to use, - defaults to choosing based on the target. - Set to 'no' to force it to not be a test. - """ - ) - - @cr.Plugin.activemethod - def Kill(self, context, targets, arguments): - """Stops all running processes that match a target.""" - raise NotImplementedError('Must be overridden.') - - @cr.Plugin.activemethod - def Run(self, context, target, arguments): - """Run a new copy of a runnable target.""" - raise NotImplementedError('Must be overridden.') - - @cr.Plugin.activemethod - def Test(self, context, target, arguments): - """Run a test target.""" - raise NotImplementedError('Must be overridden.') - - @cr.Plugin.activemethod - def Invoke(self, context, targets, arguments): - """Invoke a target. - - This dispatches to either Test or Run depending on the target type. - """ - for target in targets: - if target.is_test: - self.Test(context, target, arguments) - else: - self.Run(context, target, arguments) - - @cr.Plugin.activemethod - def Restart(self, context, targets, arguments): - """Force a target to restart if it is already running. - - Default implementation is to do a Kill Invoke sequence. - Do not call the base version if you implement a more efficient one. - """ - self.Kill(context, targets, []) - self.Invoke(context, targets, arguments) - - -class SkipRunner(Runner): - """A Runner the user chooses to bypass the run step of a command.""" - - @property - def priority(self): - return super(SkipRunner, self).priority - 1 - - def Kill(self, context, targets, arguments): - pass - - def Run(self, context, target, arguments): - pass - - def Test(self, context, target, arguments): - pass - diff --git a/chromium/tools/cr/cr/auto/__init__.py b/chromium/tools/cr/cr/auto/__init__.py deleted file mode 100644 index 698aee36359..00000000000 --- a/chromium/tools/cr/cr/auto/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A root package for all the automatically loaded modules. - -There are no built in packages below this, it holds a set of packages that -have their search paths modified in order to pick up plugins from directories -that are not known until run-time. -""" diff --git a/chromium/tools/cr/cr/auto/build/__init__.py b/chromium/tools/cr/cr/auto/build/__init__.py deleted file mode 100644 index 4f2dbd94674..00000000000 --- a/chromium/tools/cr/cr/auto/build/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A package that holds the modules loaded from the output directory."""
\ No newline at end of file diff --git a/chromium/tools/cr/cr/auto/client/__init__.py b/chromium/tools/cr/cr/auto/client/__init__.py deleted file mode 100644 index 90647c658e4..00000000000 --- a/chromium/tools/cr/cr/auto/client/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A package to hold the modules auto loaded from the client directory."""
\ No newline at end of file diff --git a/chromium/tools/cr/cr/auto/user/__init__.py b/chromium/tools/cr/cr/auto/user/__init__.py deleted file mode 100644 index 9f93de8df98..00000000000 --- a/chromium/tools/cr/cr/auto/user/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A package to hold the modules loaded from the users home directory."""
\ No newline at end of file diff --git a/chromium/tools/cr/cr/autocomplete.py b/chromium/tools/cr/cr/autocomplete.py deleted file mode 100644 index ab9ce2f5784..00000000000 --- a/chromium/tools/cr/cr/autocomplete.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Bash auto completion support. - -Contains the special mode that returns lists of possible completions for the -current command line. -""" - -import cr - - -def Complete(context): - """Attempts to build a completion list for the current command line. - - COMP_WORD contains the word that is being completed, and COMP_CWORD has - the index of that word on the command line. - - Args: - context: The cr context object, of type cr.context.Context. - """ - - _ = context - # TODO(iancottrell): support auto complete of more than just the command - # try to parse the command line using parser - print ' '.join(command.name for command in cr.Command.Plugins()) diff --git a/chromium/tools/cr/cr/base/__init__.py b/chromium/tools/cr/cr/base/__init__.py deleted file mode 100644 index 05babb89dc2..00000000000 --- a/chromium/tools/cr/cr/base/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A package for the base supporting classes of the cr tool.""" diff --git a/chromium/tools/cr/cr/base/android.py b/chromium/tools/cr/cr/base/android.py deleted file mode 100644 index cf61577adc1..00000000000 --- a/chromium/tools/cr/cr/base/android.py +++ /dev/null @@ -1,116 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""The android specific platform implementation module.""" - -import os -import subprocess - -import cr - -# This is the set of environment variables that are not automatically -# copied back from the envsetup shell -_IGNORE_ENV = [ - 'SHLVL', # Because it's nothing to do with envsetup - 'GYP_GENERATOR_FLAGS', # because we set them in they gyp handler - 'GYP_GENERATORS', # because we set them in they gyp handler - 'PATH', # Because it gets a special merge handler - 'GYP_DEFINES', # Because it gets a special merge handler -] - -# The message to print when we detect use of an android output directory in a -# client that cannot build android. -_NOT_ANDROID_MESSAGE = """ -You are trying to build for the android platform in a client that is not -android capable. -Please get a new client using "fetch android". -See https://code.google.com/p/chromium/wiki/AndroidBuildInstructions for more -details. -""" - - -class AndroidPlatform(cr.Platform): - """The implementation of Platform for the android target.""" - - ACTIVE = cr.Config.From( - CR_ENVSETUP=os.path.join('{CR_SRC}', 'build', 'android', 'envsetup.sh'), - CR_ADB=os.path.join('{ANDROID_SDK_ROOT}', 'platform-tools', 'adb'), - CR_TARGET_SUFFIX='_apk', - CR_BINARY=os.path.join('{CR_BUILD_DIR}', 'apks', '{CR_TARGET_NAME}.apk'), - CR_ACTION='android.intent.action.VIEW', - CR_PACKAGE='com.google.android.apps.{CR_TARGET}', - CR_PROCESS='{CR_PACKAGE}', - CR_ACTIVITY='.Main', - CR_INTENT='{CR_PACKAGE}/{CR_ACTIVITY}', - CR_TEST_RUNNER=os.path.join( - '{CR_SRC}', 'build', 'android', 'test_runner.py'), - CR_ADB_GDB=os.path.join('{CR_SRC}', 'build', 'android', 'adb_gdb'), - CHROMIUM_OUT_DIR='{CR_OUT_BASE}', - CR_DEFAULT_TARGET='chromium_testshell', - ) - - def __init__(self): - super(AndroidPlatform, self).__init__() - self._env = cr.Config('android-env', literal=True, export=True) - self.detected_config.AddChild(self._env) - self._env_ready = False - self._env_paths = [] - - @property - def priority(self): - return super(AndroidPlatform, self).priority + 1 - - def Prepare(self, context): - """Override Prepare from cr.Platform.""" - super(AndroidPlatform, self).Prepare(context) - # Check we are an android capable client - is_android = 'android' in context.gclient.get('target_os', '') - if not is_android: - url = context.gclient.get('solutions', [{}])[0].get('url') - is_android = (url.startswith( - 'https://chrome-internal.googlesource.com/') and - url.endswith('/internal/apps.git')) - if not is_android: - print _NOT_ANDROID_MESSAGE - exit(1) - try: - # capture the result of env setup if we have not already done so - if not self._env_ready: - # See what the env would be without env setup - before = context.exported - # Run env setup and capture/parse it's output - envsetup = 'source {CR_ENVSETUP} --target-arch={CR_ENVSETUP_ARCH}' - output = cr.Host.CaptureShell(context, envsetup + ' > /dev/null && env') - env_setup = cr.Config('envsetup', literal=True, export=True) - for line in output.split('\n'): - (key, op, value) = line.partition('=') - if op: - key = key.strip() - if key not in _IGNORE_ENV: - env_setup[key] = env_setup.ParseValue(value.strip()) - if key == 'PATH': - self._env_paths = value.strip().split(os.path.pathsep) - if key == 'GYP_DEFINES': - # Make a version of GYP_DEFINES that is the combination of base - # setting and envsetup, needs to override the overrides - # Note: Forcing it into the top level scope - sledge-hammer - context[key] = value.strip() + ' ' + before.get(key, '') - items = env_setup.exported.items() - if not items: - # Because of the way envsetup is run, the exit code does not make it - # back to us. Instead, we assume if we got no environment at all, it - # must have failed. - print 'Envsetup failed!' - exit(1) - # Find all the things that envsetup changed - for key, value in env_setup.exported.items(): - if str(value) != str(before.get(key, None)): - self._env[key] = value - self._env_ready = True - except subprocess.CalledProcessError, e: - exit(e.returncode) - - @property - def paths(self): - return self._env_paths diff --git a/chromium/tools/cr/cr/base/arch.py b/chromium/tools/cr/cr/base/arch.py deleted file mode 100644 index 743ac8efe47..00000000000 --- a/chromium/tools/cr/cr/base/arch.py +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the basic architectures supported by cr.""" - -import cr - -DEFAULT = cr.Config.From( - CR_ENVSETUP_ARCH='{CR_ARCH}', -) - - -class Arch(cr.Plugin, cr.Plugin.Type): - """Base class for implementing cr architecture targets.""" - - SELECTOR = 'CR_ARCH' - - @classmethod - def AddArguments(cls, parser): - parser.add_argument( - '--architecture', dest=cls.SELECTOR, - choices=cls.Choices(), - default=None, - help='Sets the target architecture to use. Overrides ' + cls.SELECTOR - ) - - -class IA32Arch(Arch): - - ACTIVE = cr.Config.From( - CR_ENVSETUP_ARCH='x86', - ) - - -class Mips32Arch(Arch): - - ACTIVE = cr.Config.From( - CR_ENVSETUP_ARCH='mips', - ) - - @property - def enabled(self): - return cr.AndroidPlatform.GetInstance().is_active - - -class X64Arch(Arch): - - ACTIVE = cr.Config.From( - CR_ENVSETUP_ARCH='x64', - ) - - @property - def priority(self): - return super(X64Arch, self).priority + 1 - - -class Arm32Arch(Arch): - - ACTIVE = cr.Config.From( - CR_ENVSETUP_ARCH='arm', - ) - - @property - def priority(self): - return super(Arm32Arch, self).priority + 2 - - @property - def enabled(self): - return cr.AndroidPlatform.GetInstance().is_active diff --git a/chromium/tools/cr/cr/base/buildtype.py b/chromium/tools/cr/cr/base/buildtype.py deleted file mode 100644 index 17558128c1b..00000000000 --- a/chromium/tools/cr/cr/base/buildtype.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the basic build type support in cr.""" - -import cr - - -class BuildType(cr.Plugin, cr.Plugin.Type): - """Base class for implementing cr build types. - - A build type corresponds to the second directory level in the standard output - directory format, and the BUILDTYPE environment variable used by chromium - tools. - """ - - SELECTOR = 'CR_BUILDTYPE' - - DEFAULT = cr.Config.From( - BUILDTYPE='{CR_BUILDTYPE}', - ) - - def __init__(self): - super(BuildType, self).__init__() - self.active_config.Set( - CR_TEST_MODE=self.name, - ) - - @classmethod - def AddArguments(cls, parser): - parser.add_argument( - '--type', dest=cls.SELECTOR, - choices=cls.Choices(), - default=None, - help='Sets the build type to use. Overrides ' + cls.SELECTOR - ) - - -class DebugBuildType(BuildType): - """A concrete implementation of BuildType for Debug builds.""" - - def __init__(self): - super(DebugBuildType, self).__init__() - self._name = 'Debug' - - -class ReleaseBuildType(BuildType): - """A concrete implementation of BuildType for Release builds.""" - - def __init__(self): - super(ReleaseBuildType, self).__init__() - self._name = 'Release' - - @property - def priority(self): - return BuildType.GetPlugin('Debug').priority + 1 - diff --git a/chromium/tools/cr/cr/base/client.py b/chromium/tools/cr/cr/base/client.py deleted file mode 100644 index d8eef12ec6c..00000000000 --- a/chromium/tools/cr/cr/base/client.py +++ /dev/null @@ -1,215 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Client configuration management. - -This module holds the code for detecting and configuring the current client and -it's output directories. -It is responsible for writing out the client specific plugins that tell the -rest of the cr tool what the client is capable of. -""" - -import os -import sys - -import cr -import cr.auto.build -import cr.auto.client - -# The config version currently supported. -VERSION = 0.5 -# The default directory name to store config inside -CLIENT_CONFIG_PATH = '.cr' -# The partial filename to add to a directory to get it's config file. -CLIENT_CONFIG_FILE = os.path.join(CLIENT_CONFIG_PATH, 'config.py') -# The format string for the header of a config file. -CONFIG_FILE_PREFIX = """ -# This is an autogenerated file -# it *will* be overwritten, and changes may lost -# The system will autoload any other python file in the same folder. - -import cr - -OVERRIDES = cr.Config.From(""" -# The format string for each value in a config file. -CONFIG_VAR_LINE = '\n {0} = {1!r},' -# The format string for the tail of a config file. -CONFIG_FILE_SUFFIX = '\n)\n' -# The name of the gclient config file -GCLIENT_FILENAME = '.gclient' - -# The default config values installed by this module. -DEFAULT = cr.Config.From( - CR_ROOT_PATH=os.path.join('{GOOGLE_CODE}'), - CR_CLIENT_PATH=os.path.join('{CR_ROOT_PATH}', '{CR_CLIENT_NAME}'), - CR_SRC=os.path.join('{CR_CLIENT_PATH}', 'src'), - CR_BUILD_DIR=os.path.join('{CR_SRC}', '{CR_OUT_FULL}'), -) - -# Config values determined at run time by this module. -DETECTED = cr.Config.From( - CR_CLIENT_PATH=lambda context: _DetectPath(), - # _DetectName not declared yet so pylint: disable=unnecessary-lambda - CR_CLIENT_NAME=lambda context: _DetectName(context), -) - -_cached_path = None -_cached_name = None - - -def _DetectPath(): - """A dynamic value function that tries to detect the current client.""" - global _cached_path - if _cached_path is not None: - return _cached_path - # See if we can detect the source tree root - _cached_path = os.getcwd() - while (_cached_path and - not os.path.exists(os.path.join(_cached_path, GCLIENT_FILENAME))): - old = _cached_path - _cached_path = os.path.dirname(_cached_path) - if _cached_path == old: - _cached_path = None - if _cached_path is not None: - dirname, basename = os.path.split(_cached_path) - if basename == 'src': - # we have the src path, base is one level up - _cached_path = dirname - if _cached_path is None: - _cached_path = cr.visitor.HIDDEN - return _cached_path - - -def _DetectName(context): - """A dynamic value function that works out the name of the current client.""" - global _cached_name - if _cached_name is not None: - return _cached_name - _cached_name = 'chromium' - path = context.Get('CR_CLIENT_PATH') - if path is None: - return - _cached_name = os.path.basename(path) - return _cached_name - - -def _GetConfigFilename(path): - return os.path.realpath(os.path.join(path, CLIENT_CONFIG_FILE)) - - -def _IsOutputDir(path): - return os.path.isfile(_GetConfigFilename(path)) - - -def _WriteConfig(writer, data): - writer.write(CONFIG_FILE_PREFIX) - for key, value in data.items(): - writer.write(CONFIG_VAR_LINE.format(key, value)) - writer.write(CONFIG_FILE_SUFFIX) - - -def AddArguments(parser): - parser.add_argument( - '-o', '--out', dest='_out', metavar='name', - default=None, - help='The name of the out directory to use. Overrides CR_OUT.' - ) - - -def GetOutArgument(context): - return getattr(context.args, '_out', None) - - -def ApplyOutArgument(context): - # TODO(iancottrell): be flexible, allow out to do approximate match... - out = GetOutArgument(context) - if out: - context.derived.Set(CR_OUT_FULL=out) - - -def ReadGClient(context): - """Loads the .gclient configuration for the current client. - - This will load from CR_CLIENT_PATH. - - Args: - context: The active context to load configuratin for. - Returns: - The dict of values set in the .gclient file. - - """ - # Now attempt to load and parse the .gclient file - result = {} - try: - gclient_file = context.Substitute( - os.path.join('{CR_CLIENT_PATH}', GCLIENT_FILENAME)) - with open(gclient_file, 'r') as spec_file: - # matching the behaviour of gclient, so pylint: disable=exec-used - exec(spec_file.read(), {}, result) - except IOError: - # no .gclient file, skip it - pass - return result - - -def LoadConfig(context): - """Loads the client configuration for the given context. - - This will load configuration if present from CR_CLIENT_PATH and then - CR_BUILD_DIR. - - Args: - context: The active context to load configuratin for. - Returns: - True if configuration was fully loaded. - - """ - # Load the root config, will help set default build dir - client_path = context.Find('CR_CLIENT_PATH') - if not client_path: - return False - cr.auto.client.__path__.append(os.path.join(client_path, CLIENT_CONFIG_PATH)) - cr.loader.Scan() - # Now load build dir config - build_dir = context.Find('CR_BUILD_DIR') - if not build_dir: - return False - cr.auto.build.__path__.append(os.path.join(build_dir, CLIENT_CONFIG_PATH)) - cr.loader.Scan() - return hasattr(cr.auto.build, 'config') - - -def WriteConfig(context, path, data): - """Writes a configuration out to a file. - - This writes all the key value pairs in data out to a config file below path. - - Args: - context: The context to run under. - path: The base path to write the config plugin into. - data: The key value pairs to write. - """ - filename = _GetConfigFilename(path) - config_dir = os.path.dirname(filename) - if context.dry_run: - print 'makedirs', config_dir - print 'Write config to', filename - _WriteConfig(sys.stdout, data) - else: - try: - os.makedirs(config_dir) - except OSError: - if not os.path.isdir(config_dir): - raise - with open(filename, 'w') as writer: - _WriteConfig(writer, data) - - -def PrintInfo(context): - print 'Selected output directory is', context.Find('CR_BUILD_DIR') - try: - for name in cr.auto.build.config.OVERRIDES.exported.keys(): - print ' ', name, '=', context.Get(name) - except AttributeError: - pass diff --git a/chromium/tools/cr/cr/base/host.py b/chromium/tools/cr/cr/base/host.py deleted file mode 100644 index c6e0ced86e6..00000000000 --- a/chromium/tools/cr/cr/base/host.py +++ /dev/null @@ -1,149 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Module for build host support.""" - -import os -import pipes -import subprocess - -import cr - -# Controls what verbosity level turns on command trail logging -_TRAIL_VERBOSITY = 2 - - -class Host(cr.Plugin, cr.Plugin.Type): - """Base class for implementing cr hosts. - - The host is the main access point to services provided by the machine cr - is running on. It exposes information about the machine, and runs external - commands on behalf of the actions. - """ - - def __init__(self): - super(Host, self).__init__() - - def Matches(self): - """Detects whether this is the correct host implementation. - - This method is overridden by the concrete implementations. - Returns: - true if the plugin matches the machine it is running on. - """ - return False - - @classmethod - def Select(cls, context): - for host in cls.Plugins(): - if host.Matches(): - return host - - def _Execute(self, context, command, - shell=False, capture=False, ignore_dry_run=False, - return_status=False): - """This is the only method that launches external programs. - - It is a thin wrapper around subprocess.Popen that handles cr specific - issues. The command is expanded in the context, so that context variables - are substituted. - Args: - context: the cr context to run under. - command: the command to run. - shell: whether to run the command using the shell. - capture: controls wether the output of the command is captured. - ignore_dry_run: Normally, if the context is in dry run mode the command is - printed but not executed. This flag overrides that behaviour, causing - the command to be run anyway. - return_status: switches the function to returning the status code rather - the output. - Returns: - the status if return_status is true, or the output if capture is true, - otherwise nothing. - """ - with context.Trace(): - command = [context.Substitute(arg) for arg in command if arg] - trail = context.trail - if not command: - print 'Empty command passed to execute' - exit(1) - if context.verbose: - print ' '.join(command) - if context.verbose >= _TRAIL_VERBOSITY: - print 'Command expanded the following variables:' - for key, value in trail: - print ' ', key, '=', value - if ignore_dry_run or not context.dry_run: - out = None - if capture: - out = subprocess.PIPE - try: - p = subprocess.Popen( - command, shell=shell, - env={k: str(v) for k, v in context.exported.items()}, - stdout=out) - except OSError: - print 'Failed to exec', command - # Don't log the trail if we already have - if context.verbose < _TRAIL_VERBOSITY: - print 'Variables used to build the command were:' - for key, value in trail: - print ' ', key, '=', value - exit(1) - try: - output, _ = p.communicate() - except KeyboardInterrupt: - p.terminate() - p.wait() - exit(1) - if return_status: - return p.returncode - if p.returncode != 0: - print 'Error {0} executing command {1}'.format(p.returncode, command) - exit(p.returncode) - return output or '' - return '' - - @cr.Plugin.activemethod - def Shell(self, context, *command): - command = ' '.join([pipes.quote(arg) for arg in command]) - return self._Execute(context, [command], shell=True) - - @cr.Plugin.activemethod - def Execute(self, context, *command): - return self._Execute(context, command, shell=False) - - @cr.Plugin.activemethod - def CaptureShell(self, context, *command): - return self._Execute(context, command, - shell=True, capture=True, ignore_dry_run=True) - - @cr.Plugin.activemethod - def Capture(self, context, *command): - return self._Execute(context, command, capture=True, ignore_dry_run=True) - - @cr.Plugin.activemethod - def ExecuteStatus(self, context, *command): - return self._Execute(context, command, - ignore_dry_run=True, return_status=True) - - @classmethod - def SearchPath(cls, name): - """Searches the PATH for an executable. - - Args: - name: the name of the binary to search for. - Returns: - the set of executables found, or an empty list if none. - """ - result = [] - extensions = [''] - extensions.extend(os.environ.get('PATHEXT', '').split(os.pathsep)) - for path in os.environ.get('PATH', '').split(os.pathsep): - partial = os.path.join(path, name) - for extension in extensions: - filename = partial + extension - if os.path.exists(filename) and filename not in result: - result.append(filename) - return result diff --git a/chromium/tools/cr/cr/base/linux.py b/chromium/tools/cr/cr/base/linux.py deleted file mode 100644 index 407c48efe3f..00000000000 --- a/chromium/tools/cr/cr/base/linux.py +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""The linux specific host and platform implementation module.""" - -import os - -import cr - - -class LinuxHost(cr.Host): - """The implementation of Host for linux.""" - - ACTIVE = cr.Config.From( - GOOGLE_CODE='/usr/local/google/code', - ) - - def __init__(self): - super(LinuxHost, self).__init__() - - def Matches(self): - return cr.Platform.System() == 'Linux' - - -class LinuxPlatform(cr.Platform): - """The implementation of Platform for the linux target.""" - - ACTIVE = cr.Config.From( - CR_BINARY=os.path.join('{CR_BUILD_DIR}', '{CR_BUILD_TARGET}'), - CHROME_DEVEL_SANDBOX='/usr/local/sbin/chrome-devel-sandbox', - ) - - @property - def enabled(self): - return cr.Platform.System() == 'Linux' - - @property - def priority(self): - return 2 - - @property - def paths(self): - return ['{GOMA_DIR}'] diff --git a/chromium/tools/cr/cr/base/platform.py b/chromium/tools/cr/cr/base/platform.py deleted file mode 100644 index db6f66d2983..00000000000 --- a/chromium/tools/cr/cr/base/platform.py +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Module for the target platform support.""" - -from importlib import import_module -import os - -import cr - -DEFAULT = cr.Config.From( - DEPOT_TOOLS=os.path.join('{GOOGLE_CODE}', 'depot_tools'), -) - - -class Platform(cr.Plugin, cr.Plugin.Type): - """Base class for implementing cr platforms. - - A platform is the target operating system being compiled for (linux android). - """ - - _platform_module = import_module('platform', None) - SELECTOR = 'CR_PLATFORM' - - @classmethod - def AddArguments(cls, parser): - parser.add_argument( - '--platform', dest=cls.SELECTOR, - choices=cls.Choices(), - default=None, - help='Sets the target platform to use. Overrides ' + cls.SELECTOR - ) - - @classmethod - def System(cls): - return cls._platform_module.system() - - def __init__(self): - super(Platform, self).__init__() - - def Activate(self, context): - super(Platform, self).Activate(context) - if _PathFixup not in context.fixup_hooks: - context.fixup_hooks.append(_PathFixup) - - @cr.Plugin.activemethod - def Prepare(self, context): - pass - - @property - def paths(self): - return [] - - -def _PathFixup(context, key, value): - """A context fixup that does platform specific modifications to the PATH.""" - if key == 'PATH': - paths = [] - for entry in Platform.GetActivePlugin(context).paths: - entry = context.Substitute(entry) - if entry not in paths: - paths.append(entry) - for entry in value.split(os.path.pathsep): - if entry.endswith(os.path.sep + 'goma'): - pass - elif entry not in paths: - paths.append(entry) - value = os.path.pathsep.join(paths) - return value diff --git a/chromium/tools/cr/cr/commands/__init__.py b/chromium/tools/cr/cr/commands/__init__.py deleted file mode 100644 index 852ecbedbed..00000000000 --- a/chromium/tools/cr/cr/commands/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A package for all the built in commands. - -This package has all the standard commands built in to the cr tool. -Most commands use actions to perform the real work. -""" diff --git a/chromium/tools/cr/cr/commands/build.py b/chromium/tools/cr/cr/commands/build.py deleted file mode 100644 index 2d2c27fd178..00000000000 --- a/chromium/tools/cr/cr/commands/build.py +++ /dev/null @@ -1,81 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the build commands.""" - -import cr - - -class BuildCommand(cr.Command): - """The implementation of the build command. - - This is a thin shell over the Builder.Build method of the selected builder. - """ - - def __init__(self): - super(BuildCommand, self).__init__() - self.help = 'Build a target' - self.description = (""" - Uses the specified builder for the platform to bring the target - up to date. - """) - - def AddArguments(self, subparsers): - parser = super(BuildCommand, self).AddArguments(subparsers) - cr.Builder.AddArguments(self, parser) - cr.Target.AddArguments(self, parser, allow_multiple=True) - self.ConsumeArgs(parser, 'the builder') - return parser - - def Run(self, context): - return cr.Builder.Build( - context, cr.Target.GetTargets(context), context.remains) - - -class CleanCommand(cr.Command): - """The implementation of the clean command. - - This is a thin shell over the Builder.Clean method of the selected builder. - """ - - def __init__(self): - super(CleanCommand, self).__init__() - self.help = 'Clean a target' - self.description = ( - 'Uses the specified builder to clean out built files for the target.') - - def AddArguments(self, subparsers): - parser = super(CleanCommand, self).AddArguments(subparsers) - cr.Builder.AddArguments(self, parser) - cr.Target.AddArguments(self, parser, allow_multiple=True) - self.ConsumeArgs(parser, 'the builder') - return parser - - def Run(self, context): - return cr.Builder.Clean( - context, cr.Target.GetTargets(context), context.remains) - - -class RebuildCommand(cr.Command): - """The implementation of the rebuild command. - - This is a thin shell over the Builder.Rebuild method of the selected builder. - """ - - def __init__(self): - super(RebuildCommand, self).__init__() - self.help = 'Rebuild a target' - self.description = ( - 'Uses the specified builder for the platform to rebuild a target.') - - def AddArguments(self, subparsers): - parser = super(RebuildCommand, self).AddArguments(subparsers) - cr.Builder.AddArguments(self, parser) - cr.Target.AddArguments(self, parser, allow_multiple=True) - self.ConsumeArgs(parser, 'the builder') - return parser - - def Run(self, context): - return cr.Builder.Rebuild( - context, cr.Target.GetTargets(context), context.remains) diff --git a/chromium/tools/cr/cr/commands/command.py b/chromium/tools/cr/cr/commands/command.py deleted file mode 100644 index d2e65a2be39..00000000000 --- a/chromium/tools/cr/cr/commands/command.py +++ /dev/null @@ -1,104 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -"""Module to hold the Command plugin.""" - -import argparse - -import cr - - -class Command(cr.Plugin, cr.Plugin.Type): - """Base class for implementing cr commands. - - These are the sub-commands on the command line, and modify the - accepted remaining arguments. - Commands in general do not implement the functionality directly, instead they - run a sequence of actions. - """ - - @classmethod - def Select(cls, context): - """Called to select which command is active. - - This picks a command based on the first non - argument on the command - line. - Args: - context: The context to select the command for. - Returns: - the selected command, or None if not specified on the command line. - """ - if context.args: - return getattr(context.args, '_command', None) - return None - - def __init__(self): - super(Command, self).__init__() - self.help = 'Missing help: {0}'.format(self.__class__.__name__) - self.description = None - self.epilog = None - self.parser = None - self.requires_build_dir = True - - def AddArguments(self, subparsers): - """Add arguments to the command line parser. - - Called by the main function to add the command to the command line parser. - Commands that override this function to add more arguments must invoke - this method. - Args: - subparsers: The argparse subparser manager to add this command to. - Returns: - the parser that was built for the command. - """ - self.parser = subparsers.add_parser( - self.name, - add_help=False, - help=self.help, - description=self.description or self.help, - epilog=self.epilog, - ) - self.parser.set_defaults(_command=self) - cr.Context.AddCommonArguments(self.parser) - cr.base.client.AddArguments(self.parser) - return self.parser - - def ConsumeArgs(self, parser, reason): - """Adds a remaining argument consumer to the parser. - - A helper method that commands can use to consume all remaining arguments. - Use for things like lists of targets. - Args: - parser: The parser to consume remains for. - reason: The reason to give the user in the help text. - """ - parser.add_argument( - '_remains', metavar='arguments', - nargs=argparse.REMAINDER, - help='The additional arguments to {0}.'.format(reason) - ) - - def EarlyArgProcessing(self, context): - """Called to make decisions based on speculative argument parsing. - - When this method is called, enough of the command line parsing has been - done that the command is selected. This allows the command to make any - modifications needed before the final argument parsing is done. - - Args: - context: The context that is parsing the arguments. - """ - cr.base.client.ApplyOutArgument(context) - - @cr.Plugin.activemethod - def Run(self, context): - """The main method of the command. - - This is the only thing that a command has to implement, and it should not - call this base version. - Args: - context: The context to run the command in. - """ - _ = context - raise NotImplementedError('Must be overridden.') - diff --git a/chromium/tools/cr/cr/commands/debug.py b/chromium/tools/cr/cr/commands/debug.py deleted file mode 100644 index 48fb513b3cc..00000000000 --- a/chromium/tools/cr/cr/commands/debug.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the run command.""" - -import cr - - -class DebugCommand(cr.Command): - """The implementation of the debug command. - - This is much like the run command except it launches the program under - a debugger instead. - """ - - def __init__(self): - super(DebugCommand, self).__init__() - self.help = 'Debug a binary' - - def AddArguments(self, subparsers): - parser = super(DebugCommand, self).AddArguments(subparsers) - cr.Builder.AddArguments(self, parser) - cr.Installer.AddArguments(self, parser) - cr.Debugger.AddArguments(self, parser) - cr.Target.AddArguments(self, parser) - self.ConsumeArgs(parser, 'the binary') - return parser - - def Run(self, context): - targets = cr.Target.GetTargets(context) - if not cr.Debugger.ShouldInvoke(context): - cr.Debugger.Attach(context, targets, context.remains) - elif cr.Installer.Skipping(context): - cr.Debugger.Restart(context, targets, context.remains) - else: - cr.Builder.Build(context, targets, []) - cr.Debugger.Kill(context, targets, []) - cr.Installer.Reinstall(context, targets, []) - cr.Debugger.Invoke(context, targets, context.remains) diff --git a/chromium/tools/cr/cr/commands/info.py b/chromium/tools/cr/cr/commands/info.py deleted file mode 100644 index 88af0f5aaa2..00000000000 --- a/chromium/tools/cr/cr/commands/info.py +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the info implementation of Command.""" - -import cr - - -class InfoCommand(cr.Command): - """The cr info command implementation.""" - - def __init__(self): - super(InfoCommand, self).__init__() - self.help = 'Print information about the cr environment' - - def AddArguments(self, subparsers): - parser = super(InfoCommand, self).AddArguments(subparsers) - parser.add_argument( - '-s', '--short', dest='_short', - action='store_true', default=False, - help='Short form results, useful for scripting.' - ) - self.ConsumeArgs(parser, 'the environment') - return parser - - def EarlyArgProcessing(self, context): - if getattr(context.args, '_short', False): - self.requires_build_dir = False - - def Run(self, context): - if context.remains: - for var in context.remains: - if getattr(context.args, '_short', False): - val = context.Find(var) - if val is None: - val = '' - print val - else: - print var, '=', context.Find(var) - else: - cr.base.client.PrintInfo(context) - diff --git a/chromium/tools/cr/cr/commands/init.py b/chromium/tools/cr/cr/commands/init.py deleted file mode 100644 index adcb4a180c4..00000000000 --- a/chromium/tools/cr/cr/commands/init.py +++ /dev/null @@ -1,180 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the init command.""" - -import os - -import cr - -# The set of variables to store in the per output configuration. -OUT_CONFIG_VARS = [ - 'CR_VERSION', - cr.Platform.SELECTOR, cr.BuildType.SELECTOR, cr.Arch.SELECTOR, - 'CR_OUT_BASE', 'CR_OUT_FULL', -] - - -class InitCommand(cr.Command): - """The implementation of the init command. - - The init command builds or updates an output directory. - It then uses the Prepare and Select commands to get that directory - ready to use. - """ - - def __init__(self): - super(InitCommand, self).__init__() - self.requires_build_dir = False - self.help = 'Create and configure an output directory' - self.description = (""" - If the .cr directory is not present, build it and add - the specified configuration. - If the file already exists, update the configuration with any - additional settings. - """) - self._settings = [] - - def AddArguments(self, subparsers): - """Overridden from cr.Command.""" - parser = super(InitCommand, self).AddArguments(subparsers) - cr.Platform.AddArguments(parser) - cr.BuildType.AddArguments(parser) - cr.Arch.AddArguments(parser) - cr.SelectCommand.AddPrepareArguments(parser) - parser.add_argument( - '-s', '--set', dest='_settings', metavar='settings', - action='append', - help='Configuration overrides.' - ) - return parser - - def EarlyArgProcessing(self, context): - base_settings = getattr(context.args, '_settings', None) - if base_settings: - self._settings.extend(base_settings) - # Do not call super early processing, we do not want to apply - # the output arg... - out = cr.base.client.GetOutArgument(context) - if out: - # Output directory is fully specified - # We need to deduce other settings from it's name - base, buildtype = os.path.split(out) - if not (base and buildtype): - print 'Specified output directory must be two levels' - exit(1) - if not cr.BuildType.FindPlugin(buildtype): - print 'Specified build type', buildtype, 'is not valid' - print 'Must be one of', ','.join(p.name for p in cr.BuildType.Plugins()) - exit(1) - if context.args.CR_BUILDTYPE and context.args.CR_BUILDTYPE != buildtype: - print 'If --type and --out are both specified, they must match' - print 'Got', context.args.CR_BUILDTYPE, 'and', buildtype - exit(1) - platform = context.args.CR_PLATFORM - if not platform: - # Try to guess platform based on output name - platforms = [p.name for p in cr.Platform.AllPlugins()] - matches = [p for p in platforms if p in base] - if len(matches) != 1: - print 'Platform is not set, and could not be guessed from', base - print 'Should be one of', ','.join(platforms) - if len(matches) > 1: - print 'Matched all of', ','.join(matches) - exit(1) - platform = matches[0] - context.derived.Set( - CR_OUT_FULL=out, - CR_OUT_BASE=base, - CR_PLATFORM=platform, - CR_BUILDTYPE=buildtype, - ) - if not 'CR_OUT_BASE' in context: - context.derived['CR_OUT_BASE'] = 'out_{CR_PLATFORM}' - if not 'CR_OUT_FULL' in context: - context.derived['CR_OUT_FULL'] = os.path.join( - '{CR_OUT_BASE}', '{CR_BUILDTYPE}') - - def Run(self, context): - """Overridden from cr.Command.""" - src_path = context.Get('CR_SRC') - if not os.path.isdir(src_path): - print context.Substitute('Path {CR_SRC} is not a valid client') - exit(1) - - # Ensure we have an output directory override ready to fill in - # This will only be missing if we are creating a brand new output - # directory - build_package = cr.auto.build - - # Collect the old version (and float convert) - old_version = context.Find('CR_VERSION') - try: - old_version = float(old_version) - except (ValueError, TypeError): - old_version = 0.0 - is_new = not hasattr(build_package, 'config') - if is_new: - - class FakeModule(object): - OVERRIDES = cr.Config('OVERRIDES') - - def __init__(self): - self.__name__ = 'config' - - old_version = None - config = FakeModule() - setattr(build_package, 'config', config) - cr.plugin.ChainModuleConfigs(config) - - # Force override the version - build_package.config.OVERRIDES.Set(CR_VERSION=cr.base.client.VERSION) - # Add all the variables that we always want to have - for name in OUT_CONFIG_VARS: - value = context.Find(name) - build_package.config.OVERRIDES[name] = value - # Apply the settings from the command line - for setting in self._settings: - name, separator, value = setting.partition('=') - name = name.strip() - if not separator: - value = True - else: - value = cr.Config.ParseValue(value.strip()) - build_package.config.OVERRIDES[name] = value - - # Run all the output directory init hooks - for hook in InitHook.Plugins(): - hook.Run(context, old_version, build_package.config) - # Redo activations, they might have changed - cr.plugin.Activate(context) - - # Write out the new configuration, and select it as the default - cr.base.client.WriteConfig(context, context.Get('CR_BUILD_DIR'), - build_package.config.OVERRIDES.exported) - # Prepare the platform in here, using the updated config - cr.Platform.Prepare(context) - cr.SelectCommand.Select(context) - - -class InitHook(cr.Plugin, cr.Plugin.Type): - """Base class for output directory initialization hooks. - - Implementations used to fix from old version to new ones live in the - cr.fixups package. - """ - - def Run(self, context, old_version, config): - """Run the initialization hook. - - This is invoked once per init invocation. - Args: - context: The context of the init command. - old_version: The old version, - 0.0 if the old version was bad or missing, - None if building a new output direcory. - config: The mutable config that will be written. - """ - raise NotImplementedError('Must be overridden.') - diff --git a/chromium/tools/cr/cr/commands/install.py b/chromium/tools/cr/cr/commands/install.py deleted file mode 100644 index 51a02b36eea..00000000000 --- a/chromium/tools/cr/cr/commands/install.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the install command.""" - -import cr - - -class InstallCommand(cr.Command): - """The implementation of the install command. - - This first uses Builder.Build to bring the target up to date, and then - installs it using Installer.Reinstall. - The builder installs its command line arguments, and you can use those to - select which builder is used. Selecting the skip builder - (using --builder=skip) bypasses the build stage. - """ - - def __init__(self): - super(InstallCommand, self).__init__() - self.help = 'Install a binary' - - def AddArguments(self, subparsers): - parser = super(InstallCommand, self).AddArguments(subparsers) - cr.Builder.AddArguments(self, parser) - cr.Installer.AddArguments(self, parser) - cr.Target.AddArguments(self, parser, allow_multiple=True) - self.ConsumeArgs(parser, 'the installer') - return parser - - def Run(self, context): - targets = cr.Target.GetTargets(context) - if not cr.Installer.Skipping(context): - cr.Builder.Build(context, targets, []) - cr.Installer.Reinstall(context, targets, context.remains) diff --git a/chromium/tools/cr/cr/commands/prepare.py b/chromium/tools/cr/cr/commands/prepare.py deleted file mode 100644 index 57abccef6bb..00000000000 --- a/chromium/tools/cr/cr/commands/prepare.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the prepare command.""" - -import cr - - -class PrepareCommand(cr.Command): - """The implementation of the prepare command. - - The prepare command is used to perform the steps needed to get an output - directory ready to use. These should not be the kind of things that need to - happen every time you build something, but the rarer things that you re-do - only when you get or add new source files, or change your build options. - This delegates all it's behavior to implementations of PrepareOut. These will - (mostly) be in the cr.actions package. - """ - - def __init__(self): - super(PrepareCommand, self).__init__() - self.help = 'Prepares an output directory' - self.description = (""" - This does any preparation needed for the output directory, such as - running gyp. - """) - - def Run(self, context): - self.Prepare(context) - - @classmethod - def Prepare(cls, context): - for preparation in PrepareOut.Plugins(): - preparation.Prepare(context) - - -class PrepareOut(cr.Plugin, cr.Plugin.Type): - """Base class for output directory preparation plugins. - - See PrepareCommand for details. - """ - - def Prepare(self, context): - """All PrepareOut plugins must override this method to do their work.""" - _ = context - raise NotImplementedError('Must be overridden.') - diff --git a/chromium/tools/cr/cr/commands/run.py b/chromium/tools/cr/cr/commands/run.py deleted file mode 100644 index 9b57d9439c3..00000000000 --- a/chromium/tools/cr/cr/commands/run.py +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the run command.""" - -import cr - - -class RunCommand(cr.Command): - """The implementation of the run command. - - This first uses Builder to bring the target up to date. - It then uses Installer to install the target (if needed), and - finally it uses Runner to run the target. - You can use skip version to not perform any of these steps. - """ - - def __init__(self): - super(RunCommand, self).__init__() - self.help = 'Invoke a target' - - def AddArguments(self, subparsers): - parser = super(RunCommand, self).AddArguments(subparsers) - cr.Builder.AddArguments(self, parser) - cr.Installer.AddArguments(self, parser) - cr.Runner.AddArguments(self, parser) - cr.Target.AddArguments(self, parser, allow_multiple=True) - self.ConsumeArgs(parser, 'the binary') - return parser - - def Run(self, context): - targets = cr.Target.GetTargets(context) - test_targets = [target for target in targets if target.is_test] - run_targets = [target for target in targets if not target.is_test] - if cr.Installer.Skipping(context): - # No installer, only build test targets - build_targets = test_targets - else: - build_targets = targets - if build_targets: - cr.Builder.Build(context, build_targets, []) - # See if we can use restart when not installing - if cr.Installer.Skipping(context): - cr.Runner.Restart(context, targets, context.remains) - else: - cr.Runner.Kill(context, run_targets, []) - cr.Installer.Reinstall(context, run_targets, []) - cr.Runner.Invoke(context, targets, context.remains) - diff --git a/chromium/tools/cr/cr/commands/select.py b/chromium/tools/cr/cr/commands/select.py deleted file mode 100644 index 58cebdd384d..00000000000 --- a/chromium/tools/cr/cr/commands/select.py +++ /dev/null @@ -1,61 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the select command.""" - -import cr - -# The set of variables SELECT writes into the client plugin to control the -# active output directory. -SELECT_OUT_VARS = ['CR_OUT_FULL'] - - -class SelectCommand(cr.Command): - """The implementation of the select command. - - The select command is used to set the default output directory used by all - other commands. It does this by writing out a plugin into the client root - that sets the active output path. - """ - - def __init__(self): - super(SelectCommand, self).__init__() - self.help = 'Select an output directory' - self.description = (""" - This makes the specified output directory the default for all future - operations. It also invokes prepare on that directory. - """) - - def AddArguments(self, subparsers): - parser = super(SelectCommand, self).AddArguments(subparsers) - self.AddPrepareArguments(parser) - return parser - - @classmethod - def AddPrepareArguments(cls, parser): - parser.add_argument( - '--no-prepare', dest='_no_prepare', - action='store_true', default=False, - help='Don\'t prepare the output directory.' - ) - - def Run(self, context): - self.Select(context) - - @classmethod - def Select(cls, context): - """Performs the select. - - This is also called by the init command to auto select the new output - directory. - Args: - context: The cr Context to select in. - """ - cr.base.client.WriteConfig( - context, context.Get('CR_CLIENT_PATH'), dict( - CR_OUT_FULL=context.Get('CR_OUT_FULL'))) - cr.base.client.PrintInfo(context) - # Now we run the post select actions - if not getattr(context.args, '_no_prepare', None): - cr.PrepareCommand.Prepare(context) diff --git a/chromium/tools/cr/cr/commands/shell.py b/chromium/tools/cr/cr/commands/shell.py deleted file mode 100644 index 452ebb74606..00000000000 --- a/chromium/tools/cr/cr/commands/shell.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the shell command.""" - -import os -import tempfile - -import cr - - -class ShellCommand(cr.Command): - """The implementation of the shell command. - - The shell command is the escape hatch that lets user run any program in the - same environment that cr would use if it were running it. - """ - - def __init__(self): - super(ShellCommand, self).__init__() - self.help = 'Launch a shell' - self.description = (""" - If no arguments are present, this launches an interactive system - shell (ie bash) with the environment modified to that used for the - build systems. - If any arguments are present, they are used as a command line to run - in that shell. - This allows you to run commands that are not yet available natively - in cr. - """) - - def AddArguments(self, subparsers): - parser = super(ShellCommand, self).AddArguments(subparsers) - self.ConsumeArgs(parser, 'the shell') - return parser - - def Run(self, context): - if context.remains: - cr.Host.Shell(context, *context.remains) - return - # If we get here, we are trying to launch an interactive shell - shell = os.environ.get('SHELL', None) - if shell is None: - print 'Don\'t know how to run a shell on this system' - elif shell.endswith('bash'): - ps1 = '[CR] ' + os.environ.get('PS1', '') - with tempfile.NamedTemporaryFile() as rcfile: - rcfile.write('source ~/.bashrc\nPS1="'+ps1+'"') - rcfile.flush() - cr.Host.Execute(context, shell, '--rcfile', rcfile.name) - else: - cr.Host.Execute(context, shell) diff --git a/chromium/tools/cr/cr/commands/sync.py b/chromium/tools/cr/cr/commands/sync.py deleted file mode 100644 index cef9b7a6f4a..00000000000 --- a/chromium/tools/cr/cr/commands/sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for the sync command.""" - -import os.path - -import cr - - -class SyncCommand(cr.Command): - """The implementation of the sync command. - - This command is a very thin shim over the gclient sync, and should remain so. - The only significant thing it adds is that the environment is set up so that - the run-hooks will do their work in the selected output directory. - """ - - # The configuration loaded to support this command. - DEFAULT = cr.Config.From( - GCLIENT_BINARY=os.path.join('{DEPOT_TOOLS}', 'gclient'), - ) - - # A placeholder for the detected gclient environment - DETECTED = cr.Config('DETECTED') - - def __init__(self): - super(SyncCommand, self).__init__() - self.help = 'Sync the source tree' - self.description = 'Run gclient sync with the right environment.' - - def AddArguments(self, subparsers): - parser = super(SyncCommand, self).AddArguments(subparsers) - self.ConsumeArgs(parser, 'gclient') - # TODO(iancottrell): clean no-hooks support would be nice. - return parser - - def Run(self, context): - # TODO(iancottrell): we should probably run the python directly, - # rather than the shell wrapper - # TODO(iancottrell): try to help out when the local state is not a good - # one to do a sync in - cr.Host.Execute(context, '{GCLIENT_BINARY}', 'sync', *context.remains) - - -def _AutoDetectGClient(): - """Attempts to detect gclient and it's parent repository.""" - gclient_binaries = cr.Host.SearchPath('gclient') - if gclient_binaries: - SyncCommand.DETECTED.Set(GCLIENT_BINARY=gclient_binaries[0]) - SyncCommand.DETECTED.Set(DEPOT_TOOLS=os.path.dirname(gclient_binaries[0])) - -# Invoke the auto detection -_AutoDetectGClient() diff --git a/chromium/tools/cr/cr/config.py b/chromium/tools/cr/cr/config.py deleted file mode 100644 index a19b837a446..00000000000 --- a/chromium/tools/cr/cr/config.py +++ /dev/null @@ -1,240 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Configuration variable management for the cr tool. - -This holds the classes that support the hierarchical variable management used -in the cr tool to provide all the command configuration controls. -""" - -import string - -import cr.visitor - -_PARSE_CONSTANT_VALUES = [None, True, False] -_PARSE_CONSTANTS = dict((str(value), value) for value in _PARSE_CONSTANT_VALUES) - -# GLOBALS is the singleton used to tie static global configuration objects -# together. -GLOBALS = [] - - -class _MissingToErrorFormatter(string.Formatter): - """A string formatter used in value resolve. - - The main extra it adds is a new conversion specifier 'e' that throws a - KeyError if it could not find the value. - This allows a string value to use {A_KEY!e} to indicate that it is a - formatting error if A_KEY is not present. - """ - - def convert_field(self, value, conversion): - if conversion == 'e': - result = str(value) - if not result: - raise KeyError('unknown') - return result - return super(_MissingToErrorFormatter, self).convert_field( - value, conversion) - - -class _Tracer(object): - """Traces variable lookups. - - This adds a hook to a config object, and uses it to track all variable - lookups that happen and add them to a trail. When done, it removes the hook - again. This is used to provide debugging information about what variables are - used in an operation. - """ - - def __init__(self, config): - self.config = config - self.trail = [] - - def __enter__(self): - self.config.fixup_hooks.append(self._Trace) - return self - - def __exit__(self, *_): - self.config.fixup_hooks.remove(self._Trace) - self.config.trail = self.trail - return False - - def _Trace(self, _, key, value): - self.trail.append((key, value)) - return value - - -class Config(cr.visitor.Node): - """The main variable holding class. - - This holds a set of unresolved key value pairs, and the set of child Config - objects that should be referenced when looking up a key. - Key search is one in a pre-order traversal, and new children are prepended. - This means parents override children, and the most recently added child - overrides the rest. - - Values can be simple python types, callable dynamic values, or strings. - If the value is a string, it is assumed to be a standard python format string - where the root config object is used to resolve the keys. This allows values - to refer to variables that are overriden in another part of the hierarchy. - """ - - @classmethod - def From(cls, *args, **kwargs): - """Builds an unnamed config object from a set of key,value args.""" - return Config('??').Apply(args, kwargs) - - @classmethod - def If(cls, condition, true_value, false_value=''): - """Returns a config value that selects a value based on the condition. - - Args: - condition: The variable name to select a value on. - true_value: The value to use if the variable is True. - false_value: The value to use if the resolved variable is False. - Returns: - A dynamic value. - """ - def Resolve(context): - test = context.Get(condition) - if test: - value = true_value - else: - value = false_value - return context.Substitute(value) - return Resolve - - @classmethod - def Optional(cls, value, alternate=''): - """Returns a dynamic value that defaults to an alternate. - - Args: - value: The main value to resolve. - alternate: The value to use if the main value does not resolve. - Returns: - value if it resolves, alternate otherwise. - """ - def Resolve(context): - try: - return context.Substitute(value) - except KeyError: - return context.Substitute(alternate) - return Resolve - - def __init__(self, name='--', literal=False, export=None, enabled=True): - super(Config, self).__init__(name=name, enabled=enabled, export=export) - self._literal = literal - self._formatter = _MissingToErrorFormatter() - self.fixup_hooks = [] - self.trail = [] - - @property - def literal(self): - return self._literal - - def Substitute(self, value): - return self._formatter.vformat(str(value), (), self) - - def Resolve(self, visitor, key, value): - """Resolves a value to it's final form. - - Raw values can be callable, simple values, or contain format strings. - Args: - visitor: The vistior asking to resolve a value. - key: The key being visited. - value: The unresolved value associated with the key. - Returns: - the fully resolved value. - """ - error = None - if callable(value): - value = value(self) - # Using existence of value.swapcase as a proxy for is a string - elif hasattr(value, 'swapcase'): - if not visitor.current_node.literal: - try: - value = self.Substitute(value) - except KeyError as e: - error = e - return self.Fixup(key, value), error - - def Fixup(self, key, value): - for hook in self.fixup_hooks: - value = hook(self, key, value) - return value - - @staticmethod - def ParseValue(value): - """Converts a string to a value. - - Takes a string from something like an environment variable, and tries to - build an internal typed value. Recognizes Null, booleans, and numbers as - special. - Args: - value: The the string value to interpret. - Returns: - the parsed form of the value. - """ - if value in _PARSE_CONSTANTS: - return _PARSE_CONSTANTS[value] - try: - return int(value) - except ValueError: - pass - try: - return float(value) - except ValueError: - pass - return value - - def _Set(self, key, value): - # early out if the value did not change, so we don't call change callbacks - if value == self._values.get(key, None): - return - self._values[key] = value - self.NotifyChanged() - return self - - def ApplyMap(self, arg): - for key, value in arg.items(): - self._Set(key, value) - return self - - def Apply(self, args, kwargs): - """Bulk set variables from arguments. - - Intended for internal use by the Set and From methods. - Args: - args: must be either a dict or something that can build a dict. - kwargs: must be a dict. - Returns: - self for easy chaining. - """ - if len(args) == 1: - arg = args[0] - if isinstance(arg, dict): - self.ApplyMap(arg) - else: - self.ApplyMap(dict(arg)) - elif len(args) > 1: - self.ApplyMap(dict(args)) - self.ApplyMap(kwargs) - return self - - def Set(self, *args, **kwargs): - return self.Apply(args, kwargs) - - def Trace(self): - return _Tracer(self) - - def __getitem__(self, key): - return self.Get(key) - - def __setitem__(self, key, value): - self._Set(key, value) - - def __contains__(self, key): - return self.Find(key) is not None - diff --git a/chromium/tools/cr/cr/context.py b/chromium/tools/cr/cr/context.py deleted file mode 100644 index 3cc32170641..00000000000 --- a/chromium/tools/cr/cr/context.py +++ /dev/null @@ -1,217 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Application context management for the cr tool. - -Contains all the support code to enable the shared context used by the cr tool. -This includes the configuration variables and command line handling. -""" - -import argparse -import os -import cr - - -class _DumpVisitor(cr.visitor.ExportVisitor): - """A visitor that prints all variables in a config hierarchy.""" - - def __init__(self, with_source): - super(_DumpVisitor, self).__init__({}) - self.to_dump = {} - self.with_source = with_source - - def StartNode(self): - if self.with_source: - self._DumpNow() - super(_DumpVisitor, self).StartNode() - - def EndNode(self): - if self.with_source or not self.stack: - self._DumpNow() - super(_DumpVisitor, self).EndNode() - if not self.stack: - self._DumpNow() - - def Visit(self, key, value): - super(_DumpVisitor, self).Visit(key, value) - if key in self.store: - str_value = str(self.store[key]) - if str_value != str(os.environ.get(key, None)): - self.to_dump[key] = str_value - - def _DumpNow(self): - if self.to_dump: - if self.with_source: - print 'From', self.Where() - for key in sorted(self.to_dump.keys()): - print ' ', key, '=', self.to_dump[key] - self.to_dump = {} - - -class _ShowHelp(argparse.Action): - """An argparse action to print the help text. - - This is like the built in help text printing action, except it knows to do - nothing when we are just doing the early speculative parse of the args. - """ - - def __call__(self, parser, namespace, values, option_string=None): - if parser.context.speculative: - return - command = cr.Command.GetActivePlugin(parser.context) - if command: - command.parser.print_help() - else: - parser.print_help() - exit(1) - - -class _ArgumentParser(argparse.ArgumentParser): - """An extension of an ArgumentParser to enable speculative parsing. - - It supports doing an early parse that never produces errors or output, to do - early collection of arguments that may affect what other arguments are - allowed. - """ - - def error(self, message): - if self.context.speculative: - return - super(_ArgumentParser, self).error(message) - - def parse_args(self): - if self.context.speculative: - result = self.parse_known_args() - if result: - return result[0] - return None - return super(_ArgumentParser, self).parse_args() - - def parse_known_args(self, args=None, namespace=None): - result = super(_ArgumentParser, self).parse_known_args(args, namespace) - if result is None: - return namespace, None - return result - - -class Context(cr.config.Config, cr.loader.AutoExport): - """The base context holder for the cr system. - - This is passed to almost all methods in the cr system, and holds the common - context they all shared. Mostly this is stored in the Config structure of - variables. - """ - - def __init__(self, description='', epilog=''): - super(Context, self).__init__('Context') - self._args = None - self._arguments = cr.config.Config('ARGS') - self._derived = cr.config.Config('DERIVED') - self.AddChildren(*cr.config.GLOBALS) - self.AddChildren( - cr.config.Config('ENVIRONMENT', literal=True, export=True).Set( - {k: self.ParseValue(v) for k, v in os.environ.items()}), - self._arguments, - self._derived, - ) - # Build the command line argument parser - self._parser = _ArgumentParser(add_help=False, description=description, - epilog=epilog) - self._parser.context = self - self._subparsers = self.parser.add_subparsers() - # Add the global arguments - self.AddCommonArguments(self._parser) - self._gclient = {} - - def AddSubParser(self, source): - parser = source.AddArguments(self._subparsers) - parser.context = self - - @classmethod - def AddCommonArguments(cls, parser): - """Adds the command line arguments common to all commands in cr.""" - parser.add_argument( - '-h', '--help', - action=_ShowHelp, nargs=0, - help='show the help message and exit.' - ) - parser.add_argument( - '--dry-run', dest='CR_DRY_RUN', - action='store_true', default=None, - help=""" - Don't execute commands, just print them. Implies verbose. - Overrides CR_DRY_RUN - """ - ) - parser.add_argument( - '-v', '--verbose', dest='CR_VERBOSE', - action='count', default=None, - help=""" - Print information about commands being performed. - Repeating multiple times increases the verbosity level. - Overrides CR_VERBOSE - """ - ) - - @property - def args(self): - return self._args - - @property - def arguments(self): - return self._arguments - - @property - def speculative(self): - return self._speculative - - @property - def derived(self): - return self._derived - - @property - def parser(self): - return self._parser - - @property - def remains(self): - remains = getattr(self._args, '_remains', None) - if remains and remains[0] == '--': - remains = remains[1:] - return remains - - @property - def verbose(self): - if self.autocompleting: - return False - return self.Find('CR_VERBOSE') or self.dry_run - - @property - def dry_run(self): - if self.autocompleting: - return True - return self.Find('CR_DRY_RUN') - - @property - def autocompleting(self): - return 'COMP_WORD' in os.environ - - @property - def gclient(self): - if not self._gclient: - self._gclient = cr.base.client.ReadGClient(self) - return self._gclient - - def ParseArgs(self, speculative=False): - cr.plugin.DynamicChoices.only_active = not speculative - self._speculative = speculative - self._args = self._parser.parse_args() - self._arguments.Wipe() - if self._args: - self._arguments.Set( - {k: v for k, v in vars(self._args).items() if v is not None}) - - def DumpValues(self, with_source): - _DumpVisitor(with_source).VisitNode(self) - diff --git a/chromium/tools/cr/cr/fixups/__init__.py b/chromium/tools/cr/cr/fixups/__init__.py deleted file mode 100644 index 86bfa2ad3cc..00000000000 --- a/chromium/tools/cr/cr/fixups/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A package for all the version fixups. - -All the code in this package is there to fix up older output directories and -clients to a form that works with the current version of cr. -""" diff --git a/chromium/tools/cr/cr/fixups/arch.py b/chromium/tools/cr/cr/fixups/arch.py deleted file mode 100644 index e6ac81c5083..00000000000 --- a/chromium/tools/cr/cr/fixups/arch.py +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A module for architecture output directory fixups.""" - -import cr - - -class _ArchInitHookHelper(cr.InitHook): - """Base class helper for CR_ARCH value fixups.""" - - def _VersionTest(self, old_version): - _ = old_version - return True - - def _ArchConvert(self, old_arch): - return old_arch - - def Run(self, context, old_version, config): - if old_version is None or not self._VersionTest(old_version): - return - old_arch = config.OVERRIDES.Find(cr.Arch.SELECTOR) - new_arch = self._ArchConvert(old_arch) - if new_arch != old_arch: - print '** Fixing architecture from {0} to {1}'.format(old_arch, new_arch) - config.OVERRIDES[cr.Arch.SELECTOR] = new_arch - - -class WrongArchDefaultInitHook(_ArchInitHookHelper): - """Fixes bad initial defaults. - - In the initial versions of cr before output directories were versioned - it was writing invalid architecture defaults. This detects that case and sets - the architecture to the current default instead. - """ - - def _VersionTest(self, old_version): - return old_version <= 0.0 - - def _ArchConvert(self, _): - return cr.Arch.default.name - - -class MipsAndArmRenameInitHook(_ArchInitHookHelper): - """Fixes rename of Mips and Arm to Mips32 and Arm32.""" - - def _ArchConvert(self, old_arch): - if old_arch == 'mips': - return cr.Mips32Arch.GetInstance().name - if old_arch == 'arm': - return cr.Arm32Arch.GetInstance().name - return old_arch - diff --git a/chromium/tools/cr/cr/loader.py b/chromium/tools/cr/cr/loader.py deleted file mode 100644 index ecb251b117d..00000000000 --- a/chromium/tools/cr/cr/loader.py +++ /dev/null @@ -1,123 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Module scan and load system. - -The main interface to this module is the Scan function, which triggers a -recursive scan of all packages and modules below cr, with modules being -imported as they are found. -This allows all the plugins in the system to self register. -The aim is to make writing plugins as simple as possible, minimizing the -boilerplate so the actual functionality is clearer. -""" -from importlib import import_module -import os -import sys - -import cr - -# This is the name of the variable inserted into modules to track which -# scanners have been applied. -_MODULE_SCANNED_TAG = '_CR_MODULE_SCANNED' - - -class AutoExport(object): - """A marker for classes that should be promoted up into the cr namespace.""" - - -def _AutoExportScanner(module): - """Scan the modules for things that need wiring up automatically.""" - for name, value in module.__dict__.items(): - if isinstance(value, type) and issubclass(value, AutoExport): - # Add this straight to the cr module. - if not hasattr(cr, name): - setattr(cr, name, value) - - -scan_hooks = [_AutoExportScanner] - - -def _Import(name): - """Import a module or package if it is not already imported.""" - module = sys.modules.get(name, None) - if module is not None: - return module - return import_module(name, None) - - -def _ScanModule(module): - """Runs all the scan_hooks for a module.""" - scanner_tags = getattr(module, _MODULE_SCANNED_TAG, None) - if scanner_tags is None: - # First scan, add the scanned marker set. - scanner_tags = set() - setattr(module, _MODULE_SCANNED_TAG, scanner_tags) - for scan in scan_hooks: - if scan not in scanner_tags: - scanner_tags.add(scan) - scan(module) - - -def _ScanPackage(package): - """Scan a package for child packages and modules.""" - modules = [] - # Recurse sub folders. - for path in package.__path__: - try: - basenames = os.listdir(path) - except OSError: - basenames = [] - for basename in basenames: - fullpath = os.path.join(path, basename) - if os.path.isdir(fullpath): - name = '.'.join([package.__name__, basename]) - child = _Import(name) - modules.extend(_ScanPackage(child)) - elif basename.endswith('.py') and not basename.startswith('_'): - name = '.'.join([package.__name__, basename[:-3]]) - modules.append(name) - return modules - - -def Scan(): - """Scans from the cr package down, loading modules as needed. - - This finds all packages and modules below the cr package, by scanning the - file system. It imports all the packages, and then runs post import hooks on - each module to do any automated work. One example of this is the hook that - finds all classes that extend AutoExport and copies them up into the cr - namespace directly. - - Modules are allowed to refer to each other, their import will be retried - until it succeeds or no progress can be made on any module. - """ - remains = _ScanPackage(cr) - progress = True - modules = [] - while progress and remains: - progress = False - todo = remains - remains = [] - for name in todo: - try: - module = _Import(name) - modules.append(module) - _ScanModule(module) - progress = True - except: # sink all errors here pylint: disable=bare-except - # Try this one again, if progress was made on a possible dependency - remains.append(name) - if remains: - # There are modules that won't import in any order. - # Print all the errors as we can't determine root cause. - for name in remains: - try: - _Import(name) - except ImportError as e: - print 'Failed importing', name, ':', e - exit(1) - # Now scan all the found modules one more time. - # This happens after all imports, in case any imports register scan hooks. - for module in modules: - _ScanModule(module) diff --git a/chromium/tools/cr/cr/plugin.py b/chromium/tools/cr/cr/plugin.py deleted file mode 100644 index 05a02cb1b19..00000000000 --- a/chromium/tools/cr/cr/plugin.py +++ /dev/null @@ -1,320 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""The plugin management system for the cr tool. - -This holds the Plugin class and supporting code, that controls how plugins are -found and used. -The module registers a scan hook with the cr.loader system to enable it to -discover plugins as they are loaded. -""" -from operator import attrgetter - -import cr -import cr.loader - - -def _PluginConfig(name, only_enabled=False, only_active=False): - config = cr.Config(name) - config.only_active = only_active - config.only_enabled = only_enabled or config.only_active - config.property_name = name.lower() + '_config' - return config - -_selectors = cr.Config('PRIORITY') -CONFIG_TYPES = [ - # Lowest priority, always there default values. - _PluginConfig('DEFAULT').AddChild(_selectors), - # Only turned on if the plugin is enabled. - _PluginConfig('ENABLED', only_enabled=True), - # Only turned on while the plugin is the active one. - _PluginConfig('ACTIVE', only_active=True), - # Holds detected values for active plugins. - _PluginConfig('DETECTED', only_active=True), - # Holds overrides, used in custom setup plugins. - _PluginConfig('OVERRIDES'), -] - -cr.config.GLOBALS.extend(CONFIG_TYPES) -_plugins = {} - - -# Actually a decorator, so pylint: disable=invalid-name -class classproperty(object): - """This adds a property to a class. - - This is like a simple form of @property except it is for the class, rather - than instances of the class. Only supports readonly properties. - """ - - def __init__(self, getter): - self.getter = getter - - def __get__(self, instance, owner): - return self.getter(owner) - - -class DynamicChoices(object): - """Manages the list of active plugins for command line options. - - Looks like a simple iterable, but it can change as the underlying plugins - arrive and enable/disable themselves. This allows it to be used as the - set of valid choices for the argparse command line options. - """ - - # If this is True, all DynamicChoices only return active plugins. - # If false, all plugins are included. - only_active = True - - def __init__(self, cls): - self.cls = cls - - def __contains__(self, name): - return self.cls.FindPlugin(name, self.only_active) is not None - - def __iter__(self): - return [p.name for p in self.cls.Plugins()].__iter__() - - -def _FindRoot(cls): - if Plugin.Type in cls.__bases__: - return cls - for base in cls.__bases__: - result = _FindRoot(base) - if result is not None: - return result - return None - - -class Plugin(cr.loader.AutoExport): - """Base class for managing registered plugin types.""" - - class Type(object): - """Base class that tags a class as an abstract plugin type.""" - - class activemethod(object): - """A decorator that delegates a static method to the active plugin. - - Makes a static method that delegates to the equivalent method on the - active instance of the plugin type. - """ - - def __init__(self, method): - self.method = method - - def __get__(self, instance, owner): - def unbound(context, *args, **kwargs): - active = owner.GetActivePlugin(context) - if not active: - print 'No active', owner.__name__ - exit(1) - method = getattr(active, self.method.__name__, None) - if not method: - print owner.__name__, 'does not support', self.method.__name__ - exit(1) - return method(context, *args, **kwargs) - - def bound(context, *args, **kwargs): - return self.method(instance, context, *args, **kwargs) - - if instance is None: - return unbound - return bound - - def __init__(self): - # Default the name to the lowercased class name. - self._name = self.__class__.__name__.lower() - # Strip the common suffix if present. - self._root = _FindRoot(self.__class__) - rootname = self._root.__name__.lower() - if self._name.endswith(rootname) and self.__class__ != self._root: - self._name = self._name[:-len(rootname)] - for config_root in CONFIG_TYPES: - config = cr.Config() - setattr(self, config_root.property_name, config) - self._is_active = False - - def Init(self): - """Post plugin registration initialisation method.""" - for config_root in CONFIG_TYPES: - config = getattr(self, config_root.property_name) - config.name = self.name - if config_root.only_active and not self.is_active: - config.enabled = False - if config_root.only_enabled and not self.enabled: - config.enabled = False - child = getattr(self.__class__, config_root.name, None) - if child is not None: - child.name = self.__class__.__name__ - config.AddChild(child) - config_root.AddChild(config) - - @property - def name(self): - return self._name - - @property - def priority(self): - return 0 - - @property - def enabled(self): - # By default all non type classes are enabled. - return Plugin.Type not in self.__class__.__bases__ - - @property - def is_active(self): - return self._is_active - - def Activate(self, unused_context): - assert not self._is_active - self._is_active = True - for config_root in CONFIG_TYPES: - if config_root.only_active: - getattr(self, config_root.property_name).enabled = True - - def Deactivate(self): - assert self._is_active - self._is_active = False - for config_root in CONFIG_TYPES: - if config_root.only_active: - getattr(self, config_root.property_name).enabled = False - - @classmethod - def GetInstance(cls): - """Gets an instance of this plugin. - - This looks in the plugin registry, and if an instance is not found a new - one is built and registered. - - Returns: - The registered plugin instance. - """ - plugin = _plugins.get(cls, None) - if plugin is None: - # Build a new instance of cls, and register it as the main instance. - plugin = cls() - _plugins[cls] = plugin - # Wire up the hierarchy for Config objects. - for name, value in cls.__dict__.items(): - if isinstance(value, cr.Config): - for base in cls.__bases__: - child = getattr(base, name, None) - if child is not None: - value.AddChild(child) - plugin.Init() - return plugin - - @classmethod - def AllPlugins(cls): - # Don't yield abstract roots, just children. We detect roots as direct - # sub classes of Plugin.Type - if Plugin.Type not in cls.__bases__: - yield cls.GetInstance() - for child in cls.__subclasses__(): - for p in child.AllPlugins(): - yield p - - @classmethod - def UnorderedPlugins(cls): - """Returns all enabled plugins of type cls, in undefined order.""" - plugin = cls.GetInstance() - if plugin.enabled: - yield plugin - for child in cls.__subclasses__(): - for p in child.UnorderedPlugins(): - yield p - - @classmethod - def Plugins(cls): - """Return all enabled plugins of type cls in priority order.""" - return sorted(cls.UnorderedPlugins(), - key=attrgetter('priority'), reverse=True) - - @classmethod - def Choices(cls): - return DynamicChoices(cls) - - @classmethod - def FindPlugin(cls, name, only_active=True): - if only_active: - plugins = cls.UnorderedPlugins() - else: - plugins = cls.AllPlugins() - for plugin in plugins: - if plugin.name == name or plugin.__class__.__name__ == name: - return plugin - return None - - @classmethod - def GetPlugin(cls, name): - result = cls.FindPlugin(name) - if result is None: - raise KeyError(name) - return result - - @classmethod - def GetAllActive(cls): - return [plugin for plugin in cls.UnorderedPlugins() if plugin.is_active] - - @classmethod - def GetActivePlugin(cls, context): - """Gets the active plugin of type cls. - - This method will select a plugin to be the active one, and will activate - the plugin if needed. - Args: - context: The context to select the active plugin for. - Returns: - the plugin that is currently active. - """ - actives = cls.GetAllActive() - plugin = cls.Select(context) - for active in actives: - if active != plugin: - active.Deactivate() - if plugin and not plugin.is_active: - plugin.Activate(context) - return plugin - - @classproperty - def default(cls): - """Returns the plugin that should be used if the user did not choose one.""" - result = None - for plugin in cls.UnorderedPlugins(): - if not result or plugin.priority > result.priority: - result = plugin - return result - - @classmethod - def Select(cls, context): - """Called to determine which plugin should be the active one.""" - plugin = cls.default - selector = getattr(cls, 'SELECTOR', None) - if selector: - if plugin is not None: - _selectors[selector] = plugin.name - name = context.Find(selector) - if name is not None: - plugin = cls.FindPlugin(name) - return plugin - - -def ChainModuleConfigs(module): - """Detects and connects the default Config objects from a module.""" - for config_root in CONFIG_TYPES: - if hasattr(module, config_root.name): - config = getattr(module, config_root.name) - config.name = module.__name__ - config_root.AddChild(config) - - -cr.loader.scan_hooks.append(ChainModuleConfigs) - - -def Activate(context): - """Activates a plugin for all known plugin types.""" - types = Plugin.Type.__subclasses__() - for child in types: - child.GetActivePlugin(context) diff --git a/chromium/tools/cr/cr/targets/__init__.py b/chromium/tools/cr/cr/targets/__init__.py deleted file mode 100644 index 852ecbedbed..00000000000 --- a/chromium/tools/cr/cr/targets/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""A package for all the built in commands. - -This package has all the standard commands built in to the cr tool. -Most commands use actions to perform the real work. -""" diff --git a/chromium/tools/cr/cr/targets/chrome.py b/chromium/tools/cr/cr/targets/chrome.py deleted file mode 100644 index 49d09ee98fa..00000000000 --- a/chromium/tools/cr/cr/targets/chrome.py +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Module for the chrome targets.""" - -import cr - - -class ChromeTarget(cr.NamedTarget): - NAME = 'chrome' - DEFAULT = cr.Config.From( - # CR_URL is the page to open when the target is run. - CR_URL='https://www.google.com/', - ) - CONFIG = cr.Config.From( - CR_RUN_ARGUMENTS=cr.Config.Optional('-d "{CR_URL!e}"'), - CR_TARGET_NAME='Chrome', - ) - - -class ChromeTestTarget(cr.NamedTarget): - NAME = 'chrome_test' - CONFIG = cr.Config.From( - CR_TARGET_NAME='ChromeTest', - ) diff --git a/chromium/tools/cr/cr/targets/chromium_testshell.py b/chromium/tools/cr/cr/targets/chromium_testshell.py deleted file mode 100644 index c8cf65f70c2..00000000000 --- a/chromium/tools/cr/cr/targets/chromium_testshell.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Module for the chromium_testshell targets.""" - -import cr - - -class ChromiumTestShellTarget(cr.NamedTarget): - NAME = 'chromium_testshell' - DEFAULT = cr.Config.From( - # CR_URL is the page to open when the target is run. - CR_URL='https://www.google.com/', - ) - CONFIG = cr.Config.From( - CR_RUN_ARGUMENTS=cr.Config.Optional('-d "{CR_URL!e}"'), - CR_TARGET_NAME='ChromiumTestShell', - CR_PACKAGE='org.chromium.chrome.testshell', - CR_ACTIVITY='.ChromiumTestShellActivity', - ) - - -class ChromiumTestShellTestTarget(cr.NamedTarget): - NAME = 'chromium_testshell_test' - CONFIG = cr.Config.From( - CR_TARGET_NAME='ChromiumTestShellTest', - ) - diff --git a/chromium/tools/cr/cr/targets/content_shell.py b/chromium/tools/cr/cr/targets/content_shell.py deleted file mode 100644 index f4a415dd8ea..00000000000 --- a/chromium/tools/cr/cr/targets/content_shell.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Module for the content_shell targets.""" - -import cr - - -class ContentShellTarget(cr.NamedTarget): - NAME = 'content_shell' - DEFAULT = cr.Config.From( - # CR_URL is the page to open when the target is run. - CR_URL='https://www.google.com/', - ) - CONFIG = cr.Config.From( - CR_RUN_ARGUMENTS=cr.Config.Optional('-d "{CR_URL!e}"'), - CR_TARGET_NAME='ContentShell', - CR_PACKAGE='org.chromium.content_shell_apk', - CR_ACTIVITY='.ContentShellActivity', - ) - - -class ContentShellTestTarget(cr.NamedTarget): - NAME = 'content_shell_test' - CONFIG = cr.Config.From( - CR_TARGET_NAME='ContentShellTest', - ) diff --git a/chromium/tools/cr/cr/targets/target.py b/chromium/tools/cr/cr/targets/target.py deleted file mode 100644 index e02bdb04ec2..00000000000 --- a/chromium/tools/cr/cr/targets/target.py +++ /dev/null @@ -1,157 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -"""Module to hold the Target plugin.""" - -import operator -import re - -import cr - -DEFAULT = cr.Config.From( - CR_DEFAULT_TARGET='chrome', -) - - -class Target(cr.Config, cr.AutoExport): - """Base class for implementing cr targets. - - A target is something that can be built and run. - """ - - # The default base priority - PRIORITY = 0 - # The default pattern used to try to detect whether a target is a test and - # should use the test runner. - TEST_PATTERN = re.compile('tests?$') - # The special "test type" that means it's not a test. - NOT_A_TEST = 'no' - # The default choice for the type of test when it can't be determined. - NORMAL_TEST = 'gtest' - # TODO(iancottrell): support the other test types - TEST_TYPES = [NOT_A_TEST, NORMAL_TEST] - - def __init__(self, context, target_name): - super(Target, self).__init__(target_name) - self.context = context - test_type = None - if self.TEST_PATTERN.search(target_name): - test_type = self.NORMAL_TEST - config = cr.Config('DEFAULTS').From( - CR_TARGET=target_name, - CR_TARGET_NAME='{CR_TARGET}', - CR_BUILD_TARGET=cr.Config.Optional( - '{CR_TARGET}{CR_TARGET_SUFFIX}', '{CR_TARGET}'), - CR_RUN_ARGUMENTS='', - CR_TEST_TYPE=test_type, - ) - self.AddChildren(config, context) - if hasattr(self, 'CONFIG'): - self.AddChild(self.CONFIG) - if not self.valid: - self.Set(CR_TARGET_SUFFIX='') - self.test_type = self.Find('CR_TEST_TYPE') - self.target_name = self.Find('CR_TARGET_NAME') - - @property - def build_target(self): - return self.Get('CR_BUILD_TARGET') - - @property - def verbose(self): - return self.context.verbose - - @property - def dry_run(self): - return self.context.dry_run - - @property - def valid(self): - return cr.Builder.IsTarget(self.context, self.build_target) - - @property - def is_test(self): - return self.test_type and self.test_type != self.NOT_A_TEST - - @classmethod - def AddArguments(cls, command, parser, allow_multiple=False): - nargs = '?' - help_string = 'The target to {0}' - if allow_multiple: - nargs = '*' - help_string = 'The target(s) to {0}' - parser.add_argument( - '_targets', metavar='target', - help=help_string.format(command.name), - nargs=nargs - ) - - @classmethod - def AllTargets(cls): - yield cls - for child in cls.__subclasses__(): - for t in child.AllTargets(): - yield t - - @classmethod - def CreateTarget(cls, context, target_name): - """Attempts to build a target by name. - - This searches the set of installed targets in priority order to see if any - of them are willing to handle the supplied name. - If a target cannot be found, the program will be aborted. - Args: - context: The context to run in. - target_name: The name of the target we are searching for. - Returns: - The target that matched. - """ - target_clses = sorted( - cls.AllTargets(), - key=operator.attrgetter('PRIORITY'), - reverse=True - ) - for handler in target_clses: - target = handler.Build(context, target_name) - if target: - if not target.valid: - print 'Invalid target {0} as {1}'.format( - target_name, target.build_target) - exit(1) - return target - print 'Unknown target {0}'.format(target_name) - exit(1) - - @classmethod - def GetTargets(cls, context): - target_names = getattr(context.args, '_targets', None) - if not target_names: - target_names = [context.Get('CR_DEFAULT_TARGET')] - elif hasattr(target_names, 'swapcase'): - # deal with the single target case - target_names = [target_names] - return [cls.CreateTarget(context, target_name) - for target_name in target_names] - - @classmethod - def Build(cls, context, target_name): - return cls(context, target_name) - - -class NamedTarget(Target): - """A base class for explicit named targets. - - Only matches a target if the name is an exact match. - Up it's priority to come ahead of general purpose rule matches. - """ - NAME = None - PRIORITY = Target.PRIORITY + 1 - - @classmethod - def Build(cls, context, target_name): - try: - if target_name == cls.NAME: - return cls(context, target_name) - except AttributeError: - pass - return None diff --git a/chromium/tools/cr/cr/visitor.py b/chromium/tools/cr/cr/visitor.py deleted file mode 100644 index 339040ca3c4..00000000000 --- a/chromium/tools/cr/cr/visitor.py +++ /dev/null @@ -1,257 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -""". - -""" -import collections - -# HIDDEN is a marker used to suppress a value, making it as if it were not set -# in that object. This causes the search to continue through the tree. -# This is most useful as a return value of dynamic values that want to find -# the value they are shadowing. -HIDDEN = object() - - -class VisitComplete(Exception): - """Indicates a vist traversal has finished early.""" - - -class Visitor(object): - """The base class for anything that wants to "visit" all variables. - - The two main uses of visitor are search and export. They differ in that export - is trying to find all variables, whereas search is just looking for one. - """ - - def __init__(self): - self.stack = [] - - def VisitNode(self, node): - """Called for every node in the tree.""" - if not node.enabled: - return self - try: - try: - self.stack.append(node) - self.StartNode() - # Visit all the values first - for key in self.KeysOf(node.values): - self.Visit(key, node.values[key]) - # And now recurse into all the children - for child in node.children: - self.VisitNode(child) - finally: - self.EndNode() - self.stack.pop() - except VisitComplete: - if self.stack: - # propagate back up the stack - raise - return self - - def Visit(self, key, value): - """Visit is called for every variable in each node.""" - - def StartNode(self): - """StartNode is called once for each node before traversal.""" - - def EndNode(self): - """Visit is called for every node after traversal.""" - - @property - def root_node(self): - """Returns the variable at the root of the current traversal.""" - return self.stack[0] - - @property - def current_node(self): - """Returns the node currently being scanned.""" - return self.stack[-1] - - def Resolve(self, key, value): - """Returns a fully substituted value. - - This asks the root node to do the actual work. - Args: - key: The key being visited. - value: The unresolved value associated with the key. - Returns: - the fully resolved value. - """ - return self.root_node.Resolve(self, key, value) - - def Where(self): - """Returns the current traversal stack as a string.""" - return '/'.join([entry.name for entry in self.stack]) - - -class SearchVisitor(Visitor): - """A Visitor that finds a single matching key.""" - - def __init__(self, key): - super(SearchVisitor, self).__init__() - self.key = key - self.found = False - self.error = None - - def KeysOf(self, store): - if self.key in store: - yield self.key - - def Visit(self, key, value): - value, error = self.Resolve(key, value) - if value is not HIDDEN: - self.found = True - self.value = value - self.error = error - raise VisitComplete() - - -class WhereVisitor(SearchVisitor): - """A SearchVisitor that returns the path to the matching key.""" - - def Visit(self, key, value): - self.where = self.Where() - super(WhereVisitor, self).Visit(key, value) - - -class ExportVisitor(Visitor): - """A visitor that builds a fully resolved map of all variables.""" - - def __init__(self, store): - super(ExportVisitor, self).__init__() - self.store = store - - def KeysOf(self, store): - if self.current_node.export is False: - # not exporting from this config - return - for key in store.keys(): - if key in self.store: - # duplicate - continue - if (self.current_node.export is None) and key.startswith('_'): - # non exported name - continue - yield key - - def Visit(self, key, value): - value, _ = self.Resolve(key, value) - if value is not HIDDEN: - self.store[key] = value - - -class Node(object): - """The base class for objects in a visitable node tree.""" - - def __init__(self, name='--', enabled=True, export=True): - self._name = name - self._children = collections.deque() - self._values = {} - self._viewers = [] - self.trail = [] - self._enabled = enabled - self._export = export - self._export_cache = None - - @property - def name(self): - return self._name - - @name.setter - def name(self, value): - self._name = value - - @property - def enabled(self): - return self._enabled - - @enabled.setter - def enabled(self, value): - if self._enabled == value: - return - self._enabled = value - self.NotifyChanged() - - @property - def export(self): - return self._export - - @property - def exported(self): - if self._export_cache is None: - self._export_cache = ExportVisitor({}).VisitNode(self).store - return self._export_cache - - @property - def values(self): - return self._values - - @property - def children(self): - return self._children - - def RegisterViewer(self, viewer): - self._viewers.append(viewer) - - def UnregisterViewer(self, viewer): - self._viewers.remove(viewer) - - def OnChanged(self, child): - _ = child - self.NotifyChanged() - - def NotifyChanged(self): - self._export_cache = None - for viewers in self._viewers: - viewers.OnChanged(self) - - def _AddChild(self, child): - if child and child != self and child not in self._children: - self._children.appendleft(child) - child.RegisterViewer(self) - - def AddChild(self, child): - self._AddChild(child) - self.NotifyChanged() - return self - - def AddChildren(self, *children): - for child in children: - self._AddChild(child) - self.NotifyChanged() - return self - - def Find(self, key): - search = SearchVisitor(key).VisitNode(self) - if not search.found: - return None - return search.value - - def WhereIs(self, key): - search = WhereVisitor(key).VisitNode(self) - if not search.found: - return None - return search.where - - def Get(self, key, raise_errors=False): - search = SearchVisitor(key).VisitNode(self) - if not search.found: - raise KeyError(key) - if search.error and raise_errors: - raise search.error # bad type inference pylint: disable=raising-bad-type - return search.value - - def Resolve(self, visitor, key, value): - _ = visitor, key - return value - - def Wipe(self): - for child in self._children: - child.UnregisterViewer(self) - self._children = collections.deque() - self._values = {} - self.NotifyChanged() - |