Skip to content

Lockfiles and indexes

lockfile

The lockfile, qvr.lock: every package of a build, pinned by content.

qvr lock resolves a package's dependencies and writes the result beside its manifest. The lockfile pins each package of the build to its version, its source (a directory relative to the root package, a git commit, an index entry, or the builtin standard library), and the content hashes of every module it provides:

  • core, the hash of the module's checked declarations (quivers.qiec.content_hash), which renaming, reformatting, and comments leave unchanged;
  • interface, the digest of the module's public interface (ModuleInterface.digest), which its names enter.

A build checks every pin before compiling anything, so a dependency whose content moved under an unchanged version or commit is refused. The file is a function of the manifest and the index alone: packages are sorted, paths are relative to the root package, and nothing about the machine (cache locations, times) enters it.

LOCK_FORMAT module-attribute

LOCK_FORMAT = 1

The lockfile layout this module reads and writes.

SourceKind

SourceKind = Literal['path', 'git', 'index', 'builtin']

How a locked package was found.

LockfileError

Bases: ValueError

A lockfile that cannot be read, or a build that disagrees with it.

Its message says what is wrong, naming the package and module.

LockedModule didactic-model

LockedModule(*, path: str, core: str, interface: str)

Bases: Model

The content hashes a lockfile pins for one module.

ATTRIBUTE DESCRIPTION
path

The module's path.

TYPE: str

core

The hash of its checked declarations.

TYPE: str

interface

The digest of its public interface.

TYPE: str

LockedPackage didactic-model

LockedPackage(*, name: str, version: Version, source: SourceKind, location: str = '', commit: str = '', revision: str = '', dependencies: tuple[str, ...] = (), modules: tuple[LockedModule, ...] = ())

Bases: Model

One package of a locked build.

ATTRIBUTE DESCRIPTION
name

The package's name.

TYPE: str

version

Its version.

TYPE: Version

source

How it was found.

TYPE: SourceKind

location

The directory relative to the root package (path), the repository (git), or the index's name (index); empty for the builtin package.

TYPE: str

commit

The git commit of its source, for git and index.

TYPE: str

revision

For git, the revision the manifest names (a tag, a branch, or a commit), which resolved to commit.

TYPE: str

dependencies

The names of the packages it depends on, sorted.

TYPE: tuple[str, ...]

modules

Its modules' hashes, by path.

TYPE: tuple[LockedModule, ...]

module

module(path: str) -> LockedModule | None

The pin of one module.

PARAMETER DESCRIPTION
path

The module's path.

TYPE: str

RETURNS DESCRIPTION
LockedModule | None

Its pin, or None when the package pins no such module.

Source code in src/quivers/packages/lockfile.py
def module(self, path: str) -> LockedModule | None:
    """The pin of one module.

    Parameters
    ----------
    path : str
        The module's path.

    Returns
    -------
    LockedModule | None
        Its pin, or ``None`` when the package pins no such module.
    """
    for module in self.modules:
        if module.path == path:
            return module
    return None

LockedIndex didactic-model

LockedIndex(*, name: str, url: str, commit: str)

Bases: Model

An index a locked build looked dependencies up in.

ATTRIBUTE DESCRIPTION
name

The index's name in the root manifest.

TYPE: str

url

Its repository.

TYPE: str

commit

The commit of the index the build was resolved against.

TYPE: str

Lockfile didactic-model

Lockfile(*, root: str, dependencies: tuple[str, ...] = (), indexes: tuple[LockedIndex, ...] = (), packages: tuple[LockedPackage, ...] = ())

Bases: Model

A resolved, pinned build.

ATTRIBUTE DESCRIPTION
root

The root package's name.

TYPE: str

dependencies

The root's direct dependencies, sorted.

TYPE: tuple[str, ...]

indexes

The indexes resolution read, by name.

TYPE: tuple[LockedIndex, ...]

packages

Every package of the build except the root, by name.

TYPE: tuple[LockedPackage, ...]

package

package(name: str) -> LockedPackage | None

The locked package of a name.

PARAMETER DESCRIPTION
name

A package name.

TYPE: str

RETURNS DESCRIPTION
LockedPackage | None

