Skip to content

upstream

napt.upstream

Recipes imported from other git repositories.

A project imports a recipe with napt upstream add, which writes a byte-identical pinned copy under upstream/<host>/<repo path>/<path>, writes an override in recipes/ that names the pinned copy as its parent, and records the recipe's commit and hashes in upstream.yaml at the project root. The config loader treats every parent under upstream/ as a pinned copy: the file must match its recorded hash, and only app-owned keys reach the merge.

Modules:

Name Description
add

The import engine behind napt upstream add.

remove

The removal engine behind napt upstream remove.

refresh

The scan behind napt upstream check and update.

git

Read-only transport through the git binary: list refs, fetch a ref's trees, list and read files.

lock

The upstream.yaml lockfile, canonical hashing, and the directory a repository URL maps to under upstream/.

pinned

What makes a parent a pinned copy, the hash check, and the keys a pinned parent may set.

napt.upstream.add

Importing recipes from a git repository: the engine behind napt upstream add.

An import writes each selected upstream recipe byte-identical as a pinned copy under upstream/<host>/<repo path>/<path>, writes an override in recipes/ that names the pinned copy as its parent and carries the recipe's name and id, and records each recipe's commit and hashes in upstream.yaml. Nothing is written until every selected recipe has been fetched and the configuration each override will produce has passed validation, so a bad recipe aborts the whole import with the project untouched.

OVERRIDE_SUFFIX module-attribute

OVERRIDE_SUFFIX = '.override.yaml'

What an override file is named: <app>.override.yaml.

PlannedRecipe dataclass

One recipe the import will write, or did write.

Attributes:

Name Type Description
path str

The recipe's path inside the repository.

pinned str

Where the pinned copy lands, relative to the project root.

override str

The override that runs it, relative to the project root.

app_id str

The id the override carries.

dropped tuple[str, ...]

The keys the allow list removes from the pinned copy.

duplicate_of str | None

Another recipe in the project that already uses the same id, or None.

Source code in napt/upstream/add.py
@dataclass(frozen=True)
class PlannedRecipe:
    """One recipe the import will write, or did write.

    Attributes:
        path: The recipe's path inside the repository.
        pinned: Where the pinned copy lands, relative to the project
            root.
        override: The override that runs it, relative to the project root.
        app_id: The ``id`` the override carries.
        dropped: The keys the allow list removes from the pinned copy.
        duplicate_of: Another recipe in the project that already uses the
            same ``id``, or None.
    """

    path: str
    pinned: str
    override: str
    app_id: str
    dropped: tuple[str, ...]
    duplicate_of: str | None = None

AddResult dataclass

What napt upstream add imported.

Attributes:

Name Type Description
url str

The clone URL as given.

ref str

The branch or tag imported from.

commit str

The commit fetched, recorded on each imported recipe.

recipes tuple[PlannedRecipe, ...]

Each recipe written, in repository order.

skipped tuple[str, ...]

Recipes selected through a directory that were already imported, left at their own pins.

dry_run bool

Whether nothing was written.

Source code in napt/upstream/add.py
@dataclass(frozen=True)
class AddResult:
    """What ``napt upstream add`` imported.

    Attributes:
        url: The clone URL as given.
        ref: The branch or tag imported from.
        commit: The commit fetched, recorded on each imported recipe.
        recipes: Each recipe written, in repository order.
        skipped: Recipes selected through a directory that were already
            imported, left at their own pins.
        dry_run: Whether nothing was written.
    """

    url: str
    ref: str
    commit: str
    recipes: tuple[PlannedRecipe, ...]
    skipped: tuple[str, ...]
    dry_run: bool

override_path_for

override_path_for(
    upstream_path: str, imported_from: str, dest: str | None
) -> PurePosixPath

Decides where the override for an upstream recipe lives.

One rule for files and directories: everything after the last recipes/ segment of the upstream path is mirrored under the project's recipes/ (or under dest), so recipes/Google/ chrome.yaml lands at recipes/Google/chrome.override.yaml however it was selected. Without such a segment, dest is required and the file lands under it at its path relative to the imported directory, which for a single file is its name.

Parameters:

Name Type Description Default
upstream_path str

The recipe's path inside the repository.

required
imported_from str

The --path it was selected through.

required
dest str | None

The --dest directory, relative to the project root, or None.

required

Returns:

Type Description
PurePosixPath

The override's path relative to the project root.

Raises:

Type Description
ConfigError

When the path has no recipes/ segment and no dest was given.

Source code in napt/upstream/add.py
def override_path_for(
    upstream_path: str, imported_from: str, dest: str | None
) -> PurePosixPath:
    """Decides where the override for an upstream recipe lives.

    One rule for files and directories: everything after the last
    ``recipes/`` segment of the upstream path is mirrored under the
    project's ``recipes/`` (or under ``dest``), so ``recipes/Google/
    chrome.yaml`` lands at ``recipes/Google/chrome.override.yaml`` however
    it was selected. Without such a segment, ``dest`` is required and the
    file lands under it at its path relative to the imported directory,
    which for a single file is its name.

    Args:
        upstream_path: The recipe's path inside the repository.
        imported_from: The ``--path`` it was selected through.
        dest: The ``--dest`` directory, relative to the project root, or
            None.

    Returns:
        The override's path relative to the project root.

    Raises:
        ConfigError: When the path has no ``recipes/`` segment and no
            ``dest`` was given.
    """
    parts = PurePosixPath(upstream_path).parts
    directories = parts[:-1]
    name = PurePosixPath(parts[-1]).stem + OVERRIDE_SUFFIX
    if _RECIPES_SEGMENT in directories:
        last = len(directories) - 1 - directories[::-1].index(_RECIPES_SEGMENT)
        below = directories[last + 1 :]
        root = PurePosixPath(dest) if dest else PurePosixPath(_RECIPES_SEGMENT)
        return root.joinpath(*below, name)
    if dest is None:
        raise ConfigError(
            f"{upstream_path!r} has no 'recipes/' segment to mirror; pass "
            f"--dest <directory> to say where its override goes"
        )
    base = PurePosixPath(imported_from)
    if PurePosixPath(upstream_path) == base:
        return PurePosixPath(dest, name)
    relative = PurePosixPath(upstream_path).relative_to(base)
    return PurePosixPath(dest).joinpath(*relative.parts[:-1], name)

add_recipes

add_recipes(
    project_root: Path,
    url: str,
    paths: Iterable[str],
    *,
    ref: str | None = None,
    dest: str | None = None,
    app_id: str | None = None,
    excludes: Iterable[str] = (),
    dry_run: bool = False
) -> AddResult

Imports recipes from a repository into the project.

Parameters:

Name Type Description Default
project_root Path

The directory holding recipes/, upstream/, and upstream.yaml; the current directory for the CLI.

required
url str

The clone URL.

required
paths Iterable[str]

Files or directories inside the repository to import. A directory skips recipes already tracked, so re-running it picks up what the publisher added since; a file already tracked is an error pointing at update.

required
ref str | None

A branch or tag; the default branch when None. A repository already in the lockfile keeps its recorded ref, and a different one is an error.

None
dest str | None

Where the overrides go instead of mirroring under recipes/, relative to the project root.

None
app_id str | None

An id for the override instead of the upstream one; single-file imports only.

None
excludes Iterable[str]

Globs matched against each file's path relative to the directory it was selected through.

()
dry_run bool

Report what would be written and write nothing.

False

Returns:

Type Description
AddResult

What was imported, or would be.

Raises:

Type Description
ConfigError

When a selection, path, override, or the configuration an override would produce is invalid; nothing is written.

NetworkError

When the repository cannot be reached.

