The latest development version of this page may be more current than this released 2.3.0 version.

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.

WestCommand

class west.commands.WestCommand

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_workspace

As passed to the constructor.

New in version 0.7.0.

parser

The argument parser created by calling WestCommand.add_parser().

Instance properties:

manifest

A 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 the do_run() method.

New in version 0.6.1.

Changed in version 0.7.0: This is now settable.

has_manifest

True if reading the manifest property will succeed instead of erroring out.

Constructor:

WestCommand.__init__(name, help, description, accepts_unknown_args=False, requires_workspace=True, requires_installation=None)

Abstract superclass for a west command.

Some fields, such as name, help, and description, overlap with kwargs that should be passed to the argparse.ArgumentParser added by WestCommand.add_parser. This wart is by design: argparse doesn’t make many API stability guarantees, so this information must be duplicated here for future-proofing.

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 WestCommand.run. Otherwise, it’s a fatal to pass unknown arguments.

  • requires_workspace – if true, the command requires a west workspace to run, and running it outside of one is a fatal error.

  • requires_installation – deprecated equivalent for “requires_workspace”; this may go away eventually.

New in version 0.6.0: The requires_installation parameter.

New in version 0.7.0: The requires_workspace parameter.

Methods:

WestCommand.run(args, unknown, topdir, manifest=None)

Run the command.

This raises west.commands.CommandContextError if the command cannot be run due to a context mismatch. Other exceptions may be raised as well.

Parameters

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 a parser attribute of.

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:

abstract WestCommand.do_add_parser(parser_adder)

Subclass method for registering command line arguments.

This is called by WestCommand.add_parser to register the command’s options and arguments.

Subclasses should 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()

abstract WestCommand.do_run(args, unknown)

Subclasses must implement; called to run the command.

Parameters
  • argsargparse.Namespace of parsed arguments

  • unknown – If accepts_unknown_args is true, a sequence of un-parsed argument strings.

Exceptions

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.

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

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: <workspace-topdir>/.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.

This provides API access to west configuration files and data.

Reading and writing options

west.configuration.read_config(configfile=None, config=<configparser.ConfigParser object>, topdir=None, config_file=None)

Read configuration files into config.

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.

If configfile requests local configuration options (i.e. if it is ConfigFile.LOCAL or ConfigFile.ALL:

  • If topdir is given, topdir/.west/config is read

  • Next, if WEST_CONFIG_LOCAL is set in the environment, its contents (a file) are used.

  • Otherwise, the file system is searched for a local configuration file, and a failure to find one is ignored.

Parameters
  • configfile – a west.configuration.ConfigFile

  • config – configuration object to read into

  • topdir – west workspace root to read local options from

  • config_file – deprecated alternative for configfile

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>, topdir=None)

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

  • configfilewest.configuration.ConfigFile, must not be ALL

  • topdir – west workspace root to write local config options to

The destination file to write is given by configfile. The default value (ConfigFile.LOCAL) writes to the local configuration file given by:

  • topdir/.west/config, if topdir is given, or

  • the value of ‘WEST_CONFIG_LOCAL’ in the environment, if set, or

  • the local configuration file in the west workspace found by searching the file system (raising WestNotFound if one is not found).

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-workspace configuration

  • ALL: all three of the above, where applicable

Global configuration instance

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.

This module’s functions are used whenever a running west command needs to print to standard out or error streams.

This is safe to use from extension commands if you want output that mirrors that of west itself.

Verbosity control

To set the global verbosity level, use set_verbosity().

west.log.set_verbosity(value)

Set the logging verbosity level.

Parameters

value – verbosity level to set, e.g. VERBOSE_VERY.

These verbosity levels are defined.

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.

Output functions

The main functions are dbg(), inf(), wrn(), err(), and die(). Two special cases of inf(), banner() and small_banner(), are also available for grouping output into “sections”.

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.log.banner(*args)

Prints args as a “banner” at inf() level.

The args are prefixed with ‘=== ‘ and colorized by default.

west.log.small_banner(*args)

Prints args as a smaller banner(), i.e. prefixed with ‘– ‘ and not colorized.

west.manifest

Parser and abstract data types for west manifests.

The main classes are Manifest and Project. These represent the contents of a manifest file. The recommended methods for parsing west manifests are Manifest.from_file and Manifest.from_data.

Constants and functions

west.manifest.MANIFEST_PROJECT_INDEX = 0

Index in a Manifest.projects attribute where the ManifestProject instance for the workspace is stored.