The package, or None when the build has none of that name.

Source code in src/quivers/packages/lockfile.py
def package(self, name: str) -> LockedPackage | None:
    """The locked package of a name.

    Parameters
    ----------
    name : str
        A package name.

    Returns
    -------
    LockedPackage | None
        The package, or ``None`` when the build has none of that name.
    """
    for package in self.packages:
        if package.name == name:
            return package
    return None

index

index(name: str) -> LockedIndex | None

The locked commit of a named index.

PARAMETER DESCRIPTION
name

The index's name.

TYPE: str

RETURNS DESCRIPTION
LockedIndex | None

The index, or None when resolution read no such index.

Source code in src/quivers/packages/lockfile.py
def index(self, name: str) -> LockedIndex | None:
    """The locked commit of a named index.

    Parameters
    ----------
    name : str
        The index's name.

    Returns
    -------
    LockedIndex | None
        The index, or ``None`` when resolution read no such index.
    """
    for index in self.indexes:
        if index.name == name:
            return index
    return None

render_lockfile

render_lockfile(lock: Lockfile) -> str

The lockfile as TOML text.

PARAMETER DESCRIPTION
lock

The lockfile.

TYPE: Lockfile

RETURNS DESCRIPTION
str

Deterministic TOML: the same lockfile always renders to the same bytes.

Source code in src/quivers/packages/lockfile.py
def render_lockfile(lock: Lockfile) -> str:
    """The lockfile as TOML text.

    Parameters
    ----------
    lock : Lockfile
        The lockfile.

    Returns
    -------
    str
        Deterministic TOML: the same lockfile always renders to the same
        bytes.
    """
    lines = [
        "# Written by `qvr lock` from qvr.toml and the package indexes; do not edit.",
        f"lock-version = {LOCK_FORMAT}",
        f"root = {_string(lock.root)}",
        f"dependencies = {_strings(lock.dependencies)}",
    ]
    for index in sorted(lock.indexes, key=lambda item: item.name):
        lines.extend(
            [
                "",
                "[[index]]",
                f"name = {_string(index.name)}",
                f"url = {_string(index.url)}",
                f"commit = {_string(index.commit)}",
            ]
        )
    for package in sorted(lock.packages, key=lambda item: item.name):
        lines.extend(
            [
                "",
                "[[package]]",
                f"name = {_string(package.name)}",
                f"version = {_string(package.version.render())}",
                f"source = {_string(package.source)}",
            ]
        )
        if package.location:
            lines.append(f"location = {_string(package.location)}")
        if package.commit:
            lines.append(f"commit = {_string(package.commit)}")
        if package.revision:
            lines.append(f"rev = {_string(package.revision)}")
        lines.append(f"dependencies = {_strings(package.dependencies)}")
        for module in sorted(package.modules, key=lambda item: item.path):
            lines.extend(
                [
                    "",
                    "[[package.module]]",
                    f"path = {_string(module.path)}",
                    f"core = {_string(module.core)}",
                    f"interface = {_string(module.interface)}",
                ]
            )
    return "\n".join(lines) + "\n"

parse_lockfile

parse_lockfile(text: str, *, where: str = LOCKFILE_NAME) -> Lockfile

Read a lockfile from its text.

PARAMETER DESCRIPTION
text

The TOML text render_lockfile writes.

TYPE: str

where

The file name diagnostics name.

TYPE: str DEFAULT: LOCKFILE_NAME

RETURNS DESCRIPTION
Lockfile

The lockfile.

RAISES DESCRIPTION
LockfileError

If the text is not a lockfile of this layout.