Source code in napt/upstream/add.py
def add_recipes(
    project_root: Path,
    url: str,
    paths: Iterable[str],
    *,
    ref: str | None = None,
    dest: str | None = None,
    app_id: str | None = None,
    excludes: Iterable[str] = (),
    dry_run: bool = False,
) -> AddResult:
    """Imports recipes from a repository into the project.

    Args:
        project_root: The directory holding ``recipes/``, ``upstream/``,
            and ``upstream.yaml``; the current directory for the CLI.
        url: The clone URL.
        paths: Files or directories inside the repository to import. A
            directory skips recipes already tracked, so re-running it picks
            up what the publisher added since; a file already tracked is an
            error pointing at ``update``.
        ref: A branch or tag; the default branch when None. A repository
            already in the lockfile keeps its recorded ref, and a
            different one is an error.
        dest: Where the overrides go instead of mirroring under
            ``recipes/``, relative to the project root.
        app_id: An ``id`` for the override instead of the upstream one;
            single-file imports only.
        excludes: Globs matched against each file's path relative to the
            directory it was selected through.
        dry_run: Report what would be written and write nothing.

    Returns:
        What was imported, or would be.

    Raises:
        ConfigError: When a selection, path, override, or the configuration
            an override would produce is invalid; nothing is written.
        NetworkError: When the repository cannot be reached.
    """
    logger = get_global_logger()
    paths = list(paths)
    if not paths:
        raise ConfigError("At least one --path is required")
    lockfile_path = project_root / LOCKFILE_NAME
    lock = read_lockfile(lockfile_path) if lockfile_path.is_file() else Lockfile(())
    existing = lock.find_repo(url)
    if existing is not None and ref is not None and ref != existing.ref:
        raise ConfigError(
            f"{url} is already imported from ref {existing.ref!r}; a second ref "
            f"({ref!r}) for one repository is not supported. Remove its recipes "
            f"first, or import from {existing.ref!r}."
        )
    directory = repo_directory(url)
    check_upstream_path(directory.as_posix())

    logger.info("UPSTREAM", f"Checking {url}")
    remote = ls_remote(url)
    if existing is not None:
        ref = existing.ref
    elif ref is None:
        ref = remote.default_branch
        if ref is None:
            raise ConfigError(
                f"{url} reports no default branch; pass --ref <branch or tag>"
            )
    if remote.commit_for(ref) is None:
        raise ConfigError(f"{url} has no branch or tag named {ref!r}")

    logger.info("UPSTREAM", f"Fetching {ref} from {url}")
    with FetchedRef(url, ref) as fetched:
        selected = _select_entries(fetched, paths, excludes)
        if app_id is not None and len(selected) != 1:
            raise ConfigError(
                f"--id applies to a single-file import; this selection has "
                f"{len(selected)} recipes"
            )
        known_ids = _project_ids(project_root)
        planned: list[tuple[PlannedRecipe, bytes, str]] = []
        skipped: list[str] = []
        for imported_from, entry in selected:
            # A directory import picks up what the publisher added since the
            # last one; recipes already tracked keep their own pins and are
            # refreshed by update, never by add. A recipe named directly
            # still errors below, since update is what was meant.
            pinned_rel = PurePosixPath(UPSTREAM_DIR_NAME, *directory.parts, entry.path)
            if imported_from != entry.path and _lock_entry_exists(
                project_root, pinned_rel
            ):
                skipped.append(entry.path)
                continue
            planned.append(
                _plan_one(
                    project_root,
                    fetched,
                    url,
                    ref,
                    directory,
                    entry,
                    imported_from,
                    dest,
                    app_id,
                    known_ids,
                )
            )
        commit = fetched.commit

    for recipe, _data, _text in planned:
        if recipe.dropped:
            logger.warning(
                "UPSTREAM",
                f"{recipe.path}: ignoring keys not allowed from upstream recipes: "
                + ", ".join(recipe.dropped),
            )
        if recipe.duplicate_of:
            logger.warning(
                "UPSTREAM",
                f"{recipe.path}: id {recipe.app_id!r} is already used by "
                f"{recipe.duplicate_of}; pass --id to choose another",
            )
    result = AddResult(
        url=url,
        ref=ref,
        commit=commit,
        recipes=tuple(recipe for recipe, _data, _text in planned),
        skipped=tuple(skipped),
        dry_run=dry_run,
    )
    if dry_run or not planned:
        return result

    # Pinned copies first, then overrides, then the lockfile. A run cut
    # short after a pinned copy leaves a file nothing names, which the next
    # run overwrites; one cut short after an override is reported by the
    # loader (its parent is not in the lockfile) and blocks the retry until
    # that override is removed, so the window for it is kept as late as
    # possible.
    for recipe, data, _text in planned:
        logger.verbose("UPSTREAM", f"Writing {recipe.pinned}")
        write_bytes_atomic(project_root / recipe.pinned, data)
    for recipe, _data, text in planned:
        logger.verbose("UPSTREAM", f"Writing {recipe.override}")
        write_text_atomic(project_root / recipe.override, text)
    entries = list(existing.recipes) if existing is not None else []
    for recipe, data, _text in planned:
        tree_entry = next(e for _p, e in selected if e.path == recipe.path)
        entries.append(
            LockedRecipe(
                path=recipe.path,
                override=recipe.override,
                commit=commit,
                blob=tree_entry.blob,
                sha256=canonical_sha256(data),
            )
        )
    repo = LockedRepo(
        url=existing.url if existing is not None else url,
        ref=ref,
        recipes=tuple(entries),
    )
    write_lockfile(lockfile_path, lock.replace_repo(repo, url=url))
    logger.verbose("UPSTREAM", f"Updated {lockfile_path.name}")
    return result

napt.upstream.remove

Removing an imported recipe: the engine behind napt upstream remove.

Removal deletes the pinned copy and its lockfile entry, the repository's entry and emptied directories under upstream/ once nothing of it remains, and the lockfile itself once no repository remains. The override is the user's file, so it is left alone unless asked; it is reported with its now-dangling parent so the user can inline it or delete it.

RemoveResult dataclass

What napt upstream remove did.

Attributes:

Name Type Description
path str

The pinned copy that was deleted, relative to the project root.

override str | None

The override that named it, relative to the project root, or None when the lockfile recorded none that exists.

override_deleted bool

Whether the override was deleted too.

repo_removed bool

Whether this was the repository's last recipe, so its lockfile entry and directory went with it.

Source code in napt/upstream/remove.py
@dataclass(frozen=True)
class RemoveResult:
    """What ``napt upstream remove`` did.

    Attributes:
        path: The pinned copy that was deleted, relative to the project
            root.
        override: The override that named it, relative to the project
            root, or None when the lockfile recorded none that exists.
        override_deleted: Whether the override was deleted too.
        repo_removed: Whether this was the repository's last recipe, so
            its lockfile entry and directory went with it.
    """

    path: str
    override: str | None
    override_deleted: bool
    repo_removed: bool

remove_recipe

remove_recipe(
    project_root: Path, path: Path, *, delete_override: bool = False
) -> RemoveResult

Removes one imported recipe from the project.

Parameters:

Name Type Description Default
project_root Path

The directory holding upstream/ and upstream.yaml; the current directory for the CLI.

required
path Path

The pinned copy under upstream/, or the override that names it as parent.

required
delete_override bool

Delete the override as well.

False

Returns:

Type Description
RemoveResult

What was removed.

Raises:

Type Description
ConfigError

When the path is neither a tracked pinned copy nor an override naming one, the pinned copy belongs to another project's upstream/, the lockfile is missing or malformed, or the override the lockfile records is not a project recipe naming the pinned copy.

Source code in napt/upstream/remove.py
def remove_recipe(
    project_root: Path, path: Path, *, delete_override: bool = False
) -> RemoveResult:
    """Removes one imported recipe from the project.

    Args:
        project_root: The directory holding ``upstream/`` and
            ``upstream.yaml``; the current directory for the CLI.
        path: The pinned copy under ``upstream/``, or the override that
            names it as ``parent``.
        delete_override: Delete the override as well.

    Returns:
        What was removed.

    Raises:
        ConfigError: When the path is neither a tracked pinned copy nor
            an override naming one, the pinned copy belongs to another
            project's ``upstream/``, the lockfile is missing or malformed,
            or the override the lockfile records is not a project recipe
            naming the pinned copy.
    """
    logger = get_global_logger()
    lockfile_path = project_root / LOCKFILE_NAME
    given = path.resolve()
    location = tracked_location(given)
    override_path: Path | None = None
    if location is None:
        override_path = given
        pinned = pinned_copy_of_override(given)
        location = tracked_location(pinned)
        if location is None:
            raise ConfigError(
                f"{given} names {pinned} as parent, which is not under a "
                f"tracked {UPSTREAM_DIR_NAME}/ directory"
            )
    else:
        pinned = given

    # The pinned copy must belong to this project. tracked_location accepts
    # any upstream/ with a lockfile beside it, so a parent pointing into
    # another checkout would otherwise be deleted against this lockfile.
    own_upstream = (project_root / UPSTREAM_DIR_NAME).resolve()
    if location.upstream_dir != own_upstream:
        raise ConfigError(
            f"{pinned} is under {location.upstream_dir}, not this project's "
            f"{own_upstream}; run napt upstream remove from that project"
        )

    lock = read_lockfile(lockfile_path)
    located = lock.locate(location.relative)
    if located is None:
        raise ConfigError(
            f"{pinned} is not tracked in {lockfile_path}; delete the file by hand "
            f"if it was copied in"
        )
    repo, entry = located
    directory = repo_directory(repo.url).parts

    if override_path is None:
        override_path = _recorded_override(project_root, entry.override, pinned)

    logger.info("UPSTREAM", f"Removing {entry.path} from {repo.url}")
    try:
        pinned.unlink(missing_ok=True)
    except OSError as err:
        raise ConfigError(f"Cannot delete {pinned}: {err}") from err
    _prune_empty_dirs(pinned.parent, location.upstream_dir)

    remaining = tuple(r for r in repo.recipes if r is not entry)
    repo_removed = not remaining
    new_lock: Lockfile = lock.replace_repo(
        (None if repo_removed else LockedRepo(repo.url, repo.ref, remaining)),
        url=repo.url,
    )
    if new_lock.repos:
        write_lockfile(lockfile_path, new_lock)
    else:
        # Nothing imported remains, so the lockfile goes too; the next add
        # recreates it.
        lockfile_path.unlink()
    if repo_removed:
        _prune_empty_dirs(
            location.upstream_dir / Path(*directory), location.upstream_dir
        )
        if location.upstream_dir.is_dir() and not any(location.upstream_dir.iterdir()):
            location.upstream_dir.rmdir()

    override_deleted = False
    override_rel: str | None = None
    if override_path is not None:
        override_rel = os.path.relpath(override_path, project_root).replace(os.sep, "/")
        if delete_override:
            try:
                override_path.unlink()
            except OSError as err:
                raise ConfigError(f"Cannot delete {override_path}: {err}") from err
            override_deleted = True
        else:
            logger.warning(
                "UPSTREAM",
                f"{override_rel} still names the removed file as parent; inline "
                f"the recipe there or delete it (napt upstream remove "
                f"--delete-override)",
            )
    return RemoveResult(
        path=PurePosixPath(UPSTREAM_DIR_NAME, *location.relative.parts).as_posix(),
        override=override_rel,
        override_deleted=override_deleted,
        repo_removed=repo_removed,
    )

napt.upstream.refresh

Checking pinned copies against their upstream recipes, and refreshing them.

napt upstream check and napt upstream update run the same scan. Per repository in upstream.yaml: one ls-remote; when the branch tip equals every selected recipe's commit and nothing needs rewriting, the fetch is skipped and only the local hashes are verified. Otherwise the ref is fetched trees-only once and each recipe's recorded blob id is compared to the one at its path now. update then rewrites the pinned copies that changed, each with its own new commit, and leaves every other entry alone, so a run can refresh one recipe at a time and CI can open one pull request per recipe.

RecipeStatus dataclass

What the scan found for one pinned copy.

Attributes:

Name Type Description
url str

The repository's clone URL as the lockfile records it.

path str

The upstream recipe's path inside the repository.

override str

The override that runs it, relative to the project root.

status str

One of unchanged, changed, missing, or modified-locally.

old_commit str

The commit the pinned copy was taken from.

new_commit str | None

The commit the ref resolves to now, or None when the fetch was skipped.

old_blob str

The recorded blob id.

new_blob str | None

The blob id at the path now, or None when missing or when the fetch was skipped.

updated bool

Whether update rewrote the pinned copy in this run.

dropped tuple[str, ...]

The keys the allow list removes from the new content; set only when the pinned copy was rewritten.