west.manifest.MANIFEST_REV_BRANCH = 'manifest-rev'

A git revision which points to the most recent Project update.

west.manifest.QUAL_MANIFEST_REV_BRANCH = 'refs/heads/manifest-rev'

A fully qualified reference to MANIFEST_REV_BRANCH.

west.manifest.QUAL_REFS_WEST = 'refs/west/'

Git ref space used by west for internal purposes.

west.manifest.SCHEMA_VERSION = '0.7'

The latest manifest schema version supported by this west program.

This value changes when a new version of west includes new manifest file features not supported by earlier versions of west.

west.manifest.manifest_path()

Absolute path of the manifest file in the current workspace.

Exceptions raised:

  • west.util.WestNotFound if called from outside of a west workspace

  • MalformedConfig if the configuration file has no manifest.path key

  • FileNotFoundError if no west.yml exists in manifest.path

west.manifest.validate(data)

Validate manifest data

Returns if the manifest data is valid and can be loaded by this version of west (though this may fail if the manifest contains imports which cannot be resolved).

Raises an exception otherwise.

Parameters

data – YAML manifest data as a string or object

Manifest and sub-objects

class west.manifest.Manifest(source_file=None, source_data=None, manifest_path=None, topdir=None, importer=None, import_flags=0, **kwargs)

The parsed contents of a west manifest file.

__init__(source_file=None, source_data=None, manifest_path=None, topdir=None, importer=None, import_flags=0, **kwargs)

Using from_file or from_data is usually easier than direct instantiation.

Instance attributes:

  • projects: sequence of Project

  • topdir: west workspace top level directory, or None

  • path: path to the manifest file itself, or None

  • has_imports: bool, True if the manifest contains an “import:” attribute in “self:” or “projects:”; False otherwise

Exactly one of source_file and source_data must be given.

If source_file is given:

  • If topdir is too, projects is rooted there.

  • Otherwise, topdir is found starting at source_file.

If source_data is given:

  • If topdir is too, projects is rooted there.

  • Otherwise, there is no root: projects[i].abspath and other absolute path attributes are None.

  • If source_data['manifest']['self']['path'] is unset, manifest_path is used as a fallback.

The importer kwarg, if given, is a callable. It is called when source_file requires importing manifest data that aren’t found locally. It will be called as:

importer(project, file)

where project is a Project and file is the missing file. The file’s contents at refs/heads/manifest-rev should usually be returned, potentially after fetching the project’s revision from its remote URL and updating that ref.

The return value should be a string containing manifest data, or a list of strings if file is a directory containing YAML files. A return value of None will cause the import to be ignored.

Exceptions raised:

Parameters
  • source_file – YAML file containing manifest data

  • source_data – parsed YAML data as a Python object, or a string containing unparsed YAML data

  • manifest_path – fallback ManifestProject path attribute

  • topdir – used as the west workspace top level directory

  • importer – callback to resolve missing manifest import data

  • import_flags – bit mask, controls import resolution

Changed in version 0.7.0: The importer and import_flags keyword arguments.

static from_file(source_file=None, **kwargs)

Manifest object factory given a source YAML file.

The default behavior is to find the current west workspace’s manifest file and resolve it.

Results depend on the keyword arguments given in kwargs:

  • If both source_file and topdir are given, the returned Manifest object is based on the data in source_file, rooted at topdir. The configuration files are not read in this case. This allows parsing a manifest file “as if” its project hierarchy were rooted at another location in the system.

  • If neither source_file nor topdir is given, the file system is searched for topdir. That workspace’s manifest.path configuration option is used to find source_file, topdir/<manifest.path>/west.yml.

  • If only source_file is given, topdir is found starting there. The directory containing source_file doesn’t have to be manifest.path in this case.

  • If only topdir is given, that workspace’s manifest.path is used to find source_file.

Exceptions raised:

Parameters
  • source_file – source file to load

  • kwargs – Manifest.__init__ keyword arguments

Changed in version 0.7.0: **kwargs added.

static from_data(source_data, **kwargs)

Manifest object factory given parsed YAML data.

This factory does not read any configuration files.

Letting the return value be m. Results then depend on keyword arguments in kwargs:

  • Unless topdir is given, all absolute paths in m, like m.projects[1].abspath, are None.

  • Relative paths, like m.projects[1].path, are taken from source_data.

  • If source_data['manifest']['self']['path'] is not set, then m.projects[MANIFEST_PROJECT_INDEX].abspath will be set to manifest_path if given.

Returns the same exceptions as the Manifest constructor.

