Skip to content

Packages

quivers.packages reads package manifests, resolves builds, pins them in lockfiles, computes versions from interface diffs, and migrates dependents along dependency lenses. The surface is in packages, lockfiles, and versions and the rules in packages and dependency lenses.

Page Contents
Manifests and versions qvr.toml, semantic versions, compatibility lines
Resolution package sources, minimal version selection, explanations
Lockfiles and indexes qvr.lock, index repositories, the git cache
Workspaces building packages, pins, and the package boundary
Interfaces and versions semantic interfaces, interface diffs, releases
Dependency lenses lenses and the migration of dependents and run records

packages

Packages: manifests, resolution, lockfiles, interface versioning, and dependency lenses.

A package is a directory with a qvr.toml manifest (quivers.packages.manifest). Its dependencies resolve by minimal version selection (quivers.packages.resolve) from directories, git repositories, and package indexes (quivers.packages.index), and qvr lock pins every module of the build by content hash (quivers.packages.lockfile, quivers.packages.workspace). qvr bump classifies a version's interface change (quivers.packages.interface, quivers.packages.bump), and the dependency lens of a change (quivers.packages.lenses) migrates dependents and stored runs (quivers.packages.migration).

CHANGE_LEVELS module-attribute

CHANGE_LEVELS: tuple[ChangeLevel, ...] = ('none', 'patch', 'minor', 'major')

The change levels from least to most.

LOCKFILE_NAME module-attribute

LOCKFILE_NAME = 'qvr.lock'

The lockfile's file name, beside the manifest.

MANIFEST_NAME module-attribute

MANIFEST_NAME = 'qvr.toml'

The manifest's file name.

LOCK_FORMAT module-attribute

LOCK_FORMAT = 1

The lockfile layout this module reads and writes.

CACHE_DIRECTORY module-attribute

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

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

DATA_ROLES module-attribute

DATA_ROLES: frozenset[str] = frozenset({'data', 'observation', 'index_map'})

Program parameter roles a dependent binds to data rather than passes.

SIGNATURE_KINDS module-attribute

SIGNATURE_KINDS: frozenset[str] = frozenset({'computation', 'handler', 'program'})

Declaration kinds with a signature apart from their body: a change to the body alone keeps their interface. Any change to a declaration of another kind changes its shape, which dependents see.

INVENTORY_PROTOCOL module-attribute

INVENTORY_PROTOCOL = 'json-schema'

The panproto protocol inventories and usages are written in.

LENS_DIRECTORY module-attribute

LENS_DIRECTORY = 'lenses'

Where a package keeps the lenses its breaking releases emit.

ChangeLevel

ChangeLevel = Literal['major', 'minor', 'patch', 'none']

How much a change to a package moves its version: major breaks dependents, minor adds to the interface (or changes the meaning of a program fit to data), patch changes bodies only, none changes nothing.

TomlValue

TomlValue = str | int | float | bool | list[TomlValue] | dict[str, TomlValue]

A value of a parsed TOML document.

SourceKind

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

How a locked package was found.

PackageErrorCode

PackageErrorCode = Literal['package-module-private', 'package-not-a-dependency', 'package-module-outside', 'package-hole-unlisted', 'package-hole-unknown', 'package-link-conflict', 'package-pin-mismatch', 'package-lock-stale', 'package-module-missing']

The codes a package diagnostic carries.

ChangeCategory

ChangeCategory = Literal['removed', 'renamed', 'added', 'added-site', 'kind', 'type', 'effects', 'support', 'index', 'fitted-body', 'body']

What kind of change one InterfaceChange is.

Version didactic-model

Version(*, major: int, minor: int, patch: int)

Bases: Model

A semantic version MAJOR.MINOR.PATCH.

ATTRIBUTE DESCRIPTION
major, minor, patch

The components.

TYPE: int

parse classmethod

parse(text: str) -> Version

Read a version.

PARAMETER DESCRIPTION
text

MAJOR.MINOR.PATCH with no leading zeros.

TYPE: str

RETURNS DESCRIPTION
Version

The version.

RAISES DESCRIPTION
VersionError

If the text is not a version.

Source code in src/quivers/packages/versions.py
@classmethod
def parse(cls, text: str) -> Version:
    """Read a version.

    Parameters
    ----------
    text : str
        ``MAJOR.MINOR.PATCH`` with no leading zeros.

    Returns
    -------
    Version
        The version.

    Raises
    ------
    VersionError
        If the text is not a version.
    """
    match = _VERSION.fullmatch(text.strip())
    if match is None:
        raise VersionError(
            f"{text!r} is not a version: write MAJOR.MINOR.PATCH, e.g. 1.2.0"
        )
    return cls(
        major=int(match.group(1)),
        minor=int(match.group(2)),
        patch=int(match.group(3)),
    )

key

key() -> tuple[int, int, int]

The version as a sortable key.

RETURNS DESCRIPTION
tuple[int, int, int]

(major, minor, patch).

Source code in src/quivers/packages/versions.py
def key(self) -> tuple[int, int, int]:
    """The version as a sortable key.

    Returns
    -------
    tuple[int, int, int]
        ``(major, minor, patch)``.
    """
    return (self.major, self.minor, self.patch)

render

render() -> str

The version as text.

RETURNS DESCRIPTION
str

MAJOR.MINOR.PATCH.

Source code in src/quivers/packages/versions.py
def render(self) -> str:
    """The version as text.

    Returns
    -------
    str
        ``MAJOR.MINOR.PATCH``.
    """
    return f"{self.major}.{self.minor}.{self.patch}"

line

line() -> tuple[int, ...]

The compatibility line: components up to the leftmost nonzero one.

RETURNS DESCRIPTION
tuple[int, ...]

(major,) from 1.0.0 on, (0, minor) for 0.y.z with y > 0, and (0, 0, patch) below that.

Source code in src/quivers/packages/versions.py
def line(self) -> tuple[int, ...]:
    """The compatibility line: components up to the leftmost nonzero one.

    Returns
    -------
    tuple[int, ...]
        ``(major,)`` from ``1.0.0`` on, ``(0, minor)`` for ``0.y.z``
        with ``y > 0``, and ``(0, 0, patch)`` below that.
    """
    if self.major:
        return (self.major,)
    if self.minor:
        return (0, self.minor)
    return (0, 0, self.patch)

render_line

render_line() -> str

The compatibility line as text.

RETURNS DESCRIPTION
str

1.x for line (1,), 0.3.x for (0, 3), and the exact version for 0.0.z.

Source code in src/quivers/packages/versions.py
def render_line(self) -> str:
    """The compatibility line as text.

    Returns
    -------
    str
        ``1.x`` for line ``(1,)``, ``0.3.x`` for ``(0, 3)``, and the
        exact version for ``0.0.z``.
    """
    line = self.line()
    if len(line) == 3:
        return self.render()
    return ".".join(str(part) for part in line) + ".x"

compatible

compatible(other: Version) -> bool

Whether two versions share a compatibility line.

PARAMETER DESCRIPTION
other

Another version.

TYPE: Version

RETURNS DESCRIPTION
bool

Whether one may stand in for the other.

Source code in src/quivers/packages/versions.py
def compatible(self, other: Version) -> bool:
    """Whether two versions share a compatibility line.

    Parameters
    ----------
    other : Version
        Another version.

    Returns
    -------
    bool
        Whether one may stand in for the other.
    """
    return self.line() == other.line()

bumped

bumped(level: ChangeLevel) -> Version

The next version after a change of a given level.

The leftmost nonzero component is the one a breaking change moves, so on line 0.y a breaking change bumps y and any other change bumps the patch; on line 0.0.z every change bumps z.

PARAMETER DESCRIPTION
level

The change.

TYPE: ChangeLevel

RETURNS DESCRIPTION
Version

The version that publishes it (this version for none).

Source code in src/quivers/packages/versions.py
def bumped(self, level: ChangeLevel) -> Version:
    """The next version after a change of a given level.

    The leftmost nonzero component is the one a breaking change moves,
    so on line ``0.y`` a breaking change bumps ``y`` and any other change
    bumps the patch; on line ``0.0.z`` every change bumps ``z``.

    Parameters
    ----------
    level : ChangeLevel
        The change.

    Returns
    -------
    Version
        The version that publishes it (this version for ``none``).
    """
    if level == "none":
        return self
    if self.major:
        if level == "major":
            return Version(major=self.major + 1, minor=0, patch=0)
        if level == "minor":
            return Version(major=self.major, minor=self.minor + 1, patch=0)
        return Version(major=self.major, minor=self.minor, patch=self.patch + 1)
    if self.minor:
        if level == "major":
            return Version(major=0, minor=self.minor + 1, patch=0)
        return Version(major=0, minor=self.minor, patch=self.patch + 1)
    return Version(major=0, minor=0, patch=self.patch + 1)

level_to

level_to(later: Version) -> ChangeLevel

The largest change a later version may publish over this one.

PARAMETER DESCRIPTION
later

A version greater than this one.

TYPE: Version

RETURNS DESCRIPTION
ChangeLevel

major when the line changes; otherwise minor when the component after the line's leading one grows (on line 1.x, the minor component), else patch; none for equal versions.

RAISES DESCRIPTION
VersionError

If later is not greater than this version.

Source code in src/quivers/packages/versions.py
def level_to(self, later: Version) -> ChangeLevel:
    """The largest change a later version may publish over this one.

    Parameters
    ----------
    later : Version
        A version greater than this one.

    Returns
    -------
    ChangeLevel
        ``major`` when the line changes; otherwise ``minor`` when the
        component after the line's leading one grows (on line ``1.x``,
        the minor component), else ``patch``; ``none`` for equal
        versions.

    Raises
    ------
    VersionError
        If ``later`` is not greater than this version.
    """
    if later.key() == self.key():
        return "none"
    if later.key() < self.key():
        raise VersionError(
            f"{later.render()} does not follow {self.render()}: a published "
            "version only moves forward"
        )
    if not self.compatible(later):
        return "major"
    if self.major and later.minor != self.minor:
        return "minor"
    return "patch"

VersionError

Bases: ValueError

A version or a requirement that does not parse.

Its message says what is malformed, quoting the text.

Dependency didactic-model

Dependency(*, name: str, source: DependencySource)

Bases: Model

One dependency of a package.

ATTRIBUTE DESCRIPTION
name

The depended-on package's name.

TYPE: str

source

Where it comes from.

TYPE: DependencySource

DependencySource didactic-model

DependencySource()

Bases: TaggedUnion

Where a dependency comes from.

GitSource didactic-model

GitSource(*, url: str, rev: str = '', kind: Literal['git'] = 'git')

Bases: DependencySource

A dependency found in a git repository.

ATTRIBUTE DESCRIPTION
url

The repository, as git clone takes it.

TYPE: str

rev

A commit, tag, or branch; the repository's default branch when empty.

TYPE: str

HoleSpec didactic-model

HoleSpec(*, path: str, default: str = '')

Bases: Model

A hole a package exposes.

ATTRIBUTE DESCRIPTION
path

The hole's module path.

TYPE: str

default

The module that fills it when no link does; empty for none.

TYPE: str

IndexSource didactic-model

IndexSource(*, index: str, minimum: Version, kind: Literal['index'] = 'index')

Bases: DependencySource

A dependency looked up in a package index.

ATTRIBUTE DESCRIPTION
index

The index's name in the depending package's [indexes].

TYPE: str

minimum

The version the dependent was built against; any later version on its compatibility line satisfies it.

TYPE: Version

IndexSpec didactic-model

IndexSpec(*, name: str, url: str)

Bases: Model

A package index a manifest may look dependencies up in.

ATTRIBUTE DESCRIPTION
name

The name dependencies refer to it by.

TYPE: str

url

The index's git repository.

TYPE: str

LinkSpec didactic-model

LinkSpec(*, hole: str, module: str)

Bases: Model

A hole a package fills for its own builds.

ATTRIBUTE DESCRIPTION
hole

The hole's module path.

TYPE: str

module

The filling module's path.

TYPE: str

Manifest didactic-model

Manifest(*, name: str, version: Version, modules: tuple[str, ...] = (), source: str = '.', holes: tuple[HoleSpec, ...] = (), links: tuple[LinkSpec, ...] = (), dependencies: tuple[Dependency, ...] = (), indexes: tuple[IndexSpec, ...] = ())

Bases: Model

A parsed qvr.toml.

ATTRIBUTE DESCRIPTION
name

The package's name, the first segment of its module paths.

TYPE: str

version

The package's version.

TYPE: Version

modules

The modules dependents may import, sorted.

TYPE: tuple[str, ...]

source

The directory below the package's directory that module paths are relative to (. for the package's directory itself).

TYPE: str

holes

The holes the package exposes, by path.

TYPE: tuple[HoleSpec, ...]

links

The links, by hole path.

TYPE: tuple[LinkSpec, ...]

dependencies

The dependencies, by name.

TYPE: tuple[Dependency, ...]

indexes

The indexes, by name.

TYPE: tuple[IndexSpec, ...]

dependency

dependency(name: str) -> Dependency | None

The dependency on a package.

PARAMETER DESCRIPTION
name

The package's name.

TYPE: str

RETURNS DESCRIPTION
Dependency | None

The dependency, or None when the package is not depended on.

Source code in src/quivers/packages/manifest.py
def dependency(self, name: str) -> Dependency | None:
    """The dependency on a package.

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

    Returns
    -------
    Dependency | None
        The dependency, or ``None`` when the package is not depended on.
    """
    for dependency in self.dependencies:
        if dependency.name == name:
            return dependency
    return None

index_url

index_url(name: str) -> str

The repository of a named index.

PARAMETER DESCRIPTION
name

The index's name.

TYPE: str

RETURNS DESCRIPTION
str

Its repository.

RAISES DESCRIPTION
ManifestError

If the manifest declares no such index.

Source code in src/quivers/packages/manifest.py
def index_url(self, name: str) -> str:
    """The repository of a named index.

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

    Returns
    -------
    str
        Its repository.

    Raises
    ------
    ManifestError
        If the manifest declares no such index.
    """
    for index in self.indexes:
        if index.name == name:
            return index.url
    raise ManifestError(
        f"package {self.name} names the index {name!r}, which its [indexes] "
        "table does not declare"
    )

provides

provides(module: tuple[str, ...]) -> bool

Whether a module path is in this package's namespace.

PARAMETER DESCRIPTION
module

A module path's segments.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
bool

Whether its first segment is the package's name.

Source code in src/quivers/packages/manifest.py
def provides(self, module: tuple[str, ...]) -> bool:
    """Whether a module path is in this package's namespace.

    Parameters
    ----------
    module : tuple[str, ...]
        A module path's segments.

    Returns
    -------
    bool
        Whether its first segment is the package's name.
    """
    return bool(module) and module[0] == self.name

