repomatic.git_ops module

Git operations for GitHub Actions workflows.

This module provides utilities for common Git operations in CI/CD contexts, with idempotent behavior to allow safe re-runs of failed workflows.

All operations follow a “belt-and-suspenders” approach: combine workflow timing guarantees (like workflow_run ensuring tags exist) with idempotent guards (like skip_existing on tag creation). This ensures correctness in the face of race conditions, API eventual consistency, and partial failures that are common in GitHub Actions.

Every git failure raises GitError, which carries git’s own error output. A function returns None or False instead only when it is a probe, whose question a failure answers.

Warning

Tag push requires REPOMATIC_PAT

Tags pushed with the default GITHUB_TOKEN do not trigger downstream on.push.tags workflows. The custom PAT is required so that tagging a release commit actually fires the publish and release creation jobs.

repomatic.git_ops.COMMIT_IDENTITY_EMAIL = '41898282+github-actions[bot]@users.noreply.github.com'

Commit author email for automated commits: GitHub’s own Actions bot user.

The 41898282+ prefix is the bot’s stable user ID, which makes GitHub link the commit to the verified github-actions[bot] account.

repomatic.git_ops.COMMIT_IDENTITY_NAME = 'github-actions[bot]'

Commit author name for automated commits.

repomatic.git_ops.SHORT_SHA_LENGTH = 7

Default SHA length hard-coded to 7.

Caution

The default is subject to change and depends on the size of the repository.

repomatic.git_ops.NULL_SHA = '0000000000000000000000000000000000000000'

The null SHA used by Git to represent a non-existent commit.

GitHub sends this value as the before SHA of a push that creates a branch or a tag, since there is no previous commit to compare against.

repomatic.git_ops.VERSION_TAG_GLOB = 'v[0-9]*.[0-9]*.[0-9]*'

Shell glob that selects the release tags in git tag --list.

A glob is no PEP 440 filter: v1.2.3_hotfix matches it. So every tag it selects is parsed, and a tag naming no version is skipped.

repomatic.git_ops.GIT_LOG_FORMAT = '%H%x00%B'

git log pretty-format placeholders for a single commit: full SHA, then a NUL, then the raw body.

Paired with git log -z (which terminates each commit’s output with a NUL), this frames the stream as alternating (hash, message) tokens. Commit messages may contain newlines but never NUL bytes, so splitting on NUL recovers the fields unambiguously even for multi-line messages.

repomatic.git_ops.LEASE_REJECTION_MARKERS = ('stale info', 'but expected')

What git prints when a --force-with-lease push loses its lease.

The client reports (stale info) when it sees the branch moved, and the server reports cannot lock ref '…': is at X but expected Y when the branch moves during the push itself.

exception repomatic.git_ops.GitError(returncode, cmd, output=None, stderr=None)[source]

Bases: CalledProcessError, RuntimeError

A git command that exited with a non-zero status.

The message carries what git wrote to its standard error. The message of a plain CalledProcessError names only the command and the exit code, which leaves a CI failure with no way to tell a lease rejection from a permission error.

Also a RuntimeError, like GhCommandError, so a caller handling any failed external command catches it too.

exception repomatic.git_ops.LeaseRejected(returncode, cmd, output=None, stderr=None)[source]

Bases: GitError

A --force-with-lease push refused because the branch moved.

Another writer published to the branch after the caller read its tip. force_push_branch() raises it so a caller can tell this lost race from a permission or a network failure, and handle the race on its own.

class repomatic.git_ops.Commit(hash, msg)[source]

Bases: NamedTuple

A minimal git commit.

Only the hash and message are ever consumed downstream, so a full git library object (with diffs, modified-file analysis, and complexity metrics) is unnecessary: the git CLI feeds these two fields directly.

Create new instance of Commit(hash, msg)

hash: str

The commit’s full 40-character SHA-1 hash.

msg: str

The commit message, stripped of surrounding whitespace.

repomatic.git_ops.get_commit(ref='HEAD')[source]

Return the commit at ref.

Raises:

GitError – if ref does not resolve to a commit present in the repository.

Return type:

Commit

repomatic.git_ops.list_commits(start, end)[source]

Return the commits in the start..end range, oldest first.

Follows git range semantics: start is excluded, end is included. Both endpoints must already share history locally, so a shallow clone goes through deepen_until_related() first.

Return type:

tuple[Commit, ...]

repomatic.git_ops.commit_exists(ref)[source]

Return True if ref resolves to a commit object present locally.

Return type:

bool

repomatic.git_ops.head_sha()[source]

Return the full SHA of the current HEAD commit.

Return type:

str

repomatic.git_ops.current_branch()[source]

Return the checked-out branch name, or None when HEAD is detached.

Return type:

str | None

repomatic.git_ops.checkout(ref)[source]

Check out ref (a branch name or commit SHA).

Return type:

None

repomatic.git_ops.discard_changes()[source]

Put the index and the working tree back to HEAD.

Staged changes go too, a file staged as new included: a commit that failed after its git add cannot hand its diff to whatever is committed next. Untracked files stay where they are.

Return type:

None