Source code in src/quivers/packages/lockfile.py
def parse_lockfile(text: str, *, where: str = LOCKFILE_NAME) -> Lockfile:
    """Read a lockfile from its text.

    Parameters
    ----------
    text : str
        The TOML text `render_lockfile` writes.
    where : str
        The file name diagnostics name.

    Returns
    -------
    Lockfile
        The lockfile.

    Raises
    ------
    LockfileError
        If the text is not a lockfile of this layout.
    """
    try:
        document: dict[str, TomlValue] = tomllib.loads(text)
    except tomllib.TOMLDecodeError as error:
        raise LockfileError(f"{where}: {error}") from error
    if document.get("lock-version") != LOCK_FORMAT:
        raise LockfileError(
            f"{where}: lock-version must be {LOCK_FORMAT}; run `qvr lock` to "
            "write the lockfile again"
        )
    indexes = tuple(
        LockedIndex(
            name=_field(table, "name", f"{where}: index"),
            url=_field(table, "url", f"{where}: index"),
            commit=_field(table, "commit", f"{where}: index"),
        )
        for table in _tables(document, "index", where)
    )
    packages: list[LockedPackage] = []
    for table in _tables(document, "package", where):
        name = _field(table, "name", f"{where}: package")
        here = f"{where}: package {name}"
        source = _field(table, "source", here)
        if source not in ("path", "git", "index", "builtin"):
            raise LockfileError(f"{here}: source {source!r} is not a source kind")
        try:
            version = Version.parse(_field(table, "version", here))
        except VersionError as error:
            raise LockfileError(f"{here}: {error}") from error
        modules = tuple(
            LockedModule(
                path=_field(module, "path", here),
                core=_field(module, "core", here),
                interface=_field(module, "interface", here),
            )
            for module in _tables(table, "module", here)
        )
        location = table.get("location", "")
        commit = table.get("commit", "")
        revision = table.get("rev", "")
        if not all(isinstance(item, str) for item in (location, commit, revision)):
            raise LockfileError(f"{here}: location, commit, and rev must be strings")
        assert isinstance(location, str)
        assert isinstance(commit, str)
        assert isinstance(revision, str)
        packages.append(
            LockedPackage(
                name=name,
                version=version,
                source=source,
                location=location,
                commit=commit,
                revision=revision,
                dependencies=_names(table, "dependencies", here),
                modules=modules,
            )
        )
    return Lockfile(
        root=_field(document, "root", where),
        dependencies=_names(document, "dependencies", where),
        indexes=indexes,
        packages=tuple(packages),
    )

read_lockfile

read_lockfile(directory: Path) -> Lockfile | None

The lockfile beside a manifest, if there is one.

PARAMETER DESCRIPTION
directory

The root package's directory.

TYPE: Path

RETURNS DESCRIPTION
Lockfile | None

The lockfile, or None when the package has not been locked.

RAISES DESCRIPTION
LockfileError

If the lockfile exists and is malformed.

Source code in src/quivers/packages/lockfile.py
def read_lockfile(directory: Path) -> Lockfile | None:
    """The lockfile beside a manifest, if there is one.

    Parameters
    ----------
    directory : Path
        The root package's directory.

    Returns
    -------
    Lockfile | None
        The lockfile, or ``None`` when the package has not been locked.

    Raises
    ------
    LockfileError
        If the lockfile exists and is malformed.
    """
    path = directory / LOCKFILE_NAME
    if not path.is_file():
        return None
    return parse_lockfile(path.read_text(encoding="utf-8"), where=str(path))

index

Package indexes: git repositories of package metadata.

An index needs no service. It is a git repository with one file per published version, <name>/<version>.toml::

[package]
name = "worlds"
version = "1.2.0"
git = "https://example.org/worlds.git"
commit = "3f0c...e1"

[dependencies]
logic = "1.0.0"

[[module]]
path = "worlds.boolean"
core = "9a1f..."
interface = "51c0..."

The entry says where the version's source is (a repository and a commit), which packages of the same index it depends on (each with the minimum version it was built against), and the content hashes of the modules it provides, which every build checks. Resolution reads an index at one commit, which the lockfile records, so the same manifest and index commit resolve to the same build anywhere.

PackageIndexError

Bases: ValueError

An index entry that is malformed or missing.

Its message says what is wrong, naming the index and the entry.

IndexRequirement didactic-model

IndexRequirement(*, name: str, minimum: Version)

Bases: Model

A dependency of an indexed version on another package of its index.

ATTRIBUTE DESCRIPTION
name

The package.

TYPE: str

minimum

The version it was built against.

TYPE: Version

IndexEntry didactic-model

IndexEntry(*, name: str, version: Version, url: str, commit: str, dependencies: tuple[IndexRequirement, ...] = (), modules: tuple[LockedModule, ...] = ())