Source code in napt/upstream/refresh.py
@dataclass(frozen=True)
class RecipeStatus:
    """What the scan found for one pinned copy.

    Attributes:
        url: The repository's clone URL as the lockfile records it.
        path: The upstream recipe's path inside the repository.
        override: The override that runs it, relative to the project root.
        status: One of ``unchanged``, ``changed``, ``missing``, or
            ``modified-locally``.
        old_commit: The commit the pinned copy was taken from.
        new_commit: The commit the ref resolves to now, or None when the
            fetch was skipped.
        old_blob: The recorded blob id.
        new_blob: The blob id at the path now, or None when missing or when
            the fetch was skipped.
        updated: Whether ``update`` rewrote the pinned copy in this run.
        dropped: The keys the allow list removes from the new content; set
            only when the pinned copy was rewritten.
    """

    url: str
    path: str
    override: str
    status: str
    old_commit: str
    new_commit: str | None
    old_blob: str
    new_blob: str | None
    updated: bool = False
    dropped: tuple[str, ...] = ()

RefreshResult dataclass

What napt upstream check found, or update did.

Attributes:

Name Type Description
recipes tuple[RecipeStatus, ...]

One status per selected recipe, in lockfile order.

wrote bool

Whether the run was allowed to rewrite pinned copies.

Source code in napt/upstream/refresh.py
@dataclass(frozen=True)
class RefreshResult:
    """What ``napt upstream check`` found, or ``update`` did.

    Attributes:
        recipes: One status per selected recipe, in lockfile order.
        wrote: Whether the run was allowed to rewrite pinned copies.
    """

    recipes: tuple[RecipeStatus, ...]
    wrote: bool

    @property
    def drifted(self) -> tuple[RecipeStatus, ...]:
        """The recipes whose upstream changed or disappeared."""
        return tuple(r for r in self.recipes if r.status in (CHANGED, MISSING))

    @property
    def refused(self) -> tuple[RecipeStatus, ...]:
        """The locally modified pinned copies an update left alone.

        Empty for a check, which refuses nothing because it writes nothing.
        """
        if not self.wrote:
            return ()
        return tuple(
            r for r in self.recipes if r.status == MODIFIED_LOCALLY and not r.updated
        )

drifted property

drifted: tuple[RecipeStatus, ...]

The recipes whose upstream changed or disappeared.

refused property

refused: tuple[RecipeStatus, ...]

The locally modified pinned copies an update left alone.

Empty for a check, which refuses nothing because it writes nothing.

refresh

refresh(
    project_root: Path,
    *,
    write: bool,
    paths: Iterable[Path] = (),
    force: bool = False,
    quiet: bool = False
) -> RefreshResult

Scans the tracked recipes against upstream and optionally refreshes them.

Parameters:

Name Type Description Default
project_root Path

The directory holding upstream/ and upstream.yaml; the current directory for the CLI.

required
write bool

Rewrite changed pinned copies and the lockfile (update), or only report (check).

required
paths Iterable[Path]

Overrides or pinned copies to limit the run to.

()
force bool

With write, also rewrite pinned copies that were edited locally, from the upstream recipe at the tip.

False
quiet bool

Print no progress or warning lines; the result carries the same facts (dropped per recipe), for a caller that prints machine-readable output.

False

Returns:

Type Description
RefreshResult

One status per selected recipe.

Raises:

Type Description
ConfigError

When there is no lockfile, a path is not tracked, or a repository's ref no longer exists.

NetworkError

When a repository cannot be reached.

Source code in napt/upstream/refresh.py
def refresh(
    project_root: Path,
    *,
    write: bool,
    paths: Iterable[Path] = (),
    force: bool = False,
    quiet: bool = False,
) -> RefreshResult:
    """Scans the tracked recipes against upstream and optionally refreshes them.

    Args:
        project_root: The directory holding ``upstream/`` and
            ``upstream.yaml``; the current directory for the CLI.
        write: Rewrite changed pinned copies and the lockfile (``update``),
            or only report (``check``).
        paths: Overrides or pinned copies to limit the run to.
        force: With ``write``, also rewrite pinned copies that were edited
            locally, from the upstream recipe at the tip.
        quiet: Print no progress or warning lines; the result carries the
            same facts (``dropped`` per recipe), for a caller that prints
            machine-readable output.

    Returns:
        One status per selected recipe.

    Raises:
        ConfigError: When there is no lockfile, a path is not tracked, or a
            repository's ref no longer exists.
        NetworkError: When a repository cannot be reached.
    """
    logger = get_global_logger()
    lockfile_path = project_root / LOCKFILE_NAME
    if not lockfile_path.is_file():
        raise ConfigError(
            f"{lockfile_path} does not exist; nothing has been imported with "
            f"'napt upstream add'"
        )
    lock = read_lockfile(lockfile_path)
    selected = _select(project_root, lock, paths)

    statuses: list[RecipeStatus] = []
    new_lock = lock
    for repo in lock.repos:
        wanted = selected.get(repo.url)
        if not wanted:
            continue
        entries = [e for e in repo.recipes if e.path in wanted]
        updated_entries = {e.path: e for e in repo.recipes}

        # Local drift first: it needs no network and decides what a forced
        # update has to rewrite.
        local_ok: dict[str, bool] = {}
        for entry in entries:
            pinned = _pinned_path(project_root, repo, entry)
            try:
                local_ok[entry.path] = (
                    canonical_sha256(pinned.read_bytes()) == entry.sha256
                )
            except OSError:
                local_ok[entry.path] = False

        if not quiet:
            logger.info("UPSTREAM", f"Checking {repo.url}")
        tip = ls_remote(repo.url).commit_for(repo.ref)
        if tip is None:
            raise ConfigError(
                f"{repo.url} no longer has a branch or tag named {repo.ref!r}"
            )
        needs_fetch = any(e.commit != tip for e in entries) or (
            write and force and not all(local_ok.values())
        )
        if not needs_fetch:
            for entry in entries:
                statuses.append(
                    RecipeStatus(
                        url=repo.url,
                        path=entry.path,
                        override=entry.override,
                        status=UNCHANGED if local_ok[entry.path] else MODIFIED_LOCALLY,
                        old_commit=entry.commit,
                        new_commit=None,
                        old_blob=entry.blob,
                        new_blob=None,
                    )
                )
            continue

        if not quiet:
            logger.info("UPSTREAM", f"Fetching {repo.ref} from {repo.url}")
        with FetchedRef(repo.url, repo.ref) as fetched:
            listed = {
                t.path: t.blob
                for t in fetched.list_recipe_files([e.path for e in entries])
            }
            for entry in entries:
                new_blob = listed.get(entry.path)
                if new_blob is None:
                    status = MISSING
                elif not local_ok[entry.path]:
                    status = MODIFIED_LOCALLY
                elif new_blob != entry.blob:
                    status = CHANGED
                else:
                    status = UNCHANGED
                record = RecipeStatus(
                    url=repo.url,
                    path=entry.path,
                    override=entry.override,
                    status=status,
                    old_commit=entry.commit,
                    new_commit=fetched.commit,
                    old_blob=entry.blob,
                    new_blob=new_blob,
                )
                rewrite = write and (
                    status == CHANGED or (status == MODIFIED_LOCALLY and force)
                )
                if rewrite and new_blob is not None:
                    data = fetched.read_file(entry.path)
                    dropped = _dropped_keys(data)
                    if dropped and not quiet:
                        logger.warning(
                            "UPSTREAM",
                            f"{entry.path}: ignoring keys not allowed from upstream "
                            f"recipes: " + ", ".join(dropped),
                        )
                    pinned = _pinned_path(project_root, repo, entry)
                    logger.verbose("UPSTREAM", f"Writing {pinned}")
                    write_bytes_atomic(pinned, data)
                    updated_entries[entry.path] = replace(
                        entry,
                        commit=fetched.commit,
                        blob=new_blob,
                        sha256=canonical_sha256(data),
                    )
                    record = replace(record, updated=True, dropped=dropped)
                statuses.append(record)
        new_lock = new_lock.replace_repo(
            LockedRepo(
                url=repo.url,
                ref=repo.ref,
                recipes=tuple(updated_entries[e.path] for e in repo.recipes),
            ),
            url=repo.url,
        )

    if write and new_lock != lock:
        write_lockfile(lockfile_path, new_lock)
        logger.verbose("UPSTREAM", f"Updated {lockfile_path.name}")
    return RefreshResult(recipes=tuple(statuses), wrote=write)

napt.upstream.git

Read-only git transport for upstream recipe repositories.

Every network operation of napt upstream goes through the git binary, so authentication is whatever git already does (credential helpers, SSH keys) and any host that serves git works. Nothing here touches the user's own repository: a fetch lands in a temporary directory that is removed when the operation ends.

Three guards apply to every value that reaches git from a lockfile or a command line, because upstream.yaml can be edited by anyone who can open a pull request:

  • A URL, ref, or path that starts with - is refused, so git never reads one as an option.
  • Positional arguments follow -- wherever git accepts it.
  • GIT_ALLOW_PROTOCOL limits transports to https, ssh, git, and file, so an ext:: URL, which runs a command, is never reachable.

Prompts are disabled (GIT_TERMINAL_PROMPT=0, SSH batch mode) so a missing credential fails at once instead of hanging a CI job. The variables that would point git at another repository (GIT_DIR and its relatives, which git exports into hooks) are dropped from the environment, and a git found in the current directory is refused, so the user's own repository is never the one acted on.

ALLOWED_PROTOCOLS module-attribute

ALLOWED_PROTOCOLS = 'https:ssh:git:file'

Transports git may use; ext and other command-running schemes are out.

RECIPE_SUFFIXES module-attribute

RECIPE_SUFFIXES = ('.yaml', '.yml')

File name endings that make a tree entry a recipe.

MAX_RECIPE_BYTES module-attribute

MAX_RECIPE_BYTES = 1000000

The largest file read_file fetches; a recipe is a few kilobytes.

RemoteRefs dataclass

What git ls-remote reported for a repository.

Attributes:

Name Type Description
default_branch str | None

The branch HEAD points at, or None when the server did not say.

refs dict[str, str]

Each full ref name (refs/heads/main, refs/tags/v1, and the peeled refs/tags/v1^{} of an annotated tag) mapped to its object id.

