West APIs¶
This page documents the Python APIs provided by west, as well as some additional APIs used by the west extensions in the zephyr repository.
Warning
These APIs should be considered unstable until west version 1.0 (see west #38).
Contents:
west.commands¶
All built-in and extension commands are implemented as subclasses of the
WestCommand
class defined here. Some exception types are also
provided.
-
class
west.commands.
WestCommand
¶ -
WestCommand.
__init__
(name, help, description, accepts_unknown_args=False, requires_installation=True)¶ Abstract superclass for a west command.
Some of the fields in a WestCommand (such as name, help, and description) overlap with kwargs that should be passed to the argparse.ArgumentParser which should be added in the
WestCommand.add_parser()
method. This wart is by design: argparse doesn’t make many API stability guarantees, so some of this information must be duplicated to work reliably in the future.Parameters: - name – the command’s name, as entered by the user
- help – one-line command help text
- description – multi-line command description
- accepts_unknown_args – if true, the command can handle arbitrary unknown command line arguments in its run() method. Otherwise, passing unknown arguments will cause UnknownArgumentsError to be raised.
- requires_installation – if true, the command requires a west installation to run. Running such a command outside of any installation (i.e. without a valid topdir) will exit with an error.
New in version 0.6.0: The requires_installation parameter.
Methods:
-
WestCommand.
run
(args, unknown, topdir)¶ Run the command.
This raises
CommandContextError
if the command cannot be run due to a context mismatch. Other exceptions may be raised as well.Parameters: - args – known arguments parsed via
WestCommand.add_parser()
. - unknown – unknown arguments present on the command line; this must be empty if the constructor was passed accepts_unknown_args=False.
- topdir – top level directory of west installation, or None; this is stored as an attribute before do_run() is called.
- args – known arguments parsed via
Changed in version 0.6.0: The topdir argument was added.
-
WestCommand.
add_parser
(parser_adder)¶ Registers a parser for this command, and returns it.
The parser object is stored in the
parser
attribute of this WestCommand.Parameters: parser_adder – The return value of a call to argparse.ArgumentParser.add_subparsers()
All subclasses must provide the following abstract methods, which are used to implement the above:
-
WestCommand.
do_add_parser
(parser_adder)¶ Subclass method for registering command line arguments.
This is called by WestCommand.add_parser() to do the work of adding the parser itself.
The subclass should call parser_adder.add_parser() to add an ArgumentParser for that subcommand, then add any arguments. The final parser must be returned.
Parameters: parser_adder – The return value of a call to argparse.ArgumentParser.add_subparsers()
-
WestCommand.
do_run
(args, unknown)¶ Subclasses must implement; called when the command is run.
Parameters: - args – is the namespace of parsed known arguments.
- unknown – If
accepts_unknown_args
was False when constructing this object, this parameter is an empty sequence. Otherwise, it is an iterable containing all unknown arguments present on the command line.
Instance attributes:
-
name
¶ As passed to the constructor.
-
help
¶ As passed to the constructor.
-
description
¶ As passed to the constructor.
-
accepts_unknown_args
¶ As passed to the constructor.
-
requires_installation
¶ As passed to the constructor.
-
parser
¶ The argument parser created by calling
WestCommand.add_parser()
.
Instance properties:
-
manifest
¶ A read-only property which returns the
west.manifest.Manifest
instance for the current manifest file or aborts the program if one was not provided. This is only safe to use from thedo_run()
method.
New in version 0.6.1.
-
-
class
west.commands.
CommandError
(returncode=1)¶ Bases:
RuntimeError
Indicates that a command failed.
-
returncode
¶ Recommended program exit code for this error.
-
-
class
west.commands.
CommandContextError
(returncode=1)¶ Bases:
west.commands.CommandError
Indicates that a context-dependent command could not be run.
-
class
west.commands.
ExtensionCommandError
(**kwargs)¶ Bases:
west.commands.CommandError
Exception class indicating an extension command was badly defined and could not be created.
-
__init__
(hint=None, **kwargs)¶ If hint is given, it is a string indicating the cause of the problem. All other kwargs are passed to the super constructor.
-
hint
¶ As passed to the constructor.
-
west.configuration¶
West configuration file handling.
West follows Git-like conventions for configuration file locations. There are three types of configuration file: system-wide files apply to all users on the current machine, global files apply to the current user, and local files apply to the current west installation.
System files:
- Linux:
/etc/westconfig
- macOS:
/usr/local/etc/westconfig
- Windows:
%PROGRAMDATA%\west\config
Global files:
- Linux:
~/.westconfig
or (if$XDG_CONFIG_HOME
is set)$XDG_CONFIG_HOME/west/config
- macOS:
~/.westconfig
- Windows:
.westconfig
in the user’s home directory, as determined by os.path.expanduser.
Local files:
- Linux, macOS, Windows:
<installation-root-directory>/.west/config
You can override these files’ locations with the WEST_CONFIG_SYSTEM
,
WEST_CONFIG_GLOBAL
, and WEST_CONFIG_LOCAL
environment variables.
Configuration values from later configuration files override configuration from earlier ones. Local values have highest precedence, and system values lowest.
-
class
west.configuration.
ConfigFile
¶ Types of west configuration file.
Enumeration members:
- SYSTEM: system level configuration shared by all users
- GLOBAL: global or user-wide configuration
- LOCAL: per-installation configuration
- ALL: all three of the above, where applicable
-
west.configuration.
read_config
(configfile=None, config=<configparser.ConfigParser object>, config_file=None)¶ Read configuration files into config.
Parameters: - configfile – a
west.configuration.ConfigFile
- config – configuration object to read into
- config_file – deprecated alternative spelling for configfile
Reads the files given by configfile, storing the values into the configparser.ConfigParser object config. If config is not given, the global
west.configuration.config
object is used.If configfile is given, only the files implied by its value are read. If not given,
ConfigFile.ALL
is used.- configfile – a
Changed in version 0.6.0: Errors due to an inability to find a local configuration file are ignored.
-
west.configuration.
update_config
(section, key, value, configfile=<ConfigFile.LOCAL: 4>)¶ Sets
section.key
to value in the given configuration file.Parameters: - section – config section; will be created if it does not exist
- key – key to set in the given section
- value – value to set the key to
- configfile –
west.configuration.ConfigFile
, must not be ALL
The destination file to write is given by configfile. The default value (
ConfigFile.LOCAL
) writes to the per-installation file .west/config. This function must therefore be called from a west installation if this default is used, or WestNotFound will be raised.
-
west.configuration.
config
¶ Module-global ConfigParser instance for the current configuration. This should be initialized with
west.configuration.read_config()
before being read.
west.log¶
Provides common methods for printing messages to display to the user.
WestCommand instances should generally use the functions in this
module rather than calling print() directly if possible, as these
respect the color.ui
configuration option and verbosity level.
-
west.log.
set_verbosity
(value)¶ Set the logging verbosity level.
Parameters: value – verbosity level to set, e.g. VERBOSE_VERY.
-
west.log.
VERBOSE_NONE
= 0¶ Default verbosity level, no dbg() messages printed.
-
west.log.
VERBOSE_NORMAL
= 1¶ Some verbose messages printed.
-
west.log.
VERBOSE_VERY
= 2¶ Very verbose output messages will be printed.
-
west.log.
VERBOSE_EXTREME
= 3¶ Extremely verbose output messages will be printed.
-
west.log.
dbg
(*args, level=1)¶ Print a verbose debug logging message.
Parameters: - args – sequence of arguments to print.
- value – verbosity level to set, e.g. VERBOSE_VERY.
The message is only printed if level is at least the current verbosity level.
-
west.log.
inf
(*args, colorize=False)¶ Print an informational message.
Parameters: - args – sequence of arguments to print.
- colorize – If this is True, the configuration option
color.ui
is undefined or true, and stdout is a terminal, then the message is printed in green.
-
west.log.
wrn
(*args)¶ Print a warning.
Parameters: args – sequence of arguments to print. The message is prefixed with the string
"WARNING: "
.If the configuration option
color.ui
is undefined or true and stdout is a terminal, then the message is printed in yellow.
-
west.log.
err
(*args, fatal=False)¶ Print an error.
This function does not abort the program. For that, use
die()
.Parameters: - args – sequence of arguments to print.
- fatal – if True, the the message is prefixed with “FATAL ERROR: “; otherwise, “ERROR: ” is used.
If the configuration option
color.ui
is undefined or true and stdout is a terminal, then the message is printed in red.
-
west.log.
die
(*args, exit_code=1)¶ Print a fatal error, and abort the program.
Parameters: - args – sequence of arguments to print.
- exit_code – return code the program should use when aborting.
Equivalent to
die(*args, fatal=True)
, followed by an attempt to abort with the given exit_code.
west.manifest¶
Parser and abstract data types for west manifests.
The main class is Manifest. The recommended method for creating a
Manifest instance is via its from_file()
or from_data()
helper
methods.
There are additionally Defaults, Remote, and Project types defined, which represent the values by the same names in a west manifest. (I.e. “Remote” represents one of the elements in the “remote” sequence in the manifest, and so on.) Some Default values, such as the default project revision, may be supplied by this module if they are not present in the manifest data.
-
west.manifest.
MANIFEST_PROJECT_INDEX
= 0¶ Index in projects where the project with contains project manifest file is located
-
west.manifest.
MANIFEST_REV_BRANCH
= 'manifest-rev'¶ The name of the branch that points to the revision specified in the manifest
-
west.manifest.
QUAL_MANIFEST_REV_BRANCH
= 'refs/heads/manifest-rev'¶ A qualified reference to MANIFEST_REV_BRANCH, i.e. refs/heads/manifest-rev.
-
west.manifest.
manifest_path
()¶ Return the path to the manifest file.
Raises: WestNotFound if called from outside of a west working directory, MalformedConfig if the configuration file is missing a manifest.path key, and FileNotFoundError if the manifest.path file doesn’t exist.
-
class
west.manifest.
Manifest
(source_file=None, source_data=None)¶ Represents the contents of a West manifest file.
The most convenient way to construct an instance is using the from_file and from_data helper methods.
-
static
from_file
(source_file=None)¶ Create and return a new Manifest object given a source YAML file.
Parameters: source_file – Path to a YAML file containing the manifest. If source_file is None, the value returned by
manifest_path()
is used.Raises
MalformedManifest
in case of validation errors. RaisesMalformedConfig
in case of missing configuration settings.
-
static
from_data
(source_data)¶ Create and return a new Manifest object given parsed YAML data.
Parameters: source_data – Parsed YAML data as a Python object. Raises MalformedManifest in case of validation errors. Raises MalformedConfig in case of missing configuration settings.
-
__init__
(source_file=None, source_data=None)¶ Create a new Manifest object.
Parameters: - source_file – Path to a YAML file containing the manifest.
- source_data – Parsed YAML data as a Python object.
Normally, it is more convenient to use the
from_file
andfrom_data
convenience factories than calling the constructor directly.Exactly one of the source_file and source_data parameters must be given.
Raises MalformedManifest in case of validation errors. Raises MalformedConfig in case of missing configuration settings.
-
get_remote
(name)¶ Get a manifest Remote, given its name.
New in version 0.6.1.
-
as_frozen_dict
()¶ Returns an OrderedDict representing this manifest, frozen.
The manifest is ‘frozen’ in that all Git revisions in the original data are replaced with the corresponding SHAs.
Note that this requires that all projects are checked out.
-
static
-
class
west.manifest.
Defaults
(remote=None, revision=None)¶ Represents default values in a manifest, either specified by the user or by west itself.
Defaults are neither comparable nor hashable.
-
as_dict
()¶ Return a representation of this object as a dict, as it would be parsed from an equivalent YAML manifest.
-
revision
¶ Revision to applied to projects without an explicit value.
-
-
class
west.manifest.
Remote
(name, url_base)¶ Represents a remote defined in a west manifest.
Remotes may be compared for equality, but are not hashable.
-
as_dict
()¶ Return a representation of this object as a dict, as it would be parsed from an equivalent YAML manifest.
-
name
¶ Remote name as it appears in the manifest.
-
url_base
¶ Remote url-base value as it appears in the manifest.
-
-
class
west.manifest.
Project
(name, defaults=None, path=None, clone_depth=None, revision=None, west_commands=None, remote=None, repo_path=None, url=None)¶ Represents a project defined in a west manifest.
Projects are neither comparable nor hashable.
-
__init__
(name, defaults=None, path=None, clone_depth=None, revision=None, west_commands=None, remote=None, repo_path=None, url=None)¶ Specify a Project by name, Remote, and optional information.
Parameters: - name – Project’s user-defined name in the manifest.
- defaults – If the revision parameter is not given, the project’s revision is set to defaults.revision if defaults is not None, or the west-wide default otherwise.
- path – Relative path to the project in the west
installation, if present in the manifest. If not given,
the project’s
name
is used. - clone_depth – Nonnegative integer clone depth if present in the manifest.
- revision – Project revision as given in the manifest, if present. If not given, defaults.revision is used instead.
- west_commands – path to a YAML file in the project containing a description of west extension commands provided by the project, if given.
- remote – Remote instance corresponding to this Project as specified in the manifest. This is used to build the project’s URL, and is also stored as an attribute.
- repo_path – If this and remote are not None, then
remote.url_base + repo_path
(instead ofremote.url_base + name
) is used as the project’s fetch URL. - url – The project’s fetch URL. This cannot be given with remote or repo_path.
-
as_dict
()¶ Return a representation of this object as a dict, as it would be parsed from an equivalent YAML manifest.
-
format
(s, *args, **kwargs)¶ Calls s.format() with instance-related format keys.
The formatted value is returned.
Parameters: s – string (or other object) whose format() method to call The format method is called with
*args
and the followingkwargs
:- this object’s
__slots__
/ values (name, url, etc.) - name_and_path: “self.name + (self.path)”
- remote_name: “None” if no remote, otherwise self.remote.name
- any additional kwargs passed as parameters
The kwargs passed as parameters override the other values.
- this object’s
-
git
(cmd, extra_args=(), capture_stdout=False, check=True, cwd=None)¶ Helper for running a git command using metadata from a Project instance.
Parameters: - cmd – git command as a string (or list of strings); all strings are formatted using self.format() before use.
- extra_args – sequence of additional arguments to pass to the git command (useful mostly if cmd is a string).
- capture_stdout – True if stdout should be captured into the returned object instead of being printed. The stderr output is never captured, to prevent error messages from being eaten.
- check – True if a subprocess.CalledProcessError should be raised if the git command finishes with a non-zero return code.
- cwd – directory to run command in (default: self.abspath)
Returns a CompletedProcess (which is back-ported for Python 3.4).
Changed in version 0.6.1: The
capture_stderr
kwarg.-
sha
(rev)¶ Returns the SHA of the given revision in the current project.
Parameters: rev – git revision (HEAD, v2.0.0, etc.) as a string
-
is_ancestor_of
(rev1, rev2)¶ Check if ‘rev1’ is an ancestor of ‘rev2’ in this project.
Parameters: - rev1 – commit that could be the ancestor
- rev2 – commit that could be a descendant
Returns True if rev1 is an ancestor commit of rev2 in the given project; rev1 and rev2 can be anything that resolves to a commit. (If rev1 and rev2 refer to the same commit, the return value is True, i.e. a commit is considered an ancestor of itself.) Returns False otherwise.
New in version 0.6.1.
-
is_up_to_date_with
(rev)¶ Check if a project is up to date with revision ‘rev’.
Parameters: rev – base revision to check if project is up to date with. Returns True if all commits in ‘rev’ are also in HEAD. This can be used to check if this project needs updates, rebasing, etc.; ‘rev’ can be anything that resolves to a commit.
This is a special case of is_ancestor_of() provided for convenience.
-
is_up_to_date
()¶ Returns is_up_to_date_with(self.revision).
-
-
class
west.manifest.
ManifestProject
(path=None, revision=None, url=None, west_commands=None)¶ Represents the manifest as a project.
-
as_dict
()¶ Return a representation of this object as a dict, as it would be parsed from an equivalent YAML manifest.
-
New in version 0.6.0.
-
class
west.manifest.
MalformedManifest
¶ Bases:
Exception
Exception indicating that west manifest parsing failed due to a malformed value.
-
class
west.manifest.
MalformedConfig
¶ Bases:
Exception
Exception indicating that west config is malformed and thus causing west manifest parsing to fail.
west.util¶
Miscellaneous utilities.
-
west.util.
west_dir
(start=None)¶ Returns the absolute path of the installation’s .west directory.
Starts the search from the start directory, and goes to its parents. If the start directory is not specified, the current directory is used.
Raises WestNotFound if no .west directory is found.
-
west.util.
west_topdir
(start=None, fall_back=True)¶ Like west_dir(), but returns the path to the parent directory of the .west/ directory instead, where project repositories are stored
-
class
west.util.
WestNotFound
¶ Bases:
RuntimeError
Neither the current directory nor any parent has a West installation.