Bases: Model

One published version of a package.

ATTRIBUTE DESCRIPTION
name

The package.

TYPE: str

version

The version.

TYPE: Version

url

The repository holding its source.

TYPE: str

commit

The commit of that repository.

TYPE: str

dependencies

Its dependencies, by name.

TYPE: tuple[IndexRequirement, ...]

modules

The content hashes of the modules it provides, by path.

TYPE: tuple[LockedModule, ...]

PackageIndex

PackageIndex(name: str, url: str, commit: str, cache: GitCache)

An index repository read at one commit.

PARAMETER DESCRIPTION
name

The index's name in the root manifest.

TYPE: str

url

The repository.

TYPE: str

commit

The commit read.

TYPE: str

cache

The project cache holding its mirror.

TYPE: GitCache

Source code in src/quivers/packages/index.py
def __init__(self, name: str, url: str, commit: str, cache: GitCache) -> None:
    self.name = name
    self.url = url
    self.commit = commit
    self.cache = cache
    self._files = cache.files(url, commit)

open classmethod

open(name: str, url: str, cache: GitCache, *, commit: str = '') -> PackageIndex

Open an index at a commit, or at its default branch's head.

PARAMETER DESCRIPTION
name

The index's name.

TYPE: str

url

Its repository.

TYPE: str

cache

The project cache.

TYPE: GitCache

commit

The commit to read, as a lockfile pins it; the newest commit of the default branch when empty.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
PackageIndex

The index.

RAISES DESCRIPTION
GitError

If the repository or the commit cannot be read.

Source code in src/quivers/packages/index.py
@classmethod
def open(
    cls, name: str, url: str, cache: GitCache, *, commit: str = ""
) -> PackageIndex:
    """Open an index at a commit, or at its default branch's head.

    Parameters
    ----------
    name : str
        The index's name.
    url : str
        Its repository.
    cache : GitCache
        The project cache.
    commit : str
        The commit to read, as a lockfile pins it; the newest commit of
        the default branch when empty.

    Returns
    -------
    PackageIndex
        The index.

    Raises
    ------
    GitError
        If the repository or the commit cannot be read.
    """
    resolved = cache.resolve(url, commit)
    return cls(name, url, resolved, cache)

versions

versions(package: str) -> tuple[Version, ...]

Every published version of a package.

PARAMETER DESCRIPTION
package

The package.

TYPE: str

RETURNS DESCRIPTION
tuple[Version, ...]

Its versions, ascending.

Source code in src/quivers/packages/index.py
def versions(self, package: str) -> tuple[Version, ...]:
    """Every published version of a package.

    Parameters
    ----------
    package : str
        The package.

    Returns
    -------
    tuple[Version, ...]
        Its versions, ascending.
    """
    found: list[Version] = []
    prefix = f"{package}/"
    for path in self._files:
        if not path.startswith(prefix) or not path.endswith(".toml"):
            continue
        stem = path[len(prefix) : -len(".toml")]
        try:
            found.append(Version.parse(stem))
        except VersionError:
            continue
    return tuple(sorted(found, key=Version.key))

packages

packages() -> tuple[str, ...]

Every package the index lists.

RETURNS DESCRIPTION
tuple[str, ...]

Their names, sorted.

Source code in src/quivers/packages/index.py
def packages(self) -> tuple[str, ...]:
    """Every package the index lists.

    Returns
    -------
    tuple[str, ...]
        Their names, sorted.
    """
    return tuple(
        sorted({path.split("/")[0] for path in self._files if "/" in path})
    )

entry

entry(package: str, version: Version) -> IndexEntry

The entry of one published version.

PARAMETER DESCRIPTION
package

The package.

TYPE: str

version

The version.

TYPE: Version

RETURNS DESCRIPTION
IndexEntry

Its entry.

RAISES DESCRIPTION
PackageIndexError

If the index does not list that version, or its entry disagrees with its path.

