Skip to content

livery.git

livery.git

Git access for the livery ecosystem, every call a function of the repository's root.

Reach for the named reader or mover first: livery.git.position for where a checkout stands, livery.git.fetch and livery.git.push_force for the network, livery.git.commit_all for a commit. livery.git.run and livery.git.call are the door for a subcommand no function names yet: run raises livery.git.GitError on a non-zero exit, call returns the result whatever the code.

Nothing is held between calls, so a function may be called from any process at any time and answers what git holds at that moment.

The package is also a footman plugin, plugin("livery.git"): its hook gives every task's git the ssh command that shares one connection per host (livery.git.ssh_environment), the tools' identity when the person has none (livery.git.tool_identity), an editor that never opens, and what a task marks for itself with livery.git.identity and livery.git.unsigned.

The state store, JSON rows on git refs, is here too: a livery.git.StateStore built with a caller's policy, the livery.git.Series and livery.git.Keyed declarations that read and write through it, and the snapshots that make a run's reads one listing and one fetch.

Classes:

Name Description
GitError

A git command failed; the message carries git's words verbatim.

Fetched

What fetch_store did: the mirror's size, why it failed, the refs that moved.

Keyed

A family of series under one prefix, one ref per key.

Read

What a read found: the files, the lease, and whether it could answer.

Row

One row of a series: the file it came from and its fields.

Rows

What a series read found: the rows, what it skipped, and whether it could answer.

Series

A shared ref's declaration: its rows' schema, its window, and who may write it.

Skipped

A file a read passed over: its name and why.

StateStore

A checkout's state store and the policy its builder gave it.

Functions:

Name Description
config_environment

pairs as git configuration riding the environment, after what it carries.

identity_environment

The variables that make every commit and tag by name and email.

tool_identity

The name and address a tool called prog commits under.

identity

Make the decorated task's commits carry name and email, whatever git says.

unsigned

Turn commit and tag signing off for the decorated task's git.

add

Stage path as it stands in the working tree, a removal included.

add_remote

Add the remote name at url.

amend_all

Stage everything and fold it into HEAD, message kept.

any_head

branch's head sha: local when present, else the remote's, else empty.

author_email

The address the next commit in root would carry as its author.

behind_base

How many commits origin/<base> is ahead of HEAD.

blob_at

The text of the blob digest names in the object store; empty when none.

call

Run git with args in root and return the result whatever the exit code.

changed_between

The paths matching patterns that differ between old and new.

changed_paths

Repo-relative paths this branch touches, committed or not.

clean

Remove every untracked and ignored file but the patterns in keep; the paths.

commit_all

Stage everything and commit with message.

commit_message

ref's full commit message, subject and body.

commits_since

How many commits HEAD carries beyond ref.

config_get

The repository's git config value for key; empty when unset or no repository.

config_regexp

Every config key matching pattern, with its value, read in-process.

config_set

Set key to value in the repository's git config.

config_unset

Remove key from the repository's git config; a key already absent is fine.

conflicts_with_base

Whether merging origin/<base> into HEAD would conflict.

create_branch

Create and switch to name.

current_branch

The checked-out branch name; empty when detached.

delete_branch

Delete the local branch name, merged or not.

detach

Check ref out as a detached HEAD.

dirty_paths

The paths the working tree changed, staged or not, in status order.

fetch