Source code in napt/upstream/git.py
@dataclass(frozen=True)
class RemoteRefs:
    """What ``git ls-remote`` reported for a repository.

    Attributes:
        default_branch: The branch ``HEAD`` points at, or None when the
            server did not say.
        refs: Each full ref name (``refs/heads/main``, ``refs/tags/v1``,
            and the peeled ``refs/tags/v1^{}`` of an annotated tag) mapped
            to its object id.
    """

    default_branch: str | None
    refs: dict[str, str]

    def commit_for(self, ref: str) -> str | None:
        """Finds the commit a branch or tag name points at.

        A branch wins over a tag of the same name. An annotated tag
        resolves through its peeled entry to the commit, so a pinned
        commit compares against commits only.

        Args:
            ref: A branch or tag name as the user gave it, or a full ref.

        Returns:
            The commit id, or None when the remote has no such ref.
        """
        for candidate in (
            f"refs/heads/{ref}",
            f"refs/tags/{ref}^{{}}",
            f"refs/tags/{ref}",
            f"{ref}^{{}}",
            ref,
        ):
            found = self.refs.get(candidate)
            if found is not None:
                return found
        return None

commit_for

commit_for(ref: str) -> str | None

Finds the commit a branch or tag name points at.

A branch wins over a tag of the same name. An annotated tag resolves through its peeled entry to the commit, so a pinned commit compares against commits only.

Parameters:

Name Type Description Default
ref str

A branch or tag name as the user gave it, or a full ref.

required

Returns:

Type Description
str | None

The commit id, or None when the remote has no such ref.

Source code in napt/upstream/git.py
def commit_for(self, ref: str) -> str | None:
    """Finds the commit a branch or tag name points at.

    A branch wins over a tag of the same name. An annotated tag
    resolves through its peeled entry to the commit, so a pinned
    commit compares against commits only.

    Args:
        ref: A branch or tag name as the user gave it, or a full ref.

    Returns:
        The commit id, or None when the remote has no such ref.
    """
    for candidate in (
        f"refs/heads/{ref}",
        f"refs/tags/{ref}^{{}}",
        f"refs/tags/{ref}",
        f"{ref}^{{}}",
        ref,
    ):
        found = self.refs.get(candidate)
        if found is not None:
            return found
    return None

TreeEntry dataclass

One recipe file in a fetched tree.

Attributes:

Name Type Description
path str

The file's path from the repository root, forward slashes.

blob str

The git blob id of its content.

Source code in napt/upstream/git.py
@dataclass(frozen=True)
class TreeEntry:
    """One recipe file in a fetched tree.

    Attributes:
        path: The file's path from the repository root, forward slashes.
        blob: The git blob id of its content.
    """

    path: str
    blob: str

FetchedRef

A repository's ref fetched trees-only into a temporary directory.

Use as a context manager; the directory and everything git wrote into it are removed on exit. TemporaryDirectory already retries after resetting permissions, which is what git's read-only pack files need on Windows.

Example

Read one file at a branch tip:

with FetchedRef(url, "main") as fetched:
    data = fetched.read_file("recipes/Google/chrome.yaml")

Attributes:

Name Type Description
commit

The commit the ref resolved to when fetched; the value recorded as each imported recipe's commit.

Source code in napt/upstream/git.py
class FetchedRef:
    """A repository's ref fetched trees-only into a temporary directory.

    Use as a context manager; the directory and everything git wrote into
    it are removed on exit. ``TemporaryDirectory`` already retries after
    resetting permissions, which is what git's read-only pack files need
    on Windows.

    Example:
        Read one file at a branch tip:
            ```python
            with FetchedRef(url, "main") as fetched:
                data = fetched.read_file("recipes/Google/chrome.yaml")
            ```

    Attributes:
        commit: The commit the ref resolved to when fetched; the value
            recorded as each imported recipe's ``commit``.
    """

    def __init__(self, url: str, ref: str) -> None:
        """Fetches the ref's tip without its blobs.

        Args:
            url: The clone URL.
            ref: A branch or tag name.

        Raises:
            ConfigError: When git is missing or a value starts with ``-``.
            NetworkError: When the fetch fails.
        """
        check_argument(url, "URL")
        check_argument(ref, "ref")
        self._tempdir = tempfile.TemporaryDirectory(prefix="napt-upstream-")
        self._dir = Path(self._tempdir.name)
        try:
            run_git(["init", "-q", "-b", "main"], cwd=self._dir)
            run_git(["remote", "add", "origin", "--", url], cwd=self._dir)
            # A named remote is required: below git 2.24 a filtered fetch
            # from a bare URL dies, and the promisor configuration git writes
            # lands on the remote by name.
            run_git(
                [
                    "fetch",
                    "--quiet",
                    "--depth",
                    "1",
                    "--filter=blob:none",
                    "origin",
                    ref,
                ],
                cwd=self._dir,
            )
            # FETCH_HEAD rather than ls-remote's answer, so a push between
            # the two calls cannot pin a commit the files did not come from;
            # ^{commit} dereferences an annotated tag.
            self.commit = (
                run_git(["rev-parse", "FETCH_HEAD^{commit}"], cwd=self._dir)
                .decode("ascii")
                .strip()
            )
        except BaseException:
            self._tempdir.cleanup()
            raise

    def __enter__(self) -> FetchedRef:
        """Returns the fetched ref for use inside a ``with`` block."""
        return self

    def __exit__(self, *exc_info: object) -> None:
        """Removes the temporary directory, whatever happened inside."""
        del exc_info  # The directory goes either way.
        self._tempdir.cleanup()

    def list_recipe_files(self, paths: Iterable[str]) -> list[TreeEntry]:
        """Lists the recipe files under the given repository paths.

        A directory lists every ``.yaml`` and ``.yml`` beneath it; a file
        lists itself. Each returned path has passed
        [check_upstream_path][napt.upstream.git.check_upstream_path].

        Args:
            paths: Files or directories relative to the repository root.

        Returns:
            The matching files with their blob ids, in tree order.

        Raises:
            ConfigError: When a path starts with ``-`` or a listed file's
                path has an unsafe segment.
            NetworkError: When git fails.
        """
        wanted = [check_argument(path, "path") for path in paths]
        output = run_git(
            ["ls-tree", "-r", "-z", self.commit, "--", *wanted], cwd=self._dir
        )
        entries: list[TreeEntry] = []
        for record in output.split(b"\0"):
            if not record:
                continue
            meta, _, path = record.partition(b"\t")
            mode, kind, blob = meta.decode("ascii").split(" ")
            name = path.decode("utf-8", errors="replace")
            # A symlink is listed as a blob too (mode 120000); only regular
            # files are recipes.
            if mode not in _REGULAR_FILE_MODES or kind != "blob":
                continue
            if not name.endswith(RECIPE_SUFFIXES):
                continue
            entries.append(TreeEntry(path=check_upstream_path(name), blob=blob))
        return entries

    def read_file(self, path: str) -> bytes:
        """Reads one file's exact bytes at the fetched commit.

        The blob is fetched from the remote on demand; no line-ending or
        filter conversion is applied.

        Args:
            path: The file's path from the repository root.

        Returns:
            The file's content as git stores it.

        Raises:
            ConfigError: When the path starts with ``-``, names no regular
                file at the commit (a lockfile or command-line problem, not
                a network one), or the file is larger than a recipe can be.
            NetworkError: When the blob cannot be fetched.
        """
        check_argument(path, "path")
        # The trees are local, so this answers without touching the network
        # and separates "no such file" from a failed blob fetch; the long
        # format carries the size, so an oversized blob is never fetched.
        listed = run_git(
            ["ls-tree", "-z", "--long", self.commit, "--", path], cwd=self._dir
        )
        if not listed:
            raise ConfigError(
                f"{path!r} does not exist at commit {self.commit[:12]} of the "
                f"fetched ref"
            )
        mode, kind, _blob, size = listed.split(b"\t", 1)[0].decode("ascii").split()
        if mode not in _REGULAR_FILE_MODES or kind != "blob":
            raise ConfigError(f"{path!r} is not a regular file at the fetched ref")
        if int(size) > MAX_RECIPE_BYTES:
            raise ConfigError(
                f"{path!r} is {int(size):,} bytes; a recipe larger than "
                f"{MAX_RECIPE_BYTES:,} bytes is not imported"
            )
        return run_git(["cat-file", "blob", f"{self.commit}:{path}"], cwd=self._dir)

__init__

__init__(url: str, ref: str) -> None

Fetches the ref's tip without its blobs.

Parameters:

Name Type Description Default
url str

The clone URL.

required
ref str

A branch or tag name.

required

Raises:

Type Description
ConfigError

When git is missing or a value starts with -.

NetworkError

When the fetch fails.

Source code in napt/upstream/git.py
def __init__(self, url: str, ref: str) -> None:
    """Fetches the ref's tip without its blobs.

    Args:
        url: The clone URL.
        ref: A branch or tag name.

    Raises:
        ConfigError: When git is missing or a value starts with ``-``.
        NetworkError: When the fetch fails.
    """
    check_argument(url, "URL")
    check_argument(ref, "ref")
    self._tempdir = tempfile.TemporaryDirectory(prefix="napt-upstream-")
    self._dir = Path(self._tempdir.name)
    try:
        run_git(["init", "-q", "-b", "main"], cwd=self._dir)
        run_git(["remote", "add", "origin", "--", url], cwd=self._dir)
        # A named remote is required: below git 2.24 a filtered fetch
        # from a bare URL dies, and the promisor configuration git writes
        # lands on the remote by name.
        run_git(
            [
                "fetch",
                "--quiet",
                "--depth",
                "1",
                "--filter=blob:none",
                "origin",
                ref,
            ],
            cwd=self._dir,
        )
        # FETCH_HEAD rather than ls-remote's answer, so a push between
        # the two calls cannot pin a commit the files did not come from;
        # ^{commit} dereferences an annotated tag.
        self.commit = (
            run_git(["rev-parse", "FETCH_HEAD^{commit}"], cwd=self._dir)
            .decode("ascii")
            .strip()
        )
    except BaseException:
        self._tempdir.cleanup()
        raise