Source code in src/quivers/packages/index.py
def entry(self, package: str, version: Version) -> IndexEntry:
    """The entry of one published version.

    Parameters
    ----------
    package : str
        The package.
    version : Version
        The version.

    Returns
    -------
    IndexEntry
        Its entry.

    Raises
    ------
    PackageIndexError
        If the index does not list that version, or its entry
        disagrees with its path.
    """
    path = entry_path(package, version)
    where = f"index {self.name} ({self.url} at {self.commit[:12]}): {path}"
    text = self.cache.read(self.url, self.commit, path)
    if text is None:
        raise PackageIndexError(f"{where} does not exist")
    entry = parse_entry(text, where=where)
    if entry.name != package or entry.version != version:
        raise PackageIndexError(
            f"{where} describes {entry.name} {entry.version.render()}, not "
            f"{package} {version.render()}"
        )
    return entry

entry_path

entry_path(name: str, version: Version) -> str

Where an entry lives in an index repository.

PARAMETER DESCRIPTION
name

The package.

TYPE: str

version

The version.

TYPE: Version

RETURNS DESCRIPTION
str

<name>/<version>.toml.

Source code in src/quivers/packages/index.py
def entry_path(name: str, version: Version) -> str:
    """Where an entry lives in an index repository.

    Parameters
    ----------
    name : str
        The package.
    version : Version
        The version.

    Returns
    -------
    str
        ``<name>/<version>.toml``.
    """
    return f"{name}/{version.render()}.toml"

render_entry

render_entry(entry: IndexEntry) -> str

An index entry as TOML text.

PARAMETER DESCRIPTION
entry

The entry.

TYPE: IndexEntry

RETURNS DESCRIPTION
str

The file parse_entry reads back.

Source code in src/quivers/packages/index.py
def render_entry(entry: IndexEntry) -> str:
    """An index entry as TOML text.

    Parameters
    ----------
    entry : IndexEntry
        The entry.

    Returns
    -------
    str
        The file `parse_entry` reads back.
    """
    lines = [
        "[package]",
        f"name = {_string(entry.name)}",
        f"version = {_string(entry.version.render())}",
        f"git = {_string(entry.url)}",
        f"commit = {_string(entry.commit)}",
        "",
        "[dependencies]",
    ]
    for requirement in sorted(entry.dependencies, key=lambda item: item.name):
        lines.append(f"{requirement.name} = {_string(requirement.minimum.render())}")
    for module in sorted(entry.modules, key=lambda item: item.path):
        lines.extend(
            [
                "",
                "[[module]]",
                f"path = {_string(module.path)}",
                f"core = {_string(module.core)}",
                f"interface = {_string(module.interface)}",
            ]
        )
    return "\n".join(lines) + "\n"

parse_entry

parse_entry(text: str, *, where: str) -> IndexEntry

Read an index entry.

PARAMETER DESCRIPTION
text

The entry's TOML text.

TYPE: str

where

The index and path diagnostics name.

TYPE: str

RETURNS DESCRIPTION
IndexEntry

The entry.

RAISES DESCRIPTION
PackageIndexError

If the text is not an index entry.

Source code in src/quivers/packages/index.py
def parse_entry(text: str, *, where: str) -> IndexEntry:
    """Read an index entry.

    Parameters
    ----------
    text : str
        The entry's TOML text.
    where : str
        The index and path diagnostics name.

    Returns
    -------
    IndexEntry
        The entry.

    Raises
    ------
    PackageIndexError
        If the text is not an index entry.
    """
    try:
        document: dict[str, TomlValue] = tomllib.loads(text)
    except tomllib.TOMLDecodeError as error:
        raise PackageIndexError(f"{where}: {error}") from error
    package = document.get("package")
    if not isinstance(package, dict):
        raise PackageIndexError(f"{where}: an index entry needs a [package] table")
    try:
        version = Version.parse(_text(package, "version", where))
    except VersionError as error:
        raise PackageIndexError(f"{where}: {error}") from error
    requirements: list[IndexRequirement] = []
    dependencies = document.get("dependencies", {})
    if not isinstance(dependencies, dict):
        raise PackageIndexError(f"{where}: [dependencies] must be a table")
    for name, value in sorted(dependencies.items()):
        if not isinstance(value, str):
            raise PackageIndexError(f"{where}: dependencies.{name} must be a version")
        try:
            minimum = parse_requirement(value)
        except VersionError as error:
            raise PackageIndexError(f"{where}: dependencies.{name}: {error}") from error
        requirements.append(IndexRequirement(name=name, minimum=minimum))
    modules_value = document.get("module", [])
    if not isinstance(modules_value, list):
        raise PackageIndexError(f"{where}: module must be an array of tables")
    modules: list[LockedModule] = []
    for item in modules_value:
        if not isinstance(item, dict):
            raise PackageIndexError(f"{where}: module must be an array of tables")
        modules.append(
            LockedModule(
                path=_text(item, "path", where),
                core=_text(item, "core", where),
                interface=_text(item, "interface", where),
            )
        )
    return IndexEntry(
        name=_text(package, "name", where),
        version=version,
        url=_text(package, "git", where),
        commit=_text(package, "commit", where),
        dependencies=tuple(requirements),
        modules=tuple(modules),
    )