Freshen origin/*, or the refs named, from origin.

fetch_tag

Take tag from origin as it is there, replacing the one held here.

fetch_tags

Freshen origin/* and take every tag origin holds.

file_at

The contents of path as committed at ref; empty when absent.

files_in_commit

The paths the commit at ref changed, against its first parent.

first_parent_trees

HEAD's tree id and its first-parent ancestors', newest first.

has_commits

Whether HEAD names a commit; false with no commit or no repository.

has_remote

Whether this clone has a remote called name; any other failure raises.

head_body

HEAD's commit body, without the subject.

head_message

HEAD's commit subject and its body, read in-process.

head_sha

The commit HEAD points at.

head_subject

HEAD's commit subject.

integrate

Merge origin/<base> into the current branch, after a fetch.

is_ancestor

Whether ancestor reaches descendant in this clone.

is_clean

Whether the working tree has no changes, staged or not.

last_commit_touching

The newest commit at or before ref that changed path; empty if none.

local_branch_exists

Whether branch exists locally.

local_branches

Local branch names under prefix (workflow/), short form.

log_paths

The subjects in span touching paths (a..b git range).

ls_files

The paths git lists under paths (the whole tree when none), sorted.

ls_remote

The refs remote holds among refs (every one when none is named), by sha.

main_checkout

The repository's main checkout, the same from any of its worktrees.

merge_base

The merge base of HEAD and origin/<base>; raises without one.

merge_parents

HEAD's two parents when HEAD is a merge: the base, then the head merged in.

merge_tree

The tree a merge of head onto base yields, written to this clone.

object_id

The object id spec names (HEAD:packages/forge is a tree id).

object_ids

The object ids ref holds at paths, read in-process.

oneline

The commits in span (a..b), one line each, newest first.

position

The checked-out branch name, empty when detached, and HEAD's commit.

push

Push branch to remote, setting upstream; force replaces what is there.

push_force

Force-push branch, leased on the last-seen remote state.

push_refspec

Push refspec to remote as given: a tag, or :refs/tags/x to delete one.

recent_commits

(sha, subject) for the newest count commits reachable from ref.

remote_branches

Branch names under prefix on origin, asked of the remote.

remote_head

origin/<branch>'s commit, or empty when it does not exist.

remote_tags

Tag names on origin, asked of the remote.

remote_url

The URL of the remote name.

remotes

The names of the repository's remotes.

reset_hard

Move the branch, the index and the working tree to ref; every change goes.

restore

Put paths back as HEAD has them; empty, or git's words when it could not.

run

Run git with args in root and return its standard output.

set_remote_url

Point the remote name at url.

sha_of

The commit ref resolves to; empty when this checkout cannot.

staged_text

path's text at index stage of a conflict; empty when that side has none.

subjects_ahead

The subjects of the commits HEAD carries beyond origin/<base>.

switch

Switch to the existing branch name.

switch_new

Create or reset the branch name at start (HEAD when empty); switch to it.

tag_dates

Every tag under prefix with the date it was made, YYYY-MM-DD.

tags

Every tag name the repository knows.

tracking_branches

Branch names under prefix among origin's remote-tracking refs.

tracks

Whether the repository holds the object spec names: HEAD:uv.lock, a sha.

tree_diff

The paths differing between the trees old and new.

unmerged_paths

The paths a stopped merge or rebase left conflicted, as git names them.

unpushed

The commits on any local branch that origin holds on no branch, one line each.

unstage

Take path out of the index and leave the file; an untracked path is fine.

working_tree_id

The tree id of the working tree as it stands.

worktree_add

Check ref out as a linked worktree at path, detached under detach.

worktree_remove

Remove the linked worktree at path, its changes with it.

master_up

Whether a master for url's host is up under socket_dir.

record_unsupported

Turn multiplexing off under socket_dir with words; the file written.

remote_host

The user, host and port an ssh remote url names; None for any other transport.

ssh_command

The GIT_SSH_COMMAND that multiplexes over a master under socket_dir.

ssh_environment

The environment that multiplexes a spawned git's ssh, or why not.

ssh_sockets

Where the plugin keeps its sockets: ssh under the runner's data_dir.

drop

Delete ref, on origin or in the checkout; "" when gone, else the reason.

fetch_store

Mirror the row series series under FETCHED_NAMESPACE and stamp it.

fetched_snapshot

Read the remote namespace from the checkout's mirror of origin, for the block.

list_refs

The refs under prefix by sha, remote or local; None when unlistable.

put

Write files onto ref, keeping what it already holds; "" or the reason.

read

Read ref's files, saying whether a miss is absence or failure.

remote_snapshot

Read the remote namespace through one listing for the block.

slug

name as a ref-safe and file-safe token: every other character is a dash.

sweep

The store's janitor: every series bounded, every orphan dropped; the lines.

Attributes:

Name Type Description
FETCHED
FETCHED_NAMESPACE
LOCAL_NAMESPACE
NAMESPACE
RUN_PREFIX
TRACE_NAMESPACE
WHOLE tuple[str, ...]
__version__

FETCHED module-attribute

FETCHED = Series('fetched', window=1, ci_only=False, schema=2, local=True)

FETCHED_NAMESPACE module-attribute

FETCHED_NAMESPACE = 'refs/workshop-origin/'

LOCAL_NAMESPACE module-attribute

LOCAL_NAMESPACE = 'refs/workshop-local/'

NAMESPACE module-attribute

NAMESPACE = 'refs/workshop/'

RUN_PREFIX module-attribute

RUN_PREFIX = NAMESPACE + 'run/'

TRACE_NAMESPACE module-attribute

TRACE_NAMESPACE = 'refs/workshop-trace/'

WHOLE module-attribute

WHOLE: tuple[str, ...] = ('',)

__all__ module-attribute

__all__ = ['FETCHED', 'FETCHED_NAMESPACE', 'LOCAL_NAMESPACE', 'NAMESPACE', 'RUN_PREFIX', 'TRACE_NAMESPACE', 'WHOLE', 'Fetched', 'GitError', 'Keyed', 'Read', 'Row', 'Rows', 'Series', 'Skipped', 'StateStore', '__version__', 'add', 'add_remote', 'amend_all', 'any_head', 'author_email', 'behind_base', 'blob_at', 'call', 'changed_between', 'changed_paths', 'clean', 'commit_all', 'commit_message', 'commits_since', 'config_environment', 'config_get', 'config_regexp', 'config_set', 'config_unset', 'conflicts_with_base', 'create_branch', 'current_branch', 'delete_branch', 'detach', 'dirty_paths', 'drop', 'fetch', 'fetch_store', 'fetch_tag', 'fetch_tags', 'fetched_snapshot', 'file_at', 'files_in_commit', 'first_parent_trees', 'has_commits', 'has_remote', 'head_body', 'head_message', 'head_sha', 'head_subject', 'identity', 'identity_environment', 'integrate', 'is_ancestor', 'is_clean', 'last_commit_touching', 'list_refs', 'local_branch_exists', 'local_branches', 'log_paths', 'ls_files', 'ls_remote', 'main_checkout', 'master_up', 'merge_base', 'merge_parents', 'merge_tree', 'object_id', 'object_ids', 'oneline', 'position', 'push', 'push_force', 'push_refspec', 'put', 'read', 'recent_commits', 'record_unsupported', 'remote_branches', 'remote_head', 'remote_host', 'remote_snapshot', 'remote_tags', 'remote_url', 'remotes', 'reset_hard', 'restore', 'run', 'set_remote_url', 'sha_of', 'slug', 'ssh_command', 'ssh_environment', 'ssh_sockets', 'staged_text', 'subjects_ahead', 'sweep', 'switch', 'switch_new', 'tag_dates', 'tags', 'tool_identity', 'tracking_branches', 'tracks', 'tree_diff', 'unmerged_paths', 'unpushed', 'unsigned', 'unstage', 'working_tree_id', 'worktree_add', 'worktree_remove']

__version__ module-attribute

__version__ = '0.3.0'

GitError

Bases: RuntimeError

A git command failed; the message carries git's words verbatim.

Fetched

Bases: NamedTuple

What fetch_store did: the mirror's size, why it failed, the refs that moved.

Attributes:

Name Type Description
held int

The refs the mirror holds after the fetch; zero when it failed.

why str

Empty, or why the fetch or the stamp failed, in git's words.

changed int

The refs this fetch added, moved or pruned; zero on a quiet origin.

held instance-attribute

held: int

The refs the mirror holds after the fetch; zero when it failed.

why instance-attribute

why: str

Empty, or why the fetch or the stamp failed, in git's words.

changed class-attribute instance-attribute

changed: int = 0

The refs this fetch added, moved or pruned; zero on a quiet origin.

Keyed dataclass

Keyed(name: str, keys: tuple[str, ...], window: int | None = None, ci_only: bool = True, schema: int = 1, local: bool = False, namespace: str = '', stale_after: timedelta | None = None, current: Callable[[Path], set[tuple[str, ...]] | None] | None = None, linger: timedelta | None = None, keep: Callable[[Path], int | None] | None = None, holds_rows: bool = True, blobs: str = '')

A family of series under one prefix, one ref per key.

The coverage record keeps one series per base and leg, the per-run halves one per run and leg. A family declares its key parts once: series makes the series of one key, with every part made ref-safe, and listed reads the keys the remote holds, so no caller spells a ref of the family itself.

Attributes:

Name Type Description
name str

The family's name under the namespace (coverage).

keys tuple[str, ...]

The names of the key's parts, in ref order (("leg", "package")).

window int | None

Every series' window; None keeps everything.

ci_only bool

Whether only a CI run may write the family.

schema int

The rows' schema, shared by every series.

local bool

Whether every series of the family is local, as for a livery.git.Series.

namespace str

The prefix every series of the family lives under, as for a livery.git.Series.

stale_after timedelta | None

How long a key's ref may live, by its commit time, before the janitor drops it as an orphan; None never drops by age.

current Callable[[Path], set[tuple[str, ...]] | None] | None

The keys the world still produces, from the checkout root, or None when it cannot tell; a listed key outside them is an orphan the janitor drops. None drops none.

linger timedelta | None

How long a key outside the current ones stays, by its ref's commit time, before the janitor drops it, so a run in flight that relies on it can still read it: a branch's coverage record is read by main's run for the squash that merged it, minutes after the branch is gone. None drops such a key at once.

keep Callable[[Path], int | None] | None

How many values of the key's first part the family keeps, read from the checkout root; the rest go. The parts are ranked by value, as numbers where they are numbers, so a forge's run id ranks by age without reading a commit. For a family keyed by a run, this is how many runs are kept. None, and a bound the callable cannot tell, keep everything.

holds_rows bool

Whether the family's series hold JSON rows the janitor bounds like any other series. A family of blobs (a leg's trace) says false: its files are not rows, and keep is the whole bound.

blobs str

The directory of every series' blobs, as for a livery.git.Series.

Methods:

Name Description
__post_init__
series

The series of one key, one part per declared key name.

at

The series of a key as its ref spells it, every part verbatim.

listed

The keys the remote holds under the leading parts head.

name instance-attribute

name: str

keys instance-attribute

keys: tuple[str, ...]

window class-attribute instance-attribute

window: int | None = None

ci_only class-attribute instance-attribute

ci_only: bool = True

schema class-attribute instance-attribute

schema: int = 1

local class-attribute instance-attribute

local: bool = False

namespace class-attribute instance-attribute

namespace: str = ''

stale_after class-attribute instance-attribute

stale_after: timedelta | None = None

current class-attribute instance-attribute

current: Callable[[Path], set[tuple[str, ...]] | None] | None = None

linger class-attribute instance-attribute

linger: timedelta | None = None

keep class-attribute instance-attribute

keep: Callable[[Path], int | None] | None = None

holds_rows class-attribute instance-attribute

holds_rows: bool = True

blobs class-attribute instance-attribute

blobs: str = ''

prefix property

prefix: str

The refs' common prefix, ending in a slash.

__post_init__

__post_init__() -> None
Source code in packages/git/src/livery/git/_store.py
def __post_init__(self) -> None:
    if self.local and self.ci_only:
        raise ValueError(
            f"{self.name}: a local family is written by local runs; declare"
            " it ci_only=False"
        )

series

series(*key: str) -> Series

The series of one key, one part per declared key name.

Raises:

Type Description
ValueError

When key has another number of parts.

Source code in packages/git/src/livery/git/_store.py
def series(self, *key: str) -> Series:
    """The series of one *key*, one part per declared key name.

    Raises:
        ValueError: When *key* has another number of parts.
    """
    return self.at(*(slug(part) for part in key))

at

at(*key: str) -> Series

The series of a key as its ref spells it, every part verbatim.

listed returns keys as their refs spell them, and a key written before the family made its parts ref-safe may spell a part another way; series would re-spell it and name a ref that does not exist. A listed key comes back through here.

Raises:

Type Description
ValueError

When key has another number of parts.

Source code in packages/git/src/livery/git/_store.py
def at(self, *key: str) -> Series:
    """The series of a *key* as its ref spells it, every part verbatim.

    `listed` returns keys as their refs spell them, and a key
    written before the family made its parts ref-safe may spell a
    part another way; `series` would re-spell it and name a ref
    that does not exist. A listed key comes back through here.

    Raises:
        ValueError: When *key* has another number of parts.
    """
    if len(key) != len(self.keys):
        raise ValueError(
            f"{self.name} is keyed by {', '.join(self.keys)}; got"
            f" {len(key)} part(s)"
        )
    return Series(
        "/".join((self.name, *key)),
        window=self.window,
        ci_only=self.ci_only,
        schema=self.schema,
        local=self.local,
        namespace=self.namespace,
        blobs=self.blobs,
    )

listed

listed(store: StateStore, *head: str) -> list[tuple[str, ...]] | None

The keys the remote holds under the leading parts head.

None when the remote cannot be listed. A ref under the prefix with another number of parts is not the family's and is left out.

Source code in packages/git/src/livery/git/_store.py
def listed(self, store: StateStore, *head: str) -> list[tuple[str, ...]] | None:
    """The keys the remote holds under the leading parts *head*.

    ``None`` when the remote cannot be listed. A ref under the
    prefix with another number of parts is not the family's and
    is left out.
    """
    prefix = self.prefix + "".join(slug(part) + "/" for part in head)
    refs = list_refs(store, prefix)
    if refs is None:
        return None
    keys = [tuple(name[len(self.prefix) :].split("/")) for name in refs]
    return sorted(key for key in keys if len(key) == len(self.keys))

Read dataclass

Read(files: dict[str, str] | None, sha: str | None, failed: bool, reason: str = '', names: tuple[str, ...] = ())

What a read found: the files, the lease, and whether it could answer.

Attributes:

Name Type Description
files dict[str, str] | None

The tree's files by name, or None when there is nothing to read; a read that named the files it wants holds those alone.

sha str | None

The commit the ref points at on the remote, the lease a write carries; None when the ref does not exist.

failed bool

Whether None means the transport could not answer for a ref that does exist, or a remote it could not reach, rather than a ref that has never been written. A reader may fall open on either; a writer refuses on a failure.

reason str

The transport's words when it could not answer.

names tuple[str, ...]

The name of every file the tree holds, read or not, sorted; empty when there is nothing to read.

files instance-attribute

files: dict[str, str] | None

sha instance-attribute

sha: str | None

failed instance-attribute

failed: bool

reason class-attribute instance-attribute

reason: str = ''

names class-attribute instance-attribute

names: tuple[str, ...] = ()

Row dataclass

Row(name: str, data: dict[str, Any])

One row of a series: the file it came from and its fields.

Attributes:

Name Type Description
name str

The file's name on the ref.

data dict[str, Any]

The row's fields, schema and when included.

name instance-attribute

name: str

data instance-attribute

data: dict[str, Any]

when property

when: str

When the store stamped the row, ISO 8601; empty when it never did.

Rows dataclass

Rows(rows: tuple[Row, ...], skipped: tuple[Skipped, ...] = (), failed: bool = False, reason: str = '', unread: tuple[str, ...] = (), blobs: Mapping[str, str] = dict())

What a series read found: the rows, what it skipped, and whether it could answer.

Attributes:

Name Type Description
rows tuple[Row, ...]

The rows of the series' schema, newest first.

skipped tuple[Skipped, ...]

One entry per file that is not such a row, naming the file and why; printing one gives the line.

failed bool

Whether the transport could not answer for a ref that exists, or reach the remote at all. An absent ref reads as no rows and no failure.

reason str

Why it could not answer, in the store's one wording.

unread tuple[str, ...]

The files a read that named the ones it wants passed over, by name, never read.

blobs Mapping[str, str]

The blobs the read was asked for, by name, each the text its writer wrote (livery.git.Series's blobs).

rows instance-attribute

rows: tuple[Row, ...]

skipped class-attribute instance-attribute

skipped: tuple[Skipped, ...] = ()

failed class-attribute instance-attribute

failed: bool = False

reason class-attribute instance-attribute

reason: str = ''

unread class-attribute instance-attribute

unread: tuple[str, ...] = ()

blobs class-attribute instance-attribute

blobs: Mapping[str, str] = field(default_factory=dict)

Series dataclass

Series(name: str, window: int | None = None, ci_only: bool = True, schema: int = 1, local: bool = False, age: timedelta | None = None, namespace: str = '', blobs: str = '')

A shared ref's declaration: its rows' schema, its window, and who may write it.

A series is one ref holding JSON rows of one schema, one file per row. rows and row read, put writes; the store stamps the schema and the time, keeps the window, and refuses what the declaration forbids, so a caller never parses a row, checks a schema, or trims a ref itself.

Attributes:

Name Type Description
name str

The ref's name under the namespace.

window int | None

The newest rows kept after every write, by the time the store stamped them; None keeps everything.

ci_only bool

Whether only a CI run may write it. Local runs read.

schema int

The rows' schema. A reader skips a row of another version and names it; a new field is the same version, a changed meaning is the next.

local bool

Whether the series lives in the checkout's git directory under refs/workshop-local/ instead of on the remote: never fetched or pushed, shared by the worktrees, written by local runs, so ci_only must be false.

age timedelta | None

How long a row stays before the janitor drops it, by the store's stamp; None keeps rows for the window alone.

namespace str

The prefix the ref lives under, when it is neither the shared namespace nor the local one: livery.git.TRACE_NAMESPACE is the one such prefix, pushed to origin and mirrored by nothing. Empty means the class local chooses.

blobs str

The directory, ending in a slash, of the files the series keeps beside its rows as their writer wrote them, such as a file named by its own content (facts/). A read hands them back as text and never parses one as a row, a write puts them unstamped, and the janitor counts the rows alone. Empty for none. A window ranks files by their stamps, so a series with blobs declares none.

Methods:

Name Description
__post_init__
blob

Whether the file name is one of the series' blobs, not a row.

rows

Every row of the series, newest first, with what was skipped and why.

row

The row in the file name.

file

The text of the file name on the ref, or why it could not be read.

put

Write rows, stamped, and blobs by file name; "" or the reason.

name instance-attribute

name: str

window class-attribute instance-attribute

window: int | None = None

ci_only class-attribute instance-attribute

ci_only: bool = True

schema class-attribute instance-attribute

schema: int = 1

local class-attribute instance-attribute

local: bool = False

age class-attribute instance-attribute

age: timedelta | None = None

namespace class-attribute instance-attribute

namespace: str = ''

blobs class-attribute instance-attribute

blobs: str = ''

ref property

ref: str

The full ref name, under the local namespace for a local series.

__post_init__

__post_init__() -> None
Source code in packages/git/src/livery/git/_store.py
def __post_init__(self) -> None:
    if self.local and self.ci_only:
        raise ValueError(
            f"{self.name}: a local series is written by local runs; declare"
            " it ci_only=False"
        )
    if self.namespace and self.local:
        raise ValueError(
            f"{self.name}: a series in {self.namespace} is not local; declare"
            " one or the other"
        )
    if self.blobs and (not self.blobs.endswith("/") or self.window is not None):
        raise ValueError(
            f"{self.name}: blobs name a directory ending in a slash, and a"
            " series with blobs declares no window, which ranks files by"
            " their stamps"
        )

blob

blob(name: str) -> bool

Whether the file name is one of the series' blobs, not a row.

Source code in packages/git/src/livery/git/_store.py
def blob(self, name: str) -> bool:
    """Whether the file *name* is one of the series' blobs, not a row."""
    return bool(self.blobs) and name.startswith(self.blobs)

rows

rows(store: StateStore, *, only: Callable[[str], bool] | None = None) -> Rows

Every row of the series, newest first, with what was skipped and why.

An absent ref is no rows and no failure. A ref the transport could not read is a failure with its reason, so every caller falls open the same way. A file that does not parse or is of another schema is skipped and named, and the rest stand. A blob the read accepts comes back as text in blobs. With only, the files whose names it accepts are read and parsed, and every other file is named in unread, never read: a series of large rows answers a reader of a few of them at the cost of those few.

Source code in packages/git/src/livery/git/_store.py
def rows(
    self, store: StateStore, *, only: Callable[[str], bool] | None = None
) -> Rows:
    """Every row of the series, newest first, with what was skipped and why.

    An absent ref is no rows and no failure. A ref the transport
    could not read is a failure with its reason, so every caller
    falls open the same way. A file that does not parse or is of
    another schema is skipped and named, and the rest stand. A blob
    the read accepts comes back as text in ``blobs``. With
    *only*, the files whose names it accepts are read and parsed,
    and every other file is named in ``unread``, never read: a
    series of large rows answers a reader of a few of them at the
    cost of those few.
    """
    found = read(store, self.ref, only=only)
    if found.files is None:
        return Rows((), failed=found.failed, reason=self._unreadable(found))
    rows: list[Row] = []
    skipped: list[Skipped] = []
    blobs: dict[str, str] = {}
    for name in sorted(found.files):
        if self.blob(name):
            blobs[name] = found.files[name]
            continue
        data, why = _parse(self, found.files[name])
        if data is None:
            skipped.append(Skipped(name, why))
        else:
            rows.append(Row(name, data))
    rows.sort(key=_newest, reverse=True)
    unread = tuple(name for name in found.names if name not in found.files)
    return Rows(tuple(rows), tuple(skipped), unread=unread, blobs=blobs)

row

row(store: StateStore, name: str) -> tuple[Row | None, str]

The row in the file name.

(None, "") when the ref or the file is absent, and (None, reason) when the ref could not be read or the file is not a row of the schema. The ref's other files are not read.

Source code in packages/git/src/livery/git/_store.py
def row(self, store: StateStore, name: str) -> tuple[Row | None, str]:
    """The row in the file *name*.

    ``(None, "")`` when the ref or the file is absent, and
    ``(None, reason)`` when the ref could not be read or the file
    is not a row of the schema. The ref's other files are not read.
    """
    found = read(store, self.ref, only=name.__eq__)
    if found.files is None:
        return None, self._unreadable(found)
    text = found.files.get(name)
    if text is None:
        return None, ""
    data, why = _parse(self, text)
    if data is None:
        return None, f"{name}: {why}"
    return Row(name, data), ""

file

file(store: StateStore, name: str) -> tuple[str | None, str]

The text of the file name on the ref, or why it could not be read.

For a series whose files are not rows: a leg's trace, kept as its writer wrote it. (None, "") is absence, of the ref or of the file. The ref's other files are not read.

Source code in packages/git/src/livery/git/_store.py
def file(self, store: StateStore, name: str) -> tuple[str | None, str]:
    """The text of the file *name* on the ref, or why it could not be read.

    For a series whose files are not rows: a leg's trace, kept as
    its writer wrote it. ``(None, "")`` is absence, of the ref or
    of the file. The ref's other files are not read.
    """
    found = read(store, self.ref, only=name.__eq__)
    if found.files is None:
        return None, self._unreadable(found)
    return found.files.get(name), ""

put

put(store: StateStore, rows: Mapping[str, Mapping[str, Any]], *, message: str, remove: Iterable[str] = (), blobs: Mapping[str, str] | None = None) -> str

Write rows, stamped, and blobs by file name; "" or the reason.

Every row is written with the schema and the time stamped on it, and the stamp wins over a schema or when the row carries. Each blob is written as the text given, so a blob of the same text is the same object git already holds. The files the series already holds stand, less the file names in remove, so a caller replacing a record in place names what goes and puts what changed.

The window keeps the newest rows by their stamps, so a series keyed by something other than time (a tree id) keeps its newest too. A write the declaration forbids is refused with the rule, and so is a row named as a blob, or a blob named outside the series' blobs; the transport's refusals come back as they are.

Source code in packages/git/src/livery/git/_store.py
def put(
    self,
    store: StateStore,
    rows: Mapping[str, Mapping[str, Any]],
    *,
    message: str,
    remove: Iterable[str] = (),
    blobs: Mapping[str, str] | None = None,
) -> str:
    """Write *rows*, stamped, and *blobs* by file name; ``""`` or the reason.

    Every row is written with the schema and the time stamped on
    it, and the stamp wins over a ``schema`` or ``when`` the row
    carries. Each blob is written as the text given, so a blob of
    the same text is the same object git already holds. The files
    the series already holds stand, less the file names in
    *remove*, so a caller replacing a record in place names what
    goes and puts what changed.

    The window keeps the newest rows by their stamps, so a series
    keyed by something other than time (a tree id) keeps its
    newest too. A write the declaration forbids is refused with
    the rule, and so is a row named as a blob, or a blob named
    outside the series' ``blobs``; the transport's refusals come
    back as they are.
    """
    given = dict(blobs or {})
    astray = sorted(
        [name for name in rows if self.blob(name)]
        + [name for name in given if not self.blob(name)]
    )
    if astray:
        return (
            f"refusing {self.ref}: {', '.join(astray)}: a row lives outside"
            f" the series' blobs ({self.blobs or 'none declared'}) and a"
            " blob inside them"
        )
    stamp = datetime.now(UTC).isoformat(timespec="microseconds")
    files = {
        name: json.dumps(
            {**row, "schema": self.schema, "when": stamp}, sort_keys=True
        )
        for name, row in rows.items()
    } | given
    # The transport's put: a class body is no scope for its methods.
    return put(
        store,
        self.ref,
        files,
        message=message,
        window=self.window,
        ci_only=self.ci_only,
        order=_by_when,
        remove=remove,
    )

Skipped dataclass

Skipped(name: str, why: str)

A file a read passed over: its name and why.

Attributes:

Name Type Description
name str

The file's name on the ref.

why str

Why it is not a row, in the store's one wording.

Methods:

Name Description
__str__

name instance-attribute

name: str

why instance-attribute

why: str

__str__

__str__() -> str
Source code in packages/git/src/livery/git/_store.py
def __str__(self) -> str:
    return f"{self.name}: {self.why}; skipped"

StateStore dataclass

StateStore(root: Path, in_ci: bool, identity: tuple[str, str], snapshot_variable: str, prog: str = 'fm')

A checkout's state store and the policy its builder gave it.

Attributes:

Name Type Description
root Path

The checkout whose origin holds the remote namespace and whose git directory holds the local one.

in_ci bool

Whether this process is a CI run: a put to a series declared ci_only refuses otherwise.

identity tuple[str, str]

The name and address every commit the store makes carries, author and committer.

snapshot_variable str

The environment variable a published listing's path travels in, from a parent process to its children.

prog str

The runner's command name, for the words a refusal gives a person (un `fm sync).

root instance-attribute

root: Path

in_ci instance-attribute

in_ci: bool

identity instance-attribute

identity: tuple[str, str]

snapshot_variable instance-attribute

snapshot_variable: str

prog class-attribute instance-attribute

prog: str = 'fm'

config_environment

config_environment(environ: Mapping[str, str], pairs: Sequence[tuple[str, str]]) -> dict[str, str]

pairs as git configuration riding the environment, after what it carries.

git reads GIT_CONFIG_COUNT with a key and a value per index, so an entry the outer environment already carries keeps its index and these follow it. The mapping returned holds the new entries and the count; merge it over environ.

Source code in packages/git/src/livery/git/_environment.py
def config_environment(
    environ: Mapping[str, str], pairs: Sequence[tuple[str, str]]
) -> dict[str, str]:
    """*pairs* as git configuration riding the environment, after what it carries.

    git reads `GIT_CONFIG_COUNT` with a key and a value per index, so an
    entry the outer environment already carries keeps its index and
    these follow it. The mapping returned holds the new entries and the
    count; merge it over *environ*.
    """
    raw = environ.get("GIT_CONFIG_COUNT", "")
    count = int(raw) if raw.isdigit() else 0
    made: dict[str, str] = {}
    for offset, (key, value) in enumerate(pairs):
        index = count + offset
        made[f"GIT_CONFIG_KEY_{index}"] = key
        made[f"GIT_CONFIG_VALUE_{index}"] = value
    made["GIT_CONFIG_COUNT"] = str(count + len(pairs))
    return made

identity_environment

identity_environment(name: str, email: str) -> dict[str, str]

The variables that make every commit and tag by name and email.

Author and committer both: git reads the four variables ahead of any config, so a checkout's own identity is left as it is.

Source code in packages/git/src/livery/git/_environment.py
def identity_environment(name: str, email: str) -> dict[str, str]:
    """The variables that make every commit and tag by *name* and *email*.

    Author and committer both: git reads the four variables ahead of
    any config, so a checkout's own identity is left as it is.
    """
    return {
        "GIT_AUTHOR_NAME": name,
        "GIT_AUTHOR_EMAIL": email,
        "GIT_COMMITTER_NAME": name,
        "GIT_COMMITTER_EMAIL": email,
    }

tool_identity

tool_identity(prog: str) -> tuple[str, str]

The name and address a tool called prog commits under.

For every commit a verb makes when the person has no identity of their own: a release, a loop's scratch, the state store's rows. The domain is .invalid, reserved for names that resolve nowhere.

Source code in packages/git/src/livery/git/_environment.py
def tool_identity(prog: str) -> tuple[str, str]:
    """The name and address a tool called *prog* commits under.

    For every commit a verb makes when the person has no identity of
    their own: a release, a loop's scratch, the state store's rows.
    The domain is `.invalid`, reserved for names that resolve nowhere.
    """
    return prog, f"{prog}@{prog}.invalid"

identity

identity(name: str, email: str) -> Callable[[_F], _F]

Make the decorated task's commits carry name and email, whatever git says.

Source code in packages/git/src/livery/git/_marks.py
def identity(name: str, email: str) -> Callable[[_F], _F]:
    """Make the decorated task's commits carry *name* and *email*, whatever git says."""

    def mark(fn: _F) -> _F:
        setattr(fn, IDENTITY_MARK, (name, email))
        return fn

    return mark

unsigned

unsigned(fn: _F) -> _F

Turn commit and tag signing off for the decorated task's git.

Source code in packages/git/src/livery/git/_marks.py
def unsigned(fn: _F) -> _F:
    """Turn commit and tag signing off for the decorated task's git."""
    setattr(fn, UNSIGNED_MARK, True)
    return fn

add

add(root: Path, path: str) -> None

Stage path as it stands in the working tree, a removal included.

Source code in packages/git/src/livery/git/_ops.py
def add(root: Path, path: str) -> None:
    """Stage *path* as it stands in the working tree, a removal included."""
    run(root, "add", "--all", "--", path)

add_remote

add_remote(root: Path, name: str, url: str) -> None

Add the remote name at url.

Source code in packages/git/src/livery/git/_ops.py
def add_remote(root: Path, name: str, url: str) -> None:
    """Add the remote *name* at *url*."""
    run(root, "remote", "add", name, url)

amend_all

amend_all(root: Path) -> None

Stage everything and fold it into HEAD, message kept.

Source code in packages/git/src/livery/git/_ops.py
def amend_all(root: Path) -> None:
    """Stage everything and fold it into HEAD, message kept."""
    run(root, "add", "-A")
    run(root, "commit", "--amend", "--no-edit")

any_head

any_head(root: Path, branch: str) -> str

branch's head sha: local when present, else the remote's, else empty.

A root that is no repository has no local branch, so the remote is asked.

Source code in packages/git/src/livery/git/_ops.py
def any_head(root: Path, branch: str) -> str:
    """*branch*'s head sha: local when present, else the remote's, else empty.

    A *root* that is no repository has no local branch, so the remote
    is asked.
    """
    sha: bytes | None = None
    try:
        with _objects.opened(root) as repo:
            sha = _objects.ref_value(repo, b"refs/heads/" + branch.encode())
    except _objects.NotGitRepository:
        pass
    if sha is not None:
        return sha.decode()
    result = call(root, "ls-remote", "origin", f"refs/heads/{branch}")
    if result.code == 0 and result.stdout.strip():
        return result.stdout.split()[0]
    return ""

author_email

author_email(root: Path) -> str

The address the next commit in root would carry as its author.

Resolved as git resolves it, the environment's GIT_AUTHOR_EMAIL ahead of the config, so a checkout whose identity rides the environment answers the same as one configured.

Source code in packages/git/src/livery/git/_ops.py
def author_email(root: Path) -> str:
    """The address the next commit in *root* would carry as its author.

    Resolved as git resolves it, the environment's `GIT_AUTHOR_EMAIL`
    ahead of the config, so a checkout whose identity rides the
    environment answers the same as one configured.
    """
    ident = run(root, "var", "GIT_AUTHOR_IDENT")
    _, _, rest = ident.partition("<")
    email, _, _ = rest.partition(">")
    return email.strip()

behind_base

behind_base(root: Path, base: str) -> int

How many commits origin/<base> is ahead of HEAD.

Source code in packages/git/src/livery/git/_ops.py
def behind_base(root: Path, base: str) -> int:
    """How many commits ``origin/<base>`` is ahead of HEAD."""
    with _opened(root) as repo:
        return len(_walk_span(repo, f"HEAD..origin/{base}", root))

blob_at

blob_at(root: Path, digest: str) -> str

The text of the blob digest names in the object store; empty when none.

digest is a full blob id, forty hex digits. The blob is read by its id alone, so a content no tree names any more, one a change replaced, is still read while the object store holds it. Empty when the store holds no such object, when digest is no full id, and when the id names a tree or a commit.

Raises:

Type Description
GitError

When root is not inside a repository.

Source code in packages/git/src/livery/git/_ops.py
def blob_at(root: Path, digest: str) -> str:
    """The text of the blob *digest* names in the object store; empty when none.

    *digest* is a full blob id, forty hex digits. The blob is read by
    its id alone, so a content no tree names any more, one a change
    replaced, is still read while the object store holds it. Empty
    when the store holds no such object, when *digest* is no full id,
    and when the id names a tree or a commit.

    Raises:
        GitError: When *root* is not inside a repository.
    """
    if not _FULL_SHA.match(digest):
        return ""
    with _opened(root) as repo:
        sha = digest.encode("ascii")
        if not _objects.holds(repo, sha):
            return ""
        return _objects.blob_text(repo, sha)

call

call(root: Path, *args: str) -> Result

Run git with args in root and return the result whatever the exit code.

The one door every git call takes. A caller that treats a non-zero exit as an answer reads the code; one that treats it as a failure calls livery.git.run instead. Each argument reaches the tool handle as the object it is, so a livery.footman.Secret stays marked, and every command line footman shows, a profile trace included, carries *** in its place.

Source code in packages/git/src/livery/git/_ops.py
def call(root: Path, *args: str) -> tools.Result:
    """Run git with *args* in *root* and return the result whatever the exit code.

    The one door every git call takes. A caller that treats a non-zero
    exit as an answer reads the code; one that treats it as a failure
    calls [livery.git.run][] instead. Each argument reaches the tool
    handle as the object it is, so a [livery.footman.Secret][] stays
    marked, and every command line footman shows, a profile trace
    included, carries ``***`` in its place.
    """
    return tools.git.opts(cwd=root, nofail=True, recorded=False)(*args)

changed_between

changed_between(root: Path, old: str, new: str, patterns: tuple[str, ...]) -> list[str]

The paths matching patterns that differ between old and new.

Repo-relative, as git prints them; empty when nothing matching changed. A pattern is a path or a glob as git reads one.

Source code in packages/git/src/livery/git/_ops.py
def changed_between(
    root: Path, old: str, new: str, patterns: tuple[str, ...]
) -> list[str]:
    """The paths matching *patterns* that differ between *old* and *new*.

    Repo-relative, as git prints them; empty when nothing matching
    changed. A pattern is a path or a glob as git reads one.
    """
    import fnmatch

    with _opened(root) as repo:
        changed = _objects.changed_paths_between(
            repo, _resolved(repo, old, root), _resolved(repo, new, root)
        )
    return [
        path
        for path in changed
        if any(
            fnmatch.fnmatch(path, pattern)
            or path.startswith(pattern.rstrip("/") + "/")
            or path == pattern
            for pattern in patterns
        )
    ]

changed_paths

changed_paths(root: Path, base: str) -> list[str]

Repo-relative paths this branch touches, committed or not.

The committed half diffs against the merge base with origin/<base>; the uncommitted half comes from the status listing, renames counted on both sides and untracked files named one by one (a collapsed directory reads as neither prose nor package).

Source code in packages/git/src/livery/git/_ops.py
def changed_paths(root: Path, base: str) -> list[str]:
    """Repo-relative paths this branch touches, committed or not.

    The committed half diffs against the merge base with
    ``origin/<base>``; the uncommitted half comes from the status
    listing, renames counted on both sides and untracked files
    named one by one (a collapsed directory reads as neither
    prose nor package).
    """
    since = merge_base(root, base)
    with _opened(root) as repo:
        committed = _objects.changed_paths_between(
            repo, since.encode(), _resolved(repo, "HEAD", root)
        )
    pending: list[str] = []
    for line in run(
        root, "status", "--porcelain", "--untracked-files=all"
    ).splitlines():
        pending.extend(part for part in line[3:].split(" -> ") if part)
    return sorted({path for path in committed + pending if path})

clean

clean(root: Path, *, keep: Sequence[str] = (), dry_run: bool = False) -> list[str]

Remove every untracked and ignored file but the patterns in keep; the paths.

Under dry_run nothing goes and the paths are what would.

Source code in packages/git/src/livery/git/_ops.py
def clean(root: Path, *, keep: Sequence[str] = (), dry_run: bool = False) -> list[str]:
    """Remove every untracked and ignored file but the patterns in *keep*; the paths.

    Under *dry_run* nothing goes and the paths are what would.
    """
    kept = [flag for name in keep for flag in ("-e", name)]
    out = run(root, "clean", "-ndx" if dry_run else "-fdx", *kept)
    return [
        line.removeprefix("Would remove ").removeprefix("Removing ").strip()
        for line in out.splitlines()
        if line.strip()
    ]

commit_all

commit_all(root: Path, message: str) -> None

Stage everything and commit with message.

Source code in packages/git/src/livery/git/_ops.py
def commit_all(root: Path, message: str) -> None:
    """Stage everything and commit with *message*."""
    run(root, "add", "-A")
    run(root, "commit", "-m", message)

commit_message

commit_message(root: Path, ref: str) -> str

ref's full commit message, subject and body.

Source code in packages/git/src/livery/git/_ops.py
def commit_message(root: Path, ref: str) -> str:
    """*ref*'s full commit message, subject and body."""
    with _opened(root) as repo:
        commit = _objects.commit_of(repo, _resolved(repo, ref, root))
    return _objects.message_of(commit)

commits_since

commits_since(root: Path, ref: str) -> int

How many commits HEAD carries beyond ref.

Source code in packages/git/src/livery/git/_ops.py
def commits_since(root: Path, ref: str) -> int:
    """How many commits HEAD carries beyond *ref*."""
    with _opened(root) as repo:
        return len(_walk_span(repo, f"{ref}..HEAD", root))

config_get

config_get(root: Path, key: str) -> str

The repository's git config value for key; empty when unset or no repository.

Read in-process from the config files git itself reads.

Source code in packages/git/src/livery/git/_ops.py
def config_get(root: Path, key: str) -> str:
    """The repository's git config value for *key*; empty when unset or no repository.

    Read in-process from the config files git itself reads.
    """
    try:
        with _objects.opened(root) as repo:
            return _objects.config_value(repo, key)
    except _objects.NotGitRepository:
        return ""

config_regexp

config_regexp(root: Path, pattern: str) -> dict[str, str]

Every config key matching pattern, with its value, read in-process.

Empty when nothing matches or root is no repository; a key set twice keeps its last value.

Source code in packages/git/src/livery/git/_ops.py
def config_regexp(root: Path, pattern: str) -> dict[str, str]:
    """Every config key matching *pattern*, with its value, read in-process.

    Empty when nothing matches or *root* is no repository; a key set
    twice keeps its last value.
    """
    try:
        with _objects.opened(root) as repo:
            return _objects.config_matching(repo, pattern)
    except _objects.NotGitRepository:
        return {}

config_set

config_set(root: Path, key: str, value: str) -> None

Set key to value in the repository's git config.

Source code in packages/git/src/livery/git/_ops.py
def config_set(root: Path, key: str, value: str) -> None:
    """Set *key* to *value* in the repository's git config."""
    run(root, "config", key, value)

config_unset

config_unset(root: Path, key: str) -> None

Remove key from the repository's git config; a key already absent is fine.

Source code in packages/git/src/livery/git/_ops.py
def config_unset(root: Path, key: str) -> None:
    """Remove *key* from the repository's git config; a key already absent is fine."""
    call(root, "config", "--unset", key)

conflicts_with_base

conflicts_with_base(root: Path, base: str) -> bool

Whether merging origin/<base> into HEAD would conflict.

Probed with git merge-tree so nothing in the working tree moves; exit 1 with conflicts is the answer, any other failure raises.

Source code in packages/git/src/livery/git/_ops.py
def conflicts_with_base(root: Path, base: str) -> bool:
    """Whether merging ``origin/<base>`` into HEAD would conflict.

    Probed with ``git merge-tree`` so nothing in the working tree
    moves; exit 1 with conflicts is the answer, any other failure
    raises.
    """
    result = call(
        root, "merge-tree", "--write-tree", "--name-only", "HEAD", f"origin/{base}"
    )
    if result.code in (0, 1):
        return result.code == 1
    raise GitError(
        f"git merge-tree exited {result.code}:\n{result.stdout}{result.stderr}"
    )

create_branch

create_branch(root: Path, name: str) -> None

Create and switch to name.

Source code in packages/git/src/livery/git/_ops.py
def create_branch(root: Path, name: str) -> None:
    """Create and switch to *name*."""
    run(root, "checkout", "-b", name)

current_branch

current_branch(root: Path) -> str

The checked-out branch name; empty when detached.

Source code in packages/git/src/livery/git/_ops.py
def current_branch(root: Path) -> str:
    """The checked-out branch name; empty when detached."""
    with _opened(root) as repo:
        return _branch_of(repo)

delete_branch

delete_branch(root: Path, name: str) -> None

Delete the local branch name, merged or not.

Source code in packages/git/src/livery/git/_ops.py
def delete_branch(root: Path, name: str) -> None:
    """Delete the local branch *name*, merged or not."""
    run(root, "branch", "-D", name)

detach

detach(root: Path, ref: str) -> None

Check ref out as a detached HEAD.

Source code in packages/git/src/livery/git/_ops.py
def detach(root: Path, ref: str) -> None:
    """Check *ref* out as a detached HEAD."""
    run(root, "switch", "--detach", ref)

dirty_paths

dirty_paths(root: Path) -> list[str]

The paths the working tree changed, staged or not, in status order.

Source code in packages/git/src/livery/git/_ops.py
def dirty_paths(root: Path) -> list[str]:
    """The paths the working tree changed, staged or not, in status order."""
    lines = run(root, "status", "--porcelain").splitlines()
    return [line[3:].strip() for line in lines if line.strip()]

fetch

fetch(root: Path, *refs: str, prune: bool = False, force: bool = False) -> None

Freshen origin/*, or the refs named, from origin.

prune drops the remote-tracking refs origin no longer has, so a branch the forge deleted does not linger; force takes a ref that moved to an unrelated commit, a receipt tag recut by a later wave.

Source code in packages/git/src/livery/git/_ops.py
def fetch(root: Path, *refs: str, prune: bool = False, force: bool = False) -> None:
    """Freshen ``origin/*``, or the *refs* named, from origin.

    *prune* drops the remote-tracking refs origin no longer has, so a
    branch the forge deleted does not linger; *force* takes a ref that
    moved to an unrelated commit, a receipt tag recut by a later wave.
    """
    flags = [flag for flag, on in (("--prune", prune), ("--force", force)) if on]
    run(root, "fetch", "--quiet", *flags, "origin", *refs)

fetch_tag

fetch_tag(root: Path, tag: str) -> None

Take tag from origin as it is there, replacing the one held here.

Source code in packages/git/src/livery/git/_ops.py
def fetch_tag(root: Path, tag: str) -> None:
    """Take *tag* from origin as it is there, replacing the one held here."""
    run(root, "fetch", "--quiet", "--force", "origin", "tag", tag)

fetch_tags

fetch_tags(root: Path) -> None

Freshen origin/* and take every tag origin holds.

A tag cut on the remote at a commit this clone already has is fetched here too, which a plain fetch's tag following does not promise.

Source code in packages/git/src/livery/git/_ops.py
def fetch_tags(root: Path) -> None:
    """Freshen ``origin/*`` and take every tag origin holds.

    A tag cut on the remote at a commit this clone already has is
    fetched here too, which a plain fetch's tag following does not
    promise.
    """
    run(root, "fetch", "--tags", "origin")

file_at

file_at(root: Path, ref: str, path: str) -> str

The contents of path as committed at ref; empty when absent.

Source code in packages/git/src/livery/git/_ops.py
def file_at(root: Path, ref: str, path: str) -> str:
    """The contents of *path* as committed at *ref*; empty when absent."""
    with _opened(root) as repo:
        try:
            found = _objects.object_named(repo, f"{ref}:{path}")
        except (_objects.Unresolved, KeyError):
            return ""
        if found is None:
            return ""
        return _objects.blob_text(repo, found)

files_in_commit

files_in_commit(root: Path, ref: str) -> list[str]

The paths the commit at ref changed, against its first parent.

Source code in packages/git/src/livery/git/_ops.py
def files_in_commit(root: Path, ref: str) -> list[str]:
    """The paths the commit at *ref* changed, against its first parent."""
    with _opened(root) as repo:
        sha = _resolved(repo, ref, root)
        commit = _objects.commit_of(repo, sha)
        parent = commit.parents[0] if commit.parents else None
        return _objects.changed_paths_between(repo, parent, sha)

first_parent_trees

first_parent_trees(root: Path, count: int) -> list[str]

HEAD's tree id and its first-parent ancestors', newest first.

count commits deep at most.

Source code in packages/git/src/livery/git/_ops.py
def first_parent_trees(root: Path, count: int) -> list[str]:
    """HEAD's tree id and its first-parent ancestors', newest first.

    *count* commits deep at most.
    """
    trees: list[str] = []
    with _opened(root) as repo:
        sha: bytes | None = _resolved(repo, "HEAD", root)
        while sha is not None and len(trees) < count:
            commit = _objects.commit_of(repo, sha)
            trees.append(commit.tree.decode())
            sha = commit.parents[0] if commit.parents else None
    return trees

has_commits

has_commits(root: Path) -> bool

Whether HEAD names a commit; false with no commit or no repository.

Source code in packages/git/src/livery/git/_ops.py
def has_commits(root: Path) -> bool:
    """Whether HEAD names a commit; false with no commit or no repository."""
    try:
        with _objects.opened(root) as repo:
            repo.head()
    except (_objects.NotGitRepository, KeyError):
        return False
    return True

has_remote

has_remote(root: Path, name: str = 'origin') -> bool

Whether this clone has a remote called name; any other failure raises.

Source code in packages/git/src/livery/git/_ops.py
def has_remote(root: Path, name: str = "origin") -> bool:
    """Whether this clone has a remote called *name*; any other failure raises."""
    result = call(root, "remote", "get-url", name)
    if result.code in (0, 2):
        return result.code == 0
    raise GitError(
        f"git remote get-url exited {result.code}:\n{result.stdout}{result.stderr}"
    )

head_body

head_body(root: Path) -> str

HEAD's commit body, without the subject.

Source code in packages/git/src/livery/git/_ops.py
def head_body(root: Path) -> str:
    """HEAD's commit body, without the subject."""
    return head_message(root)[1]

head_message

head_message(root: Path) -> tuple[str, str]

HEAD's commit subject and its body, read in-process.

Source code in packages/git/src/livery/git/_ops.py
def head_message(root: Path) -> tuple[str, str]:
    """HEAD's commit subject and its body, read in-process."""
    with _opened(root) as repo:
        commit = _objects.commit_of(repo, _resolved(repo, "HEAD", root))
        return _objects.subject_and_body(commit.message)

head_sha

head_sha(root: Path) -> str

The commit HEAD points at.

Raises:

Type Description
GitError

When HEAD names no commit yet.

Source code in packages/git/src/livery/git/_ops.py
def head_sha(root: Path) -> str:
    """The commit HEAD points at.

    Raises:
        GitError: When HEAD names no commit yet.
    """
    with _opened(root) as repo:
        return _head_of(repo)

head_subject

head_subject(root: Path) -> str

HEAD's commit subject.

Source code in packages/git/src/livery/git/_ops.py
def head_subject(root: Path) -> str:
    """HEAD's commit subject."""
    return head_message(root)[0]

integrate

integrate(root: Path, base: str) -> None

Merge origin/<base> into the current branch, after a fetch.

A conflict raises livery.git.GitError with git's words and leaves the merging state in place for a person to resolve; re-running the caller after the resolution is the recovery.

Source code in packages/git/src/livery/git/_ops.py
def integrate(root: Path, base: str) -> None:
    """Merge ``origin/<base>`` into the current branch, after a fetch.

    A conflict raises [livery.git.GitError][] with git's words and
    leaves the merging state in place for a person to resolve;
    re-running the caller after the resolution is the recovery.
    """
    fetch(root)
    run(root, "merge", "--no-edit", f"origin/{base}")

is_ancestor

is_ancestor(root: Path, ancestor: str, descendant: str) -> bool

Whether ancestor reaches descendant in this clone.

A commit this clone does not know cannot be an ancestor, so an unknown ancestor answers False rather than raising.

Source code in packages/git/src/livery/git/_ops.py
def is_ancestor(root: Path, ancestor: str, descendant: str) -> bool:
    """Whether *ancestor* reaches *descendant* in this clone.

    A commit this clone does not know cannot be an ancestor, so
    an unknown *ancestor* answers False rather than raising.
    """
    with _opened(root) as repo:
        try:
            first = _resolved(repo, ancestor, root)
            second = _resolved(repo, descendant, root)
        except GitError:
            return False
        return _objects.is_ancestor(repo, first, second)

is_clean

is_clean(root: Path) -> bool

Whether the working tree has no changes, staged or not.

Source code in packages/git/src/livery/git/_ops.py
def is_clean(root: Path) -> bool:
    """Whether the working tree has no changes, staged or not."""
    return not run(root, "status", "--porcelain").strip()

last_commit_touching

last_commit_touching(root: Path, path: str, *, ref: str = 'HEAD') -> str

The newest commit at or before ref that changed path; empty if none.

Source code in packages/git/src/livery/git/_ops.py
def last_commit_touching(root: Path, path: str, *, ref: str = "HEAD") -> str:
    """The newest commit at or before *ref* that changed *path*; empty if none."""
    with _opened(root) as repo:
        for commit in _objects.walk(
            repo, [_resolved(repo, ref, root)], paths=[path.encode()], limit=1
        ):
            return commit.id.decode()
    return ""

local_branch_exists

local_branch_exists(root: Path, branch: str) -> bool

Whether branch exists locally.

Source code in packages/git/src/livery/git/_ops.py
def local_branch_exists(root: Path, branch: str) -> bool:
    """Whether *branch* exists locally."""
    with _opened(root) as repo:
        return _objects.ref_value(repo, b"refs/heads/" + branch.encode()) is not None

local_branches

local_branches(root: Path, prefix: str) -> tuple[str, ...]

Local branch names under prefix (workflow/), short form.

Source code in packages/git/src/livery/git/_ops.py
def local_branches(root: Path, prefix: str) -> tuple[str, ...]:
    """Local branch names under *prefix* (``workflow/``), short form."""
    with _opened(root) as repo:
        found = _objects.refs_under(repo, b"refs/heads/" + prefix.encode(), whole=True)
    return tuple(sorted(name.removeprefix("refs/heads/") for name in found))

log_paths

log_paths(root: Path, span: str, paths: tuple[str, ...]) -> tuple[str, ...]

The subjects in span touching paths (a..b git range).

Source code in packages/git/src/livery/git/_ops.py
def log_paths(root: Path, span: str, paths: tuple[str, ...]) -> tuple[str, ...]:
    """The subjects in *span* touching *paths* (``a..b`` git range)."""
    with _opened(root) as repo:
        return tuple(
            _objects.subject_and_body(commit.message)[0]
            for commit in _walk_span(repo, span, root, paths)
        )

ls_files

ls_files(root: Path, *paths: str, others: bool = False, cached: bool = True) -> list[str]

The paths git lists under paths (the whole tree when none), sorted.

cached lists what the index holds, others the untracked files the ignore rules do not cover; both together are what a check reads. Names come back as written, through -z.

Raises:

Type Description
GitError

When git cannot list, with its words.

Source code in packages/git/src/livery/git/_ops.py
def ls_files(
    root: Path, *paths: str, others: bool = False, cached: bool = True
) -> list[str]:
    """The paths git lists under *paths* (the whole tree when none), sorted.

    *cached* lists what the index holds, *others* the untracked files
    the ignore rules do not cover; both together are what a check
    reads. Names come back as written, through ``-z``.

    Raises:
        GitError: When git cannot list, with its words.
    """
    flags = [flag for flag, on in (("--cached", cached), ("--others", others)) if on]
    if others:
        flags.append("--exclude-standard")
    out = run(root, "ls-files", "-z", *flags, "--", *paths)
    return sorted({name for name in out.split("\0") if name})

ls_remote

ls_remote(root: Path, *refs: str, tags: bool = False, remote: str = 'origin') -> dict[str, str]

The refs remote holds among refs (every one when none is named), by sha.

tags lists the tags alone, the peeled entries left out; remote is a name or a URL, and asking a URL needs no remote configured.

Source code in packages/git/src/livery/git/_ops.py
def ls_remote(
    root: Path, *refs: str, tags: bool = False, remote: str = "origin"
) -> dict[str, str]:
    """The refs *remote* holds among *refs* (every one when none is named), by sha.

    *tags* lists the tags alone, the peeled entries left out; *remote*
    is a name or a URL, and asking a URL needs no remote configured.
    """
    out = run(root, "ls-remote", *(["--tags"] if tags else []), remote, *refs)
    found: dict[str, str] = {}
    for line in out.splitlines():
        sha, _, name = line.partition("\t")
        if name.strip() and not name.endswith("^{}"):
            found[name.strip()] = sha.strip()
    return found

main_checkout

main_checkout(root: Path) -> Path

The repository's main checkout, the same from any of its worktrees.

Every worktree shares the main checkout's .git directory, which git reports as the common directory; its parent is the main checkout.

Source code in packages/git/src/livery/git/_ops.py
def main_checkout(root: Path) -> Path:
    """The repository's main checkout, the same from any of its worktrees.

    Every worktree shares the main checkout's ``.git`` directory,
    which git reports as the common directory; its parent is the
    main checkout.
    """
    with _opened(root) as repo:
        common = os.path.normpath(os.path.abspath(repo.commondir()))
    return Path(common).parent

merge_base

merge_base(root: Path, base: str) -> str

The merge base of HEAD and origin/<base>; raises without one.

A shallow clone, or a base the fetch did not bring, has none.

Raises:

Type Description
GitError

When HEAD and origin/<base> share no commit.

Source code in packages/git/src/livery/git/_ops.py
def merge_base(root: Path, base: str) -> str:
    """The merge base of HEAD and ``origin/<base>``; raises without one.

    A shallow clone, or a base the fetch did not bring, has none.

    Raises:
        GitError: When HEAD and ``origin/<base>`` share no commit.
    """
    with _opened(root) as repo:
        found = _objects.merge_base(
            repo, _resolved(repo, "HEAD", root), _resolved(repo, f"origin/{base}", root)
        )
    if found is None:
        raise GitError(f"HEAD and origin/{base} share no commit")
    return found.decode()

merge_parents

merge_parents(root: Path) -> tuple[str, str] | None

HEAD's two parents when HEAD is a merge: the base, then the head merged in.

A pull request's run on GitHub checks out the merge the forge made of the pull request's head onto its base branch; any other checkout answers None.

Source code in packages/git/src/livery/git/_ops.py
def merge_parents(root: Path) -> tuple[str, str] | None:
    """HEAD's two parents when HEAD is a merge: the base, then the head merged in.

    A pull request's run on GitHub checks out the merge the forge
    made of the pull request's head onto its base branch; any other
    checkout answers None.
    """
    with _opened(root) as repo:
        parents = _objects.commit_of(repo, _resolved(repo, "HEAD", root)).parents
    if len(parents) != 2:
        return None
    return parents[0].decode(), parents[1].decode()

merge_tree

merge_tree(root: Path, base: str, head: str) -> str

The tree a merge of head onto base yields, written to this clone.

No working tree or index is touched; only the objects are written.

Raises:

Type Description
GitError

On a conflict, with git's words.

Source code in packages/git/src/livery/git/_ops.py
def merge_tree(root: Path, base: str, head: str) -> str:
    """The tree a merge of *head* onto *base* yields, written to this clone.

    No working tree or index is touched; only the objects are
    written.

    Raises:
        GitError: On a conflict, with git's words.
    """
    return run(root, "merge-tree", "--write-tree", base, head).splitlines()[0].strip()

object_id

object_id(root: Path, spec: str) -> str

The object id spec names (HEAD:packages/forge is a tree id).

Raises:

Type Description
GitError

When spec names nothing.

Source code in packages/git/src/livery/git/_ops.py
def object_id(root: Path, spec: str) -> str:
    """The object id *spec* names (``HEAD:packages/forge`` is a tree id).

    Raises:
        GitError: When *spec* names nothing.
    """
    with _opened(root) as repo:
        try:
            found = _objects.object_named(repo, spec)
        except (_objects.Unresolved, KeyError):
            found = None
    if found is None:
        raise GitError(f"{spec} names nothing in {root}")
    return found.decode()

object_ids

object_ids(root: Path, ref: str, paths: Sequence[str]) -> dict[str, str]

The object ids ref holds at paths, read in-process.

Parameters:

Name Type Description Default
root Path

The repository's working directory.

required
ref str

The commit or tree to read, HEAD for the tip.

required
paths Sequence[str]

Repository-relative paths, files or directories.

required

Returns:

Type Description
dict[str, str]

Each path the tree holds, mapped to its object id: a tree

dict[str, str]

id for a directory, a blob id for a file. A path the tree

dict[str, str]

lacks is absent, so a caller that tolerates one reads the

dict[str, str]

mapping and a caller that does not raises on its own

dict[str, str]

behalf.

Source code in packages/git/src/livery/git/_ops.py
def object_ids(root: Path, ref: str, paths: Sequence[str]) -> dict[str, str]:
    """The object ids *ref* holds at *paths*, read in-process.

    Args:
        root: The repository's working directory.
        ref: The commit or tree to read, ``HEAD`` for the tip.
        paths: Repository-relative paths, files or directories.

    Returns:
        Each path the tree holds, mapped to its object id: a tree
        id for a directory, a blob id for a file. A path the tree
        lacks is absent, so a caller that tolerates one reads the
        mapping and a caller that does not raises on its own
        behalf.
    """
    if not paths:
        return {}
    with _opened(root) as repo:
        tree = _objects.tree_at(repo, _named(repo, ref, root))
        found: dict[str, str] = {}
        for path in paths:
            item = _objects.entry(repo, tree, path)
            if item is not None:
                found[path] = item[1].decode()
    return found

oneline

oneline(root: Path, span: str) -> list[str]

The commits in span (a..b), one line each, newest first.

Source code in packages/git/src/livery/git/_ops.py
def oneline(root: Path, span: str) -> list[str]:
    """The commits in *span* (``a..b``), one line each, newest first."""
    with _opened(root) as repo:
        return [
            f"{commit.id.decode()[:7]} {_objects.subject_and_body(commit.message)[0]}"
            for commit in _walk_span(repo, span, root)
        ]

position

position(root: Path) -> tuple[str, str]

The checked-out branch name, empty when detached, and HEAD's commit.

Both read in-process from the checkout's own files, so a flow that asks where it stands pays no process for either.

Raises:

Type Description
GitError

When HEAD names no commit yet.

Source code in packages/git/src/livery/git/_ops.py
def position(root: Path) -> tuple[str, str]:
    """The checked-out branch name, empty when detached, and HEAD's commit.

    Both read in-process from the checkout's own files, so a flow that
    asks where it stands pays no process for either.

    Raises:
        GitError: When HEAD names no commit yet.
    """
    with _opened(root) as repo:
        return _branch_of(repo), _head_of(repo)

push

push(root: Path, branch: str, *, remote: str = 'origin', force: bool = False) -> None

Push branch to remote, setting upstream; force replaces what is there.

A bare force, for a repository seconds old whose history this checkout authored; a branch others may have moved takes livery.git.push_force and its lease.

Source code in packages/git/src/livery/git/_ops.py
def push(
    root: Path, branch: str, *, remote: str = "origin", force: bool = False
) -> None:
    """Push *branch* to *remote*, setting upstream; *force* replaces what is there.

    A bare force, for a repository seconds old whose history this
    checkout authored; a branch others may have moved takes
    [livery.git.push_force][] and its lease.
    """
    run(root, "push", "--quiet", *(["--force"] if force else []), "-u", remote, branch)

push_force

push_force(root: Path, branch: str) -> None

Force-push branch, leased on the last-seen remote state.

--force-with-lease, never a bare force: the push is refused when origin moved past what this clone last fetched, so a colleague's commits pushed since then cannot be clobbered blind.

Source code in packages/git/src/livery/git/_ops.py
def push_force(root: Path, branch: str) -> None:
    """Force-push *branch*, leased on the last-seen remote state.

    ``--force-with-lease``, never a bare force: the push is
    refused when origin moved past what this clone last fetched,
    so a colleague's commits pushed since then cannot be
    clobbered blind.
    """
    run(root, "push", "--force-with-lease", "-u", "origin", branch)

push_refspec

push_refspec(root: Path, refspec: str, *, remote: str = 'origin') -> None

Push refspec to remote as given: a tag, or :refs/tags/x to delete one.

Source code in packages/git/src/livery/git/_ops.py
def push_refspec(root: Path, refspec: str, *, remote: str = "origin") -> None:
    """Push *refspec* to *remote* as given: a tag, or ``:refs/tags/x`` to delete one."""
    run(root, "push", "--quiet", remote, refspec)

recent_commits

recent_commits(root: Path, count: int, ref: str = 'HEAD') -> tuple[tuple[str, str], ...]

(sha, subject) for the newest count commits reachable from ref.

Source code in packages/git/src/livery/git/_ops.py
def recent_commits(
    root: Path, count: int, ref: str = "HEAD"
) -> tuple[tuple[str, str], ...]:
    """(sha, subject) for the newest *count* commits reachable from *ref*."""
    with _opened(root) as repo:
        return tuple(
            (commit.id.decode(), _objects.subject_and_body(commit.message)[0])
            for commit in _objects.walk(repo, [_resolved(repo, ref, root)], limit=count)
        )

remote_branches

remote_branches(root: Path, prefix: str) -> tuple[str, ...]

Branch names under prefix on origin, asked of the remote.

ls-remote, never the remote-tracking refs: a plain fetch does not prune, so a stale tracking ref outlives the forge's auto-delete and would resurrect a finished workflow.

Source code in packages/git/src/livery/git/_ops.py
def remote_branches(root: Path, prefix: str) -> tuple[str, ...]:
    """Branch names under *prefix* on origin, asked of the remote.

    ``ls-remote``, never the remote-tracking refs: a plain fetch
    does not prune, so a stale tracking ref outlives the forge's
    auto-delete and would resurrect a finished workflow.
    """
    out = run(root, "ls-remote", "--heads", "origin", f"refs/heads/{prefix}*")
    names: list[str] = []
    for line in out.splitlines():
        _, _, ref = line.partition("refs/heads/")
        if ref.strip():
            names.append(ref.strip())
    return tuple(names)

remote_head

remote_head(root: Path, branch: str) -> str

origin/<branch>'s commit, or empty when it does not exist.

Reads the local remote-tracking ref, so call livery.git.fetch first for a fresh answer.

Source code in packages/git/src/livery/git/_ops.py
def remote_head(root: Path, branch: str) -> str:
    """``origin/<branch>``'s commit, or empty when it does not exist.

    Reads the local remote-tracking ref, so call [livery.git.fetch][]
    first for a fresh answer.
    """
    with _opened(root) as repo:
        sha = _objects.ref_value(repo, b"refs/remotes/origin/" + branch.encode())
    return sha.decode() if sha is not None else ""

remote_tags

remote_tags(root: Path) -> tuple[str, ...]

Tag names on origin, asked of the remote.

ls-remote, never the local list: a tag cut elsewhere (a CI wave's receipt) is only guaranteed visible at the remote.

Source code in packages/git/src/livery/git/_ops.py
def remote_tags(root: Path) -> tuple[str, ...]:
    """Tag names on origin, asked of the remote.

    ``ls-remote``, never the local list: a tag cut elsewhere (a
    CI wave's receipt) is only guaranteed visible at the remote.
    """
    out = run(root, "ls-remote", "--tags", "origin")
    names: list[str] = []
    for line in out.splitlines():
        _, _, ref = line.partition("refs/tags/")
        ref = ref.strip().removesuffix("^{}")
        if ref:
            names.append(ref)
    return tuple(dict.fromkeys(names))

remote_url

remote_url(root: Path, name: str = 'origin') -> str

The URL of the remote name.

Raises:

Type Description
GitError

When root has no such remote.

Source code in packages/git/src/livery/git/_ops.py
def remote_url(root: Path, name: str = "origin") -> str:
    """The URL of the remote *name*.

    Raises:
        GitError: When *root* has no such remote.
    """
    with _opened(root) as repo:
        url = _objects.config_value(repo, f"remote.{name}.url")
    if not url:
        raise GitError(f"{root} has no remote {name}")
    return url

remotes

remotes(root: Path) -> tuple[str, ...]

The names of the repository's remotes.

Source code in packages/git/src/livery/git/_ops.py
def remotes(root: Path) -> tuple[str, ...]:
    """The names of the repository's remotes."""
    with _opened(root) as repo:
        found = _objects.config_matching(repo, r"^remote\.[^.]+\.url$")
    return tuple(sorted(key.split(".", 1)[1].rsplit(".", 1)[0] for key in found))

reset_hard

reset_hard(root: Path, ref: str) -> None

Move the branch, the index and the working tree to ref; every change goes.

Source code in packages/git/src/livery/git/_ops.py
def reset_hard(root: Path, ref: str) -> None:
    """Move the branch, the index and the working tree to *ref*; every change goes."""
    run(root, "reset", "--hard", ref)

restore

restore(root: Path, *paths: str) -> str

Put paths back as HEAD has them; empty, or git's words when it could not.

A path HEAD lacks refuses the whole pathspec, so a caller restoring several files it is unsure of restores them one by one.

Source code in packages/git/src/livery/git/_ops.py
def restore(root: Path, *paths: str) -> str:
    """Put *paths* back as HEAD has them; empty, or git's words when it could not.

    A path HEAD lacks refuses the whole pathspec, so a caller restoring
    several files it is unsure of restores them one by one.
    """
    result = call(root, "checkout", "HEAD", "--", *paths)
    return "" if result.code == 0 else (result.stderr or result.stdout).strip()

run

run(root: Path, *args: str) -> str

Run git with args in root and return its standard output.

Raises:

Type Description
GitError

On a non-zero exit, with git's words. The message names the call with *** for an argument that redacts itself.

Source code in packages/git/src/livery/git/_ops.py
def run(root: Path, *args: str) -> str:
    """Run git with *args* in *root* and return its standard output.

    Raises:
        GitError: On a non-zero exit, with git's words. The message
            names the call with ``***`` for an argument that redacts
            itself.
    """
    result = call(root, *args)
    if result.code != 0:
        raise GitError(
            f"git {_spelled(args)} exited {result.code}:"
            f"\n{result.stdout}{result.stderr}"
        )
    return result.stdout

set_remote_url

set_remote_url(root: Path, name: str, url: str) -> None

Point the remote name at url.

Source code in packages/git/src/livery/git/_ops.py
def set_remote_url(root: Path, name: str, url: str) -> None:
    """Point the remote *name* at *url*."""
    run(root, "remote", "set-url", name, url)

sha_of

sha_of(root: Path, ref: str) -> str

The commit ref resolves to; empty when this checkout cannot.

For a caller taking a commit-ish from a person: a sha, a branch, a tag, HEAD, HEAD~3. The common grammar resolves in-process; anything else is asked of git, and a name that resolves to nothing is an empty answer the caller reports.

Source code in packages/git/src/livery/git/_ops.py
def sha_of(root: Path, ref: str) -> str:
    """The commit *ref* resolves to; empty when this checkout cannot.

    For a caller taking a commit-ish from a person: a sha, a branch,
    a tag, ``HEAD``, ``HEAD~3``. The common grammar resolves in-process;
    anything else is asked of git, and a name that resolves to nothing
    is an empty answer the caller reports.
    """
    with _opened(root) as repo:
        try:
            return _objects.resolve(repo, ref).decode()
        except _objects.Unresolved:
            pass
    # `~0` peels to the commit as `^{commit}` does. A caret never
    # reaches git on Windows: the store runs git through a `.cmd`
    # launcher, and cmd.exe takes `^` as its escape character.
    result = call(root, "rev-parse", "--verify", f"{ref}~0")
    return result.stdout.strip() if result.code == 0 else ""

staged_text

staged_text(root: Path, path: str, stage: int) -> str

path's text at index stage of a conflict; empty when that side has none.

Stage 1 is the common ancestor, 2 the side being merged into (the base, in a rebase), 3 the side merged in (the commit replayed, in a rebase).

Source code in packages/git/src/livery/git/_ops.py
def staged_text(root: Path, path: str, stage: int) -> str:
    """*path*'s text at index *stage* of a conflict; empty when that side has none.

    Stage 1 is the common ancestor, 2 the side being merged into
    (the base, in a rebase), 3 the side merged in (the commit
    replayed, in a rebase).
    """
    result = call(root, "show", f":{stage}:{path}")
    return result.stdout if result.code == 0 else ""

subjects_ahead

subjects_ahead(root: Path, base: str) -> list[str]

The subjects of the commits HEAD carries beyond origin/<base>.

Source code in packages/git/src/livery/git/_ops.py
def subjects_ahead(root: Path, base: str) -> list[str]:
    """The subjects of the commits HEAD carries beyond ``origin/<base>``."""
    with _opened(root) as repo:
        return [
            _objects.subject_and_body(commit.message)[0]
            for commit in _walk_span(repo, f"origin/{base}..HEAD", root)
        ]

switch

switch(root: Path, name: str) -> None

Switch to the existing branch name.

Source code in packages/git/src/livery/git/_ops.py
def switch(root: Path, name: str) -> None:
    """Switch to the existing branch *name*."""
    run(root, "switch", name)

switch_new

switch_new(root: Path, name: str, start: str = '') -> None

Create or reset the branch name at start (HEAD when empty); switch to it.

Source code in packages/git/src/livery/git/_ops.py
def switch_new(root: Path, name: str, start: str = "") -> None:
    """Create or reset the branch *name* at *start* (HEAD when empty); switch to it."""
    run(root, "switch", "-C", name, *([start] if start else []))

tag_dates

tag_dates(root: Path, prefix: str) -> list[tuple[str, str]]

Every tag under prefix with the date it was made, YYYY-MM-DD.

Source code in packages/git/src/livery/git/_ops.py
def tag_dates(root: Path, prefix: str) -> list[tuple[str, str]]:
    """Every tag under *prefix* with the date it was made, ``YYYY-MM-DD``."""
    with _opened(root) as repo:
        refs = _objects.refs_under(repo, prefix.encode(), whole=True)
        return [
            (
                name.removeprefix("refs/tags/"),
                _objects.when_made(repo, sha.encode()).date().isoformat(),
            )
            for name, sha in sorted(refs.items())
        ]

tags

tags(root: Path) -> tuple[str, ...]

Every tag name the repository knows.

Source code in packages/git/src/livery/git/_ops.py
def tags(root: Path) -> tuple[str, ...]:
    """Every tag name the repository knows."""
    with _opened(root) as repo:
        return tuple(
            sorted(
                name.removeprefix("refs/tags/")
                for name in _objects.refs_under(repo, b"refs/tags/")
            )
        )

tracking_branches

tracking_branches(root: Path, prefix: str) -> tuple[str, ...]

Branch names under prefix among origin's remote-tracking refs.

Read locally, so no network and no wait, and as fresh as the last fetch: a branch pushed since is missing, and one the forge deleted lingers until a fetch prunes it. A caller that only names a branch takes that; one that deletes or protects asks origin through livery.git.remote_branches.

Source code in packages/git/src/livery/git/_ops.py
def tracking_branches(root: Path, prefix: str) -> tuple[str, ...]:
    """Branch names under *prefix* among origin's remote-tracking refs.

    Read locally, so no network and no wait, and as fresh as the
    last fetch: a branch pushed since is missing, and one the forge
    deleted lingers until a fetch prunes it. A caller that only
    names a branch takes that; one that deletes or protects asks
    origin through [livery.git.remote_branches][].
    """
    with _opened(root) as repo:
        found = _objects.refs_under(
            repo, b"refs/remotes/origin/" + prefix.encode(), whole=True
        )
    names = (name.removeprefix("refs/remotes/origin/") for name in sorted(found))
    return tuple(name for name in names if name and name != "HEAD")

tracks

tracks(root: Path, spec: str) -> bool

Whether the repository holds the object spec names: HEAD:uv.lock, a sha.

Source code in packages/git/src/livery/git/_ops.py
def tracks(root: Path, spec: str) -> bool:
    """Whether the repository holds the object *spec* names: ``HEAD:uv.lock``, a sha."""
    with _opened(root) as repo:
        try:
            if len(spec) == 40 and all(c in "0123456789abcdef" for c in spec):
                return _objects.holds(repo, spec.encode())
            return _objects.object_named(repo, spec) is not None
        except (_objects.Unresolved, KeyError):
            return False

tree_diff

tree_diff(root: Path, old: str, new: str) -> list[str]

The paths differing between the trees old and new.

A rename is both sides.

Source code in packages/git/src/livery/git/_ops.py
def tree_diff(root: Path, old: str, new: str) -> list[str]:
    """The paths differing between the trees *old* and *new*.

    A rename is both sides.
    """
    with _opened(root) as repo:
        return _objects.changed_paths_between(repo, old.encode(), new.encode())

unmerged_paths

unmerged_paths(root: Path) -> list[str]

The paths a stopped merge or rebase left conflicted, as git names them.

Source code in packages/git/src/livery/git/_ops.py
def unmerged_paths(root: Path) -> list[str]:
    """The paths a stopped merge or rebase left conflicted, as git names them."""
    out = run(root, "diff", "--name-only", "--diff-filter=U")
    return [line for line in out.splitlines() if line]

unpushed

unpushed(root: Path) -> list[str]

The commits on any local branch that origin holds on no branch, one line each.

Source code in packages/git/src/livery/git/_ops.py
def unpushed(root: Path) -> list[str]:
    """The commits on any local branch that origin holds on no branch, one line each."""
    with _opened(root) as repo:
        heads = [
            sha.encode() for sha in _objects.refs_under(repo, b"refs/heads/").values()
        ]
        remote = [
            sha.encode()
            for sha in _objects.refs_under(repo, b"refs/remotes/origin/").values()
        ]
        if not heads:
            return []
        return [
            f"{commit.id.decode()[:7]} {_objects.subject_and_body(commit.message)[0]}"
            for commit in _objects.walk(repo, heads, exclude=remote)
        ]

unstage

unstage(root: Path, path: str) -> None

Take path out of the index and leave the file; an untracked path is fine.

Source code in packages/git/src/livery/git/_ops.py
def unstage(root: Path, path: str) -> None:
    """Take *path* out of the index and leave the file; an untracked path is fine."""
    run(root, "rm", "--cached", "--quiet", "--ignore-unmatch", "--", path)

working_tree_id

working_tree_id(root: Path) -> str

The tree id of the working tree as it stands.

Tracked changes and untracked files count and ignored files do not, the view status gives, written through a scratch copy of the index so the real index is never touched. A clean checkout answers HEAD's tree, so a commit that takes everything has the id a check on the dirty tree recorded.

Source code in packages/git/src/livery/git/_ops.py
def working_tree_id(root: Path) -> str:
    """The tree id of the working tree as it stands.

    Tracked changes and untracked files count and ignored files do
    not, the view ``status`` gives, written through a scratch copy
    of the index so the real index is never touched. A clean
    checkout answers HEAD's tree, so a commit that takes everything
    has the id a check on the dirty tree recorded.
    """
    index = run(root, "rev-parse", "--git-path", "index").strip()
    real = Path(index) if Path(index).is_absolute() else root / index
    with tempfile.TemporaryDirectory() as scratch:
        copy = Path(scratch) / "index"
        if real.is_file():
            # copy2, so the copy keeps the index's own timestamps.
            # git trusts a cached stat only when the entry is older
            # than the index file; an entry as new as the index is
            # racily clean and its content is read again. A copy
            # stamped with the time of the copy looks newer than
            # every entry, which switches that rule off, and a
            # rewrite of the same size in the same second as the
            # cached stat then reads as no change at all (git
            # compares whole seconds where it is built without
            # nanosecond stat, as it is on macOS).
            shutil.copy2(real, copy)
        env = {**os.environ, "GIT_INDEX_FILE": str(copy)}
        git = tools.git.opts(cwd=root, env=env, nofail=True, recorded=False)
        for args in (("add", "-A"), ("write-tree",)):
            result = git(*args)
            if result.code != 0:
                raise GitError(
                    f"git {' '.join(args)} exited {result.code}:"
                    f"\n{result.stdout}{result.stderr}"
                )
        return result.stdout.strip()

worktree_add

worktree_add(root: Path, path: Path, ref: str, *, detach: bool = False) -> None

Check ref out as a linked worktree at path, detached under detach.

Source code in packages/git/src/livery/git/_ops.py
def worktree_add(root: Path, path: Path, ref: str, *, detach: bool = False) -> None:
    """Check *ref* out as a linked worktree at *path*, detached under *detach*."""
    run(root, "worktree", "add", *(["--detach"] if detach else []), str(path), ref)

worktree_remove

worktree_remove(root: Path, path: Path) -> None

Remove the linked worktree at path, its changes with it.

Source code in packages/git/src/livery/git/_ops.py
def worktree_remove(root: Path, path: Path) -> None:
    """Remove the linked worktree at *path*, its changes with it."""
    run(root, "worktree", "remove", "--force", str(path))

master_up

master_up(socket_dir: Path, url: str, *, timeout: float = 10.0) -> bool

Whether a master for url's host is up under socket_dir.

ssh -O check asks the master over its socket and opens no connection; a remote that is not ssh has no master and answers False.

Source code in packages/git/src/livery/git/_ssh.py
def master_up(socket_dir: Path, url: str, *, timeout: float = 10.0) -> bool:
    """Whether a master for *url*'s host is up under *socket_dir*.

    `ssh -O check` asks the master over its socket and opens no
    connection; a remote that is not ssh has no master and answers
    False.
    """
    named = remote_host(url)
    if named is None:
        return False
    user, host, port = named
    try:
        checked = subprocess.run(
            [
                "ssh",
                "-O",
                "check",
                "-o",
                f"ControlPath={_socket_path(socket_dir)}",
                "-p",
                str(port),
                f"{user}@{host}",
            ],
            capture_output=True,
            timeout=timeout,
            check=False,
        )
    except (OSError, subprocess.TimeoutExpired):
        return False
    return checked.returncode == 0

record_unsupported

record_unsupported(socket_dir: Path, words: str) -> Path

Turn multiplexing off under socket_dir with words; the file written.

Source code in packages/git/src/livery/git/_ssh.py
def record_unsupported(socket_dir: Path, words: str) -> Path:
    """Turn multiplexing off under *socket_dir* with *words*; the file written."""
    socket_dir.mkdir(parents=True, exist_ok=True)
    verdict = socket_dir / UNSUPPORTED
    verdict.write_text(words.strip() + "\n", "utf-8")
    return verdict

remote_host

remote_host(url: str) -> tuple[str, str, int] | None

The user, host and port an ssh remote url names; None for any other transport.

Both spellings ssh remotes take: git@github.com:owner/repo.git and ssh://git@host:2222/owner/repo.git. An http, https or file remote opens no ssh connection.

Source code in packages/git/src/livery/git/_ssh.py
def remote_host(url: str) -> tuple[str, str, int] | None:
    """The user, host and port an ssh remote *url* names; None for any other transport.

    Both spellings ssh remotes take: `git@github.com:owner/repo.git`
    and `ssh://git@host:2222/owner/repo.git`. An `http`, `https` or
    `file` remote opens no ssh connection.
    """
    if "://" in url:
        parts = urlsplit(url)
        if parts.scheme not in ("ssh", "git+ssh", "ssh+git"):
            return None
        return parts.username or "git", parts.hostname or "", parts.port or 22
    head, sep, _ = url.partition(":")
    if not sep or "/" in head:
        return None
    user, _, host = head.rpartition("@")
    return user or "git", host, 22

ssh_command

ssh_command(socket_dir: Path, *, idle: str) -> str

The GIT_SSH_COMMAND that multiplexes over a master under socket_dir.

ControlMaster=auto reuses a master when one is up and opens one otherwise, replacing a stale socket from an unclean exit; two spawns racing to open a master is allowed, one wins and the other connects directly. ControlPersist=<idle> keeps the master that long after the last client. The path is quoted twice over: git hands the command to a shell, and ssh then splits an option's value on spaces unless it is double-quoted, and footman's data directory on macOS has a space in it.

Source code in packages/git/src/livery/git/_ssh.py
def ssh_command(socket_dir: Path, *, idle: str) -> str:
    """The `GIT_SSH_COMMAND` that multiplexes over a master under *socket_dir*.

    `ControlMaster=auto` reuses a master when one is up and opens one
    otherwise, replacing a stale socket from an unclean exit; two
    spawns racing to open a master is allowed, one wins and the other
    connects directly. `ControlPersist=<idle>` keeps the master that
    long after the last client. The path is quoted twice over: git
    hands the command to a shell, and ssh then splits an option's
    value on spaces unless it is double-quoted, and footman's data
    directory on macOS has a space in it.
    """
    options = (
        "ControlMaster=auto",
        shlex.quote(f'ControlPath="{_socket_path(socket_dir)}"'),
        f"ControlPersist={idle}",
        *_KEEPALIVE,
    )
    return "ssh " + " ".join(f"-o {option}" for option in options)

ssh_environment

ssh_environment(socket_dir: Path, *, idle: str = '10m', environ: Mapping[str, str] | None = None, configured: str = '') -> tuple[dict[str, str], str]

The environment that multiplexes a spawned git's ssh, or why not.

Parameters:

Name Type Description Default
socket_dir Path

Where the sockets live; owner-only and short.

required
idle str

How long a master lingers after its last client, in ssh's own spelling (10m).

'10m'
environ Mapping[str, str] | None

The environment the spawn would inherit; the process's own when omitted.

None
configured str

What git's core.sshCommand says, empty when unset.

''

Returns:

Type Description
dict[str, str]

The mapping to merge into the spawn's environment, holding

str

GIT_SSH_COMMAND, and an empty reason; or an empty mapping and

tuple[dict[str, str], str]

the reason multiplexing is not used. The reason is empty when

tuple[dict[str, str], str]

the person's own setting won, which is theirs to know about.

Source code in packages/git/src/livery/git/_ssh.py
def ssh_environment(
    socket_dir: Path,
    *,
    idle: str = "10m",
    environ: Mapping[str, str] | None = None,
    configured: str = "",
) -> tuple[dict[str, str], str]:
    """The environment that multiplexes a spawned git's ssh, or why not.

    Args:
        socket_dir: Where the sockets live; owner-only and short.
        idle: How long a master lingers after its last client, in ssh's
            own spelling (`10m`).
        environ: The environment the spawn would inherit; the process's
            own when omitted.
        configured: What git's `core.sshCommand` says, empty when unset.

    Returns:
        The mapping to merge into the spawn's environment, holding
        `GIT_SSH_COMMAND`, and an empty reason; or an empty mapping and
        the reason multiplexing is not used. The reason is empty when
        the person's own setting won, which is theirs to know about.
    """
    present = (os.environ if environ is None else environ).get("GIT_SSH_COMMAND", "")
    if present and socket_dir.as_posix() not in present:
        return {}, ""
    if configured:
        return {}, ""
    directory = socket_dir.as_posix().encode()
    if len(directory) + 1 + _NAME_BUDGET > _LIMIT:
        return {}, (
            f"ssh multiplexing off: {socket_dir} leaves no room for a socket name"
            f" under the {_LIMIT}-byte unix socket path limit"
        )
    verdict = socket_dir / UNSUPPORTED
    if verdict.is_file():
        words = verdict.read_text("utf-8").strip()
        return {}, f"ssh multiplexing off ({verdict}): {words}"
    socket_dir.mkdir(parents=True, exist_ok=True)
    return {"GIT_SSH_COMMAND": ssh_command(socket_dir, idle=idle)}, ""

ssh_sockets

ssh_sockets(data_dir: Path) -> Path

Where the plugin keeps its sockets: ssh under the runner's data_dir.

The data directory is owner-only and durable, which a socket wants, and short enough on every platform for the socket path limit below.

Source code in packages/git/src/livery/git/_ssh.py
def ssh_sockets(data_dir: Path) -> Path:
    """Where the plugin keeps its sockets: `ssh` under the runner's *data_dir*.

    The data directory is owner-only and durable, which a socket wants,
    and short enough on every platform for the socket path limit below.
    """
    return data_dir / "ssh"

drop

drop(store: StateStore, ref: str) -> str

Delete ref, on origin or in the checkout; "" when gone, else the reason.

A ref that is already absent counts as gone: the janitor re-runs as its own recovery, and a second sweep must find nothing to do.

Source code in packages/git/src/livery/git/_store.py
def drop(store: StateStore, ref: str) -> str:
    """Delete *ref*, on origin or in the checkout; ``""`` when gone, else the reason.

    A ref that is already absent counts as gone: the janitor re-runs
    as its own recovery, and a second sweep must find nothing to do.
    """
    if not ref.startswith((NAMESPACE, LOCAL_NAMESPACE, TRACE_NAMESPACE)):
        return (
            f"refusing {ref}: the state store deletes only under {NAMESPACE},"
            f" {LOCAL_NAMESPACE} and {TRACE_NAMESPACE}"
        )
    if ref.startswith(LOCAL_NAMESPACE):
        try:
            with _objects.opened(store.root) as repo:
                _objects.drop_ref(repo, ref.encode())
        except _objects.NotGitRepository:
            return f"delete refused: {_no_repository(store)}"
        except OSError as error:
            return f"delete refused: {error}"
        return ""
    deleted = _git(store.root, "push", "--quiet", "origin", f":{ref}")
    words = deleted.stderr + deleted.stdout
    if deleted.code != 0 and "remote ref does not exist" not in words:
        return f"delete refused: {_words(deleted)}"
    snapshot = _snapshot(store)
    if snapshot is not None and snapshot.refs is not None:
        snapshot.refs.pop(ref, None)
        _write_published(store.root.resolve(), snapshot)
    return ""

fetch_store

fetch_store(store: StateStore, *, series: Iterable[str], branches: bool = False) -> Fetched

Mirror the row series series under FETCHED_NAMESPACE and stamp it.

One fetch, pruned, with one refspec per name below NAMESPACE: metrics lands at refs/workshop-origin/metrics, a series origin holds no ref for yet costs nothing, and a ref origin dropped goes from the mirror. Afterwards the mirror holds the named series alone: every ref under it that is not one of them, such as a family's key a fetch of a wider scope left, is deleted here. Then the origin row of FETCHED records the time, the count of refs, and the names, sorted. The names are the mirror's scope: a fetched_snapshot reads a missing ref of a named series as absent and fails a read of any other remote ref. With branches the same fetch brings origin's heads into refs/remotes/origin/, pruned the same way, so a sync that needs both pays one round trip. A fetch transfers only what the checkout lacks: on a quiet origin the round trip is the whole cost and nothing changes. Named no series and no branches, the fetch is skipped and the mirror is emptied.

Returns:

Type Description
Fetched

The refs the mirror holds and how many this fetch changed, or

Fetched

zero of each and the reason when the fetch, the prune or the

Fetched

stamp failed, with git's words; nothing here raises or prints.

Source code in packages/git/src/livery/git/_store.py
def fetch_store(
    store: StateStore, *, series: Iterable[str], branches: bool = False
) -> Fetched:
    """Mirror the row series *series* under `FETCHED_NAMESPACE` and stamp it.

    One fetch, pruned, with one refspec per name below `NAMESPACE`:
    ``metrics`` lands at ``refs/workshop-origin/metrics``, a series
    origin holds no ref for yet costs nothing, and a ref origin
    dropped goes from the mirror. Afterwards the mirror holds the
    named series alone: every ref under it that is not one of them,
    such as a family's key a fetch of a wider scope left, is deleted
    here. Then the ``origin`` row of `FETCHED` records the time, the
    count of refs, and the names, sorted. The names are the mirror's
    scope: a `fetched_snapshot` reads a missing ref of a named series
    as absent and fails a read of any other remote ref. With
    *branches* the same fetch brings origin's heads into
    ``refs/remotes/origin/``, pruned the same way, so a sync that
    needs both pays one round trip. A fetch transfers only what the
    checkout lacks: on a quiet origin the round trip is the whole
    cost and nothing changes. Named no series and no branches, the
    fetch is skipped and the mirror is emptied.

    Returns:
        The refs the mirror holds and how many this fetch changed, or
        zero of each and the reason when the fetch, the prune or the
        stamp failed, with git's words; nothing here raises or prints.
    """
    names = sorted(set(series))
    before = _local_refs(store, FETCHED_NAMESPACE) or {}
    # A pattern anchored on the whole series name, not the bare name:
    # git refuses a fetch that names an exact ref origin does not hold
    # (a series nobody has written yet) and tolerates a pattern that
    # matches nothing. The one ref such a pattern brings beyond its
    # series is one whose name extends the series' name, which the
    # deletion below takes out of the mirror again.
    refspecs = [f"+{NAMESPACE}{name}*:{FETCHED_NAMESPACE}{name}*" for name in names]
    if branches:
        refspecs.insert(0, "+refs/heads/*:refs/remotes/origin/*")
    if refspecs:
        fetched = _git(store.root, "fetch", "--quiet", "--prune", "origin", *refspecs)
        if fetched.code != 0:
            return Fetched(0, _words(fetched))
    mirrored = _local_refs(store, FETCHED_NAMESPACE)
    if mirrored is None:
        return Fetched(0, "the mirror could not be listed")
    kept = {FETCHED_NAMESPACE + name for name in names}
    strays = sorted(name for name in mirrored if name not in kept)
    if strays:
        why = _drop_mirror_refs(store, strays)
        if why:
            return Fetched(0, why)
        mirrored = {name: sha for name, sha in mirrored.items() if name in kept}
    why = FETCHED.put(
        store,
        {"origin": {"refs": len(mirrored), "series": names}},
        message="fetched origin's store",
    )
    if why:
        return Fetched(0, why)
    changed = sum(
        1
        for name in set(before) | set(mirrored)
        if before.get(name) != mirrored.get(name)
    )
    return Fetched(len(mirrored), "", changed)

fetched_snapshot

fetched_snapshot(store: StateStore) -> Generator[None]

Read the remote namespace from the checkout's mirror of origin, for the block.

Nothing inside reaches origin. The listing is the mirror fetch_store took, with origin's branches beside it from the remote-tracking refs, every commit is local already, and a write of a remote series is refused with its reason; a local series reads and writes as ever. The series the stamp names are the mirror's scope: a read of one of them answers from the mirror, a missing ref among them is absence, and a read or a listing of any other remote ref, a keyed family's refs among them, fails naming the ref and the scope, never as an absence, since the mirror never held it; a live remote_snapshot reads those. In a checkout fetch_store never stamped, or stamped under another schema, the listing is a failure naming the sync, so every read inside fails the way an unreachable origin fails, never as an absence, and every caller falls open on it. A block opened inside another snapshot for the same checkout shares the outer one.

Source code in packages/git/src/livery/git/_store.py
@contextmanager
def fetched_snapshot(store: StateStore) -> Generator[None]:
    """Read the remote namespace from the checkout's mirror of origin, for the block.

    Nothing inside reaches origin. The listing is the mirror
    `fetch_store` took, with origin's branches beside it from the
    remote-tracking refs, every commit is local already, and a write
    of a remote series is refused with its reason; a local series
    reads and writes as ever. The series the stamp names are the
    mirror's scope: a read of one of them answers from the mirror, a
    missing ref among them is absence, and a read or a listing of any
    other remote ref, a keyed family's refs among them, fails naming
    the ref and the scope, never as an absence, since the mirror never
    held it; a live `remote_snapshot` reads those. In a checkout
    `fetch_store` never stamped, or stamped under another schema, the
    listing is a failure naming the sync, so every read inside fails
    the way an unreachable origin fails, never as an absence, and
    every caller falls open on it. A block opened inside another
    snapshot for the same checkout shares the outer one.
    """
    key = store.root.resolve()
    if key in _SNAPSHOTS:
        yield
        return
    stamped, why = FETCHED.row(store, "origin")
    names = None if stamped is None else _stamped_series(stamped)
    if stamped is not None and names is None:
        why = "origin: the stamp names no series"
    if names is None:
        detail = f" ({why})" if why else ""
        reason = (
            "origin's state store has not been fetched into this checkout"
            f"{detail}: run `{store.prog} sync`"
        )
        snapshot = _Snapshot(None, reason, offline=True)
    else:
        mirrored = _local_refs(store, FETCHED_NAMESPACE)
        branches = _local_refs(store, "refs/remotes/origin/")
        if mirrored is None or branches is None:
            snapshot = _Snapshot(None, "the mirror could not be listed", offline=True)
        else:
            refs = {
                NAMESPACE + name.removeprefix(FETCHED_NAMESPACE): sha
                for name, sha in mirrored.items()
            }
            for name, sha in branches.items():
                short = name.removeprefix("refs/remotes/origin/")
                if short != "HEAD":
                    refs["refs/heads/" + short] = sha
            snapshot = _Snapshot(
                refs,
                "",
                set(refs.values()),
                offline=True,
                mirrored=frozenset(NAMESPACE + name for name in names),
            )
    _SNAPSHOTS[key] = snapshot
    try:
        yield
    finally:
        _SNAPSHOTS.pop(key, None)

list_refs

list_refs(store: StateStore, prefix: str) -> dict[str, str] | None

The refs under prefix by sha, remote or local; None when unlistable.

A prefix under the local namespace, the mirror, or the remote-tracking refs is listed from the checkout's git directory; any other answers from the open snapshot when one covers it, and from origin otherwise. A snapshot of the mirror covers the branches and a prefix at or below one of its series; a wider prefix under a remote namespace, a keyed family's, is unlistable from it, never empty, since the mirror holds none of its refs.

Source code in packages/git/src/livery/git/_store.py
def list_refs(store: StateStore, prefix: str) -> dict[str, str] | None:
    """The refs under *prefix* by sha, remote or local; ``None`` when unlistable.

    A prefix under the local namespace, the mirror, or the
    remote-tracking refs is listed from the checkout's git directory;
    any other answers from the open snapshot when one covers it, and
    from origin otherwise. A snapshot of the mirror covers the
    branches and a prefix at or below one of its series; a wider
    prefix under a remote namespace, a keyed family's, is unlistable
    from it, never empty, since the mirror holds none of its refs.
    """
    if prefix.startswith((LOCAL_NAMESPACE, FETCHED_NAMESPACE, "refs/remotes/")):
        return _local_refs(store, prefix)
    snapshot = _snapshot(store)
    if snapshot is not None and prefix.startswith(LISTED):
        if snapshot.refs is None:
            return None
        if (
            snapshot.mirrored is not None
            and not prefix.startswith("refs/heads/")
            and not any(prefix.startswith(ref) for ref in snapshot.mirrored)
        ):
            return None
        return {
            name: sha for name, sha in snapshot.refs.items() if name.startswith(prefix)
        }
    listed = _git(store.root, "ls-remote", "origin", prefix + "*")
    return _parse_listing(listed)

put

put(store: StateStore, ref: str, files: dict[str, str], *, message: str, window: int | None = None, ci_only: bool = False, order: Order | None = None, remove: Iterable[str] = (), attempts: int = ATTEMPTS) -> str

Write files onto ref, keeping what it already holds; "" or the reason.

The tree is the ref's current files, less remove, with files laid over them, trimmed to the newest window files when one is given, ranked by order or, without one, by name. The push is a compare-and-swap on the sha the read returned: a ref another writer moved in between refuses the push, and the write re-reads, merges, and retries up to attempts times. ci_only refuses a write from outside CI, naming the rule. Every refusal is the returned reason; nothing here raises or prints.

Source code in packages/git/src/livery/git/_store.py
def put(
    store: StateStore,
    ref: str,
    files: dict[str, str],
    *,
    message: str,
    window: int | None = None,
    ci_only: bool = False,
    order: Order | None = None,
    remove: Iterable[str] = (),
    attempts: int = ATTEMPTS,
) -> str:
    """Write *files* onto *ref*, keeping what it already holds; ``""`` or the reason.

    The tree is the ref's current files, less *remove*, with *files*
    laid over them, trimmed to the newest *window* files when one is
    given, ranked by *order* or, without one, by name. The push
    is a compare-and-swap on the sha the read returned: a ref another
    writer moved in between refuses the push, and the write re-reads,
    merges, and retries up to *attempts* times. *ci_only* refuses a
    write from outside CI, naming the rule. Every refusal is the
    returned reason; nothing here raises or prints.
    """
    if not ref.startswith((NAMESPACE, LOCAL_NAMESPACE, TRACE_NAMESPACE)):
        return (
            f"refusing {ref}: the state store writes only under {NAMESPACE},"
            f" {LOCAL_NAMESPACE} and {TRACE_NAMESPACE}"
        )
    if ci_only and not store.in_ci:
        return f"refusing {ref}: only a CI run writes this series; local runs read"
    opened = _snapshot(store)
    if opened is not None and opened.offline and not ref.startswith(LOCAL_NAMESPACE):
        return (
            f"refusing {ref}: this block reads origin's store as last fetched"
            " and writes nothing to origin"
        )
    for _ in range(attempts):
        current = read(store, ref)
        if current.failed:
            return (
                f"refusing to write {ref}: its current state could not be"
                f" read ({current.reason}), and a write from an unread state"
                " would erase what it holds"
            )
        gone = set(remove)
        merged = {
            name: text
            for name, text in (current.files or {}).items()
            if name not in gone
        } | files
        if window is not None and len(merged) > window:
            merged = _trim(merged, window, order)
        commit, why = _build_commit(store, merged, message)
        if why:
            return why
        if ref.startswith(LOCAL_NAMESPACE):
            # The compare-and-swap in-process: the old value is the sha
            # the read returned, or none for a ref that must not exist
            # yet, and a lost swap costs a retry.
            try:
                with _objects.opened(store.root) as repo:
                    moved = _objects.set_ref(
                        repo,
                        ref.encode(),
                        commit.encode(),
                        current.sha.encode() if current.sha else None,
                    )
            except OSError as error:
                return f"update refused: {error}"
            if not moved:
                continue
            return ""
        lease = f"--force-with-lease={ref}:{current.sha or ''}"
        pushed = _git(store.root, "push", "--quiet", lease, "origin", f"{commit}:{ref}")
        snapshot = _snapshot(store)
        if pushed.code != 0:
            if _stale(pushed):
                if snapshot is not None:
                    _relist(store, snapshot)
                continue
            return f"push refused: {_words(pushed)}"
        if snapshot is not None and snapshot.refs is not None:
            snapshot.refs[ref] = commit
            snapshot.local.add(commit)
            _write_published(store.root.resolve(), snapshot)
        return ""
    return f"gave up on {ref} after {attempts} attempts: another writer kept moving it"

read

read(store: StateStore, ref: str, *, only: Callable[[str], bool] | None = None) -> Read

Read ref's files, saying whether a miss is absence or failure.

A remote ref is fetched from origin: the fetch lands in FETCH_HEAD and creates no local ref, so a checkout accrues only unreachable objects git's own gc prunes. A failed fetch is a failure only when the ref is there: a ref that does not exist also fails the fetch, and that is the ordinary first-run case. A remote that cannot answer the probe either counts as failed: an unreachable forge must never read as "there was never a stamp". A local ref, or one of the mirror under FETCHED_NAMESPACE, is read from the checkout's own git directory: a missing ref is absence, and anything else git refuses is a failure with git's words. With only, the files whose names it accepts are read and the rest are named in names alone, never read.

Source code in packages/git/src/livery/git/_store.py
def read(
    store: StateStore, ref: str, *, only: Callable[[str], bool] | None = None
) -> Read:
    """Read *ref*'s files, saying whether a miss is absence or failure.

    A remote ref is fetched from origin: the fetch lands in
    ``FETCH_HEAD`` and creates no local ref, so a checkout accrues
    only unreachable objects git's own gc prunes. A failed fetch is a
    failure only when the ref is there: a ref that does not exist
    also fails the fetch, and that is the ordinary first-run case. A
    remote that cannot answer the probe either counts as failed: an
    unreachable forge must never read as "there was never a stamp".
    A local ref, or one of the mirror under `FETCHED_NAMESPACE`, is
    read from the checkout's own git directory: a missing ref is
    absence, and anything else git refuses is a failure with git's
    words. With *only*, the files whose names it accepts are read and
    the rest are named in ``names`` alone, never read.
    """
    if ref.startswith((LOCAL_NAMESPACE, FETCHED_NAMESPACE)):
        try:
            with _objects.opened(store.root) as repo:
                held = _objects.ref_value(repo, ref.encode())
        except _objects.NotGitRepository:
            return Read(None, None, failed=True, reason=_no_repository(store))
        if held is None:
            return Read(None, None, failed=False)
        return _tree_files(store, held.decode(), only)
    snapshot = _snapshot(store)
    if snapshot is not None:
        if snapshot.refs is None:
            return Read(
                None,
                None,
                failed=True,
                reason=f"the remote could not be listed: {snapshot.reason}",
            )
        if snapshot.mirrored is not None and ref not in snapshot.mirrored:
            return Read(
                None, None, failed=True, reason=_outside_mirror(store, snapshot, ref)
            )
        listed = snapshot.refs.get(ref)
        if listed is None:
            return Read(None, None, failed=False)
        sha, why = _reachable(store, snapshot, ref, listed)
        if why:
            return Read(None, listed, failed=True, reason=why)
        if sha is None:
            return Read(None, None, failed=False)
        return _tree_files(store, sha, only)
    fetched = _git(store.root, "fetch", "--quiet", "origin", ref)
    if fetched.code != 0:
        exists, why = _ref_exists(store, ref)
        if exists is False:
            return Read(None, None, failed=False)
        return Read(None, None, failed=True, reason=why or _words(fetched))
    return _tree_files(store, _fetch_head(store), only)

remote_snapshot

remote_snapshot(store: StateStore, *, fetch: Iterable[str] = (), publish: bool = False) -> Generator[str | None]

Read the remote namespace through one listing for the block.

One ls-remote of the store's namespace and the branches when the block opens; every read and listing of a remote ref inside answers from it, and a ref whose commit the checkout already holds is read with no network at all. The refs whose names start with a prefix in fetch (spelled below the namespace, metrics or run/1400/, or in full from refs/ for another namespace, refs/workshop-trace/about/) and whose commits the checkout lacks are fetched together, one round trip, when the block opens. A read of a ref outside them brings the ref's whole key group in one fetch (_key_group), so a loop over a family's keys costs one round trip whichever ref it reads first. A ref another writer moved after the listing is listed again and read at its current commit, so a concurrent writer never turns a read into a failure. A write inside keeps its compare-and-swap on the listed sha: a refused push lists again and retries, and a successful write records its new sha, so a read after it sees it. A listing the forge could not answer makes every read inside a failure naming the reason and every listing unlistable, never an absence. A block opened inside another for the same checkout shares the outer listing and brings what its own fetch names against it.

With publish the listing is written to a file whose path the block yields, for the caller to hand its child processes under SNAPSHOT_VARIABLE: a block a child opens reads that file instead of listing, and the child's writes record their shas in it for the children after it. A listing the parent could not take is not published and the block yields None, so a child lists for itself; a file a child cannot read, or one taken for another checkout, counts as none. Without publish the block yields None.

Source code in packages/git/src/livery/git/_store.py
@contextmanager
def remote_snapshot(
    store: StateStore, *, fetch: Iterable[str] = (), publish: bool = False
) -> Generator[str | None]:
    """Read the remote namespace through one listing for the block.

    One ``ls-remote`` of the store's namespace and the branches when
    the block opens; every read and listing of a remote ref inside
    answers from it, and a ref whose commit the checkout already
    holds is read with no network at all. The refs whose names start
    with a prefix in *fetch* (spelled below the namespace, ``metrics``
    or ``run/1400/``, or in full from ``refs/`` for another namespace,
    ``refs/workshop-trace/about/``) and whose commits the checkout
    lacks are fetched together, one round trip, when the block opens.
    A read of a ref outside them brings the ref's whole key group in
    one fetch (`_key_group`), so a loop over a family's keys costs one
    round trip whichever ref it reads first. A ref another writer
    moved after the listing is listed again and read at its current
    commit, so a concurrent writer never turns a read into a failure.
    A write inside keeps its compare-and-swap on the listed sha: a
    refused push lists again and retries, and a successful write
    records its new sha, so a read after it sees it. A listing the
    forge could not answer makes every read inside a failure naming
    the reason and every listing unlistable, never an absence. A block
    opened inside another for the same checkout shares the outer
    listing and brings what its own *fetch* names against it.

    With *publish* the listing is written to a file whose path the
    block yields, for the caller to hand its child processes under
    `SNAPSHOT_VARIABLE`: a block a child opens reads that file
    instead of listing, and the child's writes record their shas in
    it for the children after it. A listing the parent could not
    take is not published and the block yields ``None``, so a child
    lists for itself; a file a child cannot read, or one taken for
    another checkout, counts as none. Without *publish* the block
    yields ``None``.
    """
    key = store.root.resolve()
    if key in _SNAPSHOTS:
        _bring_prefixes(store, _SNAPSHOTS[key], fetch)
        yield None
        return
    snapshot = _published_snapshot(store, key)
    if snapshot is None:
        refs, why = _list_namespace(store)
        snapshot = _Snapshot(refs, why)
    refs = snapshot.refs
    _bring_prefixes(store, snapshot, fetch)
    published_here = ""
    if publish and refs is not None and snapshot.published is None:
        with tempfile.NamedTemporaryFile(
            "w", encoding="utf-8", suffix=".json", delete=False
        ) as handle:
            snapshot.published = Path(handle.name)
        _write_published(key, snapshot)
        published_here = str(snapshot.published)
    _SNAPSHOTS[key] = snapshot
    try:
        yield published_here or None
    finally:
        _SNAPSHOTS.pop(key, None)
        if published_here:
            Path(published_here).unlink(missing_ok=True)

slug

slug(name: str) -> str

name as a ref-safe and file-safe token: every other character is a dash.

Source code in packages/git/src/livery/git/_store.py
def slug(name: str) -> str:
    """*name* as a ref-safe and file-safe token: every other character is a dash."""
    return re.sub(r"[^A-Za-z0-9_-]", "-", name)

sweep

sweep(store: StateStore, declared: tuple[Series | Keyed, ...], *, remote: bool, dry_run: bool = False, now: datetime | None = None) -> list[str]

The store's janitor: every series bounded, every orphan dropped; the lines.

The scope is the run's: the local series always, the remote ones only under remote, which a caller sets inside CI, since a local run never writes the remote store. A series is trimmed to its window, and the rows older than the age it declares go. A family's keys are listed and each key's series is bounded the same way, after its orphans go: a key whose ref is older than the family's stale_after, or one the family's current keys no longer include. A family that cannot be listed, or whose current keys cannot be told, drops nothing and says so. Under dry_run every line says what would go and nothing is written. Every line names what happened; a failure is a line, never a raise, and a second sweep finds nothing to do. A remote sweep reads through one snapshot of the namespace, its caller's when one is open, so a family's keys, rows and commit times cost a fetch per key group, never one per key.

Source code in packages/git/src/livery/git/_store.py
def sweep(
    store: StateStore,
    declared: tuple[Series | Keyed, ...],
    *,
    remote: bool,
    dry_run: bool = False,
    now: datetime | None = None,
) -> list[str]:
    """The store's janitor: every series bounded, every orphan dropped; the lines.

    The scope is the run's: the local series always, the remote ones
    only under *remote*, which a caller sets inside CI, since a local
    run never writes the remote store. A series is trimmed to its
    window, and the rows older than the age it declares go. A
    family's keys are listed and each key's series is bounded the
    same way, after its orphans go: a key whose ref is older than the
    family's ``stale_after``, or one the family's ``current`` keys no
    longer include. A family that cannot be listed, or whose current
    keys cannot be told, drops nothing and says so. Under *dry_run*
    every line says what would go and nothing is written. Every line
    names what happened; a failure is a line, never a raise, and a
    second sweep finds nothing to do. A remote sweep reads through one
    snapshot of the namespace, its caller's when one is open, so a
    family's keys, rows and commit times cost a fetch per key group,
    never one per key.
    """
    moment = now or datetime.now(UTC)
    lines: list[str] = []
    skipped = False
    with remote_snapshot(store) if remote else nullcontext():
        for item in declared:
            if not item.local and not remote:
                skipped = True
            elif isinstance(item, Series):
                lines += _sweep_series(store, item, dry_run=dry_run, now=moment)
            else:
                lines += _sweep_family(store, item, dry_run=dry_run, now=moment)
    if skipped:
        lines.append("  remote series: swept inside CI, never from a machine")
    return lines