Bug 1696251 - Refactor constructors in MachCommandBase subclasses to remove them. r=mhentges,remote-protocol-reviewers

Another step towards avoiding the need for classes in mach commands;
here we are removing constructors either by changing them into helpers
or by simple refactorings.

Differential Revision: https://phabricator.services.mozilla.com/D112434
This commit is contained in:
Alex Lopez 2021-05-28 18:30:03 +00:00
parent 8fbcd44dc4
commit 1ee8086c02
5 changed files with 51 additions and 60 deletions

View File

@ -24,10 +24,6 @@ class Settings(MachCommandBase):
people create configs via a wizard, etc.
"""
def __init__(self, *args, **kwargs):
super(Settings, self).__init__(*args, **kwargs)
self._settings = self._mach_context.settings
@Command(
"settings", category="devenv", description="Show available config settings."
)
@ -42,12 +38,12 @@ class Settings(MachCommandBase):
"""List available settings."""
types = {v: k for k, v in TYPE_CLASSES.items()}
wrapper = TextWrapper(initial_indent="# ", subsequent_indent="# ")
for i, section in enumerate(sorted(self._settings)):
for i, section in enumerate(sorted(self._mach_context.settings)):
if not short:
print("%s[%s]" % ("" if i == 0 else "\n", section))
for option in sorted(self._settings[section]._settings):
meta = self._settings[section].get_meta(option)
for option in sorted(self._mach_context.settings[section]._settings):
meta = self._mach_context.settings[section].get_meta(option)
desc = meta["description"]
if short:

View File

@ -42,11 +42,6 @@ class ConditionsProvider(MachCommandBase):
@CommandProvider
class ConditionsContextProvider(MachCommandBase):
def __init__(self, *args, **kwargs):
super(ConditionsContextProvider, self).__init__(*args, **kwargs)
self.foo = self._mach_context.foo
self.bar = self._mach_context.bar
@Command("cmd_foo_ctx", category="testing", conditions=[is_foo])
def run_foo(self, command_context):
pass

View File

@ -54,9 +54,8 @@ def setup():
@CommandProvider
class RemoteCommands(MachCommandBase):
def __init__(self, *args, **kwargs):
super(RemoteCommands, self).__init__(*args, **kwargs)
self.remotedir = os.path.join(self.topsrcdir, "remote")
def remotedir(self):
return os.path.join(self.topsrcdir, "remote")
@Command(
"remote", category="misc", description="Remote protocol related operations."
@ -89,11 +88,11 @@ class RemoteCommands(MachCommandBase):
help="Do not install the just-pulled Puppeteer package,",
)
def vendor_puppeteer(self, command_context, repository, commitish, install):
puppeteer_dir = os.path.join(self.remotedir, "test", "puppeteer")
puppeteer_dir = os.path.join(self.remotedir(), "test", "puppeteer")
# Preserve our custom mocha reporter
shutil.move(
os.path.join(puppeteer_dir, "json-mocha-reporter.js"), self.remotedir
os.path.join(puppeteer_dir, "json-mocha-reporter.js"), self.remotedir()
)
shutil.rmtree(puppeteer_dir, ignore_errors=True)
os.makedirs(puppeteer_dir)
@ -124,7 +123,7 @@ class RemoteCommands(MachCommandBase):
shutil.rmtree(dir_path)
shutil.move(
os.path.join(self.remotedir, "json-mocha-reporter.js"), puppeteer_dir
os.path.join(self.remotedir(), "json-mocha-reporter.js"), puppeteer_dir
)
import yaml

View File

@ -20,6 +20,7 @@ from pprint import pprint
from mach.registrar import Registrar
from mozbuild.base import MachCommandBase
from mozbuild.util import memoize
from mach.decorators import (
Command,
CommandArgument,
@ -37,13 +38,6 @@ BASE_LINK = "http://gecko-docs.mozilla.org-l1.s3-website.us-west-2.amazonaws.com
class Documentation(MachCommandBase):
"""Helps manage in-tree documentation."""
def __init__(self, *args, **kwargs):
super(Documentation, self).__init__(*args, **kwargs)
self._manager = None
self._project = None
self._version = None
@Command(
"doc",
category="devenv",
@ -272,12 +266,11 @@ class Documentation(MachCommandBase):
return sphinx.cmd.build.build_main(args)
def manager(self):
if not self._manager:
from moztreedocs import manager
self._manager = manager
return self._manager
return manager
@memoize
def _read_project_properties(self):
import imp
@ -291,18 +284,13 @@ class Documentation(MachCommandBase):
if not project:
project = conf.project.replace(" ", "_")
self._project = project
self._version = getattr(conf, "version", None)
return {"project": project, "version": getattr(conf, "version", None)}
def project(self):
if not self._project:
self._read_project_properties()
return self._project
return self._read_project_properties()["project"]
def version(self):
if not self._version:
self._read_project_properties()
return self._version
return self._read_project_properties()["version"]
def _node_path(self):
from mozbuild.nodeutil import find_node_executable

View File

@ -18,6 +18,7 @@ from mach.decorators import (
)
from mozboot.util import get_state_dir
from mozbuild.base import BuildEnvironmentNotFoundException, MachCommandBase
from mozbuild.util import memoize
CONFIG_ENVIRONMENT_NOT_FOUND = """
@ -71,19 +72,13 @@ class TryConfig(object):
@CommandProvider
class TrySelect(MachCommandBase):
def __init__(self, *args, **kwargs):
super(TrySelect, self).__init__(*args, **kwargs)
def init(self):
from tryselect import push
push.MAX_HISTORY = self._mach_context.settings["try"]["maxhistory"]
self.subcommand = self._mach_context.handler.subcommand
self.parser = self._mach_context.handler.parser
self._presets = None
@memoize
def presets(self):
if self._presets:
return self._presets
from tryselect.preset import MergedHandler
# Create our handler using both local and in-tree presets. The first
@ -98,8 +93,7 @@ class TrySelect(MachCommandBase):
os.path.join(self.topsrcdir, "tools", "tryselect", "try_presets.yml"),
]
self._presets = MergedHandler(*preset_paths)
return self._presets
return MergedHandler(*preset_paths)
def handle_presets(self, preset_action=None, save=None, preset=None, **kwargs):
"""Handle preset related arguments.
@ -119,12 +113,14 @@ class TrySelect(MachCommandBase):
user_presets.edit()
sys.exit()
if "preset" not in self.parser.common_groups:
parser = self._mach_context.handler.parser
subcommand = self._mach_context.handler.subcommand
if "preset" not in parser.common_groups:
return kwargs
default = self.parser.get_default
default = parser.get_default
if save:
selector = self.subcommand or self._mach_context.settings["try"]["default"]
selector = subcommand or self._mach_context.settings["try"]["default"]
# Only save non-default values for simplicity.
kwargs = {k: v for k, v in kwargs.items() if v != default(k)}
@ -134,16 +130,18 @@ class TrySelect(MachCommandBase):
if preset:
if preset not in self.presets():
self.parser.error("preset '{}' does not exist".format(preset))
self._mach_context.parser.error(
"preset '{}' does not exist".format(preset)
)
name = preset
preset = self.presets()[name]
selector = preset.pop("selector")
preset.pop("description", None) # description isn't used by any selectors
if not self.subcommand:
self.subcommand = selector
elif self.subcommand != selector:
if not subcommand:
subcommand = selector
elif subcommand != selector:
print(
"error: preset '{}' exists for a different selector "
"(did you mean to run 'mach try {}' instead?)".format(
@ -171,7 +169,7 @@ class TrySelect(MachCommandBase):
to_validate = []
kwargs.setdefault("try_config", {})
for cls in six.itervalues(self.parser.task_configs):
for cls in six.itervalues(self._mach_context.handler.parser.task_configs):
try_config = cls.try_config(**kwargs)
if try_config is not None:
to_validate.append(cls)
@ -189,10 +187,12 @@ class TrySelect(MachCommandBase):
def run(self, **kwargs):
kwargs = self.handle_presets(**kwargs)
if self.parser.task_configs:
if self._mach_context.handler.parser.task_configs:
kwargs = self.handle_try_config(**kwargs)
mod = importlib.import_module("tryselect.selectors.{}".format(self.subcommand))
mod = importlib.import_module(
"tryselect.selectors.{}".format(self._mach_context.handler.subcommand)
)
return mod.run(**kwargs)
@Command(
@ -213,16 +213,20 @@ class TrySelect(MachCommandBase):
default. Run |mach try auto --help| for more information on
scheduling with the `auto` selector.
"""
self.init()
subcommand = self._mach_context.handler.subcommand
# We do special handling of presets here so that `./mach try --preset foo`
# works no matter what subcommand 'foo' was saved with.
preset = kwargs["preset"]
if preset:
if preset not in self.presets():
self.parser.error("preset '{}' does not exist".format(preset))
self._mach_context.handler.parser.error(
"preset '{}' does not exist".format(preset)
)
self.subcommand = self.presets()[preset]["selector"]
subcommand = self.presets()[preset]["selector"]
sub = self.subcommand or self._mach_context.settings["try"]["default"]
sub = subcommand or self._mach_context.settings["try"]["default"]
return self._mach_context.commands.dispatch(
"try", self._mach_context, subcommand=sub, argv=argv, **kwargs
)
@ -308,6 +312,7 @@ class TrySelect(MachCommandBase):
For more detailed documentation, please see:
https://firefox-source-docs.mozilla.org/tools/try/selectors/fuzzy.html
"""
self.init()
if kwargs.pop("interactive"):
kwargs["query"].append("INTERACTIVE")
@ -344,6 +349,7 @@ class TrySelect(MachCommandBase):
has been made, pressing the 'Push' button will automatically push the
selection to try.
"""
self.init()
self.activate_virtualenv()
path = os.path.join(
"tools", "tryselect", "selectors", "chooser", "requirements.txt"
@ -361,6 +367,7 @@ class TrySelect(MachCommandBase):
parser=get_parser("auto"),
)
def try_auto(self, command_context, **kwargs):
self.init()
return self.run(**kwargs)
@SubCommand(
@ -370,6 +377,7 @@ class TrySelect(MachCommandBase):
parser=get_parser("again"),
)
def try_again(self, command_context, **kwargs):
self.init()
return self.run(**kwargs)
@SubCommand(
@ -387,6 +395,7 @@ class TrySelect(MachCommandBase):
via Treeherder's Add New Jobs feature, located in the per-push
menu.
"""
self.init()
return self.run(**kwargs)
@SubCommand(
@ -433,6 +442,7 @@ class TrySelect(MachCommandBase):
(installable from mach vcs-setup).
"""
self.init()
try:
if self.substs.get("MOZ_ARTIFACT_BUILDS"):
kwargs["local_artifact_build"] = True
@ -457,6 +467,7 @@ class TrySelect(MachCommandBase):
)
def try_coverage(self, command_context, **kwargs):
"""Select which tasks to use using coverage data."""
self.init()
return self.run(**kwargs)
@SubCommand(
@ -467,6 +478,7 @@ class TrySelect(MachCommandBase):
)
def try_release(self, command_context, **kwargs):
"""Push the current tree to try, configured for a staging release."""
self.init()
return self.run(**kwargs)
@SubCommand(
@ -480,4 +492,5 @@ class TrySelect(MachCommandBase):
Requires VPN and shipit access.
"""
self.init()
return self.run(**kwargs)