git

Git repositories in the project cache, through the git command.

Git dependencies and package indexes are git repositories. The cache keeps a bare mirror of each repository under <root>/.qvr/packages/git and extracts each commit a build uses under <root>/.qvr/packages/src, so a build that has every pinned commit runs without the network: a revision that names a commit already in the mirror is never fetched.

CACHE_DIRECTORY module-attribute

CACHE_DIRECTORY = Path('.qvr') / 'packages'

Where a project's package cache lives, relative to its root package.

GitError

Bases: OSError

A git command that failed, or a revision that names no commit.

Its message says the command and what git reported.

GitCache

GitCache(directory: Path)

The git repositories and extracted commits of one project.

PARAMETER DESCRIPTION
directory

The cache directory, <root>/.qvr/packages.

TYPE: Path

Source code in src/quivers/packages/git.py
def __init__(self, directory: Path) -> None:
    self.directory = directory

for_package classmethod

for_package(root: Path) -> GitCache

The cache of the project whose root package is a directory.

PARAMETER DESCRIPTION
root

The root package's directory.

TYPE: Path

RETURNS DESCRIPTION
GitCache

Its cache.

Source code in src/quivers/packages/git.py
@classmethod
def for_package(cls, root: Path) -> GitCache:
    """The cache of the project whose root package is a directory.

    Parameters
    ----------
    root : Path
        The root package's directory.

    Returns
    -------
    GitCache
        Its cache.
    """
    return cls(root / CACHE_DIRECTORY)

mirror_path

mirror_path(url: str) -> Path

Where the mirror of a repository lives.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

RETURNS DESCRIPTION
Path

Its bare mirror's directory.

Source code in src/quivers/packages/git.py
def mirror_path(self, url: str) -> Path:
    """Where the mirror of a repository lives.

    Parameters
    ----------
    url : str
        The repository.

    Returns
    -------
    Path
        Its bare mirror's directory.
    """
    return self.directory / "git" / f"{self._key(url)}.git"

has_commit

has_commit(url: str, commit: str) -> bool

Whether the mirror of a repository holds a commit.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

commit

A full commit id.

TYPE: str

RETURNS DESCRIPTION
bool

Whether the commit is present without fetching.

Source code in src/quivers/packages/git.py
def has_commit(self, url: str, commit: str) -> bool:
    """Whether the mirror of a repository holds a commit.

    Parameters
    ----------
    url : str
        The repository.
    commit : str
        A full commit id.

    Returns
    -------
    bool
        Whether the commit is present without fetching.
    """
    mirror = self.mirror_path(url)
    if not mirror.is_dir():
        return False
    try:
        run_git(["cat-file", "-e", f"{commit}^{{commit}}"], cwd=mirror)
    except GitError:
        return False
    return True

fetch

fetch(url: str) -> Path

Bring a repository's mirror up to date, cloning it when absent.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

RETURNS DESCRIPTION
Path

The mirror.

RAISES DESCRIPTION
GitError

If the repository cannot be cloned or fetched.