__enter__

__enter__() -> FetchedRef

Returns the fetched ref for use inside a with block.

Source code in napt/upstream/git.py
def __enter__(self) -> FetchedRef:
    """Returns the fetched ref for use inside a ``with`` block."""
    return self

__exit__

__exit__(*exc_info: object) -> None

Removes the temporary directory, whatever happened inside.

Source code in napt/upstream/git.py
def __exit__(self, *exc_info: object) -> None:
    """Removes the temporary directory, whatever happened inside."""
    del exc_info  # The directory goes either way.
    self._tempdir.cleanup()

list_recipe_files

list_recipe_files(paths: Iterable[str]) -> list[TreeEntry]

Lists the recipe files under the given repository paths.

A directory lists every .yaml and .yml beneath it; a file lists itself. Each returned path has passed check_upstream_path.

Parameters:

Name Type Description Default
paths Iterable[str]

Files or directories relative to the repository root.

required

Returns:

Type Description
list[TreeEntry]

The matching files with their blob ids, in tree order.

Raises:

Type Description
ConfigError

When a path starts with - or a listed file's path has an unsafe segment.

NetworkError

When git fails.

Source code in napt/upstream/git.py
def list_recipe_files(self, paths: Iterable[str]) -> list[TreeEntry]:
    """Lists the recipe files under the given repository paths.

    A directory lists every ``.yaml`` and ``.yml`` beneath it; a file
    lists itself. Each returned path has passed
    [check_upstream_path][napt.upstream.git.check_upstream_path].

    Args:
        paths: Files or directories relative to the repository root.

    Returns:
        The matching files with their blob ids, in tree order.

    Raises:
        ConfigError: When a path starts with ``-`` or a listed file's
            path has an unsafe segment.
        NetworkError: When git fails.
    """
    wanted = [check_argument(path, "path") for path in paths]
    output = run_git(
        ["ls-tree", "-r", "-z", self.commit, "--", *wanted], cwd=self._dir
    )
    entries: list[TreeEntry] = []
    for record in output.split(b"\0"):
        if not record:
            continue
        meta, _, path = record.partition(b"\t")
        mode, kind, blob = meta.decode("ascii").split(" ")
        name = path.decode("utf-8", errors="replace")
        # A symlink is listed as a blob too (mode 120000); only regular
        # files are recipes.
        if mode not in _REGULAR_FILE_MODES or kind != "blob":
            continue
        if not name.endswith(RECIPE_SUFFIXES):
            continue
        entries.append(TreeEntry(path=check_upstream_path(name), blob=blob))
    return entries

read_file

read_file(path: str) -> bytes

Reads one file's exact bytes at the fetched commit.

The blob is fetched from the remote on demand; no line-ending or filter conversion is applied.

Parameters:

Name Type Description Default
path str

The file's path from the repository root.

required

Returns:

Type Description
bytes

The file's content as git stores it.

Raises:

Type Description
ConfigError

When the path starts with -, names no regular file at the commit (a lockfile or command-line problem, not a network one), or the file is larger than a recipe can be.

NetworkError

When the blob cannot be fetched.

Source code in napt/upstream/git.py
def read_file(self, path: str) -> bytes:
    """Reads one file's exact bytes at the fetched commit.

    The blob is fetched from the remote on demand; no line-ending or
    filter conversion is applied.

    Args:
        path: The file's path from the repository root.

    Returns:
        The file's content as git stores it.

    Raises:
        ConfigError: When the path starts with ``-``, names no regular
            file at the commit (a lockfile or command-line problem, not
            a network one), or the file is larger than a recipe can be.
        NetworkError: When the blob cannot be fetched.
    """
    check_argument(path, "path")
    # The trees are local, so this answers without touching the network
    # and separates "no such file" from a failed blob fetch; the long
    # format carries the size, so an oversized blob is never fetched.
    listed = run_git(
        ["ls-tree", "-z", "--long", self.commit, "--", path], cwd=self._dir
    )
    if not listed:
        raise ConfigError(
            f"{path!r} does not exist at commit {self.commit[:12]} of the "
            f"fetched ref"
        )
    mode, kind, _blob, size = listed.split(b"\t", 1)[0].decode("ascii").split()
    if mode not in _REGULAR_FILE_MODES or kind != "blob":
        raise ConfigError(f"{path!r} is not a regular file at the fetched ref")
    if int(size) > MAX_RECIPE_BYTES:
        raise ConfigError(
            f"{path!r} is {int(size):,} bytes; a recipe larger than "
            f"{MAX_RECIPE_BYTES:,} bytes is not imported"
        )
    return run_git(["cat-file", "blob", f"{self.commit}:{path}"], cwd=self._dir)

find_git

find_git() -> str

Locates the git binary.

On Windows the search includes the current directory, which for napt upstream is the user's project; a git.cmd committed there must never be what runs, so a result in the current directory is refused rather than used.

Returns:

Type Description
str

The path to git.

Raises:

Type Description
ConfigError

When git is not on PATH, or the only match is in the current directory.

Source code in napt/upstream/git.py
def find_git() -> str:
    """Locates the git binary.

    On Windows the search includes the current directory, which for
    ``napt upstream`` is the user's project; a ``git.cmd`` committed there
    must never be what runs, so a result in the current directory is
    refused rather than used.

    Returns:
        The path to ``git``.

    Raises:
        ConfigError: When git is not on ``PATH``, or the only match is in
            the current directory.
    """
    found = shutil.which("git")
    if found is None:
        raise ConfigError(
            "git is required for napt upstream and was not found on PATH. "
            "Install it from https://git-scm.com/downloads and try again."
        )
    if Path(found).resolve().parent == Path.cwd().resolve():
        raise ConfigError(
            f"Refusing to run {found}: it is in the current directory, not on "
            f"PATH. Remove it or run napt from another directory."
        )
    return found

redact_url

redact_url(value: str) -> str

Hides the user information of a URL for logs and messages.

Parameters:

Name Type Description Default
value str

Any command argument; one that is not a URL with user information is returned unchanged.

required

Returns:

Type Description
str

The value with user:password@ replaced by ***@.

Source code in napt/upstream/git.py
def redact_url(value: str) -> str:
    """Hides the user information of a URL for logs and messages.

    Args:
        value: Any command argument; one that is not a URL with user
            information is returned unchanged.

    Returns:
        The value with ``user:password@`` replaced by ``***@``.
    """
    if "://" not in value:
        return value
    parts = urlsplit(value)
    if not parts.username and not parts.password:
        return value
    host = parts.hostname or ""
    if parts.port is not None:
        host = f"{host}:{parts.port}"
    return urlunsplit(parts._replace(netloc=f"***@{host}"))

check_argument

check_argument(value: str, what: str) -> str

Refuses a value git would read as an option.

Parameters:

Name Type Description Default
value str

A URL, ref name, or repository path about to be passed to git.

required
what str

What the value is, for the message ("URL", "ref", "path").

required

Returns:

Type Description
str

The value, unchanged.

Raises:

Type Description
ConfigError

When the value is empty or starts with -.

Source code in napt/upstream/git.py
def check_argument(value: str, what: str) -> str:
    """Refuses a value git would read as an option.

    Args:
        value: A URL, ref name, or repository path about to be passed to
            git.
        what: What the value is, for the message ("URL", "ref", "path").

    Returns:
        The value, unchanged.

    Raises:
        ConfigError: When the value is empty or starts with ``-``.
    """
    if not value:
        raise ConfigError(f"The {what} is empty")
    if value.startswith("-"):
        raise ConfigError(
            f"Refusing {what} {value!r}: a value starting with '-' would be read "
            f"by git as an option"
        )
    return value

run_git

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

Runs one git command and returns its stdout.

Parameters:

Name Type Description Default
args list[str]

The arguments after git.

required
cwd Path | None

The repository to run in, or None for a command that needs none (ls-remote).

None

Returns:

Type Description
bytes

The command's stdout, as bytes, because paths and refs are not guaranteed to be UTF-8.

Raises:

Type Description
ConfigError

When git is not installed.

NetworkError

When git exits non-zero (the message carries its stderr), times out, or cannot be launched.

Source code in napt/upstream/git.py
def run_git(args: list[str], cwd: Path | None = None) -> bytes:
    """Runs one git command and returns its stdout.

    Args:
        args: The arguments after ``git``.
        cwd: The repository to run in, or None for a command that needs
            none (``ls-remote``).

    Returns:
        The command's stdout, as bytes, because paths and refs are not
            guaranteed to be UTF-8.

    Raises:
        ConfigError: When git is not installed.
        NetworkError: When git exits non-zero (the message carries its
            stderr), times out, or cannot be launched.
    """
    logger = get_global_logger()
    git = find_git()
    shown = [redact_url(arg) for arg in args]
    logger.verbose("UPSTREAM", "git " + " ".join(shown))
    try:
        completed = subprocess.run(
            [git, *args],
            cwd=cwd,
            capture_output=True,
            timeout=_TIMEOUT,
            env=_environment(),
            check=False,
        )
    except subprocess.TimeoutExpired as err:
        raise NetworkError(
            f"git {args[0]} did not finish within {_TIMEOUT} seconds"
        ) from err
    except OSError as err:
        raise NetworkError(f"Cannot run git: {err}") from err
    stderr = completed.stderr.decode("utf-8", errors="replace").strip()
    for raw, safe in zip(args, shown, strict=True):
        if raw != safe:
            stderr = stderr.replace(raw, safe)
    if completed.returncode != 0:
        raise NetworkError(
            f"git {args[0]} failed (exit {completed.returncode}): "
            f"{stderr or 'no error output'}"
        )
    if stderr:
        # Partial fetches print promisor notices on success; never an error.
        logger.debug("UPSTREAM", stderr)
    return completed.stdout

ls_remote

ls_remote(url: str) -> RemoteRefs

Lists a repository's refs without fetching anything.

Parameters:

Name Type Description Default
url str

The clone URL.

required

Returns:

Type Description
RemoteRefs

The default branch and every ref with its object id.

Raises:

Type Description
ConfigError

When git is missing or the URL starts with -.

NetworkError

When the repository cannot be reached.

