datalad-core/datalad_core/git_utils/status.py
Michael Hanke 1834f8ac57
Some checks failed
Codespell / Check for spelling errors (push) Successful in 1m0s
Ruff / Code linting (push) Successful in 1m15s
Type annotation (project) / check (push) Successful in 1m32s
Unit tests (Linux) / check (push) Has been cancelled
feat(iter_repo_status): support pathspecs
2026-06-09 13:38:44 +02:00

60 lines
2.4 KiB
Python

from collections.abc import Iterable
from pathlib import (
Path,
PurePosixPath,
)
from datasalad.gitpathspec import GitPathSpecs
from datalad_core.git_utils import types as gt
from datalad_core.runners import iter_git_subproc_zlines
def iter_repo_status(
repository: Path,
*,
untracked_files: gt.UntrackedFilesMode | None = None,
ignore_submodules: gt.IgnoreSubmodulesMode | None = None,
pathspecs: GitPathSpecs | None = None,
) -> Iterable[
gt.RepoIgnoredRecord | gt.RepoUntrackedRecord | gt.RepoModificationRecord
]:
"""Front-end for `git status --porcelain=2`
The output of the `status` command is yielded as individual records
(one per path), with dedicated types used for each of the different
record types. The values for ``untracked_files`` and ``ignore_submodules``
are passed to ``--untracked-files`` and ``--ignore-submodules``,
respectively, using the exact same semantics. Constraining the
report to content matching a set of pathspecs is also supported.
"""
cmd = ['status', '-z', '--porcelain=2', '--no-renames']
if untracked_files is not None:
cmd.append(f'--untracked-files={untracked_files}')
if ignore_submodules is not None:
cmd.append(f'--ignore-submodules={ignore_submodules}')
if pathspecs:
cmd.append('--')
cmd.extend(pathspecs.arglist())
for line in iter_git_subproc_zlines(cmd, cwd=repository):
comp = line.split(' ', maxsplit=8)
match comp[0]:
case '!':
yield gt.RepoIgnoredRecord(path=PurePosixPath(comp[1]))
case '?':
yield gt.RepoUntrackedRecord(path=PurePosixPath(comp[1]))
case '1':
yield gt.RepoModificationRecord(
modification=gt.ModificationState.from_str(comp[1]),
submodule_state=gt.SubmoduleChange.from_str(comp[2]),
mode_head=gt.GitObjectMode.from_str(comp[3]),
mode_index=gt.GitObjectMode.from_str(comp[4]),
mode_worktree=gt.GitObjectMode.from_str(comp[5]),
name_head=comp[6],
name_index=comp[7],
path=PurePosixPath(comp[8]),
)
case _:
msg = f'Got unexpected modification report from git-status {line!r}'
raise RuntimeError(msg)