mach package


mach.base module

class mach.base.CommandContext(cwd=None, 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=u'')

Bases: exceptions.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: exceptions.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

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)
static to_config(value)
static validate(value)
exception mach.config.ConfigException

Bases: exceptions.Exception

class mach.config.ConfigSettings

Bases: _abcoll.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 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 = value = settings[‘foo’][‘bar’] value =[‘bar’]

Assignment is similar: = value settings[‘foo’][‘bar’] = value settings[‘foo’].bar = value

You can even delete user-assigned values:

del 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: _abcoll.MutableMapping, object

Represents an individual config section.


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 config data by reading file objects.


Register a SettingsProvider with this settings interface.


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)
static validate(value)
class mach.config.PathType

Bases: mach.config.StringType

static from_config(config, section, option)
static validate(value)
class mach.config.PositiveIntegerType

Bases: mach.config.IntegerType

static validate(value)
class mach.config.StringType

Bases: mach.config.ConfigType

static from_config(config, section, option)
static validate(value)

Used to make sure __getattr__ wrappers around __getitem__ raise AttributeError instead of KeyError.

mach.decorators module

class mach.decorators.Command(name, **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):

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):
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):

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.


Class decorator to denote that it provides subcommands for Mach.

When this decorator is present, mach looks for commands being defined by methods inside the class.


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)

Bases: object

Decorator for functions or methods that provide a sub-command.

Mach commands can have sub-commands. e.g. mach command foo or mach 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.

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 (

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.

class mach.dispatcher.DispatchSettings
config_settings = [(u'alias.*', u'string', u'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


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.

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).


Enable JSON logging on the specified file object.

add_terminal_logging(fh=<open file '<stdout>', mode 'w'>, level=20, write_interval=False, write_times=True)

Enable logging to the terminal.


Disable logging of unstructured messages.

enable_all_structured_loggers(terminal=True, json=True)

Enable logging of all structured messages from all loggers.

terminal and json determine which log handlers to operate on. By default, all known handlers are operated on.


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 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.

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.

class mach.logging.StructuredJSONFormatter(fmt=None, datefmt=None)

Bases: logging.Formatter

Log formatter that writes a structured JSON entry.

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 number of seconds to MM:SS.DD form.

mach.main module

class mach.main.ArgumentParser(prog=None, usage=None, description=None, epilog=None, version=None, parents=[], formatter_class=<class 'argparse.HelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)

Bases: argparse.ArgumentParser

Custom implementation argument parser to make things look pretty.


Custom error reporter to give more helpful text on bad commands.

class mach.main.ContextWrapper(context, handler)

Bases: object

class mach.main.Mach(cwd)

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(context, 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. For backwards compatibility, it is also called before command dispatch without a key, allowing the context handler to add attributes to the context instance.

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 = u'%(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'
add_global_argument(*args, **kwargs)

Register a global argument with the argument parser.

Arguments are proxied to ArgumentParser.add_argument()

define_category(name, title, description, priority=50)

Provide a description for a named command category.


Returns an argument parser for the command-line interface.


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.


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, 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 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.

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=None, argv=None, subcommand=None, **kwargs)

Dispatch/run a command.

Commands can use this to call other commands.

register_category(name, title, description, priority=50)

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.

class mach.terminal.TerminalFooter(terminal)

Bases: object

Represents something drawn on the bottom of a terminal.


Module contents