Source code in napt/upstream/git.py
def ls_remote(url: str) -> RemoteRefs:
    """Lists a repository's refs without fetching anything.

    Args:
        url: The clone URL.

    Returns:
        The default branch and every ref with its object id.

    Raises:
        ConfigError: When git is missing or the URL starts with ``-``.
        NetworkError: When the repository cannot be reached.
    """
    check_argument(url, "URL")
    output = run_git(["ls-remote", "--symref", "--", url])
    default_branch: str | None = None
    refs: dict[str, str] = {}
    for raw in output.decode("utf-8", errors="replace").splitlines():
        if not raw.strip():
            continue
        left, _, right = raw.partition("\t")
        if left.startswith("ref: ") and right == "HEAD":
            target = left[len("ref: ") :]
            if target.startswith("refs/heads/"):
                default_branch = target[len("refs/heads/") :]
            continue
        if right:
            refs[right] = left
    return RemoteRefs(default_branch=default_branch, refs=refs)

check_upstream_path

check_upstream_path(path: str) -> str

Refuses a repository path that cannot become a directory tree here.

Every segment must satisfy is_safe_path_component with spaces allowed, so .., reserved device names, trailing dots, and characters Windows forbids never reach the filesystem.

Parameters:

Name Type Description Default
path str

A path from git ls-tree, forward slashes.

required

Returns:

Type Description
str

The path, unchanged.

Raises:

Type Description
ConfigError

When a segment is unsafe, naming it.

Source code in napt/upstream/git.py
def check_upstream_path(path: str) -> str:
    """Refuses a repository path that cannot become a directory tree here.

    Every segment must satisfy
    [is_safe_path_component][napt.paths.is_safe_path_component] with
    spaces allowed, so ``..``, reserved device names, trailing dots, and
    characters Windows forbids never reach the filesystem.

    Args:
        path: A path from ``git ls-tree``, forward slashes.

    Returns:
        The path, unchanged.

    Raises:
        ConfigError: When a segment is unsafe, naming it.
    """
    for segment in path.split("/"):
        if not is_safe_path_component(segment, allow_spaces=True):
            raise ConfigError(
                f"Cannot import {path!r}: the path segment {segment!r} is not a "
                f"safe directory or file name (letters, digits, spaces, '.', "
                f"'-', '_', '+', starting with a letter or digit)"
            )
    return path

napt.upstream.lock

The upstream.yaml lockfile.

upstream.yaml sits at the project root beside defaults/ and is written by napt upstream alone. It lists every imported repository and, under each, the recipes imported from it:

apiVersion: napt/v1
repos:
  - url: https://github.com/someorg/napt-recipes.git
    ref: main
    recipes:
      - path: recipes/Google/chrome.yaml
        override: recipes/Google/chrome.override.yaml
        commit: 4f2a9c1e0b7d3f8a2c6e1d9b5a4f7c3e8d2b6a1f
        blob: 9c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d
        sha256: 8e1b5f2c...

Each recipe carries its own commit, so one repository's recipes can be pinned at different points and updated one at a time.

The path of a recipe's pinned copy is never stored; it is derived from the repository URL and the recipe path, and it is the key the config loader looks an entry up by. sha256 is over the file's bytes with CRLF line endings normalized to LF, so a checkout with autocrlf on Windows hashes the same as one without.

LOCKFILE_NAME module-attribute

LOCKFILE_NAME = 'upstream.yaml'

The lockfile's name; it lives beside the upstream/ directory.

LockedRecipe dataclass

One imported recipe as the lockfile records it.

Attributes:

Name Type Description
path str

The upstream recipe's path inside its repository, forward slashes.

override str

The override that runs it, relative to the project root.

commit str

The commit the pinned copy was taken from.

blob str

The git blob id of the upstream recipe's content.

sha256 str

The canonical hash of the pinned copy.

Source code in napt/upstream/lock.py
@dataclass(frozen=True)
class LockedRecipe:
    """One imported recipe as the lockfile records it.

    Attributes:
        path: The upstream recipe's path inside its repository, forward
            slashes.
        override: The override that runs it, relative to the project root.
        commit: The commit the pinned copy was taken from.
        blob: The git blob id of the upstream recipe's content.
        sha256: The canonical hash of the pinned copy.
    """

    path: str
    override: str
    commit: str
    blob: str
    sha256: str

LockedRepo dataclass

One imported repository as the lockfile records it.

Attributes:

Name Type Description
url str

The clone URL as first given.

ref str

The branch or tag the recipes are taken from.

recipes tuple[LockedRecipe, ...]

The recipes imported from it, each with its own commit.

Source code in napt/upstream/lock.py
@dataclass(frozen=True)
class LockedRepo:
    """One imported repository as the lockfile records it.

    Attributes:
        url: The clone URL as first given.
        ref: The branch or tag the recipes are taken from.
        recipes: The recipes imported from it, each with its own commit.
    """

    url: str
    ref: str
    recipes: tuple[LockedRecipe, ...]

Lockfile dataclass

The parsed upstream.yaml.

Attributes:

Name Type Description
repos tuple[LockedRepo, ...]

Every imported repository.

Source code in napt/upstream/lock.py
@dataclass(frozen=True)
class Lockfile:
    """The parsed ``upstream.yaml``.

    Attributes:
        repos: Every imported repository.
    """

    repos: tuple[LockedRepo, ...]

    def find_repo(self, url: str) -> LockedRepo | None:
        """Finds the entry for a repository by any form of its URL.

        Args:
            url: A clone URL.

        Returns:
            The entry, or None when the repository was never imported.
        """
        for repo in self.repos:
            if same_repository(repo.url, url):
                return repo
        return None

    def replace_repo(self, repo: LockedRepo | None, *, url: str) -> Lockfile:
        """Returns a lockfile with one repository's entry replaced.

        Args:
            repo: The new entry, or None to drop the repository.
            url: The URL identifying the repository to replace; a
                repository not yet listed is appended.

        Returns:
            The new lockfile; this one is unchanged.
        """
        kept = [r for r in self.repos if not same_repository(r.url, url)]
        if repo is not None:
            position = next(
                (i for i, r in enumerate(self.repos) if same_repository(r.url, url)),
                len(kept),
            )
            kept.insert(position, repo)
        return Lockfile(repos=tuple(kept))

    def locate(self, pinned: PurePosixPath) -> tuple[LockedRepo, LockedRecipe] | None:
        """Looks a pinned copy up by its path under ``upstream/``.

        The repository part of the path is compared case-insensitively,
        since GitHub names are and Windows directories collide anyway; the
        recipe path is compared exactly, as git recorded it.

        Args:
            pinned: The file's path relative to the ``upstream/``
                directory, for example
                ``github.com/someorg/napt-recipes/recipes/Google/chrome.yaml``.

        Returns:
            The repository and recipe entries, or None when no repository
                entry tracks that pinned copy.
        """
        parts = pinned.parts
        for repo in self.repos:
            directory = repo_directory(repo.url).parts
            head = parts[: len(directory)]
            if len(head) < len(directory) or any(
                a.lower() != b.lower() for a, b in zip(head, directory, strict=True)
            ):
                continue
            recipe_path = "/".join(parts[len(directory) :])
            for recipe in repo.recipes:
                if recipe.path == recipe_path:
                    return repo, recipe
        return None

    def find(self, pinned: PurePosixPath) -> LockedRecipe | None:
        """Looks a pinned copy's recipe entry up by its path under ``upstream/``.

        Args:
            pinned: The file's path relative to the ``upstream/`` directory.

        Returns:
            The matching entry, or None; see
                [locate][napt.upstream.lock.Lockfile.locate].
        """
        located = self.locate(pinned)
        return located[1] if located is not None else None

find_repo

find_repo(url: str) -> LockedRepo | None

Finds the entry for a repository by any form of its URL.

Parameters:

Name Type Description Default
url str

A clone URL.

required

Returns:

Type Description
LockedRepo | None

The entry, or None when the repository was never imported.

Source code in napt/upstream/lock.py
def find_repo(self, url: str) -> LockedRepo | None:
    """Finds the entry for a repository by any form of its URL.

    Args:
        url: A clone URL.

    Returns:
        The entry, or None when the repository was never imported.
    """
    for repo in self.repos:
        if same_repository(repo.url, url):
            return repo
    return None

replace_repo

replace_repo(repo: LockedRepo | None, *, url: str) -> Lockfile

Returns a lockfile with one repository's entry replaced.

Parameters:

Name Type Description Default
repo LockedRepo | None

The new entry, or None to drop the repository.

required
url str

The URL identifying the repository to replace; a repository not yet listed is appended.

required

Returns:

Type Description
Lockfile

The new lockfile; this one is unchanged.

Source code in napt/upstream/lock.py
def replace_repo(self, repo: LockedRepo | None, *, url: str) -> Lockfile:
    """Returns a lockfile with one repository's entry replaced.

    Args:
        repo: The new entry, or None to drop the repository.
        url: The URL identifying the repository to replace; a
            repository not yet listed is appended.

    Returns:
        The new lockfile; this one is unchanged.
    """
    kept = [r for r in self.repos if not same_repository(r.url, url)]
    if repo is not None:
        position = next(
            (i for i, r in enumerate(self.repos) if same_repository(r.url, url)),
            len(kept),
        )
        kept.insert(position, repo)
    return Lockfile(repos=tuple(kept))

locate

locate(pinned: PurePosixPath) -> tuple[LockedRepo, LockedRecipe] | None

Looks a pinned copy up by its path under upstream/.

The repository part of the path is compared case-insensitively, since GitHub names are and Windows directories collide anyway; the recipe path is compared exactly, as git recorded it.

Parameters:

Name Type Description Default
pinned PurePosixPath

The file's path relative to the upstream/ directory, for example github.com/someorg/napt-recipes/recipes/Google/chrome.yaml.

required

Returns:

Type Description
tuple[LockedRepo, LockedRecipe] | None

The repository and recipe entries, or None when no repository entry tracks that pinned copy.

