# Copyright (c) 2018, 2019 Nordic Semiconductor ASA # Copyright 2018, 2019 Foundries.io # # SPDX-License-Identifier: Apache-2.0 '''West project commands''' import argparse import hashlib import logging import os import shlex import shutil import subprocess import sys import textwrap import time from functools import partial from os.path import abspath, basename, relpath from pathlib import Path, PurePath from time import perf_counter from urllib.parse import urlparse from west import util from west.commands import CommandError, Verbosity, WestCommand from west.configuration import Configuration from west.manifest import MANIFEST_REV_BRANCH as MANIFEST_REV from west.manifest import QUAL_MANIFEST_REV_BRANCH as QUAL_MANIFEST_REV from west.manifest import QUAL_REFS_WEST as QUAL_REFS from west.manifest import ( ImportFlag, Manifest, ManifestImportFailed, ManifestProject, Submodule, _manifest_content_at, ) from west.manifest import is_group as is_project_group # # Project-related or multi-repo commands, like "init", "update", # "diff", etc. # class _ProjectCommand(WestCommand): # Helper class which contains common code needed by various commands # in this file. def _parser(self, parser_adder, **kwargs): # Create and return a "standard" parser. kwargs['help'] = self.help kwargs['description'] = self.description kwargs['formatter_class'] = argparse.RawDescriptionHelpFormatter return parser_adder.add_parser(self.name, **kwargs) def _cloned_projects(self, args, only_active=False): # Returns _projects(args.projects, only_cloned=True) if # args.projects is not empty (i.e., explicitly given projects # are required to be cloned). Otherwise, returns all cloned # projects. if args.projects: ret = self._projects(args.projects, only_cloned=True) else: ret = [p for p in self.manifest.projects if p.is_cloned()] if args.projects or not only_active: return ret return [p for p in ret if self.manifest.is_active(p)] def _projects(self, ids, only_cloned=False): try: return self.manifest.get_projects(ids, only_cloned=only_cloned) except ValueError as ve: if len(ve.args) != 2: raise # not directly raised by get_projects() # Die with an error message on unknown or uncloned projects. unknown, uncloned = ve.args if unknown: self._die_unknown(unknown) elif only_cloned and uncloned: s = 's' if len(uncloned) > 1 else '' names = ' '.join(p.name for p in uncloned) self.die(f'uncloned project{s}: {names}.\n' ' Hint: run "west update" and retry.') else: # Should never happen, but re-raise to fail fast and # preserve a stack trace, to encourage a bug report. raise def _handle_failed(self, args, failed): # Shared code for commands (like status, diff, update) that need # to do the same thing to multiple projects, but collect # and report errors if anything failed. if not failed: self.dbg(f'git {self.name} failed for zero project') return elif len(failed) < 20: s = 's:' if len(failed) > 1 else '' projects = ', '.join(f'{p.name}' for p in failed) self.err(f'{self.name} failed for project{s} {projects}') else: self.err(f'{self.name} failed for multiple projects; see above') raise CommandError(1) def _die_unknown(self, unknown): # Scream and die about unknown projects. s = 's' if len(unknown) > 1 else '' names = ' '.join(unknown) self.die(f'unknown project name{s}/path{s}: {names}\n' ' Hint: use "west list" to list all projects.') def _has_nonempty_status(self, project): # Check if the project has any status output to print. We # manually use Popen in order to try to exit as quickly as # possible if 'git status' prints anything. popen = subprocess.Popen(['git', 'status', '--porcelain'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=project.abspath) def has_output(): # 'git status --porcelain' prints nothing if there # are no notable changes, so any output at all # means we should run 'git status' on the project. stdout, stderr = None, None try: stdout, stderr = popen.communicate(timeout=0.1) except subprocess.TimeoutExpired: pass return stdout or stderr while True: if has_output(): popen.kill() return True if popen.poll() is not None: break return has_output() class Init(_ProjectCommand): def __init__(self): super().__init__( 'init', 'create a west workspace', f'''\ Creates a west workspace. With -l, creates a workspace around an existing local repository; without -l, creates a workspace by cloning a manifest repository by URL. With -m, clones the repository at that URL and uses it as the manifest repository. If --mr is not given, the remote's default branch will be used, if it exists. With neither, -m {MANIFEST_URL_DEFAULT} is assumed. Warning: 'west init' renames and/or deletes temporary files inside the workspace being created. This fails on some filesystems when some development tool or any other program is trying to read/index these temporary files at the same time. For instance, it is required to stop Visual Studio Code before running 'west init` on the Windows NTFS filesystem. Find other, similar "Access is denied" examples in west issue #558. This is not required with most Linux filesystems that have an inode indirection layer and can wait to finalize the deletion until there is no concurrent user left. If you cannot identify or cannot stop the background scanner that is interfering with renames on your system, try the --rename-delay hack below. ''', requires_workspace=False) def do_add_parser(self, parser_adder): # We set a custom usage because there are two distinct ways # to call this command, and the default usage generated by # argparse doesn't make that very clear. parser = self._parser( parser_adder, usage=''' %(prog)s [-m URL] [--mr REVISION] [--mf FILE] [-o=GIT_CLONE_OPTION] [directory] %(prog)s -l [--mf FILE] directory ''') # Remember to update the usage if you modify any arguments. parser.add_argument('-m', '--manifest-url', help='''manifest repository URL to clone; cannot be combined with -l''') parser.add_argument('-o', '--clone-opt', action='append', default=[], help='''additional option to pass to 'git clone' (e.g. '-o=--depth=1'); may be given more than once; cannot be combined with -l''') parser.add_argument('--mr', '--manifest-rev', dest='manifest_rev', help='''manifest repository branch or tag name to check out first; cannot be combined with -l''') parser.add_argument('--mf', '--manifest-file', dest='manifest_file', help='manifest file name to use') parser.add_argument('-l', '--local', action='store_true', help='''use "directory" as an existing local manifest repository instead of cloning one from MANIFEST_URL; .west is created next to "directory" in this case, and manifest.path points at "directory"''') parser.add_argument('--rename-delay', type=int, help='''Number of seconds to wait before renaming some temporary directories. Some filesystems like NTFS cannot rename files in use; see above. This is a HACK that may or may not give enough time for some random background scanner to complete. ''') parser.add_argument( 'directory', nargs='?', default=None, help='''with -l, the path to the local manifest repository; without it, the directory to create the workspace in (defaulting to the current working directory in this case)''') return parser def do_run(self, args, _): if self.topdir: zb = os.environ.get('ZEPHYR_BASE') if zb: msg = textwrap.dedent(f''' Note: In your environment, ZEPHYR_BASE is set to: {zb} This forces west to search for a workspace there. Try unsetting ZEPHYR_BASE and re-running this command.''') else: west_dir = Path(self.topdir) / WEST_DIR msg = ("\n Hint: if you do not want a workspace there, \n" " remove this directory and re-run this command:\n\n" f" {west_dir}") self.die_already(self.topdir, msg) if args.local and (args.manifest_url or args.manifest_rev or args.clone_opt): self.die('-l cannot be combined with -m, -o or --mr') self.die_if_no_git() if args.local: topdir = self.local(args) else: topdir = self.bootstrap(args) self.banner(f'Initialized. Now run "west update" inside {topdir}.') def die_already(self, where, also=None): self.die(f'already initialized in {where}, aborting.{also or ""}') def local(self, args) -> Path: if args.manifest_rev is not None: self.die('--mr cannot be used with -l') # We need to resolve this to handle the case that args.directory # is '.'. In that case, Path('.').parent is just Path('.') instead of # Path('..'). # # https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent manifest_dir = Path(args.directory or os.getcwd()).resolve() manifest_filename = args.manifest_file or 'west.yml' manifest_file = manifest_dir / manifest_filename topdir = manifest_dir.parent rel_manifest = manifest_dir.name west_dir = topdir / WEST_DIR if not manifest_file.is_file(): self.die(f'can\'t init: no {manifest_filename} found in ' f'{manifest_dir}') self.banner('Initializing from existing manifest repository', rel_manifest) self.small_banner(f'Creating {west_dir} and local configuration file') self.create(west_dir) os.chdir(topdir) self.config = Configuration(topdir=topdir) self.config.set('manifest.path', os.fspath(rel_manifest)) self.config.set('manifest.file', manifest_filename) return topdir def bootstrap(self, args) -> Path: topdir = Path(abspath(args.directory or os.getcwd())) self.banner('Initializing in', topdir) manifest_url = args.manifest_url or MANIFEST_URL_DEFAULT if args.manifest_rev: # This works with tags, too. branch_opt = ['--branch', args.manifest_rev] else: branch_opt = [] west_dir = topdir / WEST_DIR try: already = util.west_topdir(topdir, fall_back=False) self.die_already(already) except util.WestNotFound: pass if not topdir.is_dir(): self.create(topdir, exist_ok=False) tempdir: Path = west_dir / 'manifest-tmp' if tempdir.is_dir(): self.dbg('removing existing temporary manifest directory', tempdir) shutil.rmtree(tempdir) # Test that we can rename and delete directories. For the vast # majority of users this is a no-op but some filesystem # permissions can be weird; see October 2024 example in west # issue #558. Git cloning can take a long time, so check this # first. Failing ourselves is not just faster, it's also much # clearer than when git is involved in the mix. tempdir.mkdir(parents=True) (tempdir / 'not empty').mkdir() # Ignore the --rename-delay hack here not to double the wait; # we only have a couple directories and no file at this point! tempdir2 = tempdir.parent / 'renamed tempdir' os.rename(tempdir, tempdir2) # No need to delete west_dir parent shutil.rmtree(tempdir2) # Clone the manifest repository into a temporary directory. try: self.small_banner( f'Cloning manifest repository from {manifest_url}' + (f', rev. {args.manifest_rev}' if args.manifest_rev else '')) self.check_call(['git', 'clone'] + branch_opt + args.clone_opt + [manifest_url, os.fspath(tempdir)]) except subprocess.CalledProcessError: shutil.rmtree(tempdir, ignore_errors=True) raise # Verify the manifest file exists. temp_manifest_filename = args.manifest_file or 'west.yml' temp_manifest = tempdir / temp_manifest_filename if not temp_manifest.is_file(): self.die(f'can\'t init: no {temp_manifest_filename} found in ' f'{tempdir}\n' f' Hint: check --manifest-url={manifest_url}' + (f' and --manifest-rev={args.manifest_rev}' if args.manifest_rev else '') + f' You may need to remove {west_dir} before retrying.') # Parse the manifest to get "self: path:", if it declares one. # Otherwise, use the URL. Ignore imports -- all we really # want to know is if there's a "self: path:" or not. manifest = Manifest.from_data(temp_manifest.read_text(encoding=Manifest.encoding), import_flags=ImportFlag.IGNORE) if manifest.yaml_path: manifest_path = manifest.yaml_path else: # We use PurePath() here in case manifest_url is a # windows-style path. That does the right thing in that # case, without affecting POSIX platforms, where PurePath # is PurePosixPath. manifest_path = PurePath(urlparse(manifest_url).path).name manifest_abspath = topdir / manifest_path # Some filesystems like NTFS can't rename files in use. # See west issue #558. Will ReFS address this? ren_delay = args.rename_delay if ren_delay is not None: self.inf(f"HACK: waiting {ren_delay} seconds before renaming {tempdir}") time.sleep(ren_delay) self.dbg('moving', tempdir, 'to', manifest_abspath, level=Verbosity.DBG_EXTREME) # As shutil.move() is used to relocate tempdir, if manifest_abspath # is an existing directory, tmpdir will be moved _inside_ it, instead # of _to_ that path - this must be avoided. If manifest_abspath exists # but is not a directory, then semantics depend on os.rename(), so # avoid that too... if manifest_abspath.exists(): self.die(f'target directory already exists ({manifest_abspath})') manifest_abspath.parent.mkdir(parents=True, exist_ok=True) try: shutil.move(os.fspath(tempdir), os.fspath(manifest_abspath)) except shutil.Error as e: self.die(e) self.small_banner('setting manifest.path to', manifest_path) self.config = Configuration(topdir=topdir) self.config.set('manifest.path', manifest_path) self.config.set('manifest.file', temp_manifest_filename) return topdir def create(self, directory: Path, exist_ok: bool = True) -> None: try: directory.mkdir(parents=True, exist_ok=exist_ok) except PermissionError: self.die(f'Cannot initialize in {directory}: permission denied') except FileExistsError: self.die(f'Cannot initialize in {directory}: it already exists') except Exception as e: self.die(f"Can't create {directory}: {e}") class List(_ProjectCommand): def __init__(self): super().__init__( 'list', 'print information about projects', textwrap.dedent('''\ Print information about projects in the west manifest, using format strings.''')) def do_add_parser(self, parser_adder): default_fmt = '{name:12} {path:28} {revision:40} {url}' parser = self._parser( parser_adder, epilog=f'''\ {ACTIVE_PROJECTS_HELP} Note: To list only inactive projects you can use --inactive. FORMAT STRINGS -------------- Projects are listed using a Python 3 format string. Arguments to the format string are accessed by name. The default format string is: "{default_fmt}" The following arguments are available: - name: project name in the manifest - description: project description in the manifest - url: full remote URL as specified by the manifest - path: the relative path to the project from the top level, as specified in the manifest where applicable - abspath: absolute and normalized path to the project - posixpath: like abspath, but in posix style, that is, with '/' as the separator character instead of '\\' - revision: project's revision as it appears in the manifest - sha: project's revision as a SHA. Note that use of this requires that the project has been cloned. - cloned: "cloned" if the project has been cloned, "not-cloned" otherwise - active: "active" if the project is currently active, "inactive" otherwise - clone_depth: project clone depth if specified, "None" otherwise - groups: project groups, as a comma-separated list ''') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-a', '--all', action='store_true', help='include inactive projects'), group.add_argument('-i', '--inactive', action='store_true', help='list only inactive projects'), parser.add_argument('--manifest-path-from-yaml', action='store_true', help='''print the manifest repository's path according to the manifest file YAML, which may disagree with the manifest.path configuration option'''), parser.add_argument('-f', '--format', default=default_fmt, help='''format string to use to list each project; see FORMAT STRINGS below.''') parser.add_argument('projects', metavar='PROJECT', nargs='*', help='''projects (by name or path) to operate on; see ACTIVE PROJECTS below''') return parser def do_run(self, args, user_args): def sha_thunk(project): self.die_if_no_git() if not project.is_cloned(): self.die( f'cannot get sha for uncloned project {project.name}; ' f'run "west update {project.name}" and retry') elif isinstance(project, ManifestProject): return f'{"N/A":40}' else: return project.sha(MANIFEST_REV) def cloned_thunk(project): self.die_if_no_git() return "cloned" if project.is_cloned() else "not-cloned" def active_thunk(project): self.die_if_no_git() return "active" if self.manifest.is_active(project) else "inactive" def delay(func, project): return DelayFormat(partial(func, project)) if args.inactive and args.projects: self.parser.error('-i cannot be combined with an explicit project ' 'list') for project in self._projects(args.projects): # Include the project based on the inactive flag. If the flag is # set, include only inactive projects. Otherwise, include only # active ones. include = self.manifest.is_active(project) != bool(args.inactive) # Skip not included projects unless the user said # --all or named some projects explicitly. if not (args.all or args.projects or include): self.dbg(f'{project.name}: skipping project') continue # Spelling out the format keys explicitly here gives us # future-proofing if the internal Project representation # ever changes. # # Using DelayFormat delays computing derived values, such # as SHAs, unless they are specifically requested, and then # ensures they are only computed once. try: if isinstance(project, ManifestProject): # Special-case the manifest repository while it's # still showing up in the 'projects' list. Yet # more evidence we should tackle #327. if args.manifest_path_from_yaml: path = self.manifest.yaml_path apath = (abspath(os.path.join(self.topdir, path)) if path else None) ppath = Path(apath).as_posix() if apath else None else: path = self.manifest.repo_path apath = self.manifest.repo_abspath ppath = self.manifest.repo_posixpath else: path = project.path apath = project.abspath ppath = project.posixpath result = args.format.format( name=project.name, description=project.description or "None", url=project.url or 'N/A', path=path, abspath=apath, posixpath=ppath, revision=project.revision or 'N/A', clone_depth=project.clone_depth or "None", cloned=delay(cloned_thunk, project), active=delay(active_thunk, project), sha=delay(sha_thunk, project), groups=','.join(project.groups)) except KeyError as e: # The raised KeyError seems to just put the first # invalid argument in the args tuple, regardless of # how many unrecognizable keys there were. self.die(f'unknown key "{e.args[0]}" in format string ' f'{shlex.quote(args.format)}') except IndexError: self.parser.print_usage() self.die(f'invalid format string {shlex.quote(args.format)}') except subprocess.CalledProcessError: self.die(f'subprocess failed while listing {project.name}') self.inf(result, colorize=False) class ManifestCommand(_ProjectCommand): # The slightly weird naming is to avoid a conflict with # west.manifest.Manifest. def __init__(self): super().__init__( 'manifest', 'manage the west manifest', textwrap.dedent('''\ Manages the west manifest. The following actions are available. You must give exactly one. - --resolve: print the current manifest with all imports applied, as an equivalent single manifest file. Any imported manifests must be cloned locally (with "west update"). - --freeze: like --resolve, but with all project revisions converted to their current SHAs, based on the latest manifest-rev branches. All projects must be cloned (with "west update"). - --validate: print an error and exit the process unsuccessfully if the current manifest cannot be successfully parsed. If the manifest can be parsed, print nothing and exit successfully. - --path: print the path to the top level manifest file. If this file uses imports, it will not contain all the manifest data. - --untracked: print all files and directories inside the workspace that are not tracked or managed by west. This effectively means any file or directory that is outside all of the projects' directories on disk (regardless of whether those projects are active or inactive). This is similar to `git status` for untracked files. The output format is relative to the current working directory and is stable and suitable as input for scripting. If the manifest file does not use imports, and all project revisions are SHAs, the --freeze and --resolve output will be identical after a "west update". '''), accepts_unknown_args=False) def do_add_parser(self, parser_adder): parser = self._parser(parser_adder) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--resolve', action='store_true', help='print the manifest with all imports resolved') group.add_argument('--freeze', action='store_true', help='''print the resolved manifest with SHAs for all project revisions''') group.add_argument('--validate', action='store_true', help='''validate the current manifest, exiting with an error if there are issues''') group.add_argument('--path', action='store_true', help="print the top level manifest file's path") group.add_argument('--untracked', action='store_true', help='''print all files and directories not managed or tracked by west''') group = parser.add_argument_group('options for --resolve and --freeze') group.add_argument('-o', '--out', help='output file, default is standard output') group.add_argument('--active-only', action='store_true', help='only resolve active projects') return parser def do_run(self, args, user_args): manifest = self.manifest dump_kwargs = {'default_flow_style': False, 'sort_keys': False} if args.validate: pass # nothing more to do elif args.resolve: if not args.active_only: self._die_if_manifest_project_filter('resolve') self._dump(args, manifest.as_yaml(active_only=args.active_only, **dump_kwargs)) elif args.freeze: if not args.active_only: self._die_if_manifest_project_filter('freeze') self._dump(args, manifest.as_frozen_yaml(active_only=args.active_only, **dump_kwargs)) elif args.untracked: self._untracked() elif args.path: self.inf(manifest.path) else: # Can't happen. raise RuntimeError(f'internal error: unhandled args {args}') def _die_if_manifest_project_filter(self, action): if self.config.get('manifest.project-filter') is not None: self.die(f'"west manifest --{action}" is not (yet) supported ' 'when the manifest.project-filter option is set. ' f'Add --active-only to {action} only the projects ' 'currently active in the workspace. Alternatively, ' 'please clear the project-filter configuration ' 'option and re-run this command, or contact the ' 'west developers if you have a use case for resolving ' 'the manifest while projects are made inactive by the ' 'project filter.') def _untracked(self): ''' "Performs a top-down search of the west topdir, ignoring every directory that corresponds to a west project. ''' ppaths = [] untracked = [] for project in self._projects(None): # We do not check for self.manifest.is_active(project) because # inactive projects are still considered "tracked directories". ppaths.append(Path(project.abspath)) # Since west tolerates nested projects (i.e. a project inside the directory # of another project) we must sort the project paths to ensure that we # hit the "enclosing" project first when iterating. ppaths.sort() def _find_untracked(directory): '''There are three cases for each element in a directory: - It's a project -> Do nothing, ignore the directory. - There are no projects inside -> add to untracked list. - It's not a project directory but there are some projects inside it -> recurse. The directory argument cannot be inside a project, otherwise all bets are off. ''' self.dbg(f'looking for untracked files/directories in: {directory}') for e in [e.absolute() for e in directory.iterdir()]: if not e.is_dir() or e.is_symlink(): untracked.append(e) continue self.dbg(f'processing directory: {e}') for ppath in ppaths: # We cannot use samefile() because it requires the file # to exist (not always the case with inactive or even # uncloned projects). if ppath == e: # We hit a project root directory, skip it. break elif e in ppath.parents: self.dbg(f'recursing into: {e}') _find_untracked(e) break else: # This is not a project and there is no project inside. # Add to untracked elements. untracked.append(e) continue # Avoid using Path.walk() since that returns all files and directories under # a particular directory, which is overkill in our case. Instead, recurse # only when required. _find_untracked(Path(self.topdir)) # Exclude the .west directory, which is maintained by west try: untracked.remove((Path(self.topdir) / Path(WEST_DIR)).resolve()) except ValueError: self.die(f'Directory {WEST_DIR} not found in workspace') # Sort the results for displaying to the user. untracked.sort() for u in untracked: # We cannot use Path.relative_to(p, walk_up=True) because the # walk_up parameter was only added in 3.12 self.inf(os.path.relpath(u, Path.cwd())) def _dump(self, args, to_dump): if args.out: with open(args.out, 'w') as f: f.write(to_dump) else: sys.stdout.write(to_dump) class Compare(_ProjectCommand): def __init__(self): super().__init__( 'compare', "compare project status against the manifest", textwrap.dedent('''\ Compare each project's working tree state against the results of the most recent successful "west update" command. This command prints output for a project if (and only if) at least one of the following is true: 1. its checked out commit (HEAD) is different than the commit checked out by the most recent successful "west update" (which the manifest-rev branch will point to) 2. its working tree is not clean (i.e. there are local uncommitted changes) 3. it has a local checked out branch (unless the configuration option compare.ignore-branches is true or --ignore-branches is given on the command line, either of which disable this) The command also prints output for the manifest repository if it has nonempty status. The output is meant to be human-readable, and may change. It is not a stable interface to write scripts against. This command requires git 2.22 or later.''') ) def do_add_parser(self, parser_adder): parser = self._parser(parser_adder, epilog=ACTIVE_CLONED_PROJECTS_HELP) parser.add_argument('projects', metavar='PROJECT', nargs='*', help='''projects (by name or path) to operate on; defaults to active cloned projects''') parser.add_argument('-a', '--all', action='store_true', help='include output for inactive projects') parser.add_argument('--exit-code', action='store_true', help='''exit with status code 1 if status output was printed for any project''') parser.add_argument('--ignore-branches', default=None, action='store_true', help='''skip output for projects with checked out branches and clean working trees if the branch is at the same commit as the last "west update"''') parser.add_argument('--no-ignore-branches', dest='ignore_branches', action='store_false', help='''overrides a previous --ignore-branches or any compare.ignore-branches configuration option''') return parser def do_run(self, args, ignored): self.die_if_no_git() if self.git_version_info < (2, 22): # This is for git branch --show-current. self.die('git version 2.22 or later is required') if args.ignore_branches is not None: self.ignore_branches = args.ignore_branches else: self.ignore_branches = \ self.config.getboolean('compare.ignore-branches', False) failed = [] printed_output = False for project in self._cloned_projects(args, only_active=not args.all): if isinstance(project, ManifestProject): # West doesn't track the relationship between the manifest # repository and any remote, but users are still interested # in printing output for comparisons that makes sense. if self._has_nonempty_status(project): try: self.compare(project) printed_output = True except subprocess.CalledProcessError: failed.append(project) continue # 'git status' output for all projects is noisy when there # are lots of projects. # # We avoid this problem in 2 steps: # # 1. Check if we need to print any output for the # project. # # 2. If so, run 'git status' on the project. Otherwise, # skip output for the project entirely. # # In verbose mode, we always print output. def has_checked_out_branch(project): if self.ignore_branches: return False return bool(project.git(['branch', '--show-current'], capture_stdout=True, capture_stderr=True).stdout.strip()) try: if not (self.verbosity >= Verbosity.DBG or has_checked_out_branch(project) or (project.sha(QUAL_MANIFEST_REV) != project.sha('HEAD')) or self._has_nonempty_status(project)): continue self.compare(project) printed_output = True except subprocess.CalledProcessError: failed.append(project) self._handle_failed(args, failed) if args.exit_code and printed_output: raise CommandError(1) def compare(self, project): self.banner(f'{project.name_and_path}:') self.print_rev_info(project) self.print_status(project) def print_rev_info(self, project): # For non-manifest repositories, print HEAD's and # manifest-rev's SHAs and commit titles. # # We force git not to print in color so west's colored # banner() separators stand out more in the output. if isinstance(project, ManifestProject): return def rev_info(rev): title = project.git( ['log', '-1', '--color=never', '--pretty=%h%d %s', '--decorate-refs-exclude=refs/heads/manifest-rev', rev], capture_stdout=True, capture_stderr=True).stdout.decode().rstrip() # "HEAD" is special; '--decorate-refs-exclude=HEAD' doesn't work. # Fortunately it's always first. return ( title.replace('(HEAD) ', '').replace('(HEAD, ', '(') .replace('(HEAD -> ', '(') ) head_info = rev_info('HEAD') # If manifest-rev is missing, we already failed earlier. manifest_rev_info = rev_info('manifest-rev') self.small_banner(f'manifest-rev: {manifest_rev_info}') self.inf(f' HEAD: {head_info}') def print_status(self, project): # `git status` shows `manifest-rev` "sometimes", see #643. if self.color_ui: color = '-c status.color=always' else: color = '' cp = project.git(f'{color} status', capture_stdout=True, capture_stderr=True) self.small_banner('status:') self.inf(textwrap.indent(cp.stdout.decode().rstrip(), ' ' * 4)) class Diff(_ProjectCommand): def __init__(self): super().__init__( 'diff', '"git diff" for one or more projects', '''Runs "git diff" on each of the specified projects. Unknown arguments are passed to "git diff".''', accepts_unknown_args=True, ) def do_add_parser(self, parser_adder): parser = self._parser(parser_adder, epilog=ACTIVE_CLONED_PROJECTS_HELP) parser.add_argument('projects', metavar='PROJECT', nargs='*', help='''projects (by name or path) to operate on; defaults to active cloned projects''') parser.add_argument('-a', '--all', action='store_true', help='include output for inactive projects') parser.add_argument('-m', '--manifest', action='store_true', help='show changes relative to "manifest-rev"') return parser def do_run(self, args, user_args): self.die_if_no_git() failed = [] no_diff = 0 # We may need to force git to use colors if the user wants them, # which it won't do ordinarily since stdout is not a terminal. color = ['--color=always'] if self.color_ui else [] for project in self._cloned_projects(args, only_active=not args.all): diff_commit = ( ['manifest-rev'] # see #719 and #747 # Special-case the manifest repository while it's # still showing up in the 'projects' list. Yet # more evidence we should tackle #327. if args.manifest and not isinstance(project, ManifestProject) else [] ) # Use paths that are relative to the base directory to make it # easier to see where the changes are cp = project.git(['diff', f'--src-prefix={project.path}/', f'--dst-prefix={project.path}/', '--exit-code'] + color + diff_commit, extra_args=user_args, capture_stdout=True, capture_stderr=True, check=False) # We cannot trust --exit-code alone, for instance merge # conflicts return 0 with (at least) git version 2.46.0. See # west issue #731 some_diff = cp.returncode == 1 or (cp.returncode == 0 and len(cp.stdout) > 0) if not some_diff: no_diff += 1 if some_diff or self.verbosity >= Verbosity.DBG: self.banner(f'diff for {project.name_and_path}:') self.inf(cp.stdout.decode('utf-8')) self.inf(cp.stderr.decode('utf-8')) if cp.returncode > 1: failed.append(project) if failed: self._handle_failed(args, failed) elif self.verbosity <= Verbosity.INF: self.inf(f"Empty diff in {no_diff} projects.") class Status(_ProjectCommand): def __init__(self): super().__init__( 'status', '"git status" for one or more projects', '''Runs "git status" for each of the specified projects. Unknown arguments are passed to "git status". Note: If you are looking to find untracked files and directories in the workspace use "west manifest --untracked".''', accepts_unknown_args=True, ) def do_add_parser(self, parser_adder): parser = self._parser(parser_adder, epilog=ACTIVE_CLONED_PROJECTS_HELP) parser.add_argument('projects', metavar='PROJECT', nargs='*', help='''projects (by name or path) to operate on; defaults to active cloned projects''') parser.add_argument('-a', '--all', action='store_true', help='include output for inactive projects') return parser def do_run(self, args, user_args): self.die_if_no_git() failed = [] for project in self._cloned_projects(args, only_active=not args.all): # 'git status' output for all projects is noisy when there # are lots of projects. # # We avoid this problem in 2 steps: # # 1. Check if we need to print any output for the # project. # # 2. If so, run 'git status' on the project. Otherwise, # skip output for the project entirely. # # In verbose mode, we always print output. try: if not (self.verbosity >= Verbosity.DBG or self._has_nonempty_status(project)): continue self.banner(f'status of {project.name_and_path}:') project.git('status', extra_args=user_args) except subprocess.CalledProcessError: failed.append(project) self._handle_failed(args, failed) class Update(_ProjectCommand): def __init__(self): super().__init__( 'update', 'update projects described in west manifest', textwrap.dedent('''\ Updates active projects defined in the manifest file as follows: 1. Clone the project if necessary 2. If necessary, fetch the project's revision from its remote (see "fetching behavior" below) 3. Reset the manifest-rev branch to the current manifest revision 4. Check out the new manifest-rev commit as a detached HEAD (the default), or keep/rebase existing checked out branches (see "checked out branch behavior") You must have already created a west workspace with "west init". This command does not alter the manifest repository's contents.''') ) def do_add_parser(self, parser_adder): parser = self._parser(parser_adder) parser.add_argument('--stats', action='store_true', help='''print performance statistics for update operations''') group = parser.add_argument_group( title='local project clone caches', description=textwrap.dedent('''\ Projects are usually initialized by fetching from their URLs, but they can also be cloned from caches on the local file system.''')) group.add_argument('--name-cache', help='''cached repositories are in subdirectories matching the names of projects to update. This cache has highest priority (Prio 0).''') group.add_argument('--path-cache', help='''cached repositories are in the same relative paths as the workspace being updated. This cache has lower priority (Prio 1).''') group.add_argument('--auto-cache', help='''automatically setup local cache repositories in a flat folder hierarchy, but with an additional subfolder (hashed name) for different remote URLs. Each local cache repository is automatically cloned on first usage and synced on subsequent clones. This cache has the lowest priority (Prio 2).''') parser.epilog = textwrap.dedent('''\ CACHING ------- Projects are typically initialized by fetching from remote URLs. However, they can also be cloned from local caches on the file system. Three types of caches are supported, and they may be used together. They are searched in the following order of priority: - Priority 0: --name-cache - Priority 1: --path-cache - Priority 2: --auto-cache When using local caches, after the initial setup of a workspace the remote URL of each repo is switched back to its original remote. As a result, subsequent manual updates (git pull) fetch changes directly from the original remote. Also in case of name-cache and path-cache, the local caches are not used during subsequent updates. They are only used during the initial workspace setup. Only in case of auto-cache the 'west update' process updates the local caches first, which then serve as the source for pulling changes into the workspace. Example: Assume your manifest describes this workspace structure: (workspace) ├── bar └── subdir └── foo The local caches must be structured as follows: > Name Cache Repositories should be present in a flat folder hierarchy. The cache is searched by the repository name (according to the workspace manifest). (name cache directory) ├── bar └── foo > Path Cache Repositories should be present in a folder hierarchy that matches the workspace's path layout. (path cache directory) ├── bar └── subdir └── foo > Auto Cache Use this when you prefer not to manage local caches manually. The complete folder hierarchy is setup automatically. Each repository is stored under a directory named after the basename of its remote URL. To prevent conflicts between repos with same name, a hash of the remote URL is used as subfolder. Note: Each local cache repo is automatically synced on subsequent updates. (auto cache directory) ├── bar.git │ ├── │ └── .info # contains metadata about the hash └── foo.git ├── └── .info # contains metadata about the hash ''') group = parser.add_argument_group( title='fetching behavior', description='By default, west update tries to avoid fetching.') group.add_argument('-f', '--fetch', dest='fetch_strategy', choices=['always', 'smart'], help='''how to fetch projects when updating: "always" fetches every project before update, while "smart" (default) skips fetching projects whose revisions are SHAs or tags available locally''') group.add_argument('-o', '--fetch-opt', action='append', default=[], help='''additional option to pass to 'git fetch' if fetching is necessary (e.g. 'o=--depth=1'); may be given more than once''') group.add_argument('-n', '--narrow', action='store_true', help='''fetch just the project revision if fetching is necessary; do not pass --tags to git fetch (may not work for SHA revisions depending on the Git host)''') group = parser.add_argument_group( title='checked out branch behavior', description=textwrap.dedent('''\ By default, locally checked out branches are left behind when manifest-rev commits are checked out.''')) group.add_argument('-k', '--keep-descendants', action='store_true', help='''if a checked out branch is a descendant of the new manifest-rev, leave it checked out instead (takes priority over --rebase)''') group.add_argument('-r', '--rebase', action='store_true', help='''rebase any checked out branch onto the new manifest-rev instead (leaving behind partial rebases on error)''') group = parser.add_argument_group( title='advanced options') group.add_argument('--group-filter', '--gf', action='append', default=[], metavar='FILTER', dest='group_filter', help='''proceed as if FILTER was appended to manifest.group-filter; may be given multiple times''') group.add_argument('--submodule-init-config', action='append', default=[], help='''git configuration option to set when running 'git submodule init' in '