Source code in src/quivers/packages/git.py
def fetch(self, url: str) -> Path:
    """Bring a repository's mirror up to date, cloning it when absent.

    Parameters
    ----------
    url : str
        The repository.

    Returns
    -------
    Path
        The mirror.

    Raises
    ------
    GitError
        If the repository cannot be cloned or fetched.
    """
    mirror = self.mirror_path(url)
    if mirror.is_dir():
        run_git(["remote", "update", "--prune"], cwd=mirror)
        return mirror
    mirror.parent.mkdir(parents=True, exist_ok=True)
    staging = Path(tempfile.mkdtemp(prefix=".clone-", dir=mirror.parent))
    try:
        run_git(["clone", "--mirror", "--quiet", url, str(staging / "repo.git")])
        (staging / "repo.git").rename(mirror)
    finally:
        shutil.rmtree(staging, ignore_errors=True)
    return mirror

resolve

resolve(url: str, revision: str) -> str

The commit a revision of a repository names.

A full commit id already in the mirror resolves without the network; any other revision (a tag, a branch, a short id, or the default branch for "") fetches first.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

revision

A commit, tag, or branch; empty for the default branch.

TYPE: str

RETURNS DESCRIPTION
str

The full commit id.

RAISES DESCRIPTION
GitError

If the repository cannot be fetched or the revision names no commit.

Source code in src/quivers/packages/git.py
def resolve(self, url: str, revision: str) -> str:
    """The commit a revision of a repository names.

    A full commit id already in the mirror resolves without the
    network; any other revision (a tag, a branch, a short id, or the
    default branch for ``""``) fetches first.

    Parameters
    ----------
    url : str
        The repository.
    revision : str
        A commit, tag, or branch; empty for the default branch.

    Returns
    -------
    str
        The full commit id.

    Raises
    ------
    GitError
        If the repository cannot be fetched or the revision names no
        commit.
    """
    if is_commit(revision) and self.has_commit(url, revision):
        return revision
    mirror = self.fetch(url)
    spelled = revision or "HEAD"
    try:
        output = run_git(
            ["rev-parse", "--verify", "--quiet", f"{spelled}^{{commit}}"],
            cwd=mirror,
        )
    except GitError as error:
        raise GitError(
            f"{url} has no revision {spelled!r}: name a commit, a tag, or a "
            "branch of the repository"
        ) from error
    return output.decode("ascii").strip()

read

read(url: str, commit: str, path: str) -> str | None

A file's text at a commit.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

commit

A commit in its mirror.

TYPE: str

path

The file's path in the repository, POSIX spelling.

TYPE: str

RETURNS DESCRIPTION
str | None

The file's text, or None when the commit has no such file.

RAISES DESCRIPTION
GitError

If the commit is not in the mirror.

Source code in src/quivers/packages/git.py
def read(self, url: str, commit: str, path: str) -> str | None:
    """A file's text at a commit.

    Parameters
    ----------
    url : str
        The repository.
    commit : str
        A commit in its mirror.
    path : str
        The file's path in the repository, POSIX spelling.

    Returns
    -------
    str | None
        The file's text, or ``None`` when the commit has no such file.

    Raises
    ------
    GitError
        If the commit is not in the mirror.
    """
    mirror = self._mirror_with(url, commit)
    try:
        return run_git(["show", f"{commit}:{path}"], cwd=mirror).decode("utf-8")
    except GitError:
        listing = self.files(url, commit)
        if path in listing:
            raise
        return None

files

files(url: str, commit: str) -> tuple[str, ...]

Every file of a commit.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

commit

A commit in its mirror.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

The files' paths, sorted.

RAISES DESCRIPTION
GitError

If the commit is not in the mirror.

Source code in src/quivers/packages/git.py
def files(self, url: str, commit: str) -> tuple[str, ...]:
    """Every file of a commit.

    Parameters
    ----------
    url : str
        The repository.
    commit : str
        A commit in its mirror.

    Returns
    -------
    tuple[str, ...]
        The files' paths, sorted.

    Raises
    ------
    GitError
        If the commit is not in the mirror.
    """
    mirror = self._mirror_with(url, commit)
    output = run_git(["ls-tree", "-r", "--name-only", "-z", commit], cwd=mirror)
    return tuple(
        sorted(item for item in output.decode("utf-8").split("\0") if item)
    )

checkout

checkout(url: str, commit: str) -> Path