ManifestError

Bases: ValueError

A manifest that does not describe a package.

Its message says what is wrong, naming the file and the key.

PathSource didactic-model

PathSource(*, path: str, kind: Literal['path'] = 'path')

Bases: DependencySource

A dependency found in a directory.

ATTRIBUTE DESCRIPTION
path

The directory, relative to the depending package's directory, in POSIX spelling.

TYPE: str

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

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

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

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.

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

GitError

Bases: OSError

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

Its message says the command and what git reported.

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, ...]

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

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

PackageIndexError

Bases: ValueError

An index entry that is malformed or missing.

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

Package didactic-model

Package(*, manifest: Manifest, directory: str, source: SourceKind, location: str = '', commit: str = '', revision: str = '', implicit: bool = False, published: tuple[LockedModule, ...] = ())

Bases: Model

A package's manifest and the place its modules are.

ATTRIBUTE DESCRIPTION
manifest

Its manifest.

TYPE: Manifest

directory

Its directory, absolute.

TYPE: str

source

How it was found.

TYPE: SourceKind

location

For a path dependency, the directory relative to the root package; for a git dependency, the repository; for an indexed one, the index's repository; empty for the root and the standard library.

TYPE: str

commit

The commit of its source, for git and index.

TYPE: str

revision

For git, the revision the depending manifest names.

TYPE: str

implicit

Whether every package depends on it without saying so (the standard library).

TYPE: bool

published

For an indexed version, the module hashes its index entry publishes.

TYPE: tuple[LockedModule, ...]

name property

name: str

The package's name.

RETURNS DESCRIPTION
str

manifest.name.

version property

version: Version

The package's version.

RETURNS DESCRIPTION
Version

manifest.version.

module_root

module_root() -> Path

The directory module paths of this package are relative to.

RETURNS DESCRIPTION
Path

<directory>/<manifest.source>.

Source code in src/quivers/packages/sources.py
def module_root(self) -> Path:
    """The directory module paths of this package are relative to.

    Returns
    -------
    Path
        ``<directory>/<manifest.source>``.
    """
    return Path(self.directory) / self.manifest.source

module_paths

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

Every module of the package: each .qvr file in its namespace.

RETURNS DESCRIPTION
tuple[str, ...]

The dotted module paths, sorted.

Source code in src/quivers/packages/sources.py
def module_paths(self) -> tuple[str, ...]:
    """Every module of the package: each ``.qvr`` file in its namespace.

    Returns
    -------
    tuple[str, ...]
        The dotted module paths, sorted.
    """
    root = self.module_root()
    namespace = root / self.name
    found: set[str] = set()
    candidates = [root / f"{self.name}{MODULE_SUFFIX}"]
    if namespace.is_dir():
        candidates.extend(namespace.rglob("*" + MODULE_SUFFIX))
    for file in candidates:
        if not file.is_file():
            continue
        relative = file.relative_to(root).with_suffix("")
        dotted = ".".join(relative.parts)
        try:
            parse_module_path(dotted)
        except ValueError:
            continue
        found.add(dotted)
    return tuple(sorted(found))

describe

describe() -> str

The package as diagnostics name it.

RETURNS DESCRIPTION
str

name version and, for a dependency, where it came from.

Source code in src/quivers/packages/sources.py
def describe(self) -> str:
    """The package as diagnostics name it.

    Returns
    -------
    str
        ``name version`` and, for a dependency, where it came from.
    """
    text = f"{self.name} {self.version.render()}"
    if self.source == "path":
        return f"{text} (path {self.location})"
    if self.source == "git":
        return f"{text} (git {self.location} at {self.commit[:12]})"
    if self.source == "index":
        return f"{text} (index {self.location})"
    if self.source == "builtin":
        return f"{text} (the standard library)"
    return text

PackageSources

PackageSources(root: Path, cache: GitCache)

Materialize packages from their sources.

PARAMETER DESCRIPTION
root

The root package's directory, which path dependencies are recorded relative to.

TYPE: Path

cache

The project's git cache.

TYPE: GitCache

Source code in src/quivers/packages/sources.py
def __init__(self, root: Path, cache: GitCache) -> None:
    self.root = root.resolve()
    self.cache = cache

root_package

root_package() -> Package

The root package.

RETURNS DESCRIPTION
Package

The package whose manifest is in the root directory.

RAISES DESCRIPTION
ManifestError

If its manifest is missing or malformed.

Source code in src/quivers/packages/sources.py
def root_package(self) -> Package:
    """The root package.

    Returns
    -------
    Package
        The package whose manifest is in the root directory.

    Raises
    ------
    ManifestError
        If its manifest is missing or malformed.
    """
    return Package(
        manifest=read_manifest(self.root), directory=str(self.root), source="path"
    )

directory

directory(directory: Path) -> Package

The package in a directory, as a path dependency.

PARAMETER DESCRIPTION
directory

The package's directory.

TYPE: Path

RETURNS DESCRIPTION
Package

The package, located relative to the root package.

RAISES DESCRIPTION
ManifestError

If the directory has no manifest or it is malformed.

Source code in src/quivers/packages/sources.py
def directory(self, directory: Path) -> Package:
    """The package in a directory, as a path dependency.

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

    Returns
    -------
    Package
        The package, located relative to the root package.

    Raises
    ------
    ManifestError
        If the directory has no manifest or it is malformed.
    """
    resolved = directory.resolve()
    relative = Path(_relative(resolved, self.root))
    return Package(
        manifest=read_manifest(resolved),
        directory=str(resolved),
        source="path",
        location=relative.as_posix(),
    )

git_manifest

git_manifest(url: str, commit: str) -> Manifest

The manifest at a commit of a repository, without extracting it.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

commit

The commit.

TYPE: str

RETURNS DESCRIPTION
Manifest

The manifest at the repository's top.

RAISES DESCRIPTION
ManifestError

If the commit has no manifest or it is malformed.

GitError

If the commit cannot be read.

Source code in src/quivers/packages/sources.py
def git_manifest(self, url: str, commit: str) -> Manifest:
    """The manifest at a commit of a repository, without extracting it.

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

    Returns
    -------
    Manifest
        The manifest at the repository's top.

    Raises
    ------
    ManifestError
        If the commit has no manifest or it is malformed.
    GitError
        If the commit cannot be read.
    """
    text = self.cache.read(url, commit, MANIFEST_NAME)
    where = f"{url} at {commit[:12]}: {MANIFEST_NAME}"
    if text is None:
        raise ManifestError(f"{where} does not exist: the repository is no package")
    return parse_manifest(text, where=where)

git

git(url: str, commit: str, *, source: SourceKind = 'git', revision: str = '') -> Package

The package at a commit of a repository, extracted into the cache.

PARAMETER DESCRIPTION
url

The repository.

TYPE: str

commit

The commit.

TYPE: str

source

git for a git dependency, index for an indexed version.

TYPE: SourceKind DEFAULT: 'git'

revision

The revision the depending manifest names.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
Package

The package.

RAISES DESCRIPTION
ManifestError

If the commit has no manifest or it is malformed.

GitError

If the commit cannot be read.

Source code in src/quivers/packages/sources.py
def git(
    self,
    url: str,
    commit: str,
    *,
    source: SourceKind = "git",
    revision: str = "",
) -> Package:
    """The package at a commit of a repository, extracted into the cache.

    Parameters
    ----------
    url : str
        The repository.
    commit : str
        The commit.
    source : SourceKind
        ``git`` for a git dependency, ``index`` for an indexed version.
    revision : str
        The revision the depending manifest names.

    Returns
    -------
    Package
        The package.

    Raises
    ------
    ManifestError
        If the commit has no manifest or it is malformed.
    GitError
        If the commit cannot be read.
    """
    directory = self.cache.checkout(url, commit)
    return Package(
        manifest=read_manifest(directory),
        directory=str(directory),
        source=source,
        location=url,
        commit=commit,
        revision=revision,
    )

Edge didactic-model

Edge(*, package: str, dependencies: tuple[str, ...] = ())

Bases: Model

The dependencies of one package of a resolved build.

ATTRIBUTE DESCRIPTION
package

The package.

TYPE: str

dependencies

The packages it depends on, sorted.

TYPE: tuple[str, ...]

Node didactic-model

Node(*, name: str, version: Version, origin: Origin)

Bases: Model

A package at one version, as the requirement graph visits it.

ATTRIBUTE DESCRIPTION
name

The package.

TYPE: str

version

Its version.

TYPE: Version

origin

Where it comes from.

TYPE: Origin

describe

describe() -> str

The node as explanations name it.

RETURNS DESCRIPTION
str

name version.

Source code in src/quivers/packages/resolve.py
def describe(self) -> str:
    """The node as explanations name it.

    Returns
    -------
    str
        ``name version``.
    """
    return f"{self.name} {self.version.render()}"

Origin didactic-model

Origin(*, kind: str, location: str = '', commit: str = '')

Bases: Model

Where one requirement says a package comes from.

ATTRIBUTE DESCRIPTION
kind

path, git, index, or builtin.

TYPE: str

location

The absolute directory, the repository, or the index's repository.

TYPE: str

commit

The git commit, for git.

TYPE: str

pinned

pinned() -> bool

Whether this origin fixes one version.

RETURNS DESCRIPTION
bool

True for a directory, a git commit, and the standard library.

Source code in src/quivers/packages/resolve.py
def pinned(self) -> bool:
    """Whether this origin fixes one version.

    Returns
    -------
    bool
        True for a directory, a git commit, and the standard library.
    """
    return self.kind != "index"

Requirement didactic-model

Requirement(*, dependent: Node | None = None, name: str, origin: Origin, minimum: Version | None = None, written: str)

Bases: Model

One dependency edge of the requirement graph.

ATTRIBUTE DESCRIPTION
dependent

The package that requires; None for the root.

TYPE: Node | None

name

The package required.

TYPE: str

origin

Where the dependent says it comes from.

TYPE: Origin

minimum

For an indexed requirement, the minimum version.

TYPE: Version | None

written

The requirement as explanations name it (worlds 1.x from 1.2.0, worlds from path ../worlds).

TYPE: str

Resolution didactic-model

Resolution(*, root: Package, packages: tuple[Package, ...] = (), edges: tuple[Edge, ...] = (), indexes: tuple[LockedIndex, ...] = ())

Bases: Model

A resolved build.

ATTRIBUTE DESCRIPTION
root

The root package.

TYPE: Package

packages

Every other package of the build, by name.

TYPE: tuple[Package, ...]

edges

Each package's dependencies after selection.

TYPE: tuple[Edge, ...]

indexes

The index commits read, by name.

TYPE: tuple[LockedIndex, ...]

package

package(name: str) -> Package | None

The selected package of a name, the root included.

PARAMETER DESCRIPTION
name

A package name.

TYPE: str

RETURNS DESCRIPTION
Package | None

The package, or None when the build has none.