Parameters
  • source_data – parsed YAML data as a Python object, or a string with unparsed YAML data

  • kwargs – Manifest.__init__ keyword arguments

Changed in version 0.7.0: **kwargs added, and source_data may be a str.

Conveniences for accessing sub-objects by name or other identifier:

get_projects(project_ids, allow_paths=True, only_cloned=False)

Get a list of Project objects in the manifest from project_ids.

If project_ids is empty, a copy of self.projects attribute is returned as a list. Otherwise, the returned list has projects in the same order as project_ids.

ValueError is raised if:

  • project_ids contains unknown project IDs

  • (with only_cloned) an uncloned project was found

The ValueError args attribute is a 2-tuple with a list of unknown project_ids at index 0, and a list of uncloned Project objects at index 1.

Parameters
  • project_ids – a sequence of projects, identified by name (these are matched first) or path (as a fallback, but only with allow_paths)

  • allow_paths – if true, project_ids may also contain relative or absolute project paths

  • only_cloned – raise an exception for uncloned projects

New in version 0.6.1.

Additional methods:

as_dict()

Returns a dict representing self, fully resolved.

The value is “resolved” in that the result is as if all projects had been defined in a single manifest without any import attributes.

New in version 0.7.0.

as_frozen_dict()

Returns a dict representing self, but frozen.

The value is “frozen” in that all project revisions are the full SHAs pointed to by QUAL_MANIFEST_REV_BRANCH references.

Raises RuntimeError if a project SHA can’t be resolved.

as_yaml(**kwargs)

Returns a YAML representation for self, fully resolved.

The value is “resolved” in that the result is as if all projects had been defined in a single manifest without any import attributes.

Parameters

kwargs – passed to yaml.safe_dump()

New in version 0.7.0.

as_frozen_yaml(**kwargs)

Returns a YAML representation for self, but frozen.

The value is “frozen” in that all project revisions are the full SHAs pointed to by QUAL_MANIFEST_REV_BRANCH references.

Raises RuntimeError if a project SHA can’t be resolved.

Parameters

kwargs – passed to yaml.safe_dump()

New in version 0.7.0.

class west.manifest.ImportFlag

Bit flags for handling imports when resolving a manifest.

The DEFAULT (0) value allows reading the file system to resolve “self: import:”, and running git to resolve a “projects:” import. Other flags:

  • IGNORE: ignore all “import:” attributes in “self:” and “projects:”

  • FORCE_PROJECTS: always invoke importer callback for “projects:” imports

  • IGNORE_PROJECTS: ignore “import:” attributes in “projects:” only; still respect “import:” in “self:”

class west.manifest.Project(name, url, revision=None, path=None, clone_depth=None, west_commands=None, topdir=None, remote_name=None)

Represents a project defined in a west manifest.

Attributes:

  • name: project’s unique name

  • url: project fetch URL

  • revision: revision to fetch from url when the project is updated

  • path: relative path to the project within the workspace (i.e. from topdir if that is set)

  • abspath: absolute path to the project in the native path name format (or None if topdir is)

  • posixpath: like abspath, but with slashes (/) as path separators

  • clone_depth: clone depth to fetch when first cloning the project, or None (the revision should not be a SHA if this is used)

  • west_commands: list of places to find extension commands in the project

  • topdir: the top level directory of the west workspace the project is part of, or None

  • remote_name: the name of the remote which should be set up when the project is being cloned (default: ‘origin’)

Changed in version 0.7.0: The remote attribute was removed. Its semantics could no longer be preserved when support for manifest import keys was added.

New in version 0.7.0: The remote_name and name_and_path attributes.

Constructor:

__init__(name, url, revision=None, path=None, clone_depth=None, west_commands=None, topdir=None, remote_name=None)

Project constructor.

If topdir is None, then absolute path attributes (abspath and posixpath) will also be None.

Parameters
  • name – project’s name: attribute in the manifest

  • url – fetch URL

  • revision – fetch revision

  • path – path (relative to topdir), or None for name

  • clone_depth – depth to use for initial clone

  • west_commands – path to west commands directory in the project, relative to its own base directory, topdir / path, or list of these

  • topdir – the west workspace’s top level directory

  • remote_name – the name of the remote which should be set up if the project is being cloned (default: ‘origin’)

Changed in version 0.7.0: The parameters were incompatibly changed from previous versions.

Methods:

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

git(cmd, extra_args=(), capture_stdout=False, capture_stderr=False, check=True, cwd=None)

Run a git command in the project repository.

