# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/.
import argparse import ast import difflib import errno import shlex import sys import types import uuid from collections.abc import Iterable from pathlib import Path from typing import Dict, Optional, Union
from mozfile import load_source
from .base import MissingFileError, UnknownCommandError
INVALID_ENTRY_POINT = r"""
Entry points should return a list of command providers or directories
containing command providers. The following entry point is invalid:
%s
You are seeing this because there is an error in an external module attempting
to implement a mach command. Please fix the error, or uninstall the module from
your system. """.lstrip()
class MachCommandReference: """A reference to a mach command.
class DecoratorVisitor(ast.NodeVisitor): def __init__(self):
self.results = {}
def visit_FunctionDef(self, node): # We only care about `Command` and `SubCommand` decorators, since # they are the only ones that can specify virtualenv_name
decorators = [
decorator for decorator in node.decorator_list if isinstance(decorator, ast.Call) and isinstance(decorator.func, ast.Name) and decorator.func.id in ["SubCommand", "Command"]
]
if sub_command:
self.results[command].setdefault("subcommands", {})
sub_command_dict = self.results[command]["subcommands"].setdefault(
sub_command, {}
)
if virtualenv_name:
sub_command_dict["virtualenv_name"] = virtualenv_name elif virtualenv_name: # If there is no `subcommand` we are in the `@Command` # decorator, and need to store the virtualenv_name for # the 'command'.
self.results[command]["virtualenv_name"] = virtualenv_name
self.generic_visit(node)
def command_virtualenv_info_for_module(module_path): with module_path.open("r") as file:
content = file.read()
tree = ast.parse(content)
visitor = DecoratorVisitor()
visitor.visit(tree)
site = command_dict.get("virtualenv_name", "common")
if potential_sub_command_name andnot potential_sub_command_name.startswith( "-"
):
all_sub_commands_dict = command_dict.get("subcommands", {})
if all_sub_commands_dict:
sub_command_dict = all_sub_commands_dict.get(
potential_sub_command_name, {}
)
if sub_command_dict:
site = sub_command_dict.get("virtualenv_name", "common")
setattr(namespace, "site_name", site)
def suggest_command(command):
names = MACH_COMMANDS.keys() # We first try to look for a valid command that is very similar to the given command.
suggested_commands = difflib.get_close_matches(command, names, cutoff=0.8) # If we find more than one matching command, or no command at all, # we give command suggestions instead (with a lower matching threshold). # All commands that start with the given command (for instance: # 'mochitest-plain', 'mochitest-chrome', etc. for 'mochitest-') # are also included. if len(suggested_commands) != 1:
suggested_commands = set(difflib.get_close_matches(command, names, cutoff=0.5))
suggested_commands |= {cmd for cmd in names if cmd.startswith(command)} raise UnknownCommandError(command, "run", suggested_commands)
return suggested_commands[0]
def load_commands_from_directory(path: Path): """Scan for mach commands from modules in a directory.
This takes a path to a directory, loads the .py files in it, and
registers and found mach command providers with this mach instance. """ for f in sorted(path.iterdir()): ifnot f.suffix == ".py"or f.name == "__init__.py": continue
full_path = path / f
module_name = f"mach.commands.{str(f)[0:-3]}"
def load_commands_from_file(path: Union[str, Path], module_name=None): """Scan for mach commands from a file.
This takes a path to a file and loads it as a Python module under the
module name specified. If no name is specified, a random one will be
chosen. """ if module_name isNone: # Ensure parent module is present otherwise we'll (likely) get # an error due to unknown parent. if"mach.commands"notin sys.modules:
mod = types.ModuleType("mach.commands")
sys.modules["mach.commands"] = mod
module_name = f"mach.commands.{uuid.uuid4().hex}"
try:
load_source(module_name, str(path)) except OSError as e: if e.errno != errno.ENOENT: raise
raise MissingFileError(f"{path} does not exist")
def load_commands_from_spec(
spec: Dict[str, MachCommandReference], topsrcdir: str, missing_ok=False
): """Load mach commands based on the given spec.
Takes a dictionary mapping command names to their metadata. """
modules = {spec[command].module for command in spec}
for path in modules: try:
load_commands_from_file(Path(topsrcdir) / path) except MissingFileError: ifnot missing_ok: raise
def load_commands_from_entry_point(group="mach.providers"): """Scan installed packages for mach command provider entry points. An
entry point is a function that returns a list of paths to files or
directories containing command providers.
This takes an optional group argument which specifies the entry point
group to use. Ifnot specified, it defaults to 'mach.providers'. """ try: import pkg_resources except ImportError:
print( "Could not find setuptools, ignoring command entry points",
file=sys.stderr,
) return
for entry in pkg_resources.iter_entry_points(group=group, name=None):
paths = [Path(path) for path in entry.load()()] ifnot isinstance(paths, Iterable):
print(INVALID_ENTRY_POINT % entry)
sys.exit(1)
for path in paths: if path.is_file():
load_commands_from_file(path) elif path.is_dir():
load_commands_from_directory(path) else:
print(f"command provider '{path}' does not exist")
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.30Bemerkung:
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.