Source code in napt/upstream/lock.py
def locate(self, pinned: PurePosixPath) -> tuple[LockedRepo, LockedRecipe] | None:
    """Looks a pinned copy up by its path under ``upstream/``.

    The repository part of the path is compared case-insensitively,
    since GitHub names are and Windows directories collide anyway; the
    recipe path is compared exactly, as git recorded it.

    Args:
        pinned: The file's path relative to the ``upstream/``
            directory, for example
            ``github.com/someorg/napt-recipes/recipes/Google/chrome.yaml``.

    Returns:
        The repository and recipe entries, or None when no repository
            entry tracks that pinned copy.
    """
    parts = pinned.parts
    for repo in self.repos:
        directory = repo_directory(repo.url).parts
        head = parts[: len(directory)]
        if len(head) < len(directory) or any(
            a.lower() != b.lower() for a, b in zip(head, directory, strict=True)
        ):
            continue
        recipe_path = "/".join(parts[len(directory) :])
        for recipe in repo.recipes:
            if recipe.path == recipe_path:
                return repo, recipe
    return None

find

find(pinned: PurePosixPath) -> LockedRecipe | None

Looks a pinned copy's recipe entry up by its path under upstream/.

Parameters:

Name Type Description Default
pinned PurePosixPath

The file's path relative to the upstream/ directory.

required

Returns:

Type Description
LockedRecipe | None

The matching entry, or None; see locate.

Source code in napt/upstream/lock.py
def find(self, pinned: PurePosixPath) -> LockedRecipe | None:
    """Looks a pinned copy's recipe entry up by its path under ``upstream/``.

    Args:
        pinned: The file's path relative to the ``upstream/`` directory.

    Returns:
        The matching entry, or None; see
            [locate][napt.upstream.lock.Lockfile.locate].
    """
    located = self.locate(pinned)
    return located[1] if located is not None else None

canonical_sha256

canonical_sha256(data: bytes) -> str

Hashes file bytes with Windows line endings normalized.

Parameters:

Name Type Description Default
data bytes

The file's bytes as read from disk or from git.

required

Returns:

Type Description
str

The hex digest of the bytes with every CRLF replaced by LF.

Source code in napt/upstream/lock.py
def canonical_sha256(data: bytes) -> str:
    """Hashes file bytes with Windows line endings normalized.

    Args:
        data: The file's bytes as read from disk or from git.

    Returns:
        The hex digest of the bytes with every CRLF replaced by LF.
    """
    return hashlib.sha256(data.replace(b"\r\n", b"\n")).hexdigest()

repo_directory

repo_directory(url: str) -> PurePosixPath

Names the directory under upstream/ that holds a repository's pinned copies.

The directory is the host plus every path segment of the clone URL, with the user, port, .git suffix, and trailing slash removed, so HTTPS, ssh://, and scp-like SSH forms of one repository land in one place and nested GitLab groups keep every segment. The host is lowercased; path segments keep their case and are compared case-insensitively by Lockfile.find. A URL with no host, such as file://, becomes a single directory named after the whole URL with unsafe characters replaced.

Parameters:

Name Type Description Default
url str

A clone URL as given to napt upstream add.

required

Returns:

Type Description
PurePosixPath

The repository's directory relative to upstream/.

Example

Three forms of one repository:

repo_directory("https://github.com/Org/Recipes.git")
# PurePosixPath("github.com/Org/Recipes")
repo_directory("git@github.com:Org/Recipes.git")
# PurePosixPath("github.com/Org/Recipes")
repo_directory("ssh://git@github.com:2222/Org/Recipes/")
# PurePosixPath("github.com/Org/Recipes")

Source code in napt/upstream/lock.py
def repo_directory(url: str) -> PurePosixPath:
    """Names the directory under ``upstream/`` that holds a repository's pinned copies.

    The directory is the host plus every path segment of the clone URL,
    with the user, port, ``.git`` suffix, and trailing slash removed, so
    HTTPS, ``ssh://``, and scp-like SSH forms of one repository land in one
    place and nested GitLab groups keep every segment. The host is
    lowercased; path segments keep their case and are compared
    case-insensitively by [Lockfile.find][napt.upstream.lock.Lockfile.find].
    A URL with no host, such as ``file://``, becomes a single directory
    named after the whole URL with unsafe characters replaced.

    Args:
        url: A clone URL as given to ``napt upstream add``.

    Returns:
        The repository's directory relative to ``upstream/``.

    Example:
        Three forms of one repository:
            ```python
            repo_directory("https://github.com/Org/Recipes.git")
            # PurePosixPath("github.com/Org/Recipes")
            repo_directory("git@github.com:Org/Recipes.git")
            # PurePosixPath("github.com/Org/Recipes")
            repo_directory("ssh://git@github.com:2222/Org/Recipes/")
            # PurePosixPath("github.com/Org/Recipes")
            ```
    """
    host: str | None = None
    path = ""
    scp = _SCP_LIKE.match(url)
    if scp and "://" not in url:
        host, path = scp.group("host"), scp.group("path")
    else:
        parts = urlsplit(url)
        host, path = parts.hostname, parts.path
    segments = [segment for segment in path.split("/") if segment]
    if segments and segments[-1].endswith(".git"):
        segments[-1] = segments[-1][: -len(".git")]
    if not host or not segments:
        return PurePosixPath(_UNSAFE_IN_NAME.sub("_", url))
    return PurePosixPath(host.lower(), *segments)

same_repository

same_repository(first: str, second: str) -> bool

Reports whether two clone URLs name one repository.

Parameters:

Name Type Description Default
first str

A clone URL.

required
second str

Another clone URL, in any form git accepts.

required

Returns:

Type Description
bool

True when both map to the same directory under upstream/, compared case-insensitively.

Source code in napt/upstream/lock.py
def same_repository(first: str, second: str) -> bool:
    """Reports whether two clone URLs name one repository.

    Args:
        first: A clone URL.
        second: Another clone URL, in any form git accepts.

    Returns:
        True when both map to the same directory under ``upstream/``, compared
            case-insensitively.
    """
    a, b = repo_directory(first).parts, repo_directory(second).parts
    return len(a) == len(b) and all(
        x.lower() == y.lower() for x, y in zip(a, b, strict=True)
    )

write_lockfile

write_lockfile(path: Path, lock: Lockfile) -> None

Writes upstream.yaml atomically, after a fixed header comment.

Parameters:

Name Type Description Default
path Path

The lockfile.

required
lock Lockfile

What to write.

required

Raises:

Type Description
OSError

When the file cannot be written.

Source code in napt/upstream/lock.py
def write_lockfile(path: Path, lock: Lockfile) -> None:
    """Writes ``upstream.yaml`` atomically, after a fixed header comment.

    Args:
        path: The lockfile.
        lock: What to write.

    Raises:
        OSError: When the file cannot be written.
    """
    document = {
        "apiVersion": "napt/v1",
        "repos": [
            {
                "url": repo.url,
                "ref": repo.ref,
                "recipes": [
                    {
                        "path": recipe.path,
                        "override": recipe.override,
                        "commit": recipe.commit,
                        "blob": recipe.blob,
                        "sha256": recipe.sha256,
                    }
                    for recipe in repo.recipes
                ],
            }
            for repo in lock.repos
        ],
    }
    body = yaml.safe_dump(document, sort_keys=False, allow_unicode=True)
    write_text_atomic(path, _HEADER + body)

read_lockfile

read_lockfile(path: Path) -> Lockfile

Reads upstream.yaml, once per version of the file per run.

A directory run loads many recipes that share one lockfile; the parsed result is reused until the file's size or modification time changes.

Parameters:

Name Type Description Default
path Path

The lockfile.

required

Returns:

Type Description
Lockfile

The parsed lockfile.

Raises:

Type Description
ConfigError

When the file does not exist, cannot be read, is not valid YAML, or does not have the shape napt upstream writes.

Source code in napt/upstream/lock.py
def read_lockfile(path: Path) -> Lockfile:
    """Reads ``upstream.yaml``, once per version of the file per run.

    A directory run loads many recipes that share one lockfile; the parsed
    result is reused until the file's size or modification time changes.

    Args:
        path: The lockfile.

    Returns:
        The parsed lockfile.

    Raises:
        ConfigError: When the file does not exist, cannot be read, is not
            valid YAML, or does not have the shape ``napt upstream``
            writes.
    """
    try:
        stat = path.stat()
    except FileNotFoundError as err:
        raise ConfigError(f"{path} does not exist") from err
    except OSError as err:
        raise ConfigError(f"Cannot read {path}: {err}") from err
    return _read_lockfile_version(str(path), stat.st_mtime_ns, stat.st_size)

napt.upstream.pinned

What the config loader does with a parent under upstream/.

A parent is a pinned copy when the parent reference in the override, taken relative to the override's directory, passes through a directory named upstream (any case). Only the segments between the override and the parent count, so a project that itself lives under a folder called upstream is unaffected. A parent whose resolved path sits under a tracked upstream/ directory (one with upstream.yaml beside it) is a pinned copy as well, so a symlink from elsewhere cannot present one as local. A pinned parent must be listed in the upstream.yaml beside that directory with a matching hash, and only the app-owned keys in ALLOWED_PARENT_KEYS reach the merge; everything else is tenant policy that defaults/org.yaml keeps owning without the override restating it.

A pinned copy under upstream/ is never run directly; commands run the override that names it as parent. A "pinned parent" below is a parent that is a pinned copy, as opposed to a local parent.

UPSTREAM_DIR_NAME module-attribute

UPSTREAM_DIR_NAME = 'upstream'

The reserved directory name; compared case-insensitively.

ALLOWED_PARENT_KEYS module-attribute

ALLOWED_PARENT_KEYS: dict[str, frozenset[str] | None] = {
    "apiVersion": None,
    "name": None,
    "id": None,
    "discovery": None,
    "psadt": frozenset(
        {
            "app_vars",
            "install",
            "uninstall",
            "override_msi_commands",
            "override_msix_commands",
        }
    ),
    "intune": frozenset(
        {
            "detection",
            "description",
            "publisher",
            "developer",
            "privacy_url",
            "info_url",
            "run_as_account",
            "run_as_32_bit",
            "device_restart_behavior",
            "max_run_time_minutes",
            "minimum_supported_windows_release",
        }
    ),
}

The keys a pinned parent may set.

