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 verifiedgithub-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
beforeSHA 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_hotfixmatches 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 logpretty-format placeholders for a single commit: full SHA, then aNUL, then the raw body.Paired with
git log -z(which terminates each commit’s output with aNUL), this frames the stream as alternating(hash, message)tokens. Commit messages may contain newlines but neverNULbytes, so splitting onNULrecovers 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-leasepush loses its lease.The client reports
(stale info)when it sees the branch moved, and the server reportscannot lock ref '…': is at X but expected Ywhen the branch moves during the push itself.
- exception repomatic.git_ops.GitError(returncode, cmd, output=None, stderr=None)[source]¶
Bases:
CalledProcessError,RuntimeErrorA
gitcommand that exited with a non-zero status.The message carries what git wrote to its standard error. The message of a plain
CalledProcessErrornames 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, likeGhCommandError, so a caller handling any failed external command catches it too.
- exception repomatic.git_ops.LeaseRejected(returncode, cmd, output=None, stderr=None)[source]¶
Bases:
GitErrorA
--force-with-leasepush 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:
NamedTupleA 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
gitCLI feeds these two fields directly.Create new instance of Commit(hash, msg)
- repomatic.git_ops.list_commits(start, end)[source]¶
Return the commits in the
start..endrange, 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.
- repomatic.git_ops.commit_exists(ref)[source]¶
Return
Trueif ref resolves to a commit object present locally.- Return type:
- repomatic.git_ops.current_branch()[source]¶
Return the checked-out branch name, or
NonewhenHEADis detached.
- 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 addcannot hand its diff to whatever is committed next. Untracked files stay where they are.- Return type:
- 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 toHEADtouches them.
- repomatic.git_ops.show_file(ref, path)[source]¶
Return the content of path at ref, read from the object store.
Neither
HEADnor the working tree moves, so the read is safe in any checkout, uncommitted changes included.
- repomatic.git_ops.restore_paths(ref, paths)[source]¶
Overwrite paths in the working tree with the content they hold at ref.
HEADstays 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 agit checkoutof 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:
- Return type:
- Returns:
The paths actually restored, as repository-relative pathspecs.
- repomatic.git_ops.is_shallow()[source]¶
Return
Truewhen the repository is a shallow clone.- Return type:
- 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.
Deepen a shallow clone until start and end share history.
start..endresolves 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 byfetch_commit()is a boundary of its own. So both commits being present is not enough: this deepens the clone untilmerge_base()finds the commit they share.- Parameters:
- Return type:
- Returns:
Trueonce the two commits share history.Falsewhen 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.
- 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:
- repomatic.git_ops.count_commits_between(start, end)[source]¶
Return the number of commits in the
start..endrange.Follows git range semantics: start is excluded, end is included.
- Return type:
- repomatic.git_ops.is_ancestor(maybe_ancestor, ref)[source]¶
Return whether maybe_ancestor is reachable from ref.
- repomatic.git_ops.merge_base(left, right)[source]¶
Return the best common ancestor of two commits, or
Noneif unrelated.Nonealso covers the shallow-clone case described inis_ancestor(), and a commit absent from the clone.
- repomatic.git_ops.rebase_onto(new_base, old_base, branch)[source]¶
Replay
old_base..branchon top of new_base, keeping the replayed side.--strategy-option=theirsresolves 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:
- Returns:
Trueon success. On conflict the rebase is aborted andFalsereturned, 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
HEADand 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:
- 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
finallythat 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:
- 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 addexits 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.
- 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:
- repomatic.git_ops.commit_tracked(message)[source]¶
Commit every change to a tracked file as the CI bot.
Stages what
git commit --alltakes: 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.
- 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/checkoutconfigures a single-branch fetch refspec, under which a baregit fetch origin {branch}updatesFETCH_HEADbut leavesrefs/remotes/{remote}/{branch}absent. Writing the remote-tracking ref is what later lets a push take a--force-with-leaseon it.
- 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-leaseguard: the push is refused when the branch moved in between, rather than silently discarding the other writer’s commit. PassNoneto 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:
- repomatic.git_ops.delete_remote_branch(branch, remote='origin')[source]¶
Delete branch from remote, tolerating a branch already gone.
- Return type:
- 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
- repomatic.git_ops.get_repo_slug_from_remote(remote='origin')[source]¶
Extract the
owner/reposlug from a git remote URL.Reads both HTTPS and SSH GitHub remotes, through
parse_github_repo(). ReturnsNoneif the remote is not set, not a GitHub URL, or git is unavailable.
- repomatic.git_ops.get_latest_tag_version()[source]¶
Return the highest release version among the
vX.Y.Ztags.
- 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.Zand 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.
- 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_existingis True, it returns False without failing. This allows safe re-runs of workflows that were interrupted after tag creation but before other steps.- Parameters:
- Return type:
- 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.