mach package¶
Subpackages¶
- mach.commands package
- mach.mixin package
- mach.test package
- Subpackages
- Submodules
- mach.test.conftest module
- mach.test.invoke_mach_command module
- mach.test.test_commands module
- mach.test.test_conditions module
- mach.test.test_config module
- mach.test.test_decorators module
- mach.test.test_dispatcher module
- mach.test.test_entry_point module
- mach.test.test_error_output module
- mach.test.test_logger module
- mach.test.test_mach module
- mach.test.test_site_activation module
- mach.test.test_site_compatibility module
- mach.test.zero_microseconds module
- Module contents
Submodules¶
mach.base module¶
- class mach.base.CommandContext(cwd: str, settings=None, log_manager=None, commands=None, **kwargs)¶
Bases:
object
Holds run-time state so it can easily be passed to command providers.
- exception mach.base.FailedCommandError(message, exit_code=1, reason='')¶
Bases:
Exception
Raised by commands to signal a handled failure to be printed by mach
When caught by mach a FailedCommandError will print message and exit with ‘’exit_code’’. The optional ‘’reason’’ is a string in cases where other scripts may wish to handle the exception, though this is generally intended to communicate failure to mach.
- exception mach.base.MachError¶
Bases:
Exception
Base class for all errors raised by mach itself.
- exception mach.base.MissingFileError¶
Bases:
mach.base.MachError
Attempted to load a mach commands file that doesn’t exist.
- exception mach.base.NoCommandError(namespace)¶
Bases:
mach.base.MachError
No command was passed into mach.
- exception mach.base.UnknownCommandError(command, verb, suggested_commands=None)¶
Bases:
mach.base.MachError
Raised when we attempted to execute an unknown command.
- exception mach.base.UnrecognizedArgumentError(command, arguments)¶
Bases:
mach.base.MachError
Raised when an unknown argument is passed to mach.
mach.config module¶
This file defines classes for representing config data/settings.
Config data is modeled as key-value pairs. Keys are grouped together into named sections. Individual config settings (options) have metadata associated with them. This metadata includes type, default value, valid values, etc.
The main interface to config data is the ConfigSettings class. 1 or more ConfigProvider classes are associated with ConfigSettings and define what settings are available.
- class mach.config.BooleanType¶
Bases:
mach.config.ConfigType
- static from_config(config, section, option)¶
Obtain the value of this type from a RawConfigParser.
Receives a RawConfigParser instance, a str section name, and the str option in that section to retrieve.
The implementation may assume the option exists in the RawConfigParser instance.
Implementations are not expected to validate the value. But, they should return the appropriate Python type.
- static to_config(value)¶
- static validate(value)¶
Validates a Python value conforms to this type.
Raises a TypeError or ValueError if it doesn’t conform. Does not do anything if the value is valid.
- exception mach.config.ConfigException¶
Bases:
Exception
- class mach.config.ConfigSettings¶
Bases:
collections.abc.Mapping
Interface for configuration settings.
This is the main interface to the configuration.
A configuration is a collection of sections. Each section contains key-value pairs.
When an instance is created, the caller first registers ConfigProvider instances with it. This tells the ConfigSettings what individual settings are available and defines extra metadata associated with those settings. This is used for validation, etc.
Once ConfigProvider instances are registered, a config is populated. It can be loaded from files or populated by hand.
ConfigSettings instances are accessed like dictionaries or by using attributes. e.g. the section “foo” is accessed through either settings.foo or settings[‘foo’].
Sections are modeled by the ConfigSection class which is defined inside this one. They look just like dicts or classes with attributes. To access the “bar” option in the “foo” section:
value = settings.foo.bar value = settings[‘foo’][‘bar’] value = settings.foo[‘bar’]
Assignment is similar:
settings.foo.bar = value settings[‘foo’][‘bar’] = value settings[‘foo’].bar = value
You can even delete user-assigned values:
del settings.foo.bar del settings[‘foo’][‘bar’]
If there is a default, it will be returned.
When settings are mutated, they are validated against the registered providers. Setting unknown settings or setting values to illegal values will result in exceptions being raised.
- class ConfigSection(config, name, settings)¶
Bases:
collections.abc.MutableMapping
,object
Represents an individual config section.
- get_meta(option)¶
- property options¶
- load_file(filename: Union[str, pathlib.Path])¶
- load_files(filenames: List[pathlib.Path])¶
Load a config from files specified by their paths.
Files are loaded in the order given. Subsequent files will overwrite values from previous files. If a file does not exist, it will be ignored.
- load_fps(fps)¶
Load config data by reading file objects.
- register_provider(provider)¶
Register a SettingsProvider with this settings interface.
- write(fh)¶
Write the config to a file object.
- class mach.config.ConfigType¶
Bases:
object
Abstract base class for config values.
- static from_config(config, section, option)¶
Obtain the value of this type from a RawConfigParser.
Receives a RawConfigParser instance, a str section name, and the str option in that section to retrieve.
The implementation may assume the option exists in the RawConfigParser instance.
Implementations are not expected to validate the value. But, they should return the appropriate Python type.
- static to_config(value)¶
- static validate(value)¶
Validates a Python value conforms to this type.
Raises a TypeError or ValueError if it doesn’t conform. Does not do anything if the value is valid.
- class mach.config.DefaultValue¶
Bases:
object
- class mach.config.IntegerType¶
Bases:
mach.config.ConfigType
- static from_config(config, section, option)¶
Obtain the value of this type from a RawConfigParser.
Receives a RawConfigParser instance, a str section name, and the str option in that section to retrieve.
The implementation may assume the option exists in the RawConfigParser instance.
Implementations are not expected to validate the value. But, they should return the appropriate Python type.
- static validate(value)¶
Validates a Python value conforms to this type.
Raises a TypeError or ValueError if it doesn’t conform. Does not do anything if the value is valid.
- class mach.config.PathType¶
Bases:
mach.config.StringType
- static from_config(config, section, option)¶
Obtain the value of this type from a RawConfigParser.
Receives a RawConfigParser instance, a str section name, and the str option in that section to retrieve.
The implementation may assume the option exists in the RawConfigParser instance.
Implementations are not expected to validate the value. But, they should return the appropriate Python type.
- static validate(value)¶
Validates a Python value conforms to this type.
Raises a TypeError or ValueError if it doesn’t conform. Does not do anything if the value is valid.
- class mach.config.PositiveIntegerType¶
Bases:
mach.config.IntegerType
- static validate(value)¶
Validates a Python value conforms to this type.
Raises a TypeError or ValueError if it doesn’t conform. Does not do anything if the value is valid.
- class mach.config.StringType¶
Bases:
mach.config.ConfigType
- static from_config(config, section, option)¶
Obtain the value of this type from a RawConfigParser.
Receives a RawConfigParser instance, a str section name, and the str option in that section to retrieve.
The implementation may assume the option exists in the RawConfigParser instance.
Implementations are not expected to validate the value. But, they should return the appropriate Python type.
- static validate(value)¶
Validates a Python value conforms to this type.
Raises a TypeError or ValueError if it doesn’t conform. Does not do anything if the value is valid.
- mach.config.reraise_attribute_error(func)¶
Used to make sure __getattr__ wrappers around __getitem__ raise AttributeError instead of KeyError.
mach.decorators module¶
- class mach.decorators.Command(name, metrics_path: Optional[str] = None, **kwargs)¶
Bases:
object
Decorator for functions or methods that provide a mach command.
The decorator accepts arguments that define basic attributes of the command. The following arguments are recognized:
- category – The string category to which this command belongs. Mach’s
help will group commands by category.
description – A brief description of what the command does.
- parser – an optional argparse.ArgumentParser instance or callable
that returns an argparse.ArgumentParser instance to use as the basis for the command arguments.
For example:
@Command(‘foo’, category=’misc’, description=’Run the foo action’) def foo(self, command_context):
pass
- class mach.decorators.CommandArgument(*args, **kwargs)¶
Bases:
object
Decorator for additional arguments to mach subcommands.
This decorator should be used to add arguments to mach commands. Arguments to the decorator are proxied to ArgumentParser.add_argument().
For example:
@Command(‘foo’, help=’Run the foo action’) @CommandArgument(‘-b’, ‘–bar’, action=’store_true’, default=False,
help=’Enable bar mode.’)
- def foo(self, command_context):
pass
- class mach.decorators.CommandArgumentGroup(group_name)¶
Bases:
object
Decorator for additional argument groups to mach commands.
This decorator should be used to add arguments groups to mach commands. Arguments to the decorator are proxied to ArgumentParser.add_argument_group().
For example:
@Command(‘foo’, helps=’Run the foo action’) @CommandArgumentGroup(‘group1’) @CommandArgument(‘-b’, ‘–bar’, group=’group1’, action=’store_true’,
default=False, help=’Enable bar mode.’)
- def foo(self, command_context):
pass
The name should be chosen so that it makes sense as part of the phrase ‘Command Arguments for <name>’ because that’s how it will be shown in the help message.
- mach.decorators.SettingsProvider(cls)¶
Class decorator to denote that this class provides Mach settings.
When this decorator is encountered, the underlying class will automatically be registered with the Mach registrar and will (likely) be hooked up to the mach driver.
- class mach.decorators.SubCommand(command, subcommand, description=None, parser=None, metrics_path: Optional[str] = None)¶
Bases:
object
Decorator for functions or methods that provide a sub-command.
Mach commands can have sub-commands. e.g.
mach command foo
ormach command bar
. Each sub-command has its own parser and is effectively its own mach command.The decorator accepts arguments that define basic attributes of the sub command:
command – The string of the command this sub command should be attached to.
subcommand – The string name of the sub command to register.
description – A textual description for this sub command.
- global_order = 95¶
mach.dispatcher module¶
- class mach.dispatcher.CommandAction(option_strings, dest, required=True, default=None, registrar=None, context=None)¶
Bases:
argparse.Action
An argparse action that handles mach commands.
This class is essentially a reimplementation of argparse’s sub-parsers feature. We first tried to use sub-parsers. However, they were missing features like grouping of commands (http://bugs.python.org/issue14037).
The way this works involves light magic and a partial understanding of how argparse works.
Arguments registered with an argparse.ArgumentParser have an action associated with them. An action is essentially a class that when called does something with the encountered argument(s). This class is one of those action classes.
An instance of this class is created doing something like:
parser.add_argument(‘command’, action=CommandAction, registrar=r)
Note that a mach.registrar.Registrar instance is passed in. The Registrar holds information on all the mach commands that have been registered.
When this argument is registered with the ArgumentParser, an instance of this class is instantiated. One of the subtle but important things it does is tell the argument parser that it’s interested in all of the remaining program arguments. So, when the ArgumentParser calls this action, we will receive the command name plus all of its arguments.
For more, read the docs in __call__.
- class mach.dispatcher.CommandFormatter(prog, indent_increment=2, max_help_position=24, width=None)¶
Bases:
argparse.HelpFormatter
Custom formatter to format just a subcommand.
- add_usage(*args)¶
- class mach.dispatcher.DispatchSettings¶
Bases:
object
- config_settings = [('alias.*', 'string', 'Create a command alias of the form `<alias>=<command> <args>`.\nAliases can also be used to set default arguments:\n<command>=<command> <args>')]¶
- class mach.dispatcher.NoUsageFormatter(prog, indent_increment=2, max_help_position=24, width=None)¶
Bases:
argparse.HelpFormatter
- mach.dispatcher.format_docstring(docstring)¶
Format a raw docstring into something suitable for presentation.
This function is based on the example function in PEP-0257.
mach.logging module¶
- class mach.logging.ConvertToStructuredFilter(name='')¶
Bases:
logging.Filter
Filter that converts unstructured records into structured ones.
- filter(record)¶
Determine if the specified record is to be logged.
Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.
- class mach.logging.LoggingManager¶
Bases:
object
Holds and controls global logging state.
An application should instantiate one of these and configure it as needed.
This class provides a mechanism to configure the output of logging data both from mach and from the overall logging system (e.g. from other modules).
- add_json_handler(fh)¶
Enable JSON logging on the specified file object.
- add_terminal_logging(fh=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, level=20, write_interval=False, write_times=True)¶
Enable logging to the terminal.
- disable_unstructured()¶
Disable logging of unstructured messages.
- enable_all_structured_loggers(terminal=True, json=True)¶
Enable logging of all structured messages from all loggers.
terminal
andjson
determine which log handlers to operate on. By default, all known handlers are operated on.
- enable_unstructured()¶
Enable logging of unstructured messages.
- register_structured_logger(logger, terminal=True, json=True)¶
Register a structured logger.
This needs to be called for all structured loggers that don’t chain up to the mach logger in order for their output to be captured.
- replace_terminal_handler(handler)¶
Replace the installed terminal handler.
Returns the old handler or None if none was configured. If the new handler is None, removes any existing handler and disables logging to the terminal.
- property terminal¶
- class mach.logging.StructuredHumanFormatter(start_time, write_interval=False, write_times=True)¶
Bases:
logging.Formatter
Log formatter that writes structured messages for humans.
It is important that this formatter never be added to a logger that produces unstructured/classic log messages. If it is, the call to format() could fail because the string could contain things (like JSON) that look like formatting character sequences.
Because of this limitation, format() will fail with a KeyError if an unstructured record is passed or if the structured message is malformed.
- format(record)¶
Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
- class mach.logging.StructuredJSONFormatter(fmt=None, datefmt=None, style='%', validate=True)¶
Bases:
logging.Formatter
Log formatter that writes a structured JSON entry.
- format(record)¶
Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
- class mach.logging.StructuredTerminalFormatter(start_time, write_interval=False, write_times=True)¶
Bases:
mach.logging.StructuredHumanFormatter
Log formatter for structured messages writing to a terminal.
- format(record)¶
Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
- set_terminal(terminal)¶
- mach.logging.format_seconds(total)¶
Format number of seconds to MM:SS.DD form.
- mach.logging.formatted_stack_trace(record, formatter)¶
Formatting behavior here intended to mimic a portion of the standard library’s logging.Formatter::format function
mach.main module¶
- class mach.main.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=<class 'argparse.HelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)¶
Bases:
argparse.ArgumentParser
Custom implementation argument parser to make things look pretty.
- error(message)¶
Custom error reporter to give more helpful text on bad commands.
- format_help()¶
- class mach.main.ContextWrapper(context, handler)¶
Bases:
object
- class mach.main.Mach(cwd: str)¶
Bases:
object
Main mach driver type.
This type is responsible for holding global mach state and dispatching a command from arguments.
The following attributes may be assigned to the instance to influence behavior:
- populate_context_handler – If defined, it must be a callable. The
- callable signature is the following:
populate_context_handler(key=None)
It acts as a fallback getter for the mach.base.CommandContext instance. This allows to augment the context instance with arbitrary data for use in command handlers.
- require_conditions – If True, commands that do not have any condition
functions applied will be skipped. Defaults to False.
- settings_paths – A list of files or directories in which to search
for settings files to load.
- USAGE = '%(prog)s [global arguments] command [command arguments]\n\nmach (German for "do") is the main interface to the Mozilla build system and\ncommon developer tasks.\n\nYou tell mach the command you want to perform and it does it for you.\n\nSome common commands are:\n\n %(prog)s build Build/compile the source tree.\n %(prog)s help Show full help, including the list of all commands.\n\nTo see more help for a specific command, run:\n\n %(prog)s help <command>\n'¶
- define_category(name, title, description, priority=50)¶
Provide a description for a named command category.
- get_argument_parser(context)¶
Returns an argument parser for the command-line interface.
- load_commands_from_directory(path: pathlib.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.
- 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. If not specified, it defaults to ‘mach.providers’.
- load_commands_from_file(path: Union[str, pathlib.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.
- load_settings(paths: List[pathlib.Path])¶
Load the specified settings files.
If a directory is specified, the following basenames will be searched for in this order:
machrc, .machrc
- log(level, action, params, format_str)¶
Helper method to record a structured log event.
- property require_conditions¶
- run(argv, stdin=None, stdout=None, stderr=None)¶
Runs mach with arguments provided from the command line.
Returns the integer exit code that should be used. 0 means success. All other values indicate failure.
mach.registrar module¶
- class mach.registrar.MachRegistrar¶
Bases:
object
Container for mach command and config providers.
- dispatch(name, context, argv=None, subcommand=None, **kwargs)¶
Dispatch/run a command.
Commands can use this to call other commands.
- register_category(name, title, description, priority=50)¶
- register_command_handler(handler)¶
- register_settings_provider(cls)¶
mach.requirements module¶
- class mach.requirements.MachEnvRequirements¶
Bases:
object
Requirements associated with a “virtualenv_packages.txt” definition
Represents the dependencies of a site. The source files consist of colon-delimited fields. The first field specifies the action. The remaining fields are arguments to that action. The following actions are supported:
- pth – Adds the path given as argument to “mach.pth” under
the virtualenv’s site packages directory.
pypi – Fetch the package, plus dependencies, from PyPI.
- pypi-optional – Attempt to install the package and dependencies from PyPI.
Continue using the site, even if the package could not be installed.
- packages.txt – Denotes that the specified path is a child manifest. It
will be read and processed as if its contents were concatenated into the manifest being read.
- thunderbird-packages.txt – Denotes a Thunderbird child manifest.
Thunderbird child manifests are only activated when working on Thunderbird, and they can cannot have “pypi” or “pypi-optional” entries.
- classmethod from_requirements_definition(topsrcdir: str, is_thunderbird, is_mach_or_build_site, requirements_definition)¶
- pths_as_absolute(topsrcdir: str)¶
- class mach.requirements.PthSpecifier(path: str)¶
Bases:
object
- class mach.requirements.PypiOptionalSpecifier(repercussion, requirement)¶
- class mach.requirements.PypiSpecifier(requirement)¶
Bases:
object
mach.sentry module¶
- class mach.sentry.ErrorReporter¶
Bases:
object
- abstract report_exception(exception)¶
Report the exception to remote error-tracking software.
- class mach.sentry.NoopErrorReporter¶
Bases:
mach.sentry.ErrorReporter
Drops errors instead of reporting them.
This is useful in cases where error-reporting is specifically disabled, such as when telemetry hasn’t been allowed.
- report_exception(exception)¶
Report the exception to remote error-tracking software.
- class mach.sentry.SentryErrorReporter¶
Bases:
mach.sentry.ErrorReporter
Reports errors using Sentry.
- report_exception(exception)¶
Report the exception to remote error-tracking software.
- mach.sentry.register_sentry(argv, settings, topsrcdir: pathlib.Path)¶
mach.site module¶
- class mach.site.CommandSiteManager(topsrcdir: str, state_dir: str, virtualenv_root: str, site_name: str, active_metadata: mach.site.MozSiteMetadata, site_packages_source: mach.site.SitePackagesSource, requirements: mach.requirements.MachEnvRequirements)¶
Bases:
object
Activate sites and ad-hoc-install pip packages
Provides tools to ensure that a command’s scope will have expected, compatible packages. Manages prioritization of the import scope, and ensures consistency regardless of how a virtualenv is used (whether via in-process activation, or when used standalone to invoke a script).
A few notes: * The command environment always inherits Mach’s import scope. This is because
“unloading” packages in Python is error-prone, so in-process activations will always carry Mach’s dependencies along with it. Accordingly, compatibility between each command environment and the Mach environment must be maintained
Unlike the Mach environment, command environments always have an associated physical virtualenv on-disk. This is because some commands invoke child Python processes, and that child process should have the same import scope.
- activate()¶
Activate this site in the current Python context.
If you run a random Python script and wish to “activate” the site, you can simply instantiate an instance of this class and call .activate() to make the virtualenv active.
- ensure()¶
Ensure that this virtualenv is built, up-to-date, and ready for use If using a virtualenv Python binary directly, it’s useful to call this function first to ensure that the virtualenv doesn’t have obsolete references or packages.
- classmethod from_environment(topsrcdir: str, state_dir: str, site_name: str, command_virtualenvs_dir: str)¶
- Parameters
topsrcdir – The path to the Firefox repo
state_dir – The path to the state_dir, generally ~/.mozbuild
site_name – The name of this site, such as “build”
command_virtualenvs_dir – The location under which this site’s virtualenv
created (should be) –
- install_pip_package(package)¶
Install a package via pip.
The supplied package is specified using a pip requirement specifier. e.g. ‘foo’ or ‘foo==1.0’.
If the package is already installed, this is a no-op.
- install_pip_requirements(path, require_hashes=True, quiet=False)¶
Install a pip requirements.txt file.
The supplied path is a text file containing pip requirement specifiers.
If require_hashes is True, each specifier must contain the expected hash of the downloaded package. See: https://pip.pypa.io/en/stable/reference/pip_install/#hash-checking-mode
- class mach.site.ExternalPythonSite(python_executable)¶
Bases:
object
Represents the Python site that is executing Mach
The external Python site could be a virtualenv (created by venv or virtualenv) or the system Python itself, so we can’t make any significant assumptions on its structure.
- all_site_packages_dirs()¶
- has_pip()¶
- provides_any_package(virtualenv_name, requirements)¶
- class mach.site.ExternalSitePackageValidationResult¶
Bases:
object
- add_discrepancy(requirement, found)¶
- report()¶
- class mach.site.MachSiteManager(topsrcdir: str, state_dir: Optional[str], requirements: mach.requirements.MachEnvRequirements, external_python: mach.site.ExternalPythonSite, site_packages_source: mach.site.SitePackagesSource)¶
Bases:
object
Represents the activate-able “import scope” Mach needs
Whether running independently, using the system packages, or automatically managing dependencies with “pip install”, this class provides an easy handle to verify that the “site” is up-to-date (whether than means that system packages don’t collide with vendored packages, or that the on-disk virtualenv needs rebuilding).
Note that, this is a virtual site: an on-disk Python virtualenv is only created if there will be “pip installs” into the Mach site.
- activate()¶
- ensure(*, force=False)¶
- classmethod from_environment(topsrcdir: str, get_state_dir: Callable[[], str])¶
- Parameters
topsrcdir – The path to the Firefox repo
get_state_dir – A function that resolve the path to the workdir-scoped state_dir, generally ~/.mozbuild/srcdirs/<worktree-based-dir>/
- up_to_date()¶
- class mach.site.MozSiteMetadata(hex_version: int, site_name: str, site_packages_source: mach.site.SitePackagesSource, mach_site_packages_source: mach.site.SitePackagesSource, external_python: mach.site.ExternalPythonSite, prefix: str)¶
Bases:
object
Details about a Moz-managed python site
When a Moz-managed site is active, its associated metadata is available at “MozSiteMetadata.current”.
Sites that have associated virtualenvs (so, those that aren’t strictly leaning on the external python packages) will have their metadata written to <prefix>/moz_virtualenv_metadata.json.
- current: Optional[mach.site.MozSiteMetadata] = <mach.site.MozSiteMetadata object>¶
- classmethod from_path(prefix)¶
- classmethod from_runtime()¶
- update_current_site(executable)¶
Updates necessary global state when a site is activated
Due to needing to fetch some state before the actual activation happens, this is represented as a context manager and should be used as follows:
- with metadata.update_current_site(executable):
# Perform the actual implementation of changing the site, whether that is # by exec-ing “activate_this.py” in a virtualenv, modifying the sys.path # directly, or some other means …
- write(is_finalized)¶
- exception mach.site.MozSiteMetadataOutOfDateError¶
Bases:
Exception
- class mach.site.PythonVirtualenv(prefix)¶
Bases:
object
Calculates paths of interest for general python virtual environments
- pip_install(pip_install_args)¶
- site_packages_dir()¶
- class mach.site.SitePackagesSource(value)¶
Bases:
enum.Enum
An enumeration.
- NONE = 1¶
- SYSTEM = 2¶
- VENV = 3¶
- exception mach.site.VirtualenvOutOfDateException¶
Bases:
Exception
- mach.site.resolve_requirements(topsrcdir, virtualenv_name)¶
mach.telemetry module¶
- mach.telemetry.arcrc_path()¶
- mach.telemetry.create_telemetry_from_environment(settings)¶
Creates and a Telemetry instance based on system details.
If telemetry isn’t enabled, the current interpreter isn’t Python 3, or Glean can’t be imported, then a “mock” telemetry instance is returned that doesn’t set or record any data. This allows consumers to optimistically set telemetry data without needing to specifically handle the case where the current system doesn’t support it.
- mach.telemetry.initialize_telemetry_setting(settings, topsrcdir: str, state_dir: str)¶
Enables telemetry for employees or prompts the user.
- mach.telemetry.is_applicable_telemetry_environment()¶
- mach.telemetry.is_telemetry_enabled(settings)¶
- mach.telemetry.print_telemetry_message_employee()¶
- mach.telemetry.prompt_telemetry_message_contributor()¶
- mach.telemetry.record_telemetry_settings(main_settings, state_dir: pathlib.Path, is_enabled)¶
- mach.telemetry.report_invocation_metrics(telemetry, command)¶
- mach.telemetry.resolve_is_employee(topsrcdir: pathlib.Path)¶
Detect whether or not the current user is a Mozilla employee.
Checks using Bugzilla authentication, if possible. Otherwise falls back to checking if email configured in VCS is “@mozilla.com”.
Returns True if the user could be identified as an employee, False if the user is confirmed as not being an employee, or None if the user couldn’t be identified.
- mach.telemetry.resolve_is_employee_by_credentials(topsrcdir: pathlib.Path)¶
- mach.telemetry.resolve_is_employee_by_vcs(topsrcdir: pathlib.Path)¶
- mach.telemetry.resolve_setting_from_arcconfig(topsrcdir: pathlib.Path, setting)¶
mach.telemetry_interface module¶
- class mach.telemetry_interface.GleanTelemetry¶
Bases:
object
Records and sends Telemetry using Glean.
Metrics are defined in python/mozbuild/metrics.yaml. Pings are defined in python/mozbuild/pings.yaml.
The “metrics” and “pings” properties may be replaced with no-op implementations if Glean isn’t available. This allows consumers to report telemetry without having to guard against incompatible environments.
Also tracks whether an employee was just automatically opted into telemetry during this mach invocation.
- metrics(metrics_path: Union[str, pathlib.Path])¶
- submit(_)¶
mach.terminal module¶
This file contains code for interacting with terminals.
All the terminal interaction code is consolidated so the complexity can be in one place, away from code that is commonly looked at.
- class mach.terminal.LoggingHandler¶
Bases:
logging.Handler
Custom logging handler that works with terminal window dressing.
This is alternative terminal logging handler which contains smarts for emitting terminal control characters properly. Currently, it has generic support for “footer” elements at the bottom of the screen. Functionality can be added when needed.
- emit(record)¶
Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so raises a NotImplementedError.
- flush()¶
Ensure all logging output has been flushed.
This version does nothing and is intended to be implemented by subclasses.
Bases:
object
Represents something drawn on the bottom of a terminal.
mach.util module¶
- exception mach.util.UserError¶
Bases:
Exception
Represents an error caused by something the user did wrong rather than an internal mach failure. Exceptions that are subclasses of this class will not be reported as failures to Sentry.
- mach.util.get_state_dir(specific_to_topsrcdir=False, topsrcdir=None)¶
Obtain path to a directory to hold state.
- Parameters
specific_to_topsrcdir (bool) – If True, return a state dir specific to the current srcdir instead of the global state dir (default: False)
- Returns
A path to the state dir (str)
- mach.util.setenv(key, value)¶
Compatibility shim to ensure the proper string type is used with os.environ for the version of Python being used.