A top-level key mapped to None is taken whole; one mapped to a set keeps only the named sub-keys. Any key not listed is dropped, so a field this version of NAPT does not know never reaches the merge. The rule for a new recipe field: org-policy fields stay off the list; strategy-specific, recipe-required, and absent-means-skip fields go on it.

PinnedLocation dataclass

Where a pinned copy sits relative to its upstream/ directory.

Attributes:

Name Type Description
upstream_dir Path

The upstream/ directory the parent is under.

relative PurePosixPath

The parent's path below that directory, forward slashes, which is the key its lockfile entry is found by.

Source code in napt/upstream/pinned.py
@dataclass(frozen=True)
class PinnedLocation:
    """Where a pinned copy sits relative to its ``upstream/`` directory.

    Attributes:
        upstream_dir: The ``upstream/`` directory the parent is under.
        relative: The parent's path below that directory, forward slashes,
            which is the key its lockfile entry is found by.
    """

    upstream_dir: Path
    relative: PurePosixPath

    @property
    def lockfile(self) -> Path:
        """The ``upstream.yaml`` beside the ``upstream/`` directory."""
        return self.upstream_dir.parent / LOCKFILE_NAME

lockfile property

lockfile: Path

The upstream.yaml beside the upstream/ directory.

pinned_location

pinned_location(recipe_dir: Path, parent_ref: str) -> PinnedLocation | None

Decides whether a parent reference points under upstream/.

Only the path between the override's directory and the parent is examined: an absolute reference is first made relative to the override, and leading .. segments are skipped. A reference on another drive cannot be made relative and is local.

Parameters:

Name Type Description Default
recipe_dir Path

The directory of the override declaring parent.

required
parent_ref str

The parent value as written in the override.

required

Returns:

Type Description
PinnedLocation | None

The parent's location when it is a pinned copy, or None when it is a local parent.

Source code in napt/upstream/pinned.py
def pinned_location(recipe_dir: Path, parent_ref: str) -> PinnedLocation | None:
    """Decides whether a ``parent`` reference points under ``upstream/``.

    Only the path between the override's directory and the parent is
    examined: an absolute reference is first made relative to the
    override, and leading ``..`` segments are skipped. A reference on
    another drive cannot be made relative and is local.

    Args:
        recipe_dir: The directory of the override declaring ``parent``.
        parent_ref: The ``parent`` value as written in the override.

    Returns:
        The parent's location when it is a pinned copy, or None when it is
            a local parent.
    """
    target = os.path.normpath(os.path.join(recipe_dir, parent_ref))
    try:
        relative = os.path.relpath(target, recipe_dir)
    except ValueError:
        return None
    parts = Path(relative).parts
    for index, part in enumerate(parts[:-1]):
        if _is_upstream_segment(part):
            upstream_dir = Path(
                os.path.normpath(recipe_dir.joinpath(*parts[: index + 1]))
            )
            return PinnedLocation(
                upstream_dir=upstream_dir,
                relative=PurePosixPath(*parts[index + 1 :]),
            )
    return None

tracked_location

tracked_location(path: Path) -> PinnedLocation | None

Finds the tracked upstream/ directory a file really sits under.

The path is resolved, so a symlink or junction that points into upstream/ from elsewhere is seen for what it is. A directory named upstream counts only with an upstream.yaml beside it, so a project that merely lives under a folder called upstream is not affected.

Parameters:

Name Type Description Default
path Path

A recipe or parent file.

required

Returns:

Type Description
PinnedLocation | None

The file's location under the tracked directory, or None.

Source code in napt/upstream/pinned.py
def tracked_location(path: Path) -> PinnedLocation | None:
    """Finds the tracked ``upstream/`` directory a file really sits under.

    The path is resolved, so a symlink or junction that points into
    ``upstream/`` from elsewhere is seen for what it is. A directory named
    ``upstream`` counts only with an ``upstream.yaml`` beside it, so a
    project that merely lives under a folder called ``upstream`` is not
    affected.

    Args:
        path: A recipe or parent file.

    Returns:
        The file's location under the tracked directory, or None.
    """
    resolved = path.resolve()
    for ancestor in resolved.parents:
        if (
            _is_upstream_segment(ancestor.name)
            and (ancestor.parent / LOCKFILE_NAME).is_file()
        ):
            return PinnedLocation(
                upstream_dir=ancestor,
                relative=PurePosixPath(*resolved.relative_to(ancestor).parts),
            )
    return None

pinned_copy_of_override

pinned_copy_of_override(override: Path) -> Path

Resolves an override's parent to the pinned copy it names.

Parameters:

Name Type Description Default
override Path

A recipe file that declares parent.

required

Returns:

Type Description
Path

The resolved parent path.

Raises:

Type Description
ConfigError

When the file cannot be read or declares no parent.

Source code in napt/upstream/pinned.py
def pinned_copy_of_override(override: Path) -> Path:
    """Resolves an override's ``parent`` to the pinned copy it names.

    Args:
        override: A recipe file that declares ``parent``.

    Returns:
        The resolved parent path.

    Raises:
        ConfigError: When the file cannot be read or declares no parent.
    """
    try:
        data = yaml.safe_load(override.read_text(encoding="utf-8"))
    except (OSError, UnicodeDecodeError, yaml.YAMLError) as err:
        raise ConfigError(f"Cannot read {override}: {err}") from err
    parent = data.get("parent") if isinstance(data, dict) else None
    if not isinstance(parent, str) or not parent:
        raise ConfigError(
            f"{override} declares no parent, so it is not an imported recipe's "
            f"override; pass the pinned copy under {UPSTREAM_DIR_NAME}/ instead"
        )
    return (override.resolve().parent / parent).resolve()

is_pinned_copy

is_pinned_copy(recipe_path: Path) -> bool

Reports whether a recipe file itself sits under a tracked upstream/.

Parameters:

Name Type Description Default
recipe_path Path

The recipe a command was asked to run.

required

Returns:

Type Description
bool

Whether the file is a pinned copy rather than an override.

Source code in napt/upstream/pinned.py
def is_pinned_copy(recipe_path: Path) -> bool:
    """Reports whether a recipe file itself sits under a tracked ``upstream/``.

    Args:
        recipe_path: The recipe a command was asked to run.

    Returns:
        Whether the file is a pinned copy rather than an override.
    """
    return tracked_location(recipe_path) is not None

verify_pinned_copy

verify_pinned_copy(
    parent_path: Path, location: PinnedLocation, data: bytes
) -> None

Checks a pinned parent against its lockfile entry.

Parameters:

Name Type Description Default
parent_path Path

The parent file, for messages.

required
location PinnedLocation

Where the parent sits, from pinned_location.

required
data bytes

The parent's bytes as read from disk.

required

Raises:

Type Description
ConfigError

When there is no lockfile beside the upstream/ directory, the lockfile has no entry for the file, or the file's canonical hash differs from the recorded one.

Source code in napt/upstream/pinned.py
def verify_pinned_copy(
    parent_path: Path, location: PinnedLocation, data: bytes
) -> None:
    """Checks a pinned parent against its lockfile entry.

    Args:
        parent_path: The parent file, for messages.
        location: Where the parent sits, from
            [pinned_location][napt.upstream.pinned.pinned_location].
        data: The parent's bytes as read from disk.

    Raises:
        ConfigError: When there is no lockfile beside the ``upstream/``
            directory, the lockfile has no entry for the file, or the
            file's canonical hash differs from the recorded one.
    """
    lockfile = location.lockfile
    if not lockfile.is_file():
        raise ConfigError(
            f"{parent_path} is under {location.upstream_dir} but there is no "
            f"{lockfile} tracking it. Pinned copies are written by 'napt "
            f"upstream add'; import the recipe with it, or keep a local parent "
            f"outside a directory named '{UPSTREAM_DIR_NAME}'."
        )
    entry = read_lockfile(lockfile).find(location.relative)
    if entry is None:
        raise ConfigError(
            f"{parent_path} is not tracked in {lockfile}. Import it with 'napt "
            f"upstream add', or delete the file if it was copied in by hand."
        )
    actual = canonical_sha256(data)
    if actual != entry.sha256:
        raise ConfigError(
            f"Pinned copy {parent_path} differs from what {lockfile} "
            f"recorded (sha256 {actual[:12]}, expected {entry.sha256[:12]}). "
            f"Move local edits into the override, or run 'napt upstream update' "
            f"to refresh the pinned copy."
        )

filter_pinned_parent

filter_pinned_parent(
    data: dict[str, Any],
) -> tuple[dict[str, Any], tuple[str, ...]]

Keeps only the keys a pinned parent may set.

A section the allow list restricts is filtered key by key when it is a mapping; one of another shape (a list, null, a string) is dropped whole and named, since merging it would replace the tenant's section instead of adding to it.

Parameters:

Name Type Description Default
data dict[str, Any]

The parsed parent recipe.

required

Returns:

Type Description
tuple[dict[str, Any], tuple[str, ...]]

The filtered copy and the dotted names of every dropped key, in the order the parent wrote them.

Source code in napt/upstream/pinned.py
def filter_pinned_parent(
    data: dict[str, Any],
) -> tuple[dict[str, Any], tuple[str, ...]]:
    """Keeps only the keys a pinned parent may set.

    A section the allow list restricts is filtered key by key when it is a
    mapping; one of another shape (a list, null, a string) is dropped whole
    and named, since merging it would replace the tenant's section instead
    of adding to it.

    Args:
        data: The parsed parent recipe.

    Returns:
        The filtered copy and the dotted names of every dropped key, in the
            order the parent wrote them.
    """
    kept: dict[str, Any] = {}
    dropped: list[str] = []
    for key, value in data.items():
        if key not in ALLOWED_PARENT_KEYS:
            dropped.append(str(key))
            continue
        allowed = ALLOWED_PARENT_KEYS[key]
        if allowed is None:
            kept[key] = value
            continue
        if not isinstance(value, dict):
            dropped.append(str(key))
            continue
        section: dict[str, Any] = {}
        for sub_key, sub_value in value.items():
            if sub_key in allowed:
                section[sub_key] = sub_value
            else:
                dropped.append(f"{key}.{sub_key}")
        # A section left with nothing is left out, so a parent that set only
        # tenant keys in it does not present an empty section to the merge.
        if section:
            kept[key] = section
    return kept, tuple(dropped)