repomatic.git_ops.changed_paths()[source]

Return the tracked paths whose index or working tree differs from HEAD.

What discard_changes() would throw away: a staged change and an unstaged one both count, an added or a deleted file included, and a rename counts as its two paths. Untracked files do not, since no reset to HEAD touches them.

Return type:

tuple[str, ...]

Returns:

The paths, sorted. Empty on a clean tree.

repomatic.git_ops.show_file(ref, path)[source]

Return the content of path at ref, read from the object store.

Neither HEAD nor the working tree moves, so the read is safe in any checkout, uncommitted changes included.

Parameters:
  • ref (str) – Any tree-ish: a branch, a tag, or a commit SHA.

  • path (str) – File path, relative to the current directory.

Return type:

str | None

Returns:

The file content, or None when ref holds no such file.

repomatic.git_ops.restore_paths(ref, paths)[source]

Overwrite paths in the working tree with the content they hold at ref.

HEAD stays where it is, so the checkout keeps the source tree and lock file it was cloned with and only the named files travel. That is the whole point over a git checkout of the branch: a job reading a file back from an open pull request still runs the code of the branch it was called on.

A path ref does not carry is skipped rather than deleted. The caller names the files it means to read, and one missing from ref is the first-run case, not an instruction to remove anything.

Parameters:
  • ref (str) – Any tree-ish: a branch, a tag, or a commit SHA.

  • paths (Sequence[str | Path]) – Files to restore, absolute or relative to the current directory. One outside the working tree is skipped.

Return type:

tuple[str, ...]

Returns:

The paths actually restored, as repository-relative pathspecs.

repomatic.git_ops.is_shallow()[source]

Return True when the repository is a shallow clone.

Return type:

bool

repomatic.git_ops.fetch_commit(sha, remote='origin')[source]

Make the commit sha present locally, fetching it when it is absent.

A shallow clone fetches the commit alone (--depth=1): its tree is all a comparison needs, and the history behind it can be large. A complete clone fetches without a depth, so it stays complete.

Parameters:
  • sha (str) – Full SHA of the commit.

  • remote (str) – Remote to fetch from.

Return type:

bool

Returns:

True when the commit is present afterwards. False when the remote does not serve it, like a commit a force-push left unreachable.

Deepen a shallow clone until start and end share history.

start..end resolves only once git can walk down from end to a commit that start also reaches. A shallow clone cuts that walk at its boundary, and a commit fetched on its own by fetch_commit() is a boundary of its own. So both commits being present is not enough: this deepens the clone until merge_base() finds the commit they share.

Parameters:
  • start (str) – The commit the range starts from.

  • end (str) – The commit the range ends at.

  • attempts (int) – Maximum number of deepening fetches.

  • depth (int) – Commits each fetch adds below the shallow boundary.

Return type:

bool

Returns:

True once the two commits share history. False when they still do not after every fetch, or when the clone is complete and a fetch cannot add anything.

Raises:

GitError – When a fetch fails.

repomatic.git_ops.diff_names(start, end)[source]

Return the paths that differ between start and end.

Raises:

GitError – if either ref is unknown.

Return type:

tuple[str, ...]

repomatic.git_ops.tree_sha(ref='HEAD')[source]

Return the SHA of the tree ref points at.

Two commits sharing a tree SHA carry byte-identical content, whatever their message, author or parent. That makes this the cheapest way to ask whether re-running a generator produced anything new.

Return type:

str

repomatic.git_ops.count_commits_between(start, end)[source]

Return the number of commits in the start..end range.

Follows git range semantics: start is excluded, end is included.

Return type:

int

repomatic.git_ops.is_ancestor(maybe_ancestor, ref)[source]

Return whether maybe_ancestor is reachable from ref.

Return type:

bool | None

Returns:

True or False when git can relate the two commits, and None when it cannot: a shallow clone whose grafted history stops before their common ancestor answers neither yes nor no.

repomatic.git_ops.merge_base(left, right)[source]

Return the best common ancestor of two commits, or None if unrelated.

None also covers the shallow-clone case described in is_ancestor(), and a commit absent from the clone.

Return type:

str | None

repomatic.git_ops.rebase_onto(new_base, old_base, branch)[source]

Replay old_base..branch on top of new_base, keeping the replayed side.

--strategy-option=theirs resolves overlaps in favour of the commits being replayed, which for a generated branch means the freshly generated content wins over whatever the new base happens to carry.

Return type:

bool

Returns:

True on success. On conflict the rebase is aborted and False returned, leaving branch exactly as it was: a branch built on a slightly stale base still opens a usable pull request, and the next run converges it, so this is not worth failing the job over.

repomatic.git_ops.create_branch(name)[source]

Create or reset branch name at HEAD and switch to it.

The index and working tree carry over untouched, so staged changes made before the call survive into a commit made after it.

Return type:

None

repomatic.git_ops.delete_branch(name)[source]

Delete the local branch name, even when unmerged.

Tolerates a branch that is not there. Callers reach this from a finally that cleans up a scratch branch, where the failure being cleaned up after may be the very thing that stopped the branch from being created: raising here would replace the real error with a confusing one.