Returns a subprocess.CompletedProcess.

Parameters
  • cmd – git command as a string (or list of strings)

  • extra_args – sequence of additional arguments to pass to the git command (useful mostly if cmd is a string).

  • capture_stdout – if True, git’s standard output is captured in the CompletedProcess instead of being printed.

  • capture_stderr – Like capture_stdout, but for standard error. Use with caution: this may prevent error messages from being shown to the user.

  • check – if given, subprocess.CalledProcessError is raised if git finishes with a non-zero return code

  • cwd – directory to run git in (default: self.abspath)

Changed in version 0.6.1: The capture_stderr kwarg.

Changed in version 0.7.0: The (now removed) Project.format method is no longer called on arguments.

sha(rev, cwd=None)

Get the SHA for a project revision.

Parameters
  • rev – git revision (HEAD, v2.0.0, etc.) as a string

  • cwd – directory to run command in (default: self.abspath)

Changed in version 0.7.0: Standard error is now captured.

is_ancestor_of(rev1, rev2, cwd=None)

Check if ‘rev1’ is an ancestor of ‘rev2’ in this project.

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.

Parameters
  • rev1 – commit that could be the ancestor of rev2

  • rev2 – commit that could be a descendant or rev1

  • cwd – directory to run command in (default: self.abspath)

is_cloned(cwd=None)

Returns True if self.abspath looks like a git repository’s top-level directory, and False otherwise.

Parameters

cwd – directory to run command in (default: self.abspath)

New in version 0.6.1.

is_up_to_date_with(rev, cwd=None)

Check if the project is up to date with rev, returning True if so.

This is equivalent to is_ancestor_of(rev, 'HEAD', cwd=cwd).

Parameters
  • rev – base revision to check if project is up to date with.

  • cwd – directory to run command in (default: self.abspath)

is_up_to_date(cwd=None)

Check if the project HEAD is up to date with the manifest.

This is equivalent to is_up_to_date_with(self.revision, cwd=cwd).

Parameters

cwd – directory to run command in (default: self.abspath)

read_at(path, rev=None, cwd=None)

Read file contents in the project at a specific revision.

The file contents are returned as a bytes object. The caller should decode them if necessary.

Parameters
  • path – relative path to file in this project

  • rev – revision to read path from (default: self.revision)

  • cwd – directory to run command in (default: self.abspath)

New in version 0.7.0.

listdir_at(path, rev=None, cwd=None, encoding=None)

List directory contents in the project at a specific revision.

The return value is a list of the directory’s contents as strings.

Parameters
  • path – relative path to file in this project

  • rev – revision to read path from (default: self.revision)

  • cwd – directory to run command in (default: self.abspath)

  • encoding – directory contents encoding (default: ‘utf-8’)

New in version 0.7.0.

class west.manifest.ManifestProject(path=None, west_commands=None, topdir=None)

Represents the manifest repository as a Project.

Meaningful attributes:

  • name: the string "manifest"

  • topdir: the top level directory of the west workspace the manifest project controls, or None

  • path: relative path to the manifest repository within the workspace, or None (i.e. from topdir if that is set)

  • abspath: absolute path to the manifest repository in the native path name format (or None if topdir is)

  • posixpath: like abspath, but with slashes (/) as path separators

  • west_commands:west_commands: key in the manifest’s self: map. This may be a list of such if the self section imports multiple additional files with west commands.

Other readable attributes included for Project compatibility:

  • url: always None; the west manifest is not version-controlled by west itself, even though ‘west init’ can fetch a manifest repository from a Git remote

  • revision: "HEAD"

  • clone_depth: None, because url is

A limited subset of Project methods is supported. Results for calling others are not specified.

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.

Exceptions

class west.manifest.MalformedManifest

Bases: Exception

Manifest parsing failed due to invalid data.

class west.manifest.MalformedConfig

Bases: Exception

The west configuration was malformed in a way that made a manifest operation fail.

class west.manifest.ManifestVersionError(version, file=None)

Bases: Exception

The manifest required a version of west more recent than the current version.

class west.manifest.ManifestImportFailed(project, filename)

Bases: Exception

An operation required to resolve a manifest failed.

Attributes:

  • project: the Project instance with the missing manifest data

  • filename: the missing file

west.util

Miscellaneous utilities.

Functions

west.util.west_dir(start=None)

Returns the absolute path of the workspace’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

Exceptions

class west.util.WestNotFound

Bases: RuntimeError

Neither the current directory nor any parent has a west workspace.