Source code in src/quivers/packages/resolve.py
def package(self, name: str) -> Package | None:
    """The selected package of a name, the root included.

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

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

dependencies_of

dependencies_of(name: str) -> tuple[str, ...]

The packages one package depends on, the implicit ones included.

PARAMETER DESCRIPTION
name

A package of the build.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

Their names, sorted.

Source code in src/quivers/packages/resolve.py
def dependencies_of(self, name: str) -> tuple[str, ...]:
    """The packages one package depends on, the implicit ones included.

    Parameters
    ----------
    name : str
        A package of the build.

    Returns
    -------
    tuple[str, ...]
        Their names, sorted.
    """
    for edge in self.edges:
        if edge.package == name:
            return edge.dependencies
    return ()

all_packages

all_packages() -> tuple[Package, ...]

The root and every dependency.

RETURNS DESCRIPTION
tuple[Package, ...]

The root first, then the rest by name.

Source code in src/quivers/packages/resolve.py
def all_packages(self) -> tuple[Package, ...]:
    """The root and every dependency.

    Returns
    -------
    tuple[Package, ...]
        The root first, then the rest by name.
    """
    return (self.root, *self.packages)

ResolutionError

Bases: ValueError

Requirements no build satisfies.

Its message says the explanation, one derivation step per line.

Resolver

Resolver(sources: PackageSources, *, locked: Lockfile | None = None, standard_library_root: Path = STANDARD_LIBRARY_ROOT)

Resolve a root package's requirements by minimal version selection.

PARAMETER DESCRIPTION
sources

Materializes packages.

TYPE: PackageSources

locked

A lockfile whose index and git commits to read instead of the newest ones, so a locked build resolves offline to the same build.

TYPE: Lockfile | None DEFAULT: None

standard_library_root

Where the standard library's modules are.

TYPE: Path DEFAULT: STANDARD_LIBRARY_ROOT

Source code in src/quivers/packages/resolve.py
def __init__(
    self,
    sources: PackageSources,
    *,
    locked: Lockfile | None = None,
    standard_library_root: Path = STANDARD_LIBRARY_ROOT,
) -> None:
    self.sources = sources
    self.cache: GitCache = sources.cache
    self.locked = locked
    self.standard_library_root = standard_library_root
    self._indexes: dict[str, PackageIndex] = {}
    self._index_names: dict[str, str] = {}
    self._git_manifests: dict[tuple[str, str], Manifest] = {}
    self._git_commits: dict[tuple[str, str], str] = {}
    self._git_revisions: dict[tuple[str, str], str] = {}

resolve

resolve() -> Resolution

Resolve the root package's build.

RETURNS DESCRIPTION
Resolution

Every selected package, its dependencies, and the index commits read.

RAISES DESCRIPTION
ResolutionError

If no build satisfies the requirements, with the explanation.

ManifestError

If a manifest is malformed.

GitError

If a repository cannot be read.

Source code in src/quivers/packages/resolve.py
def resolve(self) -> Resolution:
    """Resolve the root package's build.

    Returns
    -------
    Resolution
        Every selected package, its dependencies, and the index commits
        read.

    Raises
    ------
    ResolutionError
        If no build satisfies the requirements, with the explanation.
    ManifestError
        If a manifest is malformed.
    GitError
        If a repository cannot be read.
    """
    root = self.sources.root_package()
    if root.manifest.dependency(STANDARD_LIBRARY_NAME) is not None:
        raise ResolutionError(
            f"package {root.name} names {STANDARD_LIBRARY_NAME} as a dependency; the "
            "standard library ships with quivers and every package depends on it"
        )
    by_node: dict[str, Requirement] = {}
    visited: list[tuple[Requirement, Node]] = []
    pending = self._requirements(root.manifest, Path(root.directory), None)
    while pending:
        requirement = pending.pop(0)
        node, manifest, directory = self._visit(requirement, by_node)
        visited.append((requirement, node))
        key = _node_key(node)
        if key in by_node:
            continue
        by_node[key] = requirement
        pending.extend(self._node_requirements(node, manifest, directory))
    selected = self._select(visited, by_node, root.name)
    return self._materialize(root, selected, visited)

BuiltModule didactic-model

BuiltModule(*, path: str, package: str, interface: ModuleInterface, core: str, holes: tuple[str, ...] = (), qiec: QiecModule | None = field(opaque=True, extras=OPAQUE_BY_VALUE), flat: FlatProgram = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

One module of a package, checked.

ATTRIBUTE DESCRIPTION
path

The module's path.

TYPE: str

package

Its package's name.

TYPE: str

interface

Its public interface.

TYPE: ModuleInterface

core

The hash of its checked declarations.

TYPE: str

qiec

The checked core of its flat program (or, for a module that needs unfilled holes, of its checking program); None for a module that declares nothing with a core form (only signatures, say).

TYPE: QiecModule | None

flat

Its flat program.

TYPE: FlatProgram

holes

The holes its graph has that modules of its own package declare.

TYPE: tuple[str, ...]

pin

pin() -> LockedModule

The module's pin.

RETURNS DESCRIPTION
LockedModule

Its path and hashes.

Source code in src/quivers/packages/workspace.py
def pin(self) -> LockedModule:
    """The module's pin.

    Returns
    -------
    LockedModule
        Its path and hashes.
    """
    return LockedModule(
        path=self.path, core=self.core, interface=self.interface.digest()
    )

PackageError

PackageError(code: PackageErrorCode, message: str, location: SourceLocation | None = None)

Bases: ValueError

A build that violates a package rule or disagrees with its pins.

PARAMETER DESCRIPTION
code

The stable code.

TYPE: PackageErrorCode

message

What is wrong.

TYPE: str

location

Where, when the refusal points at source.

TYPE: SourceLocation | None DEFAULT: None

Source code in src/quivers/packages/workspace.py
def __init__(
    self,
    code: PackageErrorCode,
    message: str,
    location: SourceLocation | None = None,
) -> None:
    self.code: PackageErrorCode = code
    self.message = message
    self.location = location
    prefix = f"{location.render()}: " if location is not None else ""
    super().__init__(f"{prefix}error[{code}]: {message}")

PackageLoader

PackageLoader(packages: Iterable[Package])

Find a module in the package its path's first segment names.

PARAMETER DESCRIPTION
packages

Every package of the build.

TYPE: Iterable[Package]

Source code in src/quivers/packages/workspace.py
def __init__(self, packages: Iterable[Package]) -> None:
    self.packages = {package.name: package for package in packages}
    self._loaders = {
        name: FileSystemLoader((package.module_root(),))
        for name, package in self.packages.items()
    }

find

find(path: tuple[str, ...]) -> tuple[ModuleSource, ...]

The source of a module path, from its package.

PARAMETER DESCRIPTION
path

The module path's segments.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
tuple[ModuleSource, ...]

The module's source, or nothing when no package of the build provides it.

Source code in src/quivers/packages/workspace.py
def find(self, path: tuple[str, ...]) -> tuple[ModuleSource, ...]:
    """The source of a module path, from its package.

    Parameters
    ----------
    path : tuple[str, ...]
        The module path's segments.

    Returns
    -------
    tuple[ModuleSource, ...]
        The module's source, or nothing when no package of the build
        provides it.
    """
    loader = self._loaders.get(path[0]) if path else None
    return () if loader is None else loader.find(path)

available

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

Every module the build's packages provide.

RETURNS DESCRIPTION
tuple[str, ...]

The dotted paths, sorted.

Source code in src/quivers/packages/workspace.py
def available(self) -> tuple[str, ...]:
    """Every module the build's packages provide.

    Returns
    -------
    tuple[str, ...]
        The dotted paths, sorted.
    """
    return tuple(
        sorted(
            path
            for package in self.packages.values()
            for path in package.module_paths()
        )
    )

package_of

package_of(path: tuple[str, ...]) -> Package | None

The package providing a module path.

PARAMETER DESCRIPTION
path

The module path's segments.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
Package | None

The package named by its first segment, if the build has one.

Source code in src/quivers/packages/workspace.py
def package_of(self, path: tuple[str, ...]) -> Package | None:
    """The package providing a module path.

    Parameters
    ----------
    path : tuple[str, ...]
        The module path's segments.

    Returns
    -------
    Package | None
        The package named by its first segment, if the build has one.
    """
    return self.packages.get(path[0]) if path else None

Workspace

Workspace(root: Path, *, cache: GitCache | None = None, standard_library_root: Path = STANDARD_LIBRARY_ROOT)

A root package and its build.

PARAMETER DESCRIPTION
root

The root package's directory.

TYPE: Path

cache

The git cache; the project's own (<root>/.qvr/packages) when omitted.

TYPE: GitCache | None DEFAULT: None

standard_library_root

Where the standard library's modules are.

TYPE: Path DEFAULT: STANDARD_LIBRARY_ROOT

Source code in src/quivers/packages/workspace.py
def __init__(
    self,
    root: Path,
    *,
    cache: GitCache | None = None,
    standard_library_root: Path = STANDARD_LIBRARY_ROOT,
) -> None:
    self.root = root.resolve()
    self.cache = cache if cache is not None else GitCache.for_package(self.root)
    self.sources = PackageSources(self.root, self.cache)
    self.standard_library_root = standard_library_root

discover classmethod

discover(start: Path, *, cache: GitCache | None = None, standard_library_root: Path = STANDARD_LIBRARY_ROOT) -> Workspace

The workspace of the package containing a path.

PARAMETER DESCRIPTION
start

A file or directory inside the package.

TYPE: Path

cache

The git cache, as for the constructor.

TYPE: GitCache | None DEFAULT: None

standard_library_root

Where the standard library's modules are.

TYPE: Path DEFAULT: STANDARD_LIBRARY_ROOT

RETURNS DESCRIPTION
Workspace

The workspace.

RAISES DESCRIPTION
ManifestError

If no directory at or above start has a qvr.toml.

Source code in src/quivers/packages/workspace.py
@classmethod
def discover(
    cls,
    start: Path,
    *,
    cache: GitCache | None = None,
    standard_library_root: Path = STANDARD_LIBRARY_ROOT,
) -> Workspace:
    """The workspace of the package containing a path.

    Parameters
    ----------
    start : Path
        A file or directory inside the package.
    cache : GitCache | None
        The git cache, as for the constructor.
    standard_library_root : Path
        Where the standard library's modules are.

    Returns
    -------
    Workspace
        The workspace.

    Raises
    ------
    ManifestError
        If no directory at or above ``start`` has a ``qvr.toml``.
    """
    root = find_package_root(start)
    if root is None:
        raise ManifestError(
            f"no qvr.toml at or above {start}: a package is a directory with a "
            "qvr.toml manifest"
        )
    return cls(root, cache=cache, standard_library_root=standard_library_root)

resolve

resolve(*, locked: Lockfile | None = None) -> Resolution

Resolve the root manifest.

PARAMETER DESCRIPTION
locked

A lockfile whose index and git commits to read; the newest ones when omitted.

TYPE: Lockfile | None DEFAULT: None

RETURNS DESCRIPTION
Resolution

The build.

RAISES DESCRIPTION
ResolutionError

If no build satisfies the requirements.

Source code in src/quivers/packages/workspace.py
def resolve(self, *, locked: Lockfile | None = None) -> Resolution:
    """Resolve the root manifest.

    Parameters
    ----------
    locked : Lockfile | None
        A lockfile whose index and git commits to read; the newest ones
        when omitted.

    Returns
    -------
    Resolution
        The build.

    Raises
    ------
    ResolutionError
        If no build satisfies the requirements.
    """
    return Resolver(
        self.sources,
        locked=locked,
        standard_library_root=self.standard_library_root,
    ).resolve()

locked_build

locked_build(locked: Lockfile) -> Resolution

The build a lockfile records, read from the lockfile alone.

The manifest is not consulted beyond the root package itself: each package is materialized from its pinned source (a directory, a git commit, the index entry at the locked index commit, or the standard library), so the build migrated from stays reachable after the manifest has moved on.

PARAMETER DESCRIPTION
locked

The lockfile.

TYPE: Lockfile

RETURNS DESCRIPTION
Resolution

The locked build.

RAISES DESCRIPTION
PackageError

If a locked package no longer has the version the lockfile records.

GitError

If a pinned commit cannot be read.

Source code in src/quivers/packages/workspace.py
def locked_build(self, locked: Lockfile) -> Resolution:
    """The build a lockfile records, read from the lockfile alone.

    The manifest is not consulted beyond the root package itself: each
    package is materialized from its pinned source (a directory, a git
    commit, the index entry at the locked index commit, or the standard
    library), so the build migrated *from* stays reachable after the
    manifest has moved on.

    Parameters
    ----------
    locked : Lockfile
        The lockfile.

    Returns
    -------
    Resolution
        The locked build.

    Raises
    ------
    PackageError
        If a locked package no longer has the version the lockfile
        records.
    GitError
        If a pinned commit cannot be read.
    """
    root = self.sources.root_package()
    packages: list[Package] = []
    for pinned in locked.packages:
        if pinned.source == "builtin":
            package = standard_library(self.standard_library_root)
        elif pinned.source == "path":
            package = self.sources.directory(self.root / pinned.location)
        elif pinned.source == "git":
            package = self.sources.git(
                pinned.location, pinned.commit, revision=pinned.revision
            )
        else:
            index_record = next(
                (item for item in locked.indexes if item.url == pinned.location),
                None,
            )
            if index_record is None:
                raise PackageError(
                    "package-lock-stale",
                    f"qvr.lock pins {pinned.name} from the index {pinned.location}, "
                    "which it records no commit of",
                )
            index = PackageIndex.open(
                index_record.name,
                index_record.url,
                self.cache,
                commit=index_record.commit,
            )
            entry = index.entry(pinned.name, pinned.version)
            package = self.sources.git(entry.url, entry.commit, source="index")
            package = package.with_(
                location=pinned.location, published=entry.modules
            )
        if package.version != pinned.version:
            raise PackageError(
                "package-lock-stale",
                f"qvr.lock pins {pinned.name} {pinned.version.render()}, but its "
                f"source now holds {package.describe()}",
            )
        packages.append(package)
    edges = [Edge(package=root.name, dependencies=locked.dependencies)]
    edges.extend(
        Edge(package=pinned.name, dependencies=pinned.dependencies)
        for pinned in locked.packages
    )
    return Resolution(
        root=root,
        packages=tuple(sorted(packages, key=lambda item: item.name)),
        edges=tuple(sorted(edges, key=lambda item: item.package)),
        indexes=locked.indexes,
    )

loader

loader(resolution: Resolution) -> PackageLoader

The loader of a resolved build.

PARAMETER DESCRIPTION
resolution

The build.

TYPE: Resolution

RETURNS DESCRIPTION
PackageLoader

Finds every module of every package.

Source code in src/quivers/packages/workspace.py
def loader(self, resolution: Resolution) -> PackageLoader:
    """The loader of a resolved build.

    Parameters
    ----------
    resolution : Resolution
        The build.

    Returns
    -------
    PackageLoader
        Finds every module of every package.
    """
    return PackageLoader(resolution.all_packages())
links(resolution: Resolution) -> dict[str, str]

The links of a build: default links, then the root's own.

PARAMETER DESCRIPTION
resolution

The build.

TYPE: Resolution

RETURNS DESCRIPTION
dict[str, str]

Hole path to filling module.

RAISES DESCRIPTION
PackageError

If two packages give one hole different defaults and the root does not link it.

Source code in src/quivers/packages/workspace.py
def links(self, resolution: Resolution) -> dict[str, str]:
    """The links of a build: default links, then the root's own.

    Parameters
    ----------
    resolution : Resolution
        The build.

    Returns
    -------
    dict[str, str]
        Hole path to filling module.

    Raises
    ------
    PackageError
        If two packages give one hole different defaults and the root
        does not link it.
    """
    own = {link.hole: link.module for link in resolution.root.manifest.links}
    defaults: dict[str, tuple[str, str]] = {}
    for package in resolution.all_packages():
        for hole in package.manifest.holes:
            if not hole.default or hole.path in own:
                continue
            prior = defaults.get(hole.path)
            if prior is not None and prior[0] != hole.default:
                raise PackageError(
                    "package-link-conflict",
                    f"packages {prior[1]} and {package.name} give the hole "
                    f"{hole.path} different defaults ({prior[0]} and "
                    f"{hole.default}); link it in [links] of "
                    f"{resolution.root.name}",
                )
            defaults.setdefault(hole.path, (hole.default, package.name))
    merged = {path: module for path, (module, _package) in defaults.items()}
    merged.update(own)
    return dict(sorted(merged.items()))

load

load(module: str, resolution: Resolution, *, extra_links: Mapping[str, str] | None = None, overlay: Mapping[str, str] | None = None) -> ModuleGraph

Load the module graph rooted at one module of the build.

PARAMETER DESCRIPTION
module

The root module's path.

TYPE: str

resolution

The build.

TYPE: Resolution

extra_links

Links beyond the build's (an experiment's), which win.

TYPE: Mapping[str, str] | None DEFAULT: None

overlay

Module texts, by path, read instead of the packages' files (an editor's buffers, a migration's output).

TYPE: Mapping[str, str] | None DEFAULT: None

RETURNS DESCRIPTION
ModuleGraph

The checked graph, linked with the build's links for the holes it has.

RAISES DESCRIPTION
PackageError

If no package provides the module, or an import or link crosses a package boundary the rules forbid.

ModuleError

If the graph does not load or resolve.

Source code in src/quivers/packages/workspace.py
def load(
    self,
    module: str,
    resolution: Resolution,
    *,
    extra_links: Mapping[str, str] | None = None,
    overlay: Mapping[str, str] | None = None,
) -> ModuleGraph:
    """Load the module graph rooted at one module of the build.

    Parameters
    ----------
    module : str
        The root module's path.
    resolution : Resolution
        The build.
    extra_links : Mapping[str, str] | None
        Links beyond the build's (an experiment's), which win.
    overlay : Mapping[str, str] | None
        Module texts, by path, read instead of the packages' files (an
        editor's buffers, a migration's output).

    Returns
    -------
    ModuleGraph
        The checked graph, linked with the build's links for the holes
        it has.

    Raises
    ------
    PackageError
        If no package provides the module, or an import or link
        crosses a package boundary the rules forbid.
    ModuleError
        If the graph does not load or resolve.
    """
    loader = self.loader(resolution)
    finder: ModuleLoader = (
        ChainLoader((MappingLoader(dict(overlay), label="<overlay>"), loader))
        if overlay
        else loader
    )
    path = parse_module_path(module)
    found = finder.find(path)
    if not found:
        raise PackageError(
            "package-module-missing",
            f"no package of the build provides module {module}",
        )
    source = found[0]
    unlinked = load_graph(source, finder)
    links = dict(self.links(resolution))
    links.update(extra_links or {})
    # Link only the holes some module imports: a hole a module merely
    # declares is needed by no code of this graph.
    holes = {
        ".".join(resolved.module.path)
        for checked in unlinked.checked.values()
        for resolved in checked.imports
        if isinstance(resolved.module, HoleModule)
    }
    relevant = {hole: filler for hole, filler in links.items() if hole in holes}
    graph = load_graph(source, finder, links=relevant) if relevant else unlinked
    self._check_visibility(graph, resolution, loader)
    return graph

build_module

build_module(module: str, resolution: Resolution, *, extra_links: Mapping[str, str] | None = None, overlay: Mapping[str, str] | None = None) -> BuiltModule

Check one module of the build as a root.

PARAMETER DESCRIPTION
module

The module's path.

TYPE: str

resolution

The build.

TYPE: Resolution

extra_links

Links beyond the build's.

TYPE: Mapping[str, str] | None DEFAULT: None

overlay

Module texts read instead of the packages' files.

TYPE: Mapping[str, str] | None DEFAULT: None

RETURNS DESCRIPTION
BuiltModule

The checked module and its hashes. A module that needs holes no link fills is hashed by its checking program, which checks it against the holes' signatures.

RAISES DESCRIPTION
PackageError

If an import crosses a package boundary the rules forbid.

ModuleError

If the graph does not load or resolve.

CompileError

If the module does not compile.

Source code in src/quivers/packages/workspace.py
def build_module(
    self,
    module: str,
    resolution: Resolution,
    *,
    extra_links: Mapping[str, str] | None = None,
    overlay: Mapping[str, str] | None = None,
) -> BuiltModule:
    """Check one module of the build as a root.

    Parameters
    ----------
    module : str
        The module's path.
    resolution : Resolution
        The build.
    extra_links : Mapping[str, str] | None
        Links beyond the build's.
    overlay : Mapping[str, str] | None
        Module texts read instead of the packages' files.

    Returns
    -------
    BuiltModule
        The checked module and its hashes. A module that needs holes no
        link fills is hashed by its checking program, which checks it
        against the holes' signatures.

    Raises
    ------
    PackageError
        If an import crosses a package boundary the rules forbid.
    ModuleError
        If the graph does not load or resolve.
    CompileError
        If the module does not compile.
    """
    graph = self.load(module, resolution, extra_links=extra_links, overlay=overlay)
    flat = interpret(graph)
    label = graph.loaded[graph.root].source.label
    checking = check_module_language(flat, module_name=module, file_path=label)
    if flat.unfilled:
        # A module that needs holes no link fills checks against the
        # holes' signatures alone; its checking program is its core.
        checked = checking
    else:
        compiler = Compiler(flat.module, module_name=module, file_path=label)
        compiler.check()
        checked = compiler.qiec_module
        if checked is not None and flat.laws:
            check_signature_laws(flat, checked)
    loader = self.loader(resolution)
    provider = loader.package_of(parse_module_path(module))
    name = provider.name if provider is not None else ""
    holes = tuple(
        sorted(
            ".".join(hole.path)
            for hole, declaration in graph.holes.items()
            if isinstance(declaration.module, SourceModule)
            and declaration.module.path[:1] == (name,)
        )
    )
    return BuiltModule(
        path=module,
        package=name,
        interface=graph.checked[graph.root].interface,
        core=module_core_hash(checked),
        qiec=checked,
        flat=flat,
        holes=holes,
    )

build_package

build_package(package: Package, resolution: Resolution) -> tuple[BuiltModule, ...]

Check the modules of one package that the build pins.

The root package's every module is checked; a dependency's exposed modules are (its private modules are checked through them).

PARAMETER DESCRIPTION
package

A package of the build.

TYPE: Package

resolution

The build.

TYPE: Resolution

RETURNS DESCRIPTION
tuple[BuiltModule, ...]

The checked modules, by path.

RAISES DESCRIPTION
PackageError

If an exposed module does not exist or a hole is unlisted.

ModuleError

If a module does not load or resolve.

CompileError

If a module does not compile.

Source code in src/quivers/packages/workspace.py
def build_package(
    self, package: Package, resolution: Resolution
) -> tuple[BuiltModule, ...]:
    """Check the modules of one package that the build pins.

    The root package's every module is checked; a dependency's exposed
    modules are (its private modules are checked through them).

    Parameters
    ----------
    package : Package
        A package of the build.
    resolution : Resolution
        The build.

    Returns
    -------
    tuple[BuiltModule, ...]
        The checked modules, by path.

    Raises
    ------
    PackageError
        If an exposed module does not exist or a hole is unlisted.
    ModuleError
        If a module does not load or resolve.
    CompileError
        If a module does not compile.
    """
    available = package.module_paths()
    for exposed in package.manifest.modules:
        if exposed not in available:
            raise PackageError(
                "package-module-missing",
                f"package {package.name} exposes {exposed}, which is no file "
                f"below {package.module_root()}",
            )
    modules = (
        available
        if package.name == resolution.root.name
        else package.manifest.modules
    )
    built = tuple(self.build_module(path, resolution) for path in modules)
    self._check_holes(package, built)
    return built

pinned_modules

pinned_modules(package: Package, resolution: Resolution) -> tuple[BuiltModule, ...]

The checked modules a lockfile pins for one dependency.

The standard library ships with quivers, so its version (the release it ships with) identifies its content: it is not checked or pinned module by module. Every other dependency's exposed modules are.

PARAMETER DESCRIPTION
package

A dependency of the build.

TYPE: Package

resolution

The build.

TYPE: Resolution

RETURNS DESCRIPTION
tuple[BuiltModule, ...]

Its pinned modules, by path.

RAISES DESCRIPTION
PackageError

If a module violates a package rule.

ModuleError

If a module does not load or resolve.

CompileError

If a module does not compile.

Source code in src/quivers/packages/workspace.py
def pinned_modules(
    self, package: Package, resolution: Resolution
) -> tuple[BuiltModule, ...]:
    """The checked modules a lockfile pins for one dependency.

    The standard library ships with quivers, so its version (the
    release it ships with) identifies its content: it is not checked
    or pinned module by module. Every other dependency's exposed
    modules are.

    Parameters
    ----------
    package : Package
        A dependency of the build.
    resolution : Resolution
        The build.

    Returns
    -------
    tuple[BuiltModule, ...]
        Its pinned modules, by path.

    Raises
    ------
    PackageError
        If a module violates a package rule.
    ModuleError
        If a module does not load or resolve.
    CompileError
        If a module does not compile.
    """
    if package.source == "builtin":
        return ()
    return self.build_package(package, resolution)

lock

lock() -> Lockfile

Resolve the manifest afresh, check every package, and pin it.

RETURNS DESCRIPTION
Lockfile

The lockfile, also written beside the manifest.

RAISES DESCRIPTION
ResolutionError

If no build satisfies the requirements.

PackageError

If a module violates a package rule, or an indexed version's modules differ from the hashes its index entry publishes.

ModuleError

If a module does not load or resolve.

CompileError

If a module does not compile.

Source code in src/quivers/packages/workspace.py
def lock(self) -> Lockfile:
    """Resolve the manifest afresh, check every package, and pin it.

    Returns
    -------
    Lockfile
        The lockfile, also written beside the manifest.

    Raises
    ------
    ResolutionError
        If no build satisfies the requirements.
    PackageError
        If a module violates a package rule, or an indexed version's
        modules differ from the hashes its index entry publishes.
    ModuleError
        If a module does not load or resolve.
    CompileError
        If a module does not compile.
    """
    resolution = self.resolve()
    lockfile = self._lockfile(resolution)
    (self.root / LOCKFILE_NAME).write_text(
        render_lockfile(lockfile), encoding="utf-8"
    )
    return lockfile

build

build() -> tuple[Lockfile, tuple[BuiltModule, ...]]

Build the root package against its lockfile.

RETURNS DESCRIPTION
tuple[Lockfile, tuple[BuiltModule, ...]]

The lockfile and the root package's checked modules.

RAISES DESCRIPTION
PackageError

If the package has no lockfile, the manifest has moved away from it (package-lock-stale), or a module's hashes differ from its pins (package-pin-mismatch).

ResolutionError

If no build satisfies the requirements.

ModuleError

If a module does not load or resolve.

CompileError

If a module does not compile.

Source code in src/quivers/packages/workspace.py
def build(self) -> tuple[Lockfile, tuple[BuiltModule, ...]]:
    """Build the root package against its lockfile.

    Returns
    -------
    tuple[Lockfile, tuple[BuiltModule, ...]]
        The lockfile and the root package's checked modules.

    Raises
    ------
    PackageError
        If the package has no lockfile, the manifest has moved away
        from it (``package-lock-stale``), or a module's hashes differ
        from its pins (``package-pin-mismatch``).
    ResolutionError
        If no build satisfies the requirements.
    ModuleError
        If a module does not load or resolve.
    CompileError
        If a module does not compile.
    """
    locked = read_lockfile(self.root)
    if locked is None:
        raise PackageError(
            "package-lock-stale",
            f"{self.root / LOCKFILE_NAME} does not exist; run `qvr lock` first",
        )
    resolution = self.resolve(locked=locked)
    self._check_against(locked, resolution)
    for package in resolution.packages:
        pinned = locked.package(package.name)
        assert pinned is not None
        built = self.pinned_modules(package, resolution)
        _compare_pins(
            package, pinned.modules, tuple(m.pin() for m in built), "qvr.lock pins"
        )
    return locked, self.build_package(resolution.root, resolution)

InterfaceSymbol didactic-model

InterfaceSymbol(*, path: str, kind: str, module: str, identity: str, origin: str = '', type: str = '', effects: str = '', support: str = '', index: str = '', body: str = '', fitted: bool = False, display: str = '')

Bases: Model

One thing a dependent of a package can name or rely on.

ATTRIBUTE DESCRIPTION
path

How dependents spell it: the exposing module's path, then the name, then (for a site or data parameter) its label.

TYPE: str

kind

family, constructor, computation, program, ...; site:sample, site:observe, site:marginal for a site; data:<role> for a data parameter.

TYPE: str

module

The exposing module.

TYPE: str

origin

The declaring module's path and the name there, as name resolution reports it (empty for a site or data parameter).

TYPE: str

identity

The rename-stable identity.

TYPE: str

type

The digest of its type or shape.

TYPE: str

effects

The digest of its effect row (computations).

TYPE: str

support

What fixes a site's support: its family, plate, and axes.

TYPE: str

index

The digest of a data parameter's index type and axes.

TYPE: str

body

The declaration's whole content hash.

TYPE: str

fitted

For a program: whether it is fit to data (it observes, or takes data parameters).

TYPE: bool

display

How messages show it: the declaring line, or a site's family.

TYPE: str

PackageInterface didactic-model

PackageInterface(*, package: str, version: Version, symbols: tuple[InterfaceSymbol, ...] = ())

Bases: Model

The semantic interface of one package version.

ATTRIBUTE DESCRIPTION
package

The package.

TYPE: str

version

The version.

TYPE: Version

symbols

Every symbol, by path.

TYPE: tuple[InterfaceSymbol, ...]

symbol

symbol(path: str) -> InterfaceSymbol | None

The symbol at a path.

PARAMETER DESCRIPTION
path

A symbol path.

TYPE: str

RETURNS DESCRIPTION
InterfaceSymbol | None

The symbol, or None when the interface has none there.

Source code in src/quivers/packages/interface.py
def symbol(self, path: str) -> InterfaceSymbol | None:
    """The symbol at a path.

    Parameters
    ----------
    path : str
        A symbol path.

    Returns
    -------
    InterfaceSymbol | None
        The symbol, or ``None`` when the interface has none there.
    """
    for symbol in self.symbols:
        if symbol.path == path:
            return symbol
    return None

to_data

to_data() -> dict[str, object]

The interface as JSON-compatible data.

RETURNS DESCRIPTION
dict[str, object]

The package, version, and symbols.

Source code in src/quivers/packages/interface.py
def to_data(self) -> dict[str, object]:
    """The interface as JSON-compatible data.

    Returns
    -------
    dict[str, object]
        The package, version, and symbols.
    """
    return {
        "package": self.package,
        "version": self.version.render(),
        "symbols": [
            json.loads(symbol.model_dump_json()) for symbol in self.symbols
        ],
    }

DependencyLens didactic-model

DependencyLens(*, package: str, old_version: Version, new_version: Version, renames: tuple[Rename, ...] = (), removed: tuple[str, ...] = (), added: tuple[str, ...] = (), old_paths: tuple[str, ...] = (), chain: str = '', morphism: str = '')

Bases: Model

The lens from one version of a package's interface to another.

ATTRIBUTE DESCRIPTION
package

The package.

TYPE: str

old_version, new_version

The versions.

TYPE: Version

renames

The symbols kept under new paths, by old path.

TYPE: tuple[Rename, ...]

removed

The old paths with no image.

TYPE: tuple[str, ...]

added

The new paths no old symbol maps to.

TYPE: tuple[str, ...]

old_paths

Every old path.

TYPE: tuple[str, ...]

chain

The residual protolens chain, as panproto's JSON.

TYPE: str

morphism

The renaming theory morphism, as panproto's JSON.

TYPE: str

between classmethod

The lens from an old interface to a new one.

PARAMETER DESCRIPTION
old

The interfaces.

TYPE: PackageInterface

new

The interfaces.

TYPE: PackageInterface

RETURNS DESCRIPTION
DependencyLens

The renames, the residual chain, and the renaming morphism.

RAISES DESCRIPTION
LensError

If panproto cannot derive the residual chain.

Source code in src/quivers/packages/lenses.py
@classmethod
def between(cls, old: PackageInterface, new: PackageInterface) -> DependencyLens:
    """The lens from an old interface to a new one.

    Parameters
    ----------
    old, new : PackageInterface
        The interfaces.

    Returns
    -------
    DependencyLens
        The renames, the residual chain, and the renaming morphism.

    Raises
    ------
    LensError
        If panproto cannot derive the residual chain.
    """
    renames, removed, added = _renames(old, new)
    back = {rename.new: rename.old for rename in renames}
    old_paths = [symbol.path for symbol in old.symbols]
    new_in_old = [back.get(symbol.path, symbol.path) for symbol in new.symbols]
    try:
        chain = panproto.diff_to_protolens(
            _inventory(old_paths), _inventory(new_in_old)
        )
    except panproto.LensError as error:
        raise LensError(
            f"panproto cannot derive the interface chain of {old.package}: {error}"
        ) from error
    image = {rename.old: rename.new for rename in renames}
    sort_map = {_ROOT: _ROOT}
    for path in old_paths:
        if path in removed:
            continue
        target = image.get(path, path)
        sort_map[path] = target
        sort_map[path + _USE] = target + _USE
    morphism = panproto.TheoryMorphism(
        f"{old.package}@{old.version.render()}..{new.version.render()}",
        f"{old.package}@{old.version.render()}",
        f"{new.package}@{new.version.render()}",
        sort_map,
    )
    return cls(
        package=old.package,
        old_version=old.version,
        new_version=new.version,
        renames=renames,
        removed=removed,
        added=added,
        old_paths=tuple(sorted(old_paths)),
        chain=chain.to_json(),
        morphism=morphism.to_json(),
    )

image

image(path: str) -> str | None

Where an old symbol is in the new interface.

PARAMETER DESCRIPTION
path

An old symbol path.

TYPE: str

RETURNS DESCRIPTION
str | None

Its new path, or None when it was removed.

Source code in src/quivers/packages/lenses.py
def image(self, path: str) -> str | None:
    """Where an old symbol is in the new interface.

    Parameters
    ----------
    path : str
        An old symbol path.

    Returns
    -------
    str | None
        Its new path, or ``None`` when it was removed.
    """
    if path in self.removed:
        return None
    for rename in self.renames:
        if rename.old == path:
            return rename.new
    return path

is_identity

is_identity() -> bool

Whether the lens renames, removes, and adds nothing.

RETURNS DESCRIPTION
bool

Whether dependents need no change.

Source code in src/quivers/packages/lenses.py
def is_identity(self) -> bool:
    """Whether the lens renames, removes, and adds nothing.

    Returns
    -------
    bool
        Whether dependents need no change.
    """
    return not (self.renames or self.removed or self.added)

apply

apply(fleet: Mapping[str, tuple[Use, ...]]) -> tuple[MemberOutcome, ...]

Apply the lens to the usages of every dependent at once.

The residual chain is fused, lifted along the renaming morphism, and applied to each dependent's usage schema; each usage is read through the lens it instantiates, and the places its complement holds are the ones no lens reaches. With no residual change, the morphism alone maps every place.

PARAMETER DESCRIPTION
fleet

Each dependent's places, by name.

TYPE: Mapping[str, tuple[Use, ...]]

RETURNS DESCRIPTION
tuple[MemberOutcome, ...]

Each dependent's renamed and unmigratable places, by name.

RAISES DESCRIPTION
LensError

If a use names a symbol the old interface does not have.

Source code in src/quivers/packages/lenses.py
def apply(self, fleet: Mapping[str, tuple[Use, ...]]) -> tuple[MemberOutcome, ...]:
    """Apply the lens to the usages of every dependent at once.

    The residual chain is fused, lifted along the renaming morphism, and
    applied to each dependent's usage schema; each usage is read through
    the lens it instantiates, and the places its complement holds are
    the ones no lens reaches. With no residual change, the morphism
    alone maps every place.

    Parameters
    ----------
    fleet : Mapping[str, tuple[Use, ...]]
        Each dependent's places, by name.

    Returns
    -------
    tuple[MemberOutcome, ...]
        Each dependent's renamed and unmigratable places, by name.

    Raises
    ------
    LensError
        If a use names a symbol the old interface does not have.
    """
    known = set(self.old_paths)
    for member, uses in fleet.items():
        for use in uses:
            if use.symbol not in known:
                raise LensError(
                    f"{member} names {use.symbol}, which {self.package} "
                    f"{self.old_version.render()} does not provide"
                )
    chain = panproto.ProtolensChain.from_json(self.chain)
    kept_by: dict[str, set[str]] = {}
    reasons: dict[str, str] = {}
    if len(chain):
        morphism = panproto.TheoryMorphism.from_json(self.morphism)
        lifted = panproto.lift_protolens(chain.fuse(), morphism)
        protocol = panproto.get_builtin_protocol(INVENTORY_PROTOCOL)
        schemas = {
            member: _inventory([use.symbol for use in uses])
            for member, uses in fleet.items()
        }
        result = panproto.apply_to_fleet(lifted, schemas, protocol)
        for member, lens in result.applied.items():
            uses = fleet[member]
            document: dict[str, list[str]] = {}
            for use in uses:
                document.setdefault(use.symbol, []).append(use.place)
            instance = panproto.Instance.from_json(
                schemas[member], _ROOT, json.dumps(document, sort_keys=True)
            )
            view, _complement = lens.get(instance)
            kept = json.loads(view.to_json())
            kept_by[member] = {
                f"{symbol}\0{place}"
                for symbol, places in kept.items()
                for place in places
            }
        for member, failures in result.skipped.items():
            reasons[member] = "; ".join(failures)
    outcomes: list[MemberOutcome] = []
    for member in sorted(fleet):
        renamed: list[RenamedUse] = []
        dropped: list[Unmigratable] = []
        kept_places = kept_by.get(member)
        for use in fleet[member]:
            target = self.image(use.symbol)
            if member in reasons:
                dropped.append(Unmigratable(use=use, reason=reasons[member]))
                continue
            survives = (
                target is not None
                if kept_places is None
                else f"{use.symbol}\0{use.place}" in kept_places
            )
            if not survives or target is None:
                dropped.append(
                    Unmigratable(
                        use=use,
                        reason=f"{use.symbol} was removed from {self.package} in "
                        f"{self.new_version.render()} and has no replacement",
                    )
                )
                continue
            renamed.append(RenamedUse(use=use, new=target))
        outcomes.append(
            MemberOutcome(
                member=member, renames=tuple(renamed), unmigratable=tuple(dropped)
            )
        )
    return tuple(outcomes)

to_json

to_json() -> str

The lens as the JSON document qvr bump emits.

RETURNS DESCRIPTION
str

Canonical JSON.

Source code in src/quivers/packages/lenses.py
def to_json(self) -> str:
    """The lens as the JSON document `qvr bump` emits.

    Returns
    -------
    str
        Canonical JSON.
    """
    return json.dumps(json.loads(self.model_dump_json()), sort_keys=True, indent=2)

from_json classmethod

from_json(text: str) -> DependencyLens

Read an emitted lens.

PARAMETER DESCRIPTION
text

What to_json wrote.

TYPE: str

RETURNS DESCRIPTION
DependencyLens

The lens.

Source code in src/quivers/packages/lenses.py
@classmethod
def from_json(cls, text: str) -> DependencyLens:
    """Read an emitted lens.

    Parameters
    ----------
    text : str
        What `to_json` wrote.

    Returns
    -------
    DependencyLens
        The lens.
    """
    return cls.model_validate_json(text)

LensError

Bases: ValueError

A lens that cannot be built or applied.

Its message says what failed.

MemberOutcome didactic-model

MemberOutcome(*, member: str, renames: tuple[RenamedUse, ...] = (), unmigratable: tuple[Unmigratable, ...] = ())

Bases: Model

What a lens does to one dependent.

ATTRIBUTE DESCRIPTION
member

The dependent.

TYPE: str

renames

Each kept place with its symbol's new path.

TYPE: tuple[RenamedUse, ...]

unmigratable

Each place no lens reaches.

TYPE: tuple[Unmigratable, ...]

Rename didactic-model

Rename(*, old: str, new: str, kind: str)

Bases: Model

A symbol the new interface keeps under another path.

ATTRIBUTE DESCRIPTION
old

Its old path.

TYPE: str

new

Its new path.

TYPE: str

kind

Its kind.

TYPE: str

RenamedUse didactic-model

RenamedUse(*, use: Use, new: str)

Bases: Model

A kept place and its symbol's new path.

ATTRIBUTE DESCRIPTION
use

The place.

TYPE: Use

new

The symbol's path in the new interface.

TYPE: str

Unmigratable didactic-model

Unmigratable(*, use: Use, reason: str)

Bases: Model

A place no lens reaches.

ATTRIBUTE DESCRIPTION
use

The place.

TYPE: Use

reason

Why: the symbol was removed with no replacement, or the dependent's usage did not satisfy the lens.

TYPE: str

Use didactic-model

Use(*, symbol: str, place: str)

Bases: Model

One place a dependent names a symbol.

ATTRIBUTE DESCRIPTION
symbol

The symbol's old path.

TYPE: str

place

Where (a key the dependent understands: a byte span of a module, or a site key of a run record).

TYPE: str

BumpError

Bases: ValueError

A proposed version that understates its interface change.

Its message says the proposed and required versions, and the changes that require more.

InterfaceChange didactic-model

InterfaceChange(*, level: ChangeLevel, category: ChangeCategory, symbol: str, renamed_to: str = '', detail: str)

Bases: Model

One change between two interfaces.

ATTRIBUTE DESCRIPTION
level

How much it moves the version.

TYPE: ChangeLevel

category

What changed.

TYPE: ChangeCategory

symbol

The symbol's old path (its new path for an addition).

TYPE: str

renamed_to

For a rename, the new path.

TYPE: str

detail

A sentence describing the change.

TYPE: str

render

render() -> str

The change as one line.

RETURNS DESCRIPTION
str

level symbol: detail.

Source code in src/quivers/packages/bump.py
def render(self) -> str:
    """The change as one line.

    Returns
    -------
    str
        ``level  symbol: detail``.
    """
    return f"{self.level:<5}  {self.symbol}: {self.detail}"

InterfaceDiff didactic-model

InterfaceDiff(*, package: str, old_version: Version, changes: tuple[InterfaceChange, ...] = (), lens: DependencyLens)

Bases: Model

The changes from one version of a package's interface to another.

ATTRIBUTE DESCRIPTION
package

The package.

TYPE: str

old_version

The version compared against.

TYPE: Version

changes

Every change, by symbol.

TYPE: tuple[InterfaceChange, ...]

lens

The lens dependents migrate along.

TYPE: DependencyLens

level property

level: ChangeLevel

The largest change.

RETURNS DESCRIPTION
ChangeLevel

none when nothing changed.

required

required() -> Version

The smallest version that publishes the change.

RETURNS DESCRIPTION
Version

The old version bumped at the largest change's level.

Source code in src/quivers/packages/bump.py
def required(self) -> Version:
    """The smallest version that publishes the change.

    Returns
    -------
    Version
        The old version bumped at the largest change's level.
    """
    return self.old_version.bumped(self.level)

check

check(proposed: Version) -> None

Refuse a version that understates the change.

PARAMETER DESCRIPTION
proposed

The version to publish.

TYPE: Version

RAISES DESCRIPTION
BumpError

If proposed is below the required version, or does not follow the old version although something changed.

Source code in src/quivers/packages/bump.py
def check(self, proposed: Version) -> None:
    """Refuse a version that understates the change.

    Parameters
    ----------
    proposed : Version
        The version to publish.

    Raises
    ------
    BumpError
        If ``proposed`` is below the required version, or does not
        follow the old version although something changed.
    """
    required = self.required()
    if self.level == "none":
        return
    if proposed.key() <= self.old_version.key():
        raise BumpError(
            f"{self.package} {proposed.render()} does not follow "
            f"{self.old_version.render()}, but the interface changed; publish "
            f"{required.render()} or later"
        )
    if proposed.key() < required.key():
        published = self.old_version.level_to(proposed)
        understated = [
            change
            for change in self.changes
            if CHANGE_LEVELS.index(change.level) > CHANGE_LEVELS.index(published)
        ]
        raise BumpError(
            f"{self.package} {proposed.render()} understates the change from "
            f"{self.old_version.render()}: it is a {self.level} change, so the "
            f"version must be at least {required.render()}:\n"
            + "\n".join(f"  {change.render()}" for change in understated)
        )

ReleaseError

Bases: ValueError

A release that cannot be made.

Its message says what prevents it.

VersionInterface didactic-model

VersionInterface(*, interface: PackageInterface, modules: tuple[BuiltModule, ...] = ())

Bases: Model

A package version's interface and the modules it was computed from.

ATTRIBUTE DESCRIPTION
interface

The interface.

TYPE: PackageInterface

modules

Its exposed modules, checked.

TYPE: tuple[BuiltModule, ...]

DependencyMigration didactic-model

DependencyMigration(*, lens: DependencyLens, files: tuple[MigratedFile, ...] = (), unmigratable: tuple[SiteReport, ...] = ())

Bases: Model

The outcome of migrating a package's dependents of one dependency.

ATTRIBUTE DESCRIPTION
lens

The lens applied.

TYPE: DependencyLens

files

Every module and run record that migrated, by path.

TYPE: tuple[MigratedFile, ...]

unmigratable

Every place no lens reaches, by file and position; a file with such a place is not rewritten.

TYPE: tuple[SiteReport, ...]

write

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

Write every migrated file that changed.

RETURNS DESCRIPTION
tuple[str, ...]

The paths written.

Source code in src/quivers/packages/migration.py
def write(self) -> tuple[str, ...]:
    """Write every migrated file that changed.

    Returns
    -------
    tuple[str, ...]
        The paths written.
    """
    written: list[str] = []
    for migrated in self.files:
        if migrated.changed:
            Path(migrated.path).write_text(migrated.text, encoding="utf-8")
            written.append(migrated.path)
    return tuple(written)

DependencyMigrationError

Bases: ValueError

A dependency migration that cannot start.

Its message says why.

DependencyMigrator

DependencyMigrator(workspace: Workspace, dependency: str, old: Version, new: Version)

Migrate one package's modules and run records across a dependency change.

PARAMETER DESCRIPTION
workspace

The dependent package.

TYPE: Workspace

dependency

The dependency's name.

TYPE: str

old

The version the package is locked to.

TYPE: Version

new

The version its manifest now resolves to.

TYPE: Version

Source code in src/quivers/packages/migration.py
def __init__(
    self, workspace: Workspace, dependency: str, old: Version, new: Version
) -> None:
    self.workspace = workspace
    self.dependency = dependency
    self.old_version = old
    self.new_version = new
    locked = read_lockfile(workspace.root)
    if locked is None:
        raise DependencyMigrationError(
            f"{workspace.root} has no qvr.lock: the lockfile records the version "
            "migrated from; lock the package before changing the dependency"
        )
    self.old_build = workspace.locked_build(locked)
    self.new_build = workspace.resolve()
    self.old_package = self._package(self.old_build, old, "locked build")
    self.new_package = self._package(self.new_build, new, "manifest")
    self.old_interface = package_version_interface(
        Path(self.old_package.directory), workspace.cache
    ).interface
    self.new_interface = package_version_interface(
        Path(self.new_package.directory), workspace.cache
    ).interface
    emitted = read_emitted_lens(
        Path(self.new_package.directory), dependency, old, new
    )
    self.lens = (
        emitted
        if emitted is not None
        else DependencyLens.between(self.old_interface, self.new_interface)
    )

modules

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

The package's own modules, which the migration covers.

RETURNS DESCRIPTION
tuple[str, ...]

Their paths.

Source code in src/quivers/packages/migration.py
def modules(self) -> tuple[str, ...]:
    """The package's own modules, which the migration covers.

    Returns
    -------
    tuple[str, ...]
        Their paths.
    """
    return self.new_build.root.module_paths()

migrate

migrate(records: Iterable[Path] = ()) -> DependencyMigration

Migrate every module of the package and the given run records.

PARAMETER DESCRIPTION
records

Run records (qvr run --json output) of the package's programs.

TYPE: Iterable[Path] DEFAULT: ()

RETURNS DESCRIPTION
DependencyMigration

The migrated texts and every unmigratable place.

RAISES DESCRIPTION
DependencyMigrationError

If the migration cannot start.

MigrationError

If a rewritten module does not parse.

Source code in src/quivers/packages/migration.py
def migrate(self, records: Iterable[Path] = ()) -> DependencyMigration:
    """Migrate every module of the package and the given run records.

    Parameters
    ----------
    records : Iterable[Path]
        Run records (``qvr run --json`` output) of the package's
        programs.

    Returns
    -------
    DependencyMigration
        The migrated texts and every unmigratable place.

    Raises
    ------
    DependencyMigrationError
        If the migration cannot start.
    MigrationError
        If a rewritten module does not parse.
    """
    origins = _origins(self.old_interface)
    fleet: dict[str, tuple[Use, ...]] = {}
    places: dict[str, dict[str, _Place]] = {}
    sources: dict[str, tuple[str, str]] = {}
    for module in self.modules():
        graph = self.workspace.load(module, self.old_build)
        source = graph.loaded[graph.root].source
        uses, located = _uses(graph, origins)
        fleet[module] = uses
        places[module] = located
        sources[module] = (source.file or source.label, source.text)
    outcomes = self.lens.apply(fleet)
    files: list[MigratedFile] = []
    reports: list[SiteReport] = []
    migrated_texts: dict[str, str] = {}
    for outcome in outcomes:
        path, text = sources[outcome.member]
        if outcome.unmigratable:
            reports.extend(
                self._report(path, places[outcome.member], item)
                for item in outcome.unmigratable
            )
            continue
        new_text = self._rewrite(outcome, places[outcome.member], text)
        migrated_texts[outcome.member] = new_text
        files.append(
            MigratedFile(path=path, text=new_text, changed=new_text != text)
        )
    if not reports:
        self._check_captures(migrated_texts, outcomes)
    for record in records:
        migrated, record_reports = self.migrate_record(record, migrated_texts)
        reports.extend(record_reports)
        if migrated is not None:
            files.append(migrated)
    return DependencyMigration(
        lens=self.lens,
        files=tuple(sorted(files, key=lambda item: item.path)),
        unmigratable=tuple(reports),
    )

migrate_record

migrate_record(record: Path, migrated: Mapping[str, str]) -> tuple[MigratedFile | None, tuple[SiteReport, ...]]

Migrate one run record of one of the package's programs.

PARAMETER DESCRIPTION
record

The record, as qvr run --json writes it.

TYPE: Path

migrated

The package's migrated module texts, by path.

TYPE: Mapping[str, str]

RETURNS DESCRIPTION
tuple[MigratedFile | None, tuple[SiteReport, ...]]

The migrated record (None when a site of it has no counterpart) and the unmigratable sites.

RAISES DESCRIPTION
DependencyMigrationError

If the record is not a run record of one of the package's programs.

Source code in src/quivers/packages/migration.py
def migrate_record(
    self, record: Path, migrated: Mapping[str, str]
) -> tuple[MigratedFile | None, tuple[SiteReport, ...]]:
    """Migrate one run record of one of the package's programs.

    Parameters
    ----------
    record : Path
        The record, as ``qvr run --json`` writes it.
    migrated : Mapping[str, str]
        The package's migrated module texts, by path.

    Returns
    -------
    tuple[MigratedFile | None, tuple[SiteReport, ...]]
        The migrated record (``None`` when a site of it has no
        counterpart) and the unmigratable sites.

    Raises
    ------
    DependencyMigrationError
        If the record is not a run record of one of the package's
        programs.
    """
    loaded: JsonData = json.loads(record.read_text(encoding="utf-8"))
    if not isinstance(loaded, dict):
        raise DependencyMigrationError(f"{record} is not a run record")
    data = loaded
    stored = data.get("sites")
    if not isinstance(stored, dict):
        raise DependencyMigrationError(
            f"{record} is not a run record: it has no site table"
        )
    table = SiteTable.from_data(stored)
    module = self._record_module(record, table)
    if module not in migrated:
        return None, (
            SiteReport(
                file=str(record),
                symbol=table.entry,
                reason=f"its module {module} has unmigratable places",
            ),
        )
    new_table = self._site_table(module, table.entry, migrated)
    old_interface = _site_interface(table, self.old_version)
    new_interface = _site_interface(new_table, self.new_version)
    lens = DependencyLens.between(old_interface, new_interface)
    uses = tuple(Use(symbol=site.key, place=site.key) for site in table.sites)
    (outcome,) = lens.apply({str(record): uses})
    if outcome.unmigratable:
        return None, tuple(
            SiteReport(
                file=str(record),
                symbol=item.use.symbol,
                reason=f"the stored site {item.use.symbol} has no counterpart in "
                f"{table.entry} against {self.dependency} "
                f"{self.new_version.render()}: its declaration changed",
            )
            for item in outcome.unmigratable
        )
    keys = {renamed.use.symbol: renamed.new for renamed in outcome.renames}
    renamed_names = self._renamed_flat_names()
    migrated_data: dict[str, JsonData] = {
        key: _rename_strings(value, renamed_names)
        for key, value in data.items()
        if key not in ("sites", "site_values")
    }
    migrated_data["sites"] = _json_data(new_table.to_data())
    values = data.get("site_values")
    if isinstance(values, dict):
        migrated_data["site_values"] = {
            keys.get(key, key): value for key, value in values.items()
        }
    text = json.dumps(migrated_data, indent=2) + "\n"
    original = record.read_text(encoding="utf-8")
    return MigratedFile(path=str(record), text=text, changed=text != original), ()

MigratedFile didactic-model

MigratedFile(*, path: str, text: str, changed: bool)

Bases: Model

One file a dependency migration rewrites.

ATTRIBUTE DESCRIPTION
path

The file.

TYPE: str

text

Its migrated text.

TYPE: str

changed

Whether the text differs from the file's.

TYPE: bool

SiteReport didactic-model

SiteReport(*, file: str, line: int = 0, column: int = 0, symbol: str, reason: str)

Bases: Model

A place a dependency migration could not migrate.

ATTRIBUTE DESCRIPTION
file

The module file or run record.

TYPE: str

line, column

Where (0 for a run record's site).

TYPE: int

symbol

The dependency's symbol the place names.

TYPE: str

reason

Why no lens reaches it.

TYPE: str

render

render() -> str

The report as one diagnostic line.

RETURNS DESCRIPTION
str

file:line:col: unmigratable: symbol: reason.

Source code in src/quivers/packages/migration.py
def render(self) -> str:
    """The report as one diagnostic line.

    Returns
    -------
    str
        ``file:line:col: unmigratable: symbol: reason``.
    """
    where = self.file if not self.line else f"{self.file}:{self.line}:{self.column}"
    return f"{where}: unmigratable: {self.symbol}: {self.reason}"

level_at_least

level_at_least(level: ChangeLevel, floor: ChangeLevel) -> ChangeLevel

The larger of two change levels.

PARAMETER DESCRIPTION
level

Two levels.

TYPE: ChangeLevel

floor

Two levels.

TYPE: ChangeLevel

RETURNS DESCRIPTION
ChangeLevel

The one further along CHANGE_LEVELS.

Source code in src/quivers/packages/versions.py
def level_at_least(level: ChangeLevel, floor: ChangeLevel) -> ChangeLevel:
    """The larger of two change levels.

    Parameters
    ----------
    level, floor : ChangeLevel
        Two levels.

    Returns
    -------
    ChangeLevel
        The one further along `CHANGE_LEVELS`.
    """
    return level if CHANGE_LEVELS.index(level) >= CHANGE_LEVELS.index(floor) else floor

parse_requirement

parse_requirement(text: str) -> Version

Read a dependency's version requirement: the minimum version it needs.

PARAMETER DESCRIPTION
text

A version such as 1.2.0.

TYPE: str

RETURNS DESCRIPTION
Version

The minimum; any later version on its compatibility line satisfies the requirement.

RAISES DESCRIPTION
VersionError

If the text is a range or not a version: minimal version selection reads a requirement as the version the dependent was built against.

Source code in src/quivers/packages/versions.py
def parse_requirement(text: str) -> Version:
    """Read a dependency's version requirement: the minimum version it needs.

    Parameters
    ----------
    text : str
        A version such as ``1.2.0``.

    Returns
    -------
    Version
        The minimum; any later version on its compatibility line satisfies
        the requirement.

    Raises
    ------
    VersionError
        If the text is a range or not a version: minimal version selection
        reads a requirement as the version the dependent was built against.
    """
    stripped = text.strip()
    if any(mark in stripped for mark in _RANGE_MARKS):
        raise VersionError(
            f"{text!r} is a version range; a dependency names the minimum version "
            "it was built against (e.g. 1.2.0), and any later version on that "
            "compatibility line satisfies it"
        )
    return Version.parse(stripped)

find_package_root

find_package_root(start: Path) -> Path | None

The nearest directory at or above a path that holds a manifest.

PARAMETER DESCRIPTION
start

A file or directory.

TYPE: Path

RETURNS DESCRIPTION
Path | None

The package's directory, or None when no directory above has a qvr.toml.

Source code in src/quivers/packages/manifest.py
def find_package_root(start: Path) -> Path | None:
    """The nearest directory at or above a path that holds a manifest.

    Parameters
    ----------
    start : Path
        A file or directory.

    Returns
    -------
    Path | None
        The package's directory, or ``None`` when no directory above has a
        ``qvr.toml``.
    """
    current = start.resolve()
    if current.is_file():
        current = current.parent
    for directory in (current, *current.parents):
        if (directory / MANIFEST_NAME).is_file():
            return directory
    return None

parse_manifest

parse_manifest(text: str, *, where: str = MANIFEST_NAME) -> Manifest

Read a manifest from its text.

PARAMETER DESCRIPTION
text

The TOML text.

TYPE: str

where

The file name diagnostics name.

TYPE: str DEFAULT: MANIFEST_NAME

RETURNS DESCRIPTION
Manifest

The manifest.

RAISES DESCRIPTION
ManifestError

If the text is not TOML, a key is unknown or mistyped, a name is not a package name, a module is outside the package's namespace, or a dependency names an undeclared index.

Source code in src/quivers/packages/manifest.py
def parse_manifest(text: str, *, where: str = MANIFEST_NAME) -> Manifest:
    """Read a manifest from its text.

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

    Returns
    -------
    Manifest
        The manifest.

    Raises
    ------
    ManifestError
        If the text is not TOML, a key is unknown or mistyped, a name is not
        a package name, a module is outside the package's namespace, or a
        dependency names an undeclared index.
    """
    try:
        document: dict[str, TomlValue] = tomllib.loads(text)
    except tomllib.TOMLDecodeError as error:
        raise ManifestError(f"{where}: {error}") from error
    _refuse_unknown(
        document, ("package", "holes", "links", "dependencies", "indexes"), where
    )
    package = _table(document, "package", where)
    if not package:
        raise ManifestError(f"{where}: a manifest needs a [package] table")
    _refuse_unknown(
        package, ("name", "version", "modules", "source"), f"{where}: package"
    )
    name = _string(package, "name", f"{where}: package")
    if not _NAME.fullmatch(name):
        raise ManifestError(
            f"{where}: package.name {name!r} is not a package name: a lowercase "
            "identifier, the first segment of every module path the package "
            "provides"
        )
    try:
        version = Version.parse(_string(package, "version", f"{where}: package"))
    except VersionError as error:
        raise ManifestError(f"{where}: package.version: {error}") from error
    modules_value = package.get("modules", [])
    if not isinstance(modules_value, list) or not all(
        isinstance(item, str) for item in modules_value
    ):
        raise ManifestError(f"{where}: package.modules must be a list of module paths")
    modules: list[str] = []
    for item in modules_value:
        assert isinstance(item, str)
        path = _module_path(item, f"{where}: package.modules")
        if path.split(".")[0] != name:
            raise ManifestError(
                f"{where}: package.modules lists {path!r}, which is outside the "
                f"package's namespace: its modules are {name} and {name}.*"
            )
        if path in modules:
            raise ManifestError(f"{where}: package.modules lists {path!r} twice")
        modules.append(path)
    source = (
        _string(package, "source", f"{where}: package") if "source" in package else "."
    )
    if Path(source).is_absolute() or ".." in Path(source).parts:
        raise ManifestError(
            f"{where}: package.source {source!r} must be a directory inside the package"
        )
    holes: list[HoleSpec] = []
    for path, value in sorted(_table(document, "holes", where).items()):
        here = f"{where}: holes.{path}"
        _module_path(path, here)
        if not isinstance(value, dict):
            raise ManifestError(f'{here} must be a table, e.g. {{ default = "m" }}')
        _refuse_unknown(value, ("default",), here)
        default = _string(value, "default", here) if "default" in value else ""
        if default:
            _module_path(default, f"{here}.default")
        holes.append(HoleSpec(path=path, default=default))
    links: list[LinkSpec] = []
    for path, value in sorted(_table(document, "links", where).items()):
        here = f"{where}: links.{path}"
        _module_path(path, here)
        if not isinstance(value, str):
            raise ManifestError(f"{here} must be the filling module's path")
        links.append(LinkSpec(hole=path, module=_module_path(value, here)))
    indexes: list[IndexSpec] = []
    for index, value in sorted(_table(document, "indexes", where).items()):
        if not isinstance(value, str):
            raise ManifestError(
                f"{where}: indexes.{index} must be the index repository's URL"
            )
        indexes.append(IndexSpec(name=index, url=value))
    dependencies: list[Dependency] = []
    for dependency_name, value in sorted(
        _table(document, "dependencies", where).items()
    ):
        dependency = _dependency(dependency_name, value, where)
        if dependency_name == name:
            raise ManifestError(f"{where}: package {name} cannot depend on itself")
        origin = dependency.source
        if isinstance(origin, IndexSource):
            declared = tuple(index.name for index in indexes)
            if not origin.index:
                if len(declared) != 1:
                    raise ManifestError(
                        f"{where}: dependencies.{dependency_name} must name its "
                        'index (index = "..."): the manifest declares '
                        + (
                            "no [indexes]"
                            if not declared
                            else f"several: {', '.join(declared)}"
                        )
                    )
                dependency = dependency.with_(source=origin.with_(index=declared[0]))
            elif origin.index not in declared:
                raise ManifestError(
                    f"{where}: dependencies.{dependency_name} names the index "
                    f"{origin.index!r}, which [indexes] does not declare"
                )
        dependencies.append(dependency)
    return Manifest(
        name=name,
        version=version,
        modules=tuple(sorted(modules)),
        source=Path(source).as_posix(),
        holes=tuple(holes),
        links=tuple(links),
        dependencies=tuple(dependencies),
        indexes=tuple(indexes),
    )

read_manifest

read_manifest(directory: Path) -> Manifest

Read the manifest of a package directory.

PARAMETER DESCRIPTION
directory

The package's directory.

TYPE: Path

RETURNS DESCRIPTION
Manifest

Its manifest.

RAISES DESCRIPTION
ManifestError

If the directory has no manifest or the manifest is malformed.

Source code in src/quivers/packages/manifest.py
def read_manifest(directory: Path) -> Manifest:
    """Read the manifest of a package directory.

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

    Returns
    -------
    Manifest
        Its manifest.

    Raises
    ------
    ManifestError
        If the directory has no manifest or the manifest is malformed.
    """
    path = directory / MANIFEST_NAME
    try:
        text = path.read_text(encoding="utf-8")
    except FileNotFoundError as error:
        raise ManifestError(f"{directory} has no {MANIFEST_NAME}") from error
    except OSError as error:
        raise ManifestError(f"{path}: {error}") from error
    return parse_manifest(text, where=str(path))

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))

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"

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

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

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)

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"

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),
    )

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"

standard_library

standard_library(root: Path = STANDARD_LIBRARY_ROOT) -> Package

The standard library, the package every package depends on.

Its version is the version of quivers it ships with, and every module below std/ is exposed.

PARAMETER DESCRIPTION
root

The directory its std modules live in.

TYPE: Path DEFAULT: STANDARD_LIBRARY_ROOT

RETURNS DESCRIPTION
Package

The package.

Source code in src/quivers/packages/sources.py
def standard_library(root: Path = STANDARD_LIBRARY_ROOT) -> Package:
    """The standard library, the package every package depends on.

    Its version is the version of quivers it ships with, and every module
    below ``std/`` is exposed.

    Parameters
    ----------
    root : Path
        The directory its ``std`` modules live in.

    Returns
    -------
    Package
        The package.
    """
    manifest = Manifest(
        name=STANDARD_LIBRARY_NAME,
        version=Version.parse(quivers.__version__.split("+")[0].split(".dev")[0]),
    )
    package = Package(
        manifest=manifest,
        directory=str(root.resolve()),
        source="builtin",
        implicit=True,
    )
    return package.with_(manifest=manifest.with_(modules=package.module_paths()))

explain_conflict

explain_conflict(left: Requirement, right: Requirement, reason: str, by_node: Mapping[str, Requirement], root: str) -> str

Explain two requirements no single version satisfies.

The explanation derives an incompatibility from the two requirements and lifts it, one dependency edge at a time, until both sides are the root, as PubGrub reports a failure.

PARAMETER DESCRIPTION
left

The conflicting requirements.

TYPE: Requirement

right

The conflicting requirements.

TYPE: Requirement

reason

Why no version satisfies both.

TYPE: str

by_node

The requirement that first reached each visited node.

TYPE: Mapping[str, Requirement]

root

The root package's name.

TYPE: str

RETURNS DESCRIPTION
str

The explanation, one step per line.

Source code in src/quivers/packages/resolve.py
def explain_conflict(
    left: Requirement,
    right: Requirement,
    reason: str,
    by_node: Mapping[str, Requirement],
    root: str,
) -> str:
    """Explain two requirements no single version satisfies.

    The explanation derives an incompatibility from the two requirements
    and lifts it, one dependency edge at a time, until both sides are the
    root, as PubGrub reports a failure.

    Parameters
    ----------
    left, right : Requirement
        The conflicting requirements.
    reason : str
        Why no version satisfies both.
    by_node : Mapping[str, Requirement]
        The requirement that first reached each visited node.
    root : str
        The root package's name.

    Returns
    -------
    str
        The explanation, one step per line.
    """
    who = {"left": _who(left, root), "right": _who(right, root)}
    lines = [
        f"Because {who['left']} depends on {left.written}",
        f"  and {who['right']} depends on {right.written},",
    ]
    if who["left"] == who["right"]:
        lines.append(f"  {who['left']} cannot be satisfied ({reason}).")
    else:
        lines.append(f"  {who['left']} is incompatible with {who['right']} ({reason}).")
    steps = [("left", step) for step in reversed(_chain(left, by_node)[:-1])]
    steps.extend(("right", step) for step in reversed(_chain(right, by_node)[:-1]))
    _lift(steps, who, root, lines, "{left} is incompatible with {right}")
    return "\n".join(lines)

explain_missing

explain_missing(requirement: Requirement, reason: str, by_node: Mapping[str, Requirement], root: str) -> str

Explain a requirement nothing satisfies.

PARAMETER DESCRIPTION
requirement

The requirement.

TYPE: Requirement

reason

Why nothing satisfies it.

TYPE: str

by_node

The requirement that first reached each visited node.

TYPE: Mapping[str, Requirement]

root

The root package's name.

TYPE: str

RETURNS DESCRIPTION
str

The explanation, one step per line.

Source code in src/quivers/packages/resolve.py
def explain_missing(
    requirement: Requirement,
    reason: str,
    by_node: Mapping[str, Requirement],
    root: str,
) -> str:
    """Explain a requirement nothing satisfies.

    Parameters
    ----------
    requirement : Requirement
        The requirement.
    reason : str
        Why nothing satisfies it.
    by_node : Mapping[str, Requirement]
        The requirement that first reached each visited node.
    root : str
        The root package's name.

    Returns
    -------
    str
        The explanation, one step per line.
    """
    who = {"left": _who(requirement, root)}
    lines = [
        f"Because {who['left']} depends on {requirement.written}",
        f"  and {reason},",
        f"  {who['left']} is forbidden.",
    ]
    steps = [("left", step) for step in reversed(_chain(requirement, by_node)[:-1])]
    _lift(steps, who, root, lines, "{left} is forbidden")
    return "\n".join(lines)

load_package_file

load_package_file(file: str | Path, *, links: Mapping[str, str] | None = None) -> ModuleGraph | None

The module graph rooted at a file, read in its package's build.

PARAMETER DESCRIPTION
file

The root module's file.

TYPE: str | Path

links

Links beyond the build's (an experiment's), which win.

TYPE: Mapping[str, str] | None DEFAULT: None

RETURNS DESCRIPTION
ModuleGraph | None

The checked graph, or None when the file is no module of a package (package_module_of).

RAISES DESCRIPTION
ManifestError

If the package's manifest is malformed.

PackageError

If an import or link crosses a package boundary the rules forbid, or the lockfile does not match the packages.

ModuleError

If the graph does not load or resolve.

Source code in src/quivers/packages/workspace.py
def load_package_file(
    file: str | Path, *, links: Mapping[str, str] | None = None
) -> ModuleGraph | None:
    """The module graph rooted at a file, read in its package's build.

    Parameters
    ----------
    file : str | Path
        The root module's file.
    links : Mapping[str, str] | None
        Links beyond the build's (an experiment's), which win.

    Returns
    -------
    ModuleGraph | None
        The checked graph, or ``None`` when the file is no module of a
        package (`package_module_of`).

    Raises
    ------
    ManifestError
        If the package's manifest is malformed.
    PackageError
        If an import or link crosses a package boundary the rules forbid,
        or the lockfile does not match the packages.
    ModuleError
        If the graph does not load or resolve.
    """
    found = package_module_of(file)
    if found is None:
        return None
    workspace, module = found
    return workspace.load(module, package_build(workspace), extra_links=links)

module_core_hash

module_core_hash(module: QiecModule | None) -> str

The hash of a root module's own checked declarations.

The root's declarations are the ones with bare names in its flat program; each enters by its declaration kind and content hash, so renaming, reformatting, and comments leave the hash unchanged.

PARAMETER DESCRIPTION
module

The checked core of a flat program; None for a module with no core declarations, which hashes as the empty set.

TYPE: QiecModule | None

RETURNS DESCRIPTION
str

The digest.

Source code in src/quivers/packages/workspace.py
def module_core_hash(module: QiecModule | None) -> str:
    """The hash of a root module's own checked declarations.

    The root's declarations are the ones with bare names in its flat
    program; each enters by its declaration kind and content hash, so
    renaming, reformatting, and comments leave the hash unchanged.

    Parameters
    ----------
    module : QiecModule | None
        The checked core of a flat program; ``None`` for a module with no
        core declarations, which hashes as the empty set.

    Returns
    -------
    str
        The digest.
    """
    if module is None:
        return tagged_digest("package-module", [])
    own = sorted(
        f"{declaration.kind}:{declaration.hash}"
        for declaration in module_hashes(module).declarations
        if split_module(declaration.name)[0] is None
    )
    return tagged_digest("package-module", list(own))

package_build

package_build(workspace: Workspace) -> Resolution

The build a package's modules are read in.

PARAMETER DESCRIPTION
workspace

The package's workspace.

TYPE: Workspace

RETURNS DESCRIPTION
Resolution

The build its qvr.lock records, or the one its manifest resolves to when it has no lockfile.

RAISES DESCRIPTION
LockfileError

If the lockfile is malformed.

PackageError

If a locked package no longer has the version the lockfile records.

ResolutionError

If no build satisfies the manifest's requirements.

Source code in src/quivers/packages/workspace.py
def package_build(workspace: Workspace) -> Resolution:
    """The build a package's modules are read in.

    Parameters
    ----------
    workspace : Workspace
        The package's workspace.

    Returns
    -------
    Resolution
        The build its ``qvr.lock`` records, or the one its manifest resolves
        to when it has no lockfile.

    Raises
    ------
    LockfileError
        If the lockfile is malformed.
    PackageError
        If a locked package no longer has the version the lockfile records.
    ResolutionError
        If no build satisfies the manifest's requirements.
    """
    locked = read_lockfile(workspace.root)
    return workspace.locked_build(locked) if locked is not None else workspace.resolve()

package_module_of

package_module_of(file: str | Path) -> tuple[Workspace, str] | None

The package a module file belongs to, and the file's module path.

A .qvr file is a module of a package when the nearest qvr.toml at or above it declares a package whose namespace holds the file below the package's module root: coins/model.qvr below a package named coins whose source is . is the module coins.model.

PARAMETER DESCRIPTION
file

The file.

TYPE: str | Path

RETURNS DESCRIPTION
tuple[Workspace, str] | None

The package's workspace and the module path, or None when no manifest is above the file or the file lies outside the package's namespace.

RAISES DESCRIPTION
ManifestError

If the nearest manifest is malformed.

Source code in src/quivers/packages/workspace.py
def package_module_of(file: str | Path) -> tuple[Workspace, str] | None:
    """The package a module file belongs to, and the file's module path.

    A ``.qvr`` file is a module of a package when the nearest ``qvr.toml``
    at or above it declares a package whose namespace holds the file below
    the package's module root: ``coins/model.qvr`` below a package named
    ``coins`` whose ``source`` is ``.`` is the module ``coins.model``.

    Parameters
    ----------
    file : str | Path
        The file.

    Returns
    -------
    tuple[Workspace, str] | None
        The package's workspace and the module path, or ``None`` when no
        manifest is above the file or the file lies outside the package's
        namespace.

    Raises
    ------
    ManifestError
        If the nearest manifest is malformed.
    """
    path = Path(file).resolve()
    if not path.name.endswith(".qvr"):
        return None
    directory = find_package_root(path)
    if directory is None:
        return None
    workspace = Workspace(directory)
    package = workspace.sources.root_package()
    module_root = package.module_root().resolve()
    if not path.is_relative_to(module_root):
        return None
    parts = path.relative_to(module_root).with_suffix("").parts
    if not parts or parts[0] != package.name:
        return None
    return workspace, ".".join(parts)

package_interface

package_interface(package: str, version: Version, modules: Iterable[BuiltModule]) -> PackageInterface

The semantic interface of a package's exposed modules.

PARAMETER DESCRIPTION
package

The package's name.

TYPE: str

version

Its version.

TYPE: Version

modules

Its exposed modules, checked.

TYPE: Iterable[BuiltModule]

RETURNS DESCRIPTION
PackageInterface

Every symbol of every module, by path.

Source code in src/quivers/packages/interface.py
def package_interface(
    package: str, version: Version, modules: Iterable[BuiltModule]
) -> PackageInterface:
    """The semantic interface of a package's exposed modules.

    Parameters
    ----------
    package : str
        The package's name.
    version : Version
        Its version.
    modules : Iterable[BuiltModule]
        Its exposed modules, checked.

    Returns
    -------
    PackageInterface
        Every symbol of every module, by path.
    """
    symbols: list[InterfaceSymbol] = []
    for built in modules:
        if built.qiec is None:
            symbols.extend(_declared_only(built))
            continue
        symbols.extend(_ModuleSymbols(built, built.qiec).symbols())
    return PackageInterface(
        package=package,
        version=version,
        symbols=tuple(sorted(symbols, key=lambda symbol: symbol.path)),
    )

inventory_schema

inventory_schema(interface: PackageInterface) -> Schema

The inventory of an interface: one vertex per symbol.

PARAMETER DESCRIPTION
interface

The interface.

TYPE: PackageInterface

RETURNS DESCRIPTION
Schema

A json-schema schema whose root object has one array property per symbol path, holding the places a dependent names it.

Source code in src/quivers/packages/lenses.py
def inventory_schema(interface: PackageInterface) -> panproto.Schema:
    """The inventory of an interface: one vertex per symbol.

    Parameters
    ----------
    interface : PackageInterface
        The interface.

    Returns
    -------
    panproto.Schema
        A ``json-schema`` schema whose root object has one array property
        per symbol path, holding the places a dependent names it.
    """
    return _inventory([symbol.path for symbol in interface.symbols])

diff_interfaces

diff_interfaces(old: PackageInterface, new: PackageInterface) -> InterfaceDiff

Classify every change from one interface to another.

PARAMETER DESCRIPTION
old

The interface compared against.

TYPE: PackageInterface

new

The new interface.

TYPE: PackageInterface

RETURNS DESCRIPTION
InterfaceDiff

The changes and the lens dependents migrate along.

RAISES DESCRIPTION
LensError

If panproto cannot derive the lens.

Source code in src/quivers/packages/bump.py
def diff_interfaces(old: PackageInterface, new: PackageInterface) -> InterfaceDiff:
    """Classify every change from one interface to another.

    Parameters
    ----------
    old : PackageInterface
        The interface compared against.
    new : PackageInterface
        The new interface.

    Returns
    -------
    InterfaceDiff
        The changes and the lens dependents migrate along.

    Raises
    ------
    LensError
        If panproto cannot derive the lens.
    """
    lens = DependencyLens.between(old, new)
    changes: list[InterfaceChange] = []
    for rename in lens.renames:
        changes.append(
            InterfaceChange(
                level="major",
                category="renamed",
                symbol=rename.old,
                renamed_to=rename.new,
                detail=f"the {rename.kind} was renamed to {rename.new}; dependents "
                "migrate along the lens",
            )
        )
    for path in lens.removed:
        symbol = old.symbol(path)
        kind = symbol.kind if symbol is not None else "symbol"
        changes.append(
            InterfaceChange(
                level="major",
                category="removed",
                symbol=path,
                detail=f"the {kind} was removed with no replacement",
            )
        )
    for path in lens.added:
        symbol = new.symbol(path)
        assert symbol is not None
        changes.append(_added(symbol))
    for symbol in old.symbols:
        target = lens.image(symbol.path)
        if target is None:
            continue
        counterpart = new.symbol(target)
        if counterpart is None:
            continue
        facts = _facts(symbol, counterpart)
        for category, detail in facts:
            changes.append(
                InterfaceChange(
                    level="major", category=category, symbol=symbol.path, detail=detail
                )
            )
        if facts or symbol.body == counterpart.body:
            continue
        if symbol.kind.startswith(("site:", "data:")):
            # A site or data parameter follows its program, whose own body
            # change is reported once, on the program.
            continue
        if symbol.fitted or counterpart.fitted:
            changes.append(
                InterfaceChange(
                    level="minor",
                    category="fitted-body",
                    symbol=symbol.path,
                    detail="the body of a program fit to data changed, so fits of "
                    "it change meaning",
                )
            )
        else:
            changes.append(
                InterfaceChange(
                    level="patch",
                    category="body",
                    symbol=symbol.path,
                    detail="its body changed under the same interface",
                )
            )
    return InterfaceDiff(
        package=new.package,
        old_version=old.version,
        changes=tuple(
            sorted(changes, key=lambda change: (change.symbol, change.category))
        ),
        lens=lens,
    )

lens_file

lens_file(package: str, old: Version, new: Version) -> str

The file name a lens between two versions is emitted under.

PARAMETER DESCRIPTION
package

The package.

TYPE: str

old

The versions.

TYPE: Version

new

The versions.

TYPE: Version

RETURNS DESCRIPTION
str

<package>-<old>-to-<new>.json.

Source code in src/quivers/packages/release.py
def lens_file(package: str, old: Version, new: Version) -> str:
    """The file name a lens between two versions is emitted under.

    Parameters
    ----------
    package : str
        The package.
    old, new : Version
        The versions.

    Returns
    -------
    str
        ``<package>-<old>-to-<new>.json``.
    """
    return f"{package}-{old.render()}-to-{new.render()}.json"

package_version_interface

package_version_interface(directory: Path, cache: GitCache) -> VersionInterface

Check a package's exposed modules and compute its interface.

PARAMETER DESCRIPTION
directory

The package's directory.

TYPE: Path

cache

The cache its git and indexed dependencies are read through.

TYPE: GitCache

RETURNS DESCRIPTION
VersionInterface

The interface and the checked modules.

RAISES DESCRIPTION
ManifestError

If the manifest is malformed.

ResolutionError

If its dependencies do not resolve.

PackageError

If a module violates a package rule.

ModuleError

If a module does not load or resolve.

CompileError

If a module does not compile.

Source code in src/quivers/packages/release.py
def package_version_interface(directory: Path, cache: GitCache) -> VersionInterface:
    """Check a package's exposed modules and compute its interface.

    Parameters
    ----------
    directory : Path
        The package's directory.
    cache : GitCache
        The cache its git and indexed dependencies are read through.

    Returns
    -------
    VersionInterface
        The interface and the checked modules.

    Raises
    ------
    ManifestError
        If the manifest is malformed.
    ResolutionError
        If its dependencies do not resolve.
    PackageError
        If a module violates a package rule.
    ModuleError
        If a module does not load or resolve.
    CompileError
        If a module does not compile.
    """
    workspace = Workspace(directory, cache=cache)
    resolution = workspace.resolve()
    return _interface(workspace, resolution)

previous_version

previous_version(directory: Path, against: str, cache: GitCache) -> Path

The directory of the package version to compare against.

PARAMETER DESCRIPTION
directory

The package's current directory.

TYPE: Path

against

A directory holding the previous version, or a git revision (a tag such as v1.2.0, a branch, a commit) of the repository holding the package.

TYPE: str

cache

Where a revision is extracted.

TYPE: GitCache

RETURNS DESCRIPTION
Path

The previous version's package directory.

RAISES DESCRIPTION
GitError

If against is no directory and names no revision of the package's repository.

ReleaseError

If the revision has no manifest at the package's place.

Source code in src/quivers/packages/release.py
def previous_version(directory: Path, against: str, cache: GitCache) -> Path:
    """The directory of the package version to compare against.

    Parameters
    ----------
    directory : Path
        The package's current directory.
    against : str
        A directory holding the previous version, or a git revision (a tag
        such as ``v1.2.0``, a branch, a commit) of the repository holding
        the package.
    cache : GitCache
        Where a revision is extracted.

    Returns
    -------
    Path
        The previous version's package directory.

    Raises
    ------
    GitError
        If ``against`` is no directory and names no revision of the
        package's repository.
    ReleaseError
        If the revision has no manifest at the package's place.
    """
    candidate = Path(against)
    if candidate.is_dir():
        return candidate.resolve()
    top, relative = repository_of(directory)
    url = top.resolve().as_uri()
    commit = cache.resolve(url, against)
    tree = cache.checkout(url, commit)
    package = tree / relative
    if not (package / MANIFEST_NAME).is_file():
        raise ReleaseError(
            f"{against} ({commit[:12]}) of {top} has no {MANIFEST_NAME} at "
            f"{relative}: the package did not exist there"
        )
    return package

publish

publish(index_checkout: Path, url: str, revision: str, cache: GitCache) -> IndexEntry

Add a package version to an index.

The version is read from a commit of its repository, so what is published is exactly what dependents will fetch. Its modules are checked and pinned; its interface is compared with the newest version the index lists, and a version that understates the change, or that the index already lists, is refused. The entry is written into the index checkout and committed there; pushing it is left to the caller.

PARAMETER DESCRIPTION
index_checkout

A git working tree of the index repository.

TYPE: Path

url

The package's repository.

TYPE: str

revision

The commit, tag, or branch to publish.

TYPE: str

cache

The project cache.

TYPE: GitCache

RETURNS DESCRIPTION
IndexEntry

The published entry.

RAISES DESCRIPTION
ReleaseError

If the package depends on anything but packages of this index, or the version is already published.

BumpError

If the version understates its change.

GitError

If a repository cannot be read or the commit cannot be made.

Source code in src/quivers/packages/release.py
def publish(
    index_checkout: Path,
    url: str,
    revision: str,
    cache: GitCache,
) -> IndexEntry:
    """Add a package version to an index.

    The version is read from a commit of its repository, so what is
    published is exactly what dependents will fetch. Its modules are
    checked and pinned; its interface is compared with the newest version
    the index lists, and a version that understates the change, or that
    the index already lists, is refused. The entry is written into the
    index checkout and committed there; pushing it is left to the caller.

    Parameters
    ----------
    index_checkout : Path
        A git working tree of the index repository.
    url : str
        The package's repository.
    revision : str
        The commit, tag, or branch to publish.
    cache : GitCache
        The project cache.

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

    Raises
    ------
    ReleaseError
        If the package depends on anything but packages of this index, or
        the version is already published.
    BumpError
        If the version understates its change.
    GitError
        If a repository cannot be read or the commit cannot be made.
    """
    commit = cache.resolve(url, revision)
    directory = cache.checkout(url, commit)
    manifest = read_manifest(directory)
    index_url = (
        run_git(["config", "--get", "remote.origin.url"], cwd=index_checkout)
        .decode("utf-8")
        .strip()
    )
    for dependency in manifest.dependencies:
        source = dependency.source
        if not isinstance(source, IndexSource):
            raise ReleaseError(
                f"{manifest.name} depends on {dependency.name} through "
                f"{source.kind}; a published package depends only on packages of "
                "its index, so every dependent can resolve it"
            )
        if not same_repository(manifest.index_url(source.index), index_url):
            raise ReleaseError(
                f"{manifest.name} depends on {dependency.name} from "
                f"{manifest.index_url(source.index)}, not from this index "
                f"({index_url})"
            )
    current = Workspace(directory, cache=cache)
    resolution = current.resolve()
    built = _interface(current, resolution)
    local = (
        PackageIndex(
            "publishing",
            index_checkout.resolve().as_uri(),
            run_git(["rev-parse", "HEAD"], cwd=index_checkout).decode("ascii").strip(),
            GitCache(cache.directory),
        )
        if _has_commits(index_checkout)
        else None
    )
    versions = local.versions(manifest.name) if local is not None else ()
    if manifest.version in versions:
        raise ReleaseError(
            f"the index already lists {manifest.name} {manifest.version.render()}; "
            "a published version never changes"
        )
    earlier = [
        version for version in versions if version.key() < manifest.version.key()
    ]
    if earlier and local is not None:
        previous = local.entry(manifest.name, earlier[-1])
        old_directory = cache.checkout(previous.url, previous.commit)
        old = package_version_interface(old_directory, cache).interface
        diff_interfaces(old, built.interface).check(manifest.version)
    entry = IndexEntry(
        name=manifest.name,
        version=manifest.version,
        url=url,
        commit=commit,
        dependencies=tuple(
            IndexRequirement(name=dependency.name, minimum=dependency.source.minimum)
            for dependency in manifest.dependencies
            if isinstance(dependency.source, IndexSource)
        ),
        modules=tuple(module.pin() for module in built.modules),
    )
    target = index_checkout / entry_path(entry.name, entry.version)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(render_entry(entry), encoding="utf-8")
    relative = target.relative_to(index_checkout).as_posix()
    run_git(["add", "--", relative], cwd=index_checkout)
    run_git(
        [
            "commit",
            "--quiet",
            "-m",
            f"publish {entry.name} {entry.version.render()}",
            "--",
            relative,
        ],
        cwd=index_checkout,
    )
    return entry

read_emitted_lens

read_emitted_lens(directory: Path, package: str, old: Version, new: Version) -> DependencyLens | None

The lens a package version emitted for its move from an older one.

PARAMETER DESCRIPTION
directory

The new version's package directory.

TYPE: Path

package

The package.

TYPE: str

old

The versions.

TYPE: Version

new

The versions.

TYPE: Version

RETURNS DESCRIPTION
DependencyLens | None

The emitted lens, or None when the version emitted none.

Source code in src/quivers/packages/release.py
def read_emitted_lens(
    directory: Path, package: str, old: Version, new: Version
) -> DependencyLens | None:
    """The lens a package version emitted for its move from an older one.

    Parameters
    ----------
    directory : Path
        The new version's package directory.
    package : str
        The package.
    old, new : Version
        The versions.

    Returns
    -------
    DependencyLens | None
        The emitted lens, or ``None`` when the version emitted none.
    """
    path = directory / LENS_DIRECTORY / lens_file(package, old, new)
    if not path.is_file():
        return None
    return DependencyLens.from_json(path.read_text(encoding="utf-8"))

repository_of

repository_of(directory: Path) -> tuple[Path, str]

The git repository holding a directory, and the directory's place in it.

PARAMETER DESCRIPTION
directory

A directory inside a git working tree.

TYPE: Path

RETURNS DESCRIPTION
tuple[Path, str]

The working tree's top and the directory relative to it (POSIX).

RAISES DESCRIPTION
GitError

If the directory is in no git working tree.

Source code in src/quivers/packages/release.py
def repository_of(directory: Path) -> tuple[Path, str]:
    """The git repository holding a directory, and the directory's place in it.

    Parameters
    ----------
    directory : Path
        A directory inside a git working tree.

    Returns
    -------
    tuple[Path, str]
        The working tree's top and the directory relative to it (POSIX).

    Raises
    ------
    GitError
        If the directory is in no git working tree.
    """
    top = Path(
        run_git(["rev-parse", "--show-toplevel"], cwd=directory).decode("utf-8").strip()
    )
    relative = directory.resolve().relative_to(top.resolve()).as_posix()
    return top, relative

set_manifest_version

set_manifest_version(directory: Path, version: Version) -> None

Rewrite the version in a manifest, leaving the rest of it as written.

PARAMETER DESCRIPTION
directory

The package's directory.

TYPE: Path

version

The new version.

TYPE: Version

RAISES DESCRIPTION
ManifestError

If the manifest has no version line in its [package] table.

Source code in src/quivers/packages/release.py
def set_manifest_version(directory: Path, version: Version) -> None:
    """Rewrite the version in a manifest, leaving the rest of it as written.

    Parameters
    ----------
    directory : Path
        The package's directory.
    version : Version
        The new version.

    Raises
    ------
    ManifestError
        If the manifest has no version line in its [package] table.
    """
    path = directory / MANIFEST_NAME
    text = path.read_text(encoding="utf-8")
    package_start = text.find("[package]")
    following = text.find("\n[", package_start + 1)
    end = len(text) if following < 0 else following
    section = text[package_start:end]
    match = _VERSION_LINE.search(section)
    if package_start < 0 or match is None:
        raise ManifestError(f"{path}: [package] has no version line to rewrite")
    updated = section[: match.start(2)] + version.render() + section[match.end(2) :]
    path.write_text(text[:package_start] + updated + text[end:], encoding="utf-8")
    read_manifest(directory)

file_resolutions

file_resolutions(graph: ModuleGraph) -> tuple[Resolution, ...]

Every name resolution of a graph's root file, module bodies included.

PARAMETER DESCRIPTION
graph

A graph rooted at a file.

TYPE: ModuleGraph

RETURNS DESCRIPTION
tuple[Resolution, ...]

The root module's resolutions, then those of the modules, signatures, and templates declared in it.

Source code in src/quivers/packages/migration.py
def file_resolutions(graph: ModuleGraph) -> tuple[NameResolution, ...]:
    """Every name resolution of a graph's root file, module bodies included.

    Parameters
    ----------
    graph : ModuleGraph
        A graph rooted at a file.

    Returns
    -------
    tuple[NameResolution, ...]
        The root module's resolutions, then those of the modules,
        signatures, and templates declared in it.
    """
    found = list(graph.checked[graph.root].resolutions)
    names = graph.loaded[graph.root].names
    if not names.regions:
        return tuple(found)
    system = ModuleSystem(graph, {})
    for region in names.regions:
        found.extend(
            system.checked(RegionRef(file=graph.root, vid=region.vid)).resolutions
        )
    return tuple(found)