Return type:

None

repomatic.git_ops.stage_all(paths=())[source]

Stage working-tree changes, untracked files included.

Stages the whole tree by default. paths narrows that to a git pathspec list, for a job whose own steps leave more behind than they mean to commit: a linter installed into the checkout, a lock file a package manager rewrote on the way past. Anything outside the pathspec stays dirty and is left for the caller to restore or discard.

A pathspec matching nothing is dropped rather than fatal. git add exits 128 on the first one it cannot resolve and stages nothing at all, so a glob covering output a run happened not to produce would take the whole job down with it. Filtering first also keeps one stale entry in a list from silently costing the others their staging.

Parameters:

paths (Sequence[str]) – Git pathspecs to stage. Empty stages everything.

Return type:

bool

Returns:

True when the index ends up carrying something to commit.

repomatic.git_ops.commit_staged(message)[source]

Commit the staged tree as the CI bot and return the new commit SHA.

The identity is supplied per-command via -c, since CI checkouts carry no git identity of their own.

Return type:

str

repomatic.git_ops.commit_tracked(message)[source]

Commit every change to a tracked file as the CI bot.

Stages what git commit --all takes: modified and deleted tracked files. An untracked file stays out of the commit, so nothing a tool leaves behind in the checkout can ride along.

Parameters:

message (str) – The commit message.

Return type:

str

Returns:

The SHA of the new commit.

Raises:

GitError – When no tracked file changed, or when git cannot commit.

repomatic.git_ops.fetch_remote_branch(branch, remote='origin')[source]

Fetch branch into its remote-tracking ref and return the SHA.

The refspec is explicit because actions/checkout configures a single-branch fetch refspec, under which a bare git fetch origin {branch} updates FETCH_HEAD but leaves refs/remotes/{remote}/{branch} absent. Writing the remote-tracking ref is what later lets a push take a --force-with-lease on it.

Return type:

str | None

Returns:

The remote branch tip, or None when the branch does not exist on the remote.

repomatic.git_ops.force_push_branch(local_ref, branch, expected_sha, remote='origin')[source]

Publish local_ref as branch on remote, overwriting what is there.

expected_sha is the remote tip the caller last observed, which becomes a --force-with-lease guard: the push is refused when the branch moved in between, rather than silently discarding the other writer’s commit. Pass None to create a branch that does not exist yet, where a plain push already fails if someone wins the race.

Raises:
  • LeaseRejected – When the branch moved since expected_sha was read.

  • GitError – When the push is rejected for any other reason.

Return type:

None

repomatic.git_ops.delete_remote_branch(branch, remote='origin')[source]

Delete branch from remote, tolerating a branch already gone.

Return type:

None

repomatic.git_ops.list_contributor_identities()[source]

Return every author and committer identity found in the history.

No normalization happens: all variations of author and committer strings attached to all commits are returned as-is, in Name <email> form.

For format output syntax, see: https://git-scm.com/docs/pretty-formats#Documentation/pretty-formats.txt-aN

Raises:

GitError – When git cannot read the history.

Return type:

set[str]

repomatic.git_ops.get_repo_slug_from_remote(remote='origin')[source]

Extract the owner/repo slug from a git remote URL.

Reads both HTTPS and SSH GitHub remotes, through parse_github_repo(). Returns None if the remote is not set, not a GitHub URL, or git is unavailable.

Return type:

str | None

repomatic.git_ops.get_latest_tag_version()[source]

Return the highest release version among the vX.Y.Z tags.

Return type:

Version | None

Returns:

The version, or None when no tag names one.

Raises:

GitError – When git cannot list the tags.

repomatic.git_ops.get_release_version_from_commits(max_count=10)[source]

Extract release version from recent commit messages.

Searches recent commits for messages matching the pattern [changelog] Release vX.Y.Z and returns the version from the most recent match.

This provides a fallback when tags haven’t been pushed yet due to race conditions between workflows. The release commit message contains the version information before the tag is created.

Parameters:

max_count (int) – Maximum number of commits to search.

Return type:

Version | None

Returns:

The version from the most recent release commit, or None if not found.

repomatic.git_ops.get_all_version_tags()[source]

Map every release version to the date of its tag.

Return type:

dict[str, str]

Returns:

Version strings (without the v prefix) mapped to dates in YYYY-MM-DD format.

Raises:

GitError – When git cannot list the tags.

repomatic.git_ops.create_and_push_tag(tag, commit=None, push=True, skip_existing=True)[source]

Create and optionally push a Git tag.

This function is idempotent: if the tag already exists and skip_existing is True, it returns False without failing. This allows safe re-runs of workflows that were interrupted after tag creation but before other steps.

Parameters:
  • tag (str) – The tag name to create.

  • commit (str | None) – The commit to tag. Defaults to HEAD.

  • push (bool) – Whether to push the tag to the origin remote.

  • skip_existing (bool) – If True, skip silently when tag exists. If False, raise an error. Defaults to True.

Return type:

bool

Returns:

True if the tag was created, False if it already existed.

Raises:
  • ValueError – If tag exists and skip_existing is False.

  • GitError – If Git operations fail.