A directory holding a commit's files, extracted once.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

commit

A full commit id.

TYPE: str

RETURNS DESCRIPTION
Path

The extracted tree, <cache>/src/<repository key>-<commit>.

RAISES DESCRIPTION
GitError

If the commit is not in the repository.

Source code in src/quivers/packages/git.py
def checkout(self, url: str, commit: str) -> Path:
    """A directory holding a commit's files, extracted once.

    Parameters
    ----------
    url : str
        The repository.
    commit : str
        A full commit id.

    Returns
    -------
    Path
        The extracted tree, ``<cache>/src/<repository key>-<commit>``.

    Raises
    ------
    GitError
        If the commit is not in the repository.
    """
    target = self.directory / "src" / f"{self._key(url)}-{commit}"
    if target.is_dir():
        return target
    mirror = self._mirror_with(url, commit)
    archive = run_git(["archive", "--format=tar", commit], cwd=mirror)
    target.parent.mkdir(parents=True, exist_ok=True)
    staging = Path(tempfile.mkdtemp(prefix=".extract-", dir=target.parent))
    try:
        with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
            tar.extractall(staging / "tree", filter="data")
        (staging / "tree").rename(target)
    finally:
        shutil.rmtree(staging, ignore_errors=True)
    return target

run_git

run_git(arguments: list[str], *, cwd: Path | None = None) -> bytes

Run one git command and return its standard output.

PARAMETER DESCRIPTION
arguments

The arguments after git.

TYPE: list[str]

cwd

The directory to run in.

TYPE: Path | None DEFAULT: None

RETURNS DESCRIPTION
bytes

What the command wrote to standard output.

RAISES DESCRIPTION
GitError

If git is not installed or the command exits with a failure.

Source code in src/quivers/packages/git.py
def run_git(arguments: list[str], *, cwd: Path | None = None) -> bytes:
    """Run one git command and return its standard output.

    Parameters
    ----------
    arguments : list[str]
        The arguments after ``git``.
    cwd : Path | None
        The directory to run in.

    Returns
    -------
    bytes
        What the command wrote to standard output.

    Raises
    ------
    GitError
        If git is not installed or the command exits with a failure.
    """
    command = ["git", *arguments]
    try:
        completed = subprocess.run(
            command,
            cwd=cwd,
            env=_environment(),
            capture_output=True,
            check=False,
        )
    except FileNotFoundError as error:
        raise GitError(
            "the git command is not installed; git dependencies and package "
            "indexes are read with it"
        ) from error
    if completed.returncode != 0:
        detail = completed.stderr.decode("utf-8", errors="replace").strip()
        raise GitError(f"git {' '.join(arguments)} failed: {detail}")
    return completed.stdout

is_commit

is_commit(revision: str) -> bool

Whether a revision is spelled as a full commit id.

PARAMETER DESCRIPTION
revision

A revision.

TYPE: str

RETURNS DESCRIPTION
bool

Whether it is forty lowercase hexadecimal digits.

Source code in src/quivers/packages/git.py
def is_commit(revision: str) -> bool:
    """Whether a revision is spelled as a full commit id.

    Parameters
    ----------
    revision : str
        A revision.

    Returns
    -------
    bool
        Whether it is forty lowercase hexadecimal digits.
    """
    return _COMMIT.fullmatch(revision) is not None

same_repository

same_repository(left: str, right: str) -> bool

Whether two spellings name one repository.

A local repository may be spelled as a path or as a file:// URL; both name the same directory. Remote URLs are compared as written.

PARAMETER DESCRIPTION
left

Two repository spellings.

TYPE: str

right

Two repository spellings.

TYPE: str

RETURNS DESCRIPTION
bool

Whether they name the same repository.

Source code in src/quivers/packages/git.py
def same_repository(left: str, right: str) -> bool:
    """Whether two spellings name one repository.

    A local repository may be spelled as a path or as a ``file://`` URL;
    both name the same directory. Remote URLs are compared as written.

    Parameters
    ----------
    left, right : str
        Two repository spellings.

    Returns
    -------
    bool
        Whether they name the same repository.
    """
    return _canonical(left) == _canonical(right)