Compare commits
18
Commits
No files matched your search
@@ -71,3 +71,9 @@ jobs:
|
||||
contents: read
|
||||
security-events: write
|
||||
uses: ./.github/workflows/lint-docker.yml
|
||||
|
||||
quality:
|
||||
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
|
||||
permissions:
|
||||
contents: read
|
||||
uses: infinito-nexus/quality/.github/workflows/quality.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
|
||||
@@ -8,19 +8,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
lint-python:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install ruff
|
||||
run: pip install ruff
|
||||
|
||||
- name: Run ruff
|
||||
run: |
|
||||
ruff check src tests
|
||||
uses: infinito-nexus/quality/.github/workflows/tool.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
|
||||
with:
|
||||
tool: ruff
|
||||
args: check src tests
|
||||
@@ -1,5 +1,16 @@
|
||||
# Changelog
|
||||
|
||||
## [2.5.0] - 2026-11-13
|
||||
|
||||
Added:
|
||||
|
||||
- Branch: *cleanup --local* deletes merged branches only where git would
|
||||
- Review: expand and collapse are icon buttons with labels
|
||||
|
||||
Fixed:
|
||||
|
||||
- GC: merged local-only branches are removed without a forge token
|
||||
|
||||
## [2.4.0] - 2026-11-07
|
||||
|
||||
Added:
|
||||
|
||||
@@ -80,6 +80,7 @@ versioning features it can drive **end-to-end workflows**:
|
||||
| `pkgmgr worktree flow clear [PATH] [--json]` | Removes the merge flow |
|
||||
| `pkgmgr worktree cleanup [--apply]` | Removes clean worktrees whose commits are merged or pushed: pinned `worktree-fini` hook, compose stack, checkout; the branch stays |
|
||||
| `pkgmgr branch cleanup [--apply]` | Removes merged branches that no worktree holds, locally and on the remotes |
|
||||
| `pkgmgr branch cleanup --local [--apply] [--json] [--merged-into REF]...` | Deletes only local branches whose tip is an ancestor of the remote-tracking default or of a `--merged-into` REF, each with `git update-ref --no-deref -d` against the planned sha and then its `branch.<name>` section in the repository's own config file (`git config --file <git common dir>/config`; a section it cannot remove is noted on the done item), also when the branch has an upstream or remote copy. Every git call of `--local` runs without any inherited `GIT_*` variable but `GIT_CEILING_DIRECTORIES`, which only narrows repository discovery, so a directory below a ceiling is never resolved to the repository above it; only the config reads of `deleteMerged` and of the upstreams run twice, both with the system config: once with the caller's `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_PARAMETERS` and `GIT_CONFIG_COUNT` with its `GIT_CONFIG_KEY_<n>` and `GIT_CONFIG_VALUE_<n>`, once without any of them, without `XDG_CONFIG_HOME` and with `HOME` set to the passwd home, and a branch either read keeps stays, so the environment can add keeps but never remove one. A `--merged-into` REF must name exactly one branch or remote-tracking ref, as `git rev-parse --symbolic-full-name` resolves it, in every scanned repository git can read; `X~0`, `X^0`, `X@{0}`, a sha, a range or an unknown ref stops the run. The default comes from `origin`, or from the only remote when there is no `origin`: the ref `refs/remotes/<remote>/HEAD`, else `main`, else `master` resolves to, every symref step inside `refs/remotes/<remote>/`, so never a local branch or `HEAD`; without one, for example with several remotes and no `origin`, the repository is refused, also under `--merged-into`; so is one whose `refs`, `packed-refs`, `reftable`, `logs` or `logs/refs` is a symlink (git-new-workdir), one with a symlink anywhere below `refs/`, `reftable/` or `logs/refs/` (for example `refs/heads/team` linked to another clone's heads), one whose git dir is neither its git common dir nor directly under `<common>/worktrees/` (a registration moved elsewhere), or one whose git output is not UTF-8. The repository is the one the current directory belongs to, also in a submodule or with a separate git dir; one whose main worktree belongs to another repository (`core.worktree`), whose git dir is neither its git common dir nor directly under `<common>/worktrees/`, or whose path is not UTF-8 is refused with exit 2. Skips a symbolic branch, every branch a symbolic ref anywhere under `refs/` (also a tag or remote-tracking one) or under the main worktree's or any registration's `refs/worktree/` points to, a branch that is itself a `--merged-into` target, a branch a worktree holds or that the HEAD of the main repository or of any `worktrees/<id>` registration names (also one `git worktree list` omits or whose id is no valid ref name, read through `git --git-dir=<dir> symbolic-ref HEAD`, so also under reftable), one a rebase or bisect in any worktree works on, one merged only by patch or PR, and, as `git branch --delete-merged` keeps them, one whose `branch.<name>.deleteMerged` is false in the config of any worktree (also its `config.worktree` or an `includeIf "onbranch:..."` file) or in the system config file, and the local upstream, as git's `%(upstream)` resolves it in any worktree, of any branch that stays, also of one that `--branch` or `--exclude` leaves out, each shown as kept with its reason; these holds are read through the git common dir, whichever worktree is scanned, and a registration, symbolic ref, HEAD or state file they cannot read refuses the repository; when a repository vanishes, moves or stops being readable, or its default or a `--merged-into` target stops resolving mid-run, its later items are skipped with that reason and the plan is still printed. A repository git or the filesystem fails on while planning (for example a dangling `.git` file under `--all`) is refused with that reason and the run goes on. The plan, refused repositories included, is printed (as JSON with `--json`), and the run exits 1 when an item failed, else 2 when a repository was refused, else 0. It stops with a message on stderr, no plan and exit 2 in exactly these cases: without `--all`, the current directory is not inside a git repository, its git dir is neither its git common dir nor directly under `<common>/worktrees/`, its main worktree belongs to another repository (`core.worktree`), or its path or git output is not UTF-8; `--apply` outside the host PID namespace; a `--merged-into` REF refused as above; a `--branch` that matches no item (also one that exists only on a remote). Meant for working clones and their worktrees, not for a bare server repository. Not mirrored from `git branch --delete-merged`: git also keeps a branch whose push would update its own upstream; `--local` does not. A branch is deleted before its planned local upstream; right before each delete its holds and then itLine truncated
|
||||
| `pkgmgr branch tree [--format json\|yaml] [--output FILE]` | Writes every managed repository's branches and worktrees with their cleanup state, without fetching |
|
||||
| `pkgmgr gc [--all] [--apply]` | Both cleanups in one pass, for the current repository or every managed one |
|
||||
| `pkgmgr gc --report [--all] [--root DIR] [--threshold-mb MB] [--docker] [--json]` | Read-only disk inventory: worktree sizes, changes a cleanup would keep, `--root` children, core dumps, docker usage, free space per filesystem |
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
rec {
|
||||
pkgmgr = pyPkgs.buildPythonApplication {
|
||||
pname = "package-manager";
|
||||
version = "2.4.0";
|
||||
version = "2.5.0";
|
||||
|
||||
# Use the git repo as source
|
||||
src = ./.;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Maintainer: Kevin Veen-Birkenbach <info@veen.world>
|
||||
|
||||
pkgname=package-manager
|
||||
pkgver=2.4.0
|
||||
pkgver=2.5.0
|
||||
pkgrel=1
|
||||
pkgdesc="Local-flake wrapper for Kevin's package-manager (Nix-based)."
|
||||
arch=('any')
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
package-manager (2.5.0-1) unstable; urgency=medium
|
||||
|
||||
Added:
|
||||
|
||||
- Branch: *cleanup --local* deletes merged branches only where git would
|
||||
- Review: expand and collapse are icon buttons with labels
|
||||
|
||||
Fixed:
|
||||
|
||||
- GC: merged local-only branches are removed without a forge token
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Fri, 13 Nov 2026 22:53:12 +0000
|
||||
|
||||
package-manager (2.4.0-1) unstable; urgency=medium
|
||||
|
||||
Added:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Name: package-manager
|
||||
Version: 2.4.0
|
||||
Version: 2.5.0
|
||||
Release: 1%{?dist}
|
||||
Summary: Wrapper that runs Kevin's package-manager via Nix flake
|
||||
|
||||
@@ -74,6 +74,16 @@ echo ">>> package-manager removed. Nix itself was not removed."
|
||||
/usr/lib/package-manager/
|
||||
|
||||
%changelog
|
||||
* Fri Nov 13 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.5.0-1
|
||||
- Added:
|
||||
|
||||
- - Branch: *cleanup --local* deletes merged branches only where git would
|
||||
- - Review: expand and collapse are icon buttons with labels
|
||||
|
||||
- Fixed:
|
||||
|
||||
- - GC: merged local-only branches are removed without a forge token
|
||||
|
||||
* Sat Nov 07 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.4.0-1
|
||||
- Added:
|
||||
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "kpmx"
|
||||
version = "2.4.0"
|
||||
version = "2.5.0"
|
||||
description = "Kevin's package-manager tool (pkgmgr)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
@@ -52,4 +52,4 @@ include = ["pkgmgr*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"pkgmgr.config" = ["*.yml", "*.yaml"]
|
||||
"pkgmgr.actions.review" = ["*.j2"]
|
||||
"pkgmgr.actions.review" = ["*.j2", "*.LICENSE"]
|
||||
+768
-32
@@ -8,9 +8,11 @@ import sys
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from functools import cache
|
||||
from graphlib import CycleError, TopologicalSorter
|
||||
|
||||
from pkgmgr.actions.worktree.hooks import FINI_HOOK, hook_command, run_hook
|
||||
from pkgmgr.core.git.errors import GitRunError
|
||||
from pkgmgr.core.git.errors import GitBaseError, GitRunError
|
||||
from pkgmgr.core.git.queries import (
|
||||
FILTER_CONFIG,
|
||||
UNSAFE_CONFIG,
|
||||
@@ -18,9 +20,16 @@ from pkgmgr.core.git.queries import (
|
||||
local_config,
|
||||
resolve_base_branch,
|
||||
)
|
||||
from pkgmgr.core.git.run import END_OF_OPTIONS, SCAN_FLAGS, run
|
||||
from pkgmgr.core.git.run import (
|
||||
CONFIG_VIEWS,
|
||||
END_OF_OPTIONS,
|
||||
SCAN_FLAGS,
|
||||
run,
|
||||
strict_env,
|
||||
)
|
||||
|
||||
from .gc_forge import ForgeFacts, fetch_forge_facts
|
||||
from .held import _common_dir, _git_dirs, _held_branches, _symbolic
|
||||
from .nofollow import canonical, remove_tree
|
||||
|
||||
Registrations = tuple[str, dict[str, list[str]]]
|
||||
@@ -30,6 +39,7 @@ Snapshot = tuple[
|
||||
dict[int, str],
|
||||
dict[str, tuple[str | None, int | None, int | None, bool]],
|
||||
Registrations,
|
||||
Callable[[], dict[str, str]],
|
||||
]
|
||||
|
||||
# PROC_PID_INIT_INO: only the initial PID namespace sees every process of the host.
|
||||
@@ -53,8 +63,18 @@ REFUSAL = (
|
||||
"Refusing: not in the host PID namespace (e.g. a sandbox), so running "
|
||||
"processes and worktree locks cannot be verified. Run it on the host."
|
||||
)
|
||||
SCOPES = ("worktree", "branch", "all", "purge")
|
||||
SCOPES = ("worktree", "branch", "all", "purge", "local")
|
||||
NOT_LINKED = "not a linked worktree of this repository"
|
||||
NO_REMOTE_DEFAULT = (
|
||||
"refused: no remote-tracking default (origin, else the only remote: "
|
||||
"refs/remotes/<remote>/HEAD, main or master, resolving inside "
|
||||
"refs/remotes/<remote>/), so --local cannot tell which branches are merged"
|
||||
)
|
||||
NOT_UTF8 = "refused: git output (ref, remote or path names) is not UTF-8"
|
||||
DEFAULT_NAMES = ("HEAD", "main", "master")
|
||||
DELETE_MERGED_KEY = r"^branch\..*\.deletemerged$"
|
||||
SHARED_STORES = ("refs", "packed-refs", "reftable", "logs", "logs/refs")
|
||||
WALKED_STORES = ("refs", "reftable", "logs/refs")
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -136,6 +156,10 @@ class Repo:
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
items: list[Item] = field(default_factory=list)
|
||||
unsafe: list[str] = field(default_factory=list)
|
||||
refused: str | None = None
|
||||
common: str = ""
|
||||
opted_out: set[str] = field(default_factory=set)
|
||||
upstreams: set[tuple[str, str]] = field(default_factory=set)
|
||||
|
||||
|
||||
def host_pid_namespace() -> bool:
|
||||
@@ -149,12 +173,91 @@ def main_repo_root(cwd: str) -> str:
|
||||
return os.path.dirname(_common_dir(cwd))
|
||||
|
||||
|
||||
def local_repo_root(cwd: str) -> str:
|
||||
"""
|
||||
Resolve the main worktree of the repository cwd belongs to, for scope
|
||||
`local`.
|
||||
|
||||
Args:
|
||||
cwd: a directory inside a checkout, also of a submodule or a
|
||||
repository with a separate git dir.
|
||||
|
||||
Returns:
|
||||
`git rev-parse --show-toplevel` when cwd is in the main worktree,
|
||||
else the first `git worktree list` entry; either way of cwd's own
|
||||
repository.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when that root's git common dir is not cwd's, when
|
||||
cwd's git dir is not its repository's own (see _own_git_dir),
|
||||
when either is no repository, or when git output is not UTF-8.
|
||||
"""
|
||||
try:
|
||||
with strict_env():
|
||||
common, git_dir = _own_git_dir(cwd)
|
||||
in_main = git_dir == common
|
||||
root = (in_main and _toplevel(cwd)) or _worktrees(cwd)[0].path
|
||||
root_common = os.path.realpath(_common_dir(root))
|
||||
except UnicodeDecodeError as exc:
|
||||
raise GitBaseError(f"{NOT_UTF8} for {cwd!r}") from exc
|
||||
except OSError as exc:
|
||||
raise GitBaseError(f"{cwd}: {exc}") from exc
|
||||
if root_common != common:
|
||||
raise GitBaseError(
|
||||
f"{cwd}: main worktree {root} belongs to another repository than {common}"
|
||||
)
|
||||
return root
|
||||
|
||||
|
||||
def _own_git_dir(cwd: str) -> tuple[str, str]:
|
||||
"""
|
||||
Resolve cwd's git common dir and git dir, refusing a foreign git dir.
|
||||
|
||||
Args:
|
||||
cwd: a directory inside a checkout or a git dir.
|
||||
|
||||
Returns:
|
||||
The realpaths of `git rev-parse --git-common-dir` and
|
||||
`--absolute-git-dir`.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when the git dir is neither the common dir nor directly
|
||||
under `<common>/worktrees/`.
|
||||
"""
|
||||
common = os.path.realpath(_common_dir(cwd))
|
||||
git_dir = os.path.realpath(_git(["rev-parse", "--absolute-git-dir"], cwd))
|
||||
if git_dir != common and os.path.dirname(git_dir) != os.path.join(
|
||||
common, "worktrees"
|
||||
):
|
||||
raise GitBaseError(
|
||||
f"{cwd}: git dir {git_dir} is neither {common} nor directly under "
|
||||
f"{common}/worktrees"
|
||||
)
|
||||
return common, git_dir
|
||||
|
||||
|
||||
def _toplevel(cwd: str) -> str:
|
||||
"""
|
||||
Read the work tree root of cwd's checkout.
|
||||
|
||||
Args:
|
||||
cwd: a directory inside a checkout.
|
||||
|
||||
Returns:
|
||||
`git rev-parse --show-toplevel`, or "" in a bare repository.
|
||||
"""
|
||||
try:
|
||||
return _git(["rev-parse", "--show-toplevel"], cwd)
|
||||
except GitRunError:
|
||||
return ""
|
||||
|
||||
|
||||
def _git(args: list[str], cwd: str) -> str:
|
||||
return run(args, cwd=cwd, scan=True)
|
||||
|
||||
|
||||
def _common_dir(cwd: str) -> str:
|
||||
return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
|
||||
def _config_read(args: list[str], cwd: str, view: str) -> str:
|
||||
return run(args, cwd=cwd, scan=True, config_view=view)
|
||||
|
||||
|
||||
def _docker(args: list[str]) -> str:
|
||||
@@ -415,6 +518,26 @@ def human_size(size: int) -> str:
|
||||
return f"{value / 1024:.1f}T"
|
||||
|
||||
|
||||
def _needs_forge(item: Item, tree: Worktree | None) -> bool:
|
||||
"""
|
||||
Whether deciding the item needs the forge's PR and protection facts.
|
||||
|
||||
Args:
|
||||
item: the classified item.
|
||||
tree: the worktree holding its branch, or None.
|
||||
|
||||
Returns:
|
||||
False only for a branch that no worktree holds, without upstream and
|
||||
remote branch, merged into the default by ancestry; True otherwise.
|
||||
"""
|
||||
return not (
|
||||
tree is None
|
||||
and item.merged_by == "ancestor"
|
||||
and item.upstream is None
|
||||
and not item.remotes
|
||||
)
|
||||
|
||||
|
||||
def _skip(
|
||||
repo: Repo,
|
||||
item: Item,
|
||||
@@ -425,12 +548,14 @@ def _skip(
|
||||
number = repo.forge.open_heads.get(item.branch) if item.branch else None
|
||||
if number:
|
||||
return f"open-pr #{number}"
|
||||
if repo.forge.unavailable:
|
||||
if repo.forge.unavailable and _needs_forge(item, tree):
|
||||
return "forge unavailable"
|
||||
if tree is None:
|
||||
return None
|
||||
if tree.main:
|
||||
return "checked out in main worktree"
|
||||
if repo.scope == "local":
|
||||
return f"checked out in worktree {tree.path}"
|
||||
if not checkout:
|
||||
return "worktree checkout missing"
|
||||
if repo.containers is None:
|
||||
@@ -533,7 +658,7 @@ def _build(
|
||||
tree: Worktree | None,
|
||||
snapshot: Snapshot,
|
||||
) -> Item:
|
||||
local, remote, cwds, tracking, registrations = snapshot
|
||||
local, remote, cwds, tracking = snapshot[:4]
|
||||
upstream, ahead, behind, gone = tracking.get(
|
||||
branch or "", (None, None, None, False)
|
||||
)
|
||||
@@ -627,7 +752,7 @@ def _build(
|
||||
and (time.time() - item.last_activity) / 3600 < repo.min_age
|
||||
):
|
||||
item.skip = f"younger than {repo.min_age:g} h"
|
||||
item.actions = _actions(repo, item, tree, checkout, dirty, registrations)
|
||||
item.actions = _actions(repo, item, tree, checkout, dirty, snapshot)
|
||||
if repo.unsafe:
|
||||
item.actions = [a for a in item.actions if not a.startswith("remote-branch:")]
|
||||
return item
|
||||
@@ -639,8 +764,11 @@ def _actions(
|
||||
tree: Worktree | None,
|
||||
checkout: bool,
|
||||
dirty: int,
|
||||
registrations: Registrations,
|
||||
snapshot: Snapshot,
|
||||
) -> list[str]:
|
||||
if repo.scope == "local":
|
||||
return _local_actions(repo, item, tree, snapshot[5])
|
||||
registrations = snapshot[4]
|
||||
tree_part: list[str] = []
|
||||
if tree:
|
||||
if (
|
||||
@@ -679,6 +807,31 @@ def _actions(
|
||||
return actions
|
||||
|
||||
|
||||
def _local_actions(
|
||||
repo: Repo,
|
||||
item: Item,
|
||||
tree: Worktree | None,
|
||||
held: Callable[[], dict[str, str]],
|
||||
) -> list[str]:
|
||||
if item.state != "merged-clean" or not item.local_sha or tree is not None:
|
||||
return []
|
||||
hold = held().get(item.branch)
|
||||
if hold:
|
||||
item.skip = item.skip or hold
|
||||
return []
|
||||
return _ancestor_action(repo, item)
|
||||
|
||||
|
||||
def _ancestor_action(repo: Repo, item: Item) -> list[str]:
|
||||
targets = [repo.default, *repo.lines]
|
||||
if any(_is_ancestor(item.local_sha, ref, repo.repo) for ref in targets):
|
||||
return ["local-branch"]
|
||||
item.skip = item.skip or (
|
||||
f"merged by {item.merged_by}, tip is no ancestor of {', '.join(targets)}"
|
||||
)
|
||||
return []
|
||||
|
||||
|
||||
def _snapshot(repo: Repo) -> tuple[list[Worktree], Snapshot]:
|
||||
local, remote, tracking = _refs(repo.repo, repo.remotes)
|
||||
cwds = _process_cwds() if repo.host_ns else {}
|
||||
@@ -688,6 +841,7 @@ def _snapshot(repo: Repo) -> tuple[list[Worktree], Snapshot]:
|
||||
cwds,
|
||||
tracking,
|
||||
_registrations(repo.repo),
|
||||
cache(lambda: _held_branches(repo.repo)),
|
||||
)
|
||||
|
||||
|
||||
@@ -695,12 +849,15 @@ def _items(repo: Repo) -> list[Item]:
|
||||
trees, snapshot = _snapshot(repo)
|
||||
local, remote, *_ = snapshot
|
||||
by_branch = {t.branch: t for t in trees if t.branch}
|
||||
names = (
|
||||
sorted(by_branch)
|
||||
if repo.scope == "worktree"
|
||||
else sorted(set(local) | set(remote) | set(by_branch))
|
||||
)
|
||||
items = [_build(repo, name, by_branch.get(name), snapshot) for name in names]
|
||||
names = {
|
||||
"worktree": set(by_branch),
|
||||
"local": set(local) | set(by_branch),
|
||||
}.get(repo.scope, set(local) | set(remote) | set(by_branch))
|
||||
items = [
|
||||
_build(repo, name, by_branch.get(name), snapshot) for name in sorted(names)
|
||||
]
|
||||
if repo.scope == "local":
|
||||
return items
|
||||
items += [
|
||||
_build(repo, None, tree, snapshot)
|
||||
for tree in trees
|
||||
@@ -727,6 +884,66 @@ def _stale(repo_root: str) -> list[Item]:
|
||||
return items
|
||||
|
||||
|
||||
def _default_remote(remotes: list[str]) -> str | None:
|
||||
"""
|
||||
Pick the one remote whose default scope `local` may measure against.
|
||||
|
||||
Args:
|
||||
remotes: the configured remote names.
|
||||
|
||||
Returns:
|
||||
origin when configured, else the only remote, else None.
|
||||
"""
|
||||
if "origin" in remotes:
|
||||
return "origin"
|
||||
return remotes[0] if len(remotes) == 1 else None
|
||||
|
||||
|
||||
def _resolve_within(refs: dict[str, str], ref: str) -> str | None:
|
||||
"""
|
||||
Follow a ref's symref chain without leaving a set of refs.
|
||||
|
||||
Args:
|
||||
refs: refs under one prefix, as _symbolic lists them.
|
||||
ref: the full ref name to resolve.
|
||||
|
||||
Returns:
|
||||
The plain ref the chain ends at, or None when a step leaves refs,
|
||||
loops or ref is missing.
|
||||
"""
|
||||
seen: set[str] = set()
|
||||
while ref in refs and ref not in seen:
|
||||
seen.add(ref)
|
||||
if not refs[ref]:
|
||||
return ref
|
||||
ref = refs[ref]
|
||||
return None
|
||||
|
||||
|
||||
def _remote_default(repo_root: str, remotes: list[str]) -> str | None:
|
||||
"""
|
||||
Pick the remote-tracking ref that scope `local` measures merges against.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
remotes: the configured remote names.
|
||||
|
||||
Returns:
|
||||
For the remote _default_remote picks, the plain ref its HEAD, else
|
||||
main, else master resolves to while every step stays inside
|
||||
`refs/remotes/<remote>/`; else None.
|
||||
"""
|
||||
remote = _default_remote(remotes)
|
||||
if remote is None:
|
||||
return None
|
||||
refs = _symbolic(repo_root, f"refs/remotes/{remote}")
|
||||
for name in DEFAULT_NAMES:
|
||||
target = _resolve_within(refs, f"refs/remotes/{remote}/{name}")
|
||||
if target:
|
||||
return target
|
||||
return None
|
||||
|
||||
|
||||
def _lines(
|
||||
repo_root: str, refs: list[str], remotes: list[str], warnings: list[str]
|
||||
) -> tuple[dict[str, tuple[str, set[str]]], set[str]]:
|
||||
@@ -758,6 +975,116 @@ def _lines(
|
||||
return lines, names
|
||||
|
||||
|
||||
def _branch_names(repo_root: str, ref: str, remotes: list[str]) -> set[str]:
|
||||
"""
|
||||
Name the branch a merged-into ref is, whatever form it was given in.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
ref: the ref as given, e.g. `refs/heads/x`, `x` or `origin/x`.
|
||||
remotes: the configured remote names.
|
||||
|
||||
Returns:
|
||||
`x` for a ref that resolves to `refs/heads/x` or
|
||||
`refs/remotes/<remote>/x`, else nothing.
|
||||
"""
|
||||
out = _git(["rev-parse", "--symbolic-full-name", END_OF_OPTIONS, ref], repo_root)
|
||||
full = out.splitlines()[-1] if out else ""
|
||||
prefixes = ["refs/heads/", *(f"refs/remotes/{r}/" for r in remotes)]
|
||||
return {full.removeprefix(p) for p in prefixes if full.startswith(p)}
|
||||
|
||||
|
||||
def _raise(exc: OSError) -> None:
|
||||
raise exc
|
||||
|
||||
|
||||
def _shared_refs(repo_root: str) -> str:
|
||||
"""
|
||||
Detect a ref store that other checkouts share through a symlink.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
|
||||
Returns:
|
||||
The refusal reason when `refs`, `packed-refs`, `reftable`, `logs` or
|
||||
`logs/refs` in the git common dir is a symlink (git-new-workdir), or
|
||||
any entry below `refs/`, `reftable/` or `logs/refs/` is, else "".
|
||||
|
||||
Raises:
|
||||
OSError: when a directory below them cannot be listed.
|
||||
"""
|
||||
common = _common_dir(repo_root)
|
||||
shared = [
|
||||
name for name in SHARED_STORES if os.path.islink(os.path.join(common, name))
|
||||
]
|
||||
stores = [] if shared else [os.path.join(common, s) for s in WALKED_STORES]
|
||||
for store in filter(os.path.isdir, stores):
|
||||
for parent, dirs, files in os.walk(store, onerror=_raise):
|
||||
shared += [
|
||||
os.path.relpath(os.path.join(parent, name), common)
|
||||
for name in sorted(dirs + files)
|
||||
if os.path.islink(os.path.join(parent, name))
|
||||
]
|
||||
if not shared:
|
||||
return ""
|
||||
return (
|
||||
f"refused: {', '.join(shared)} in {common} is a symlink, so checkouts "
|
||||
"sharing these refs hold branches git cannot list"
|
||||
)
|
||||
|
||||
|
||||
def _refused(
|
||||
repo_root: str,
|
||||
containers: list[Container] | None,
|
||||
host_ns: bool,
|
||||
reason: str,
|
||||
warnings: list[str],
|
||||
*,
|
||||
scope: str,
|
||||
sizes: bool,
|
||||
min_age: float | None,
|
||||
activity: bool,
|
||||
**_options: object,
|
||||
) -> Repo:
|
||||
"""
|
||||
Build a repository that scope `local` refuses: no items, nothing deleted.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
containers: as plan_repo takes them.
|
||||
host_ns: as plan_repo takes it.
|
||||
reason: why the repository is refused; also appended to warnings.
|
||||
warnings: warnings gathered so far.
|
||||
scope: the planned scope.
|
||||
sizes: as plan_repo takes it.
|
||||
min_age: as plan_repo takes it.
|
||||
activity: as plan_repo takes it.
|
||||
_options: the other plan_repo options, unused.
|
||||
|
||||
Returns:
|
||||
The refused repository.
|
||||
"""
|
||||
return Repo(
|
||||
repo=repo_root,
|
||||
default="",
|
||||
remotes=[],
|
||||
protected=set(),
|
||||
first_parent=set(),
|
||||
urls={},
|
||||
forge=ForgeFacts(),
|
||||
containers=containers,
|
||||
host_ns=host_ns,
|
||||
lines={},
|
||||
sizes=sizes,
|
||||
min_age=min_age,
|
||||
scope=scope,
|
||||
activity=activity,
|
||||
hooks={},
|
||||
warnings=[*warnings, reason],
|
||||
refused=reason,
|
||||
)
|
||||
|
||||
|
||||
def plan_repo(
|
||||
repo_root: str,
|
||||
containers: list[Container] | None,
|
||||
@@ -795,6 +1122,8 @@ def plan_repo(
|
||||
"""
|
||||
if scope not in SCOPES:
|
||||
raise ValueError(f"unknown scope {scope!r}")
|
||||
if scope == "local":
|
||||
_own_git_dir(repo_root)
|
||||
warnings: list[str] = []
|
||||
unsafe = local_config(repo_root, UNSAFE_CONFIG)
|
||||
if unsafe:
|
||||
@@ -834,9 +1163,25 @@ def plan_repo(
|
||||
)
|
||||
except GitRunError:
|
||||
continue
|
||||
default = next(iter(heads.values()), None) or resolve_base_branch(
|
||||
"main", "master", cwd=repo_root, scan=True
|
||||
)
|
||||
if scope == "local":
|
||||
default = _remote_default(repo_root, remotes)
|
||||
reason = _shared_refs(repo_root) or (NO_REMOTE_DEFAULT if not default else "")
|
||||
if reason:
|
||||
return _refused(
|
||||
repo_root,
|
||||
containers,
|
||||
host_ns,
|
||||
reason,
|
||||
warnings,
|
||||
scope=scope,
|
||||
sizes=sizes,
|
||||
min_age=min_age,
|
||||
activity=activity,
|
||||
)
|
||||
else:
|
||||
default = next(iter(heads.values()), None) or resolve_base_branch(
|
||||
"main", "master", cwd=repo_root, scan=True
|
||||
)
|
||||
head_names = {ref[len(remote) + 1 :] for remote, ref in heads.items()}
|
||||
|
||||
urls = {r: _git(["remote", "get-url", "--", r], repo_root) for r in remotes}
|
||||
@@ -844,6 +1189,10 @@ def plan_repo(
|
||||
if forge.unavailable:
|
||||
warnings.append(f"forge unavailable: {forge.unavailable}")
|
||||
lines, line_names = _lines(repo_root, merged_into, remotes, warnings)
|
||||
if scope == "local":
|
||||
line_names |= {
|
||||
name for ref in lines for name in _branch_names(repo_root, ref, remotes)
|
||||
}
|
||||
|
||||
repo = Repo(
|
||||
repo=repo_root,
|
||||
@@ -875,9 +1224,140 @@ def plan_repo(
|
||||
unsafe=unsafe,
|
||||
)
|
||||
repo.items = _items(repo)
|
||||
if scope == "local":
|
||||
repo.opted_out = _opted_out(repo_root)
|
||||
repo.upstreams = _local_upstreams(repo_root)
|
||||
return repo
|
||||
|
||||
|
||||
def _opted_out(repo_root: str) -> set[str]:
|
||||
"""
|
||||
Find the branches whose `branch.<name>.deleteMerged` is false.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
|
||||
Returns:
|
||||
Each branch that `git --git-dir=<dir> config` sets false in, for each
|
||||
of _git_dirs (so also config.worktree and includeIf onbranch) in each
|
||||
of CONFIG_VIEWS, so the union of what the caller's config variables
|
||||
and the default system and global config give.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when git cannot read one of these configs.
|
||||
"""
|
||||
names: set[str] = set()
|
||||
for git_dir in _git_dirs(repo_root):
|
||||
for view in CONFIG_VIEWS:
|
||||
try:
|
||||
out = _config_read(
|
||||
[
|
||||
f"--git-dir={git_dir}",
|
||||
"config",
|
||||
"--null",
|
||||
"--type=bool",
|
||||
"--get-regexp",
|
||||
DELETE_MERGED_KEY,
|
||||
],
|
||||
repo_root,
|
||||
view,
|
||||
)
|
||||
except GitRunError as exc:
|
||||
if exc.returncode == 1:
|
||||
continue
|
||||
raise
|
||||
for record in out.split("\0"):
|
||||
key, _, value = record.partition("\n")
|
||||
if value == "false":
|
||||
names.add(key.removeprefix("branch.").removesuffix(".deletemerged"))
|
||||
return names
|
||||
|
||||
|
||||
def _local_upstreams(repo_root: str) -> set[tuple[str, str]]:
|
||||
"""
|
||||
Read each local branch's upstream as git resolves it in any worktree.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
|
||||
Returns:
|
||||
(branch, upstream branch) for each `%(upstream)` under `refs/heads/`
|
||||
that `git --git-dir=<dir> for-each-ref` gives for any of _git_dirs in
|
||||
any of CONFIG_VIEWS.
|
||||
"""
|
||||
pairs: set[tuple[str, str]] = set()
|
||||
for git_dir in _git_dirs(repo_root):
|
||||
for view in CONFIG_VIEWS:
|
||||
out = _config_read(
|
||||
[
|
||||
f"--git-dir={git_dir}",
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(upstream)",
|
||||
"refs/heads",
|
||||
],
|
||||
repo_root,
|
||||
view,
|
||||
)
|
||||
for line in out.splitlines():
|
||||
ref, _, upstream = line.partition("\0")
|
||||
if upstream.startswith("refs/heads/"):
|
||||
pairs.add(
|
||||
(
|
||||
ref.removeprefix("refs/heads/"),
|
||||
upstream.removeprefix("refs/heads/"),
|
||||
)
|
||||
)
|
||||
return pairs
|
||||
|
||||
|
||||
def _keep_by_config(repo: Repo, chosen: Callable[[Item], bool]) -> None:
|
||||
"""
|
||||
Keep, as `git branch --delete-merged` does, each branch whose
|
||||
`branch.<name>.deleteMerged` is false and each local upstream of a branch
|
||||
that stays, also of one kept so or one the filters leave out.
|
||||
|
||||
Args:
|
||||
repo: a repository planned with scope `local`; each kept item that
|
||||
would be deleted loses its actions and gets the reason as its skip.
|
||||
chosen: the --branch and --exclude filter; only an eligible chosen
|
||||
item is deleted, every other branch stays.
|
||||
"""
|
||||
pending = {
|
||||
item.branch: item for item in repo.items if item.eligible and chosen(item)
|
||||
}
|
||||
for name, reason in _config_keeps(
|
||||
repo.opted_out, repo.upstreams, set(pending)
|
||||
).items():
|
||||
item = pending[name]
|
||||
item.actions = []
|
||||
item.skip = item.skip or reason
|
||||
|
||||
|
||||
def _config_keeps(
|
||||
opted_out: set[str], upstreams: set[tuple[str, str]], pending: set[str]
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
Args:
|
||||
opted_out: branches whose `branch.<name>.deleteMerged` is false.
|
||||
upstreams: (branch, local upstream branch) pairs.
|
||||
pending: the branches that would be deleted; every other stays.
|
||||
|
||||
Returns:
|
||||
Pending branch -> keep reason, for each one opted out or the local
|
||||
upstream of a branch that stays, also of one kept so.
|
||||
"""
|
||||
reasons = {name: f"kept: branch.{name}.deleteMerged is false" for name in opted_out}
|
||||
leaving = set(pending)
|
||||
while True:
|
||||
for child, parent in sorted(upstreams):
|
||||
if child not in leaving:
|
||||
reasons.setdefault(parent, f"kept: local upstream of {child}")
|
||||
kept = reasons.keys() & leaving
|
||||
if not kept:
|
||||
return {name: reasons[name] for name in pending - leaving}
|
||||
leaving -= kept
|
||||
|
||||
|
||||
def _pins(
|
||||
hooks: dict[str, dict[str, list[str]]], repo_root: str, warnings: list[str]
|
||||
) -> dict[str, list[str]]:
|
||||
@@ -985,6 +1465,32 @@ def _changed_by_hook(repo: Repo, item: Item) -> str | None:
|
||||
return _busy(_process_cwds(), path) if repo.host_ns else None
|
||||
|
||||
|
||||
def _drop_branch_config(repo_root: str, branch: str) -> str | None:
|
||||
"""
|
||||
Remove a deleted branch's `branch.<name>` section, as `branch -D` does,
|
||||
from the config file in the repository's own git common dir.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
branch: the deleted branch; a missing section is no error.
|
||||
|
||||
Returns:
|
||||
None, or a note why the section was kept, e.g. a locked config.
|
||||
"""
|
||||
config = os.path.join(_common_dir(repo_root), "config")
|
||||
try:
|
||||
_git(
|
||||
["config", "--file", config, "--remove-section", f"branch.{branch}"],
|
||||
repo_root,
|
||||
)
|
||||
except GitRunError as exc:
|
||||
stderr = (exc.stderr or "").strip()
|
||||
if "no such section" in stderr.lower():
|
||||
return None
|
||||
return f"config branch.{branch} kept: {(stderr or str(exc)).splitlines()[0]}"
|
||||
return None
|
||||
|
||||
|
||||
def execute(repo: Repo, item: Item) -> None:
|
||||
fresh = _rebuild(repo, item)
|
||||
if _fingerprint(fresh) != _fingerprint(item):
|
||||
@@ -1100,6 +1606,153 @@ def _render(
|
||||
)
|
||||
|
||||
|
||||
def _plan(
|
||||
root: str, containers: list[Container] | None, host_ns: bool, options: dict
|
||||
) -> Repo:
|
||||
"""
|
||||
Plan one repository; under scope `local` refuse, instead of raising, one
|
||||
that git or the filesystem fails on or whose git output is not UTF-8.
|
||||
|
||||
Args:
|
||||
root: main worktree root of the repository.
|
||||
containers: as plan_repo takes them.
|
||||
host_ns: as plan_repo takes it.
|
||||
options: the plan_repo keyword options.
|
||||
|
||||
Returns:
|
||||
The planned repository, under scope `local` with its realpath git
|
||||
common dir, or the refused one.
|
||||
"""
|
||||
if options["scope"] != "local":
|
||||
return plan_repo(root, containers, host_ns, **options)
|
||||
try:
|
||||
repo = plan_repo(root, containers, host_ns, **options)
|
||||
repo.common = os.path.realpath(_common_dir(root))
|
||||
return repo
|
||||
except UnicodeDecodeError:
|
||||
reason = NOT_UTF8
|
||||
except (GitBaseError, OSError, ValueError) as exc:
|
||||
reason = f"refused: {_describe(exc)}"
|
||||
return _refused(root, containers, host_ns, reason, [], **options)
|
||||
|
||||
|
||||
def _gone(repo: Repo) -> str:
|
||||
"""
|
||||
Check that a repository planned with scope `local` is still the one
|
||||
planned and that its targets still resolve.
|
||||
|
||||
Args:
|
||||
repo: the planned repository.
|
||||
|
||||
Returns:
|
||||
Why its remaining items must be skipped, else "".
|
||||
"""
|
||||
try:
|
||||
if os.path.realpath(_common_dir(repo.repo)) != repo.common:
|
||||
return f"repository {repo.repo} is no longer the planned one"
|
||||
gone = [
|
||||
ref
|
||||
for ref in (repo.default, *repo.lines)
|
||||
if _sha(repo.repo, f"{ref}^{{commit}}") is None
|
||||
]
|
||||
except (GitBaseError, OSError, ValueError) as exc:
|
||||
return f"repository {repo.repo} unreadable: {_describe(exc)}"
|
||||
return f"target {', '.join(gone)} is gone" if gone else ""
|
||||
|
||||
|
||||
def _delete_order(repo: Repo, items: list[Item]) -> list[Item]:
|
||||
"""
|
||||
Args:
|
||||
repo: a repository planned with scope `local`.
|
||||
items: its eligible chosen items, in plan order.
|
||||
|
||||
Returns:
|
||||
The items with each branch before its local upstream, as the plan
|
||||
read them; plan order on an upstream cycle, whose members the
|
||||
re-check of _delete_local then keeps.
|
||||
"""
|
||||
by_name = {item.branch: item for item in items}
|
||||
graph: dict[str, set[str]] = {name: set() for name in by_name}
|
||||
for child, parent in sorted(repo.upstreams):
|
||||
if child != parent and child in by_name and parent in by_name:
|
||||
graph[parent].add(child)
|
||||
try:
|
||||
return [by_name[name] for name in TopologicalSorter(graph).static_order()]
|
||||
except CycleError:
|
||||
return items
|
||||
|
||||
|
||||
def _delete_local(repo: Repo, item: Item) -> None:
|
||||
"""
|
||||
Args:
|
||||
repo: a repository planned with scope `local`.
|
||||
item: an eligible item, deleted after every planned branch whose
|
||||
local upstream it is; it ends done, or skipped when its holds,
|
||||
then its `deleteMerged` and the upstreams of every branch still
|
||||
present, re-read right before the delete, keep it.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when git cannot re-read the repository or the sha moved.
|
||||
OSError: when a state file cannot be read.
|
||||
ValueError: when a state file is not UTF-8.
|
||||
"""
|
||||
fresh = _rebuild(repo, item)
|
||||
if _fingerprint(fresh) != _fingerprint(item):
|
||||
item.result = f"skipped: changed since plan ({fresh.skip or fresh.reason})"
|
||||
return
|
||||
kept = _config_keeps(
|
||||
_opted_out(repo.repo), _local_upstreams(repo.repo), {item.branch}
|
||||
).get(item.branch)
|
||||
if kept:
|
||||
item.result = f"skipped: changed since plan ({kept})"
|
||||
return
|
||||
_git(
|
||||
["update-ref", "--no-deref", "-d", f"refs/heads/{item.branch}", item.local_sha],
|
||||
repo.repo,
|
||||
)
|
||||
note = _drop_branch_config(repo.repo, item.branch)
|
||||
item.result = "; ".join(["done", *([note] if note else [])])
|
||||
|
||||
|
||||
def _apply(repo: Repo, item: Item) -> None:
|
||||
"""
|
||||
Execute one planned item; under scope `local` without raising.
|
||||
|
||||
Args:
|
||||
repo: the planned repository.
|
||||
item: an eligible item; under scope `local` it ends with a done,
|
||||
failed or skipped result, skipped as _gone tells.
|
||||
"""
|
||||
if repo.scope != "local":
|
||||
execute(repo, item)
|
||||
return
|
||||
gone = _gone(repo)
|
||||
if gone:
|
||||
item.result = f"skipped: {gone}"
|
||||
return
|
||||
try:
|
||||
_delete_local(repo, item)
|
||||
except (RuntimeError, OSError, ValueError) as exc:
|
||||
item.result = f"failed: {_describe(exc)}"
|
||||
|
||||
|
||||
def _exit_code(repos: list[Repo], apply: bool) -> int:
|
||||
"""
|
||||
Settle the exit code of a cleanup run.
|
||||
|
||||
Args:
|
||||
repos: the planned and, with apply, executed repositories.
|
||||
apply: whether the plan was executed.
|
||||
|
||||
Returns:
|
||||
1 when an applied item failed, else 2 when a repository was
|
||||
refused, else 0.
|
||||
"""
|
||||
if apply and _finish(repos):
|
||||
return 1
|
||||
return 2 if any(repo.refused for repo in repos) else 0
|
||||
|
||||
|
||||
def prepare(
|
||||
repo_roots: list[str],
|
||||
include: list[str],
|
||||
@@ -1107,8 +1760,8 @@ def prepare(
|
||||
options: dict,
|
||||
) -> tuple[list[Repo], bool, Callable[[Item], bool]] | None:
|
||||
host_ns = host_pid_namespace()
|
||||
containers = list_compose_containers()
|
||||
repos = [plan_repo(root, containers, host_ns, **options) for root in repo_roots]
|
||||
containers = [] if options["scope"] == "local" else list_compose_containers()
|
||||
repos = [_plan(root, containers, host_ns, options) for root in repo_roots]
|
||||
unknown = [
|
||||
name
|
||||
for name in include
|
||||
@@ -1123,13 +1776,16 @@ def prepare(
|
||||
item.matches(n) for n in exclude
|
||||
)
|
||||
|
||||
for repo in repos:
|
||||
if repo.scope == "local":
|
||||
_keep_by_config(repo, chosen)
|
||||
return repos, host_ns, chosen
|
||||
|
||||
|
||||
def _finish(repos: list[Repo]) -> int:
|
||||
results = [item.result for repo in repos for item in repo.items if item.result]
|
||||
if any(result.startswith("done") for result in results) and any(
|
||||
repo.containers is not None for repo in repos
|
||||
repo.containers is not None and repo.scope != "local" for repo in repos
|
||||
):
|
||||
for args in (["image", "prune", "-f"], ["builder", "prune", "-f"]):
|
||||
try:
|
||||
@@ -1160,7 +1816,16 @@ def cleanup(
|
||||
scope: `worktree` removes clean worktrees whose commits are merged or
|
||||
pushed (hook, stack, checkout; the branch stays); `branch` removes
|
||||
merged branches without a worktree, local and remote; `all` does
|
||||
both in one pass.
|
||||
both in one pass; `local` deletes, with `update-ref -d` against
|
||||
the planned sha, each local branch that no worktree, rebase or
|
||||
bisect holds, that _keep_by_config does not keep, both re-checked
|
||||
right before its delete, which follows the deletes of the
|
||||
branches it is the local upstream of, and whose tip is an
|
||||
ancestor of the
|
||||
remote-tracking
|
||||
default or a merged_into line, refuses a repository without such
|
||||
a default, and reads no forge token, runs no fetch, push, docker,
|
||||
hook or prune.
|
||||
apply: execute the plan instead of only printing it.
|
||||
as_json: print the plan as JSON instead of text lines.
|
||||
include: only items whose branch or worktree path matches one of these.
|
||||
@@ -1172,9 +1837,10 @@ def cleanup(
|
||||
CLI; a worktree-fini hook runs only for a root pinned there.
|
||||
|
||||
Returns:
|
||||
0 on success, 1 when an applied item failed, 2 when refused.
|
||||
As _exit_code settles it: 1 when an applied item failed, else 2 when
|
||||
refused (also a repository scope `local` refused), else 0.
|
||||
"""
|
||||
if scope not in ("worktree", "branch", "all"):
|
||||
if scope not in ("worktree", "branch", "all", "local"):
|
||||
raise ValueError(f"unknown cleanup scope {scope!r}")
|
||||
if apply and not host_pid_namespace():
|
||||
print(REFUSAL, file=sys.stderr)
|
||||
@@ -1186,7 +1852,76 @@ def cleanup(
|
||||
"scope": scope,
|
||||
"activity": False,
|
||||
"hooks": hooks,
|
||||
"fetch": scope != "local",
|
||||
"forge_source": (lambda _urls: ForgeFacts()) if scope == "local" else None,
|
||||
}
|
||||
if scope != "local":
|
||||
return _run(repo_roots, options, include, exclude, apply, as_json)
|
||||
with strict_env():
|
||||
bad = _bad_lines(repo_roots, merged_into)
|
||||
if bad:
|
||||
print(f"Refusing: {bad}", file=sys.stderr)
|
||||
return 2
|
||||
return _run(repo_roots, options, include, exclude, apply, as_json)
|
||||
|
||||
|
||||
def _bad_lines(repo_roots: list[str], merged_into: list[str]) -> str:
|
||||
"""
|
||||
Check that every merged-into ref of scope `local` names one branch.
|
||||
|
||||
Args:
|
||||
repo_roots: main worktree roots of the repositories to scan; one git
|
||||
cannot read is left to the planning, which refuses it.
|
||||
merged_into: the refs as given.
|
||||
|
||||
Returns:
|
||||
Why a ref is refused, when in some repository it is unknown or
|
||||
`rev-parse --symbolic-full-name` does not name exactly one ref under
|
||||
`refs/heads/` or `refs/remotes/`, else "".
|
||||
"""
|
||||
for root in repo_roots:
|
||||
for ref in merged_into:
|
||||
try:
|
||||
out = _git(
|
||||
["rev-parse", "--symbolic-full-name", END_OF_OPTIONS, ref], root
|
||||
)
|
||||
except GitRunError:
|
||||
return f"--merged-into {ref} names no ref in {root}"
|
||||
except (GitBaseError, OSError, ValueError):
|
||||
break
|
||||
names = [line for line in out.splitlines() if line != END_OF_OPTIONS]
|
||||
if len(names) != 1 or not names[0].startswith(
|
||||
("refs/heads/", "refs/remotes/")
|
||||
):
|
||||
return (
|
||||
f"--merged-into {ref} is not exactly one branch or "
|
||||
f"remote-tracking ref in {root}"
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def _run(
|
||||
repo_roots: list[str],
|
||||
options: dict,
|
||||
include: list[str],
|
||||
exclude: list[str],
|
||||
apply: bool,
|
||||
as_json: bool,
|
||||
) -> int:
|
||||
"""
|
||||
Plan, print and with apply execute a cleanup, as cleanup describes it.
|
||||
|
||||
Args:
|
||||
repo_roots: main worktree roots of the repositories to scan.
|
||||
options: the plan_repo keyword options.
|
||||
include: as cleanup takes it.
|
||||
exclude: as cleanup takes it.
|
||||
apply: as cleanup takes it.
|
||||
as_json: as cleanup takes it.
|
||||
|
||||
Returns:
|
||||
2 for an unknown include, else as _exit_code settles it.
|
||||
"""
|
||||
prepared = prepare(repo_roots, include, exclude, options)
|
||||
if prepared is None:
|
||||
return 2
|
||||
@@ -1194,15 +1929,16 @@ def cleanup(
|
||||
|
||||
if apply:
|
||||
for repo in repos:
|
||||
for item in repo.items:
|
||||
if item.eligible and chosen(item):
|
||||
execute(repo, item)
|
||||
print(
|
||||
f"[{scope}] {item.branch or item.worktree}: {item.result}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
todo = [item for item in repo.items if item.eligible and chosen(item)]
|
||||
for item in _delete_order(repo, todo) if repo.scope == "local" else todo:
|
||||
_apply(repo, item)
|
||||
print(
|
||||
f"[{options['scope']}] {item.branch or item.worktree}: "
|
||||
f"{item.result}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
_render(repos, host_ns, chosen, as_json)
|
||||
return _finish(repos) if apply else 0
|
||||
return _exit_code(repos, apply)
|
||||
|
||||
|
||||
def branch_purge(
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from pkgmgr.core.git import GitRunError, run
|
||||
|
||||
HELD_FILES = (
|
||||
("rebase-merge/head-name", "rebase in progress"),
|
||||
("rebase-merge/update-refs", "rebase in progress"),
|
||||
("rebase-apply/head-name", "rebase in progress"),
|
||||
("BISECT_START", "bisect in progress"),
|
||||
)
|
||||
|
||||
|
||||
def _git(args: list[str], cwd: str) -> str:
|
||||
return run(args, cwd=cwd, scan=True)
|
||||
|
||||
|
||||
def _common_dir(cwd: str) -> str:
|
||||
return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
|
||||
|
||||
|
||||
def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
|
||||
args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix]
|
||||
out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root)
|
||||
return dict(line.split("\x00", 1) for line in out.splitlines())
|
||||
|
||||
|
||||
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
|
||||
heads: dict[str, str] = {}
|
||||
for git_dir in git_dirs:
|
||||
try:
|
||||
target = _git(
|
||||
[f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root
|
||||
)
|
||||
except GitRunError as exc:
|
||||
if exc.returncode == 1:
|
||||
continue
|
||||
raise
|
||||
if target.startswith("refs/heads/"):
|
||||
heads.setdefault(
|
||||
target.removeprefix("refs/heads/"), f"checked out in {git_dir}"
|
||||
)
|
||||
return heads
|
||||
|
||||
|
||||
def _git_dirs(repo_root: str) -> list[str]:
|
||||
common = _common_dir(repo_root)
|
||||
base = os.path.join(common, "worktrees")
|
||||
entries = sorted(os.listdir(base)) if os.path.isdir(base) else []
|
||||
return [common, *(os.path.join(base, entry) for entry in entries)]
|
||||
|
||||
|
||||
def _held_branches(repo_root: str) -> dict[str, str]:
|
||||
git_dirs = _git_dirs(repo_root)
|
||||
held: dict[str, str] = {}
|
||||
_symref_holds(repo_root, git_dirs, held)
|
||||
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
|
||||
held.setdefault(branch, reason)
|
||||
for git_dir in git_dirs:
|
||||
_state_file_holds(git_dir, held)
|
||||
return held
|
||||
|
||||
|
||||
def _symref_holds(repo_root: str, git_dirs: list[str], held: dict[str, str]) -> None:
|
||||
symrefs = _symbolic(repo_root, "refs", git_dirs[0])
|
||||
for git_dir in git_dirs[1:]:
|
||||
for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items():
|
||||
symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target
|
||||
for ref, target in symrefs.items():
|
||||
if target and ref.startswith("refs/heads/"):
|
||||
held.setdefault(
|
||||
ref.removeprefix("refs/heads/"), f"symbolic ref to {target}"
|
||||
)
|
||||
if target.startswith("refs/heads/"):
|
||||
held.setdefault(
|
||||
target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}"
|
||||
)
|
||||
|
||||
|
||||
def _state_file_holds(git_dir: str, held: dict[str, str]) -> None:
|
||||
for name, operation in HELD_FILES:
|
||||
try:
|
||||
with open(os.path.join(git_dir, name), encoding="utf-8") as fh:
|
||||
lines = fh.read().splitlines()
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
for line in lines:
|
||||
ref = line.strip().removeprefix("ref: ")
|
||||
if ref.startswith("refs/heads/") or name == "BISECT_START":
|
||||
held.setdefault(
|
||||
ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}"
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from pkgmgr.actions.mirror.io import read_mirrors_file
|
||||
from pkgmgr.actions.mirror.types import Repository
|
||||
@@ -12,20 +12,62 @@ from pkgmgr.core.version.semver import SemVer
|
||||
|
||||
from .git_tags import head_semver_tags
|
||||
from .pypi_url import parse_pypi_project_url
|
||||
from .types import PyPITarget
|
||||
|
||||
UPLOAD_URLS = {
|
||||
"pypi.org": "https://upload.pypi.org/legacy/",
|
||||
"test.pypi.org": "https://test.pypi.org/legacy/",
|
||||
}
|
||||
|
||||
|
||||
def _require_tool(module: str) -> None:
|
||||
def _child_env(repo_dir: str) -> dict[str, str]:
|
||||
"""
|
||||
Args:
|
||||
repo_dir: absolute path of the repository being published.
|
||||
|
||||
Returns:
|
||||
The environment for build and twine without pkgmgr's own variables,
|
||||
so no PKGMGR_* token reaches a build backend or an upload, and
|
||||
without PYTHONPATH entries inside repo_dir, so no repository file
|
||||
shadows build or twine.
|
||||
"""
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("PKGMGR_")}
|
||||
if "PYTHONPATH" in env:
|
||||
root = os.path.realpath(repo_dir)
|
||||
kept = [
|
||||
entry
|
||||
for entry in env["PYTHONPATH"].split(os.pathsep)
|
||||
if entry and os.path.commonpath([root, os.path.realpath(entry)]) != root
|
||||
]
|
||||
if kept:
|
||||
env["PYTHONPATH"] = os.pathsep.join(kept)
|
||||
else:
|
||||
del env["PYTHONPATH"]
|
||||
return env
|
||||
|
||||
|
||||
def _require_tool(module: str, cwd: str, env: dict[str, str]) -> None:
|
||||
"""
|
||||
Args:
|
||||
module: the Python module run with -m.
|
||||
cwd: an empty private directory, so no file of the repository
|
||||
shadows the module on sys.path.
|
||||
env: the child environment from _child_env.
|
||||
"""
|
||||
try:
|
||||
subprocess.run(
|
||||
["python", "-m", module, "--help"],
|
||||
[sys.executable, "-m", module, "--help"],
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"Required Python module '{module}' is not available. "
|
||||
f"Install it via: pip install {module}"
|
||||
f"Required Python module '{module}' is not available to "
|
||||
f"{sys.executable}. Install it via: "
|
||||
f"{sys.executable} -m pip install {module}"
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -66,22 +108,38 @@ def publish(
|
||||
print("[PREVIEW] Would build and upload to PyPI.")
|
||||
return
|
||||
|
||||
_require_tool("build")
|
||||
_require_tool("twine")
|
||||
with tempfile.TemporaryDirectory() as out:
|
||||
_upload(target, os.path.abspath(repo_dir), out, interactive, allow_prompt)
|
||||
|
||||
dist_dir = os.path.join(repo_dir, "dist")
|
||||
if os.path.isdir(dist_dir):
|
||||
shutil.rmtree(dist_dir, ignore_errors=True)
|
||||
print("[INFO] Publish completed.")
|
||||
|
||||
|
||||
def _upload(
|
||||
target: PyPITarget, repo_dir: str, out: str, interactive: bool, allow_prompt: bool
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
target: the PyPI target parsed from the mirror URL.
|
||||
repo_dir: absolute path of the repository to build.
|
||||
out: an empty private directory that receives the artifacts and is
|
||||
the working directory of every child process.
|
||||
interactive: allow interactive token resolution.
|
||||
allow_prompt: allow prompting for the token.
|
||||
"""
|
||||
env = _child_env(repo_dir)
|
||||
_require_tool("build", out, env)
|
||||
_require_tool("twine", out, env)
|
||||
|
||||
subprocess.run(
|
||||
["python", "-m", "build"],
|
||||
cwd=repo_dir,
|
||||
[sys.executable, "-m", "build", "--outdir", out, repo_dir],
|
||||
cwd=out,
|
||||
env=env,
|
||||
check=True,
|
||||
)
|
||||
|
||||
artifacts = sorted(glob.glob(os.path.join(dist_dir, "*")))
|
||||
artifacts = sorted(os.path.join(out, name) for name in os.listdir(out))
|
||||
if not artifacts:
|
||||
raise RuntimeError("No build artifacts found in dist/.")
|
||||
raise RuntimeError("No build artifacts found.")
|
||||
|
||||
resolver = TokenResolver()
|
||||
|
||||
@@ -98,15 +156,18 @@ def publish(
|
||||
),
|
||||
).token
|
||||
|
||||
env = dict(os.environ)
|
||||
env["TWINE_USERNAME"] = "__token__"
|
||||
env["TWINE_PASSWORD"] = token
|
||||
|
||||
subprocess.run(
|
||||
["python", "-m", "twine", "upload", *artifacts],
|
||||
cwd=repo_dir,
|
||||
env=env,
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"twine",
|
||||
"upload",
|
||||
"--non-interactive",
|
||||
"--repository-url",
|
||||
UPLOAD_URLS[target.host],
|
||||
*artifacts,
|
||||
],
|
||||
cwd=out,
|
||||
env={**env, "TWINE_USERNAME": "__token__", "TWINE_PASSWORD": token},
|
||||
check=True,
|
||||
)
|
||||
|
||||
print("[INFO] Publish completed.")
|
||||
@@ -8,6 +8,36 @@ try:
|
||||
except ImportError:
|
||||
import tomli as tomllib # type: ignore
|
||||
|
||||
from pkgmgr.core.version.source import dynamic_version_source, version_literal
|
||||
|
||||
|
||||
def update_module_version(
|
||||
path: str, name: str, new_version: str, preview: bool
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
path: the module file that holds the version literal.
|
||||
name: the attribute assigned the version, e.g. __version__.
|
||||
new_version: the version to write.
|
||||
preview: print the change instead of writing it.
|
||||
|
||||
Raises:
|
||||
RuntimeError: the file holds no `name = "..."` literal.
|
||||
"""
|
||||
with open(path, encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
new_content, count = version_literal(name).subn(
|
||||
lambda mm: f"{mm.group(1)}{new_version}{mm.group(3)}", content, count=1
|
||||
)
|
||||
if count == 0:
|
||||
raise RuntimeError(f"Missing {name} literal in {path}")
|
||||
if preview:
|
||||
print(f"[PREVIEW] Would update {name} in {path} to {new_version}")
|
||||
return
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(new_content)
|
||||
print(f"Updated {name} in {path} to {new_version}")
|
||||
|
||||
|
||||
def update_pyproject_version(
|
||||
pyproject_path: str, new_version: str, preview: bool = False
|
||||
@@ -23,7 +53,12 @@ def update_pyproject_version(
|
||||
print(f"[WARN] Could not read pyproject.toml: {exc}")
|
||||
return
|
||||
|
||||
project = tomllib.loads(content).get("project")
|
||||
data = tomllib.loads(content)
|
||||
project = data.get("project")
|
||||
source = dynamic_version_source(pyproject_path, data)
|
||||
if source is not None:
|
||||
update_module_version(*source, new_version, preview)
|
||||
return
|
||||
if project is None or "version" in project.get("dynamic", []):
|
||||
print("[INFO] pyproject.toml declares no static version, skipping.")
|
||||
return
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2019-2024 The Bootstrap Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -1,5 +1,9 @@
|
||||
{% set status_letters = {"added": "A", "deleted": "D", "modified": "M", "renamed": "R", "copied": "C", "untracked": "U"} %}
|
||||
{% set signs = {"add": "+", "del": "-", "ctx": "", "meta": ""} %}
|
||||
{% set icon_paths = {
|
||||
"arrows-expand": "M1 8a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 8M7.646.146a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 1.707V5.5a.5.5 0 0 1-1 0V1.707L6.354 2.854a.5.5 0 1 1-.708-.708zM8 10a.5.5 0 0 1 .5.5v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 0 1 .708-.708L7.5 14.293V10.5A.5.5 0 0 1 8 10",
|
||||
"arrows-collapse": "M1 8a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 8m7-8a.5.5 0 0 1 .5.5v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 1 1 .708-.708L7.5 4.293V.5A.5.5 0 0 1 8 0m-.5 11.707-1.146 1.147a.5.5 0 0 1-.708-.708l2-2a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 11.707V15.5a.5.5 0 0 1-1 0z",
|
||||
} %}
|
||||
{% set style %}
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
@@ -93,6 +97,7 @@ input[type="search"] { width: 260px; max-width: 100%; padding: 5px 10px; border:
|
||||
input[type="search"]:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
|
||||
button { padding: 5px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--subtle); color: var(--text); font: 500 13px var(--sans); cursor: pointer; }
|
||||
button:hover { border-color: var(--muted); }
|
||||
button.icon { display: inline-flex; align-items: center; justify-content: center; padding: 6px 8px; }
|
||||
main { padding-top: 24px; padding-bottom: 80px; }
|
||||
.group { margin-bottom: 36px; }
|
||||
h2 { display: flex; flex-wrap: wrap; align-items: baseline; gap: 12px; margin: 0 0 12px; font-size: 17px; font-weight: 600; }
|
||||
@@ -187,6 +192,7 @@ details.commit > summary { padding: 10px 14px; }
|
||||
})();
|
||||
{% endset %}
|
||||
{% macro stat(added, removed) %}<span class="stat"><span class="add">+{{ added }}</span><span class="del">−{{ removed }}</span></span>{% endmacro %}
|
||||
{% macro icon(name) %}<svg class="bi bi-{{ name }}" width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true" focusable="false"><path fill-rule="evenodd" d="{{ icon_paths[name] }}"/></svg>{% endmacro %}
|
||||
{% macro plural(count, word) %}{{ count }} {{ word }}{{ "" if count == 1 else "s" }}{% endmacro %}
|
||||
{% macro file_block(file, open) %}
|
||||
<details class="file" id="{{ file.anchor }}" data-path="{{ file.search }}"{% if open %} open{% endif %}>
|
||||
@@ -282,8 +288,8 @@ details.commit > summary { padding: 10px 14px; }
|
||||
<div class="spacer"></div>
|
||||
<input id="filter" type="search" placeholder="Filter files by path ( / )" autocomplete="off" spellcheck="false" aria-label="Filter files by path">
|
||||
<span id="filter-count" class="muted"></span>
|
||||
<button type="button" id="expand-all">Expand all</button>
|
||||
<button type="button" id="collapse-all">Collapse all</button>
|
||||
<button type="button" id="expand-all" class="icon" title="Expand all" aria-label="Expand all">{{ icon("arrows-expand") }}</button>
|
||||
<button type="button" id="collapse-all" class="icon" title="Collapse all" aria-label="Collapse all">{{ icon("arrows-collapse") }}</button>
|
||||
</div>
|
||||
</nav>
|
||||
<main>
|
||||
|
||||
@@ -11,7 +11,7 @@ from pkgmgr.actions.branch import (
|
||||
open_branch,
|
||||
tree,
|
||||
)
|
||||
from pkgmgr.actions.branch.gc import main_repo_root
|
||||
from pkgmgr.actions.branch.gc import local_repo_root, main_repo_root
|
||||
from pkgmgr.cli.context import CLIContext
|
||||
from pkgmgr.core.git.errors import GitBaseError
|
||||
from pkgmgr.core.repository.dir import get_repo_dir
|
||||
@@ -60,14 +60,23 @@ def refresh_tree(roots: list[str]) -> None:
|
||||
print(f"WARN tree file not rewritten for {root}: {exc}", file=sys.stderr)
|
||||
|
||||
|
||||
def scan_repo_roots(args, ctx: CLIContext) -> list[str]:
|
||||
def scan_repo_roots(args, ctx: CLIContext, local: bool = False) -> list[str]:
|
||||
"""
|
||||
Resolve the repositories a scan covers: the current one, or every
|
||||
pkgmgr-managed one with --all. Exits with 2 outside a repository.
|
||||
|
||||
Args:
|
||||
args: parsed arguments; `all` selects every managed repository.
|
||||
ctx: CLI context.
|
||||
local: resolve the current repository as scope `local` does, also in
|
||||
a submodule or with a separate git dir, refusing a mismatch.
|
||||
|
||||
Returns:
|
||||
The main worktree roots to scan.
|
||||
"""
|
||||
if not args.all:
|
||||
try:
|
||||
return [main_repo_root(".")]
|
||||
return [(local_repo_root if local else main_repo_root)(".")]
|
||||
except GitBaseError as exc:
|
||||
print(f"Not inside a git repository: {exc}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
@@ -84,7 +93,7 @@ def scan_options(args) -> dict:
|
||||
|
||||
|
||||
def run_cleanup(args, ctx: CLIContext, scope: str) -> None:
|
||||
roots = scan_repo_roots(args, ctx)
|
||||
roots = scan_repo_roots(args, ctx, local=scope == "local")
|
||||
code = cleanup(
|
||||
roots,
|
||||
scope=scope,
|
||||
@@ -94,7 +103,7 @@ def run_cleanup(args, ctx: CLIContext, scope: str) -> None:
|
||||
hooks=pinned_hooks(ctx),
|
||||
**scan_options(args),
|
||||
)
|
||||
if args.apply:
|
||||
if args.apply and scope != "local":
|
||||
refresh_tree(roots)
|
||||
sys.exit(code)
|
||||
|
||||
@@ -107,8 +116,9 @@ def handle_branch(args, ctx: CLIContext) -> None:
|
||||
- pkgmgr branch open [<name>] [--base <branch>]
|
||||
- pkgmgr branch close [<name>] [--base <branch>] [--force|-f]
|
||||
- pkgmgr branch drop [<name>] [--base <branch>] [--force|-f]
|
||||
- pkgmgr branch cleanup [--apply] [--json] [--all] [--branch N]... [--exclude N]...
|
||||
[--merged-into REF]... [--sizes] [--min-age HOURS]
|
||||
- pkgmgr branch cleanup [--apply] [--json] [--local] [--all] [--branch N]...
|
||||
[--exclude N]... [--merged-into REF]... [--sizes]
|
||||
[--min-age HOURS]
|
||||
- pkgmgr branch purge [--all] [--branch N]... [--exclude N]...
|
||||
[--merged-into REF]... [--sizes] [--min-age HOURS]
|
||||
- pkgmgr branch tree [--format json|yaml] [--output FILE]
|
||||
@@ -124,7 +134,7 @@ def handle_branch(args, ctx: CLIContext) -> None:
|
||||
)
|
||||
|
||||
if args.subcommand == "cleanup":
|
||||
run_cleanup(args, ctx, "branch")
|
||||
run_cleanup(args, ctx, "local" if args.local else "branch")
|
||||
|
||||
if args.subcommand == "purge":
|
||||
roots = scan_repo_roots(args, ctx)
|
||||
|
||||
@@ -105,6 +105,41 @@ def add_branch_subparsers(
|
||||
),
|
||||
)
|
||||
add_apply_options(branch_cleanup)
|
||||
branch_cleanup.add_argument(
|
||||
"--local",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Delete only local branches whose tip is an ancestor of origin's "
|
||||
"remote-tracking default (else the only remote's) or a --merged-into "
|
||||
"REF, against the planned sha; refuse a repository without such a "
|
||||
"default, one git fails on, one whose holds cannot be read, one "
|
||||
"whose git dir is neither its common dir nor directly under "
|
||||
"<common>/worktrees/ and one with a symlink in or below refs, "
|
||||
"packed-refs, reftable or logs/refs, and still print the plan; skip "
|
||||
"a symbolic branch, a branch any symbolic ref of any worktree names, "
|
||||
"a branch a worktree, worktree registration, rebase or bisect holds, "
|
||||
"a --merged-into target, a branch with branch.<name>.deleteMerged "
|
||||
"false in any worktree's or the system config and the local "
|
||||
"upstream of a branch that stays, also of one --branch or --exclude "
|
||||
"leaves out; "
|
||||
"run git without inherited GIT_* variables but "
|
||||
"GIT_CEILING_DIRECTORIES; the keep config reads run once with the "
|
||||
"caller's GIT_CONFIG_* variables and once with the default system "
|
||||
"and passwd-home config, and either read's keep counts; read no "
|
||||
"forge token; "
|
||||
"never fetch, push, delete a remote branch, run docker or hooks, or "
|
||||
"refresh the branch tree file; exit 1 when an item failed, else 2 "
|
||||
"when a repository was refused, else 0; exit 2 without a plan when, "
|
||||
"without --all, the current directory is in no git repository, its "
|
||||
"git dir is neither its common dir nor directly under "
|
||||
"<common>/worktrees/, its main worktree belongs to another "
|
||||
"repository or its path or git output is not UTF-8, on --apply "
|
||||
"outside the host PID namespace, on a --merged-into REF that is not "
|
||||
"exactly one branch or remote-tracking ref (X~0, X^0, X@{0}, a sha), "
|
||||
"and on a --branch "
|
||||
"that matches nothing; meant for working clones"
|
||||
),
|
||||
)
|
||||
|
||||
branch_purge = branch_subparsers.add_parser(
|
||||
"purge",
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextvars
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import subprocess
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
|
||||
from .errors import GitNotRepositoryError, GitRunError
|
||||
|
||||
@@ -52,10 +57,20 @@ SCAN_UNSET = (
|
||||
"GIT_PAGER",
|
||||
"PAGER",
|
||||
)
|
||||
STRICT_KEEP = ("GIT_CEILING_DIRECTORIES",)
|
||||
CONFIG_READ_KEEP = re.compile(
|
||||
r"GIT_CONFIG_(GLOBAL|SYSTEM|PARAMETERS|COUNT|KEY_\d+|VALUE_\d+)"
|
||||
)
|
||||
CALLER_CONFIG = "caller"
|
||||
DEFAULT_CONFIG = "default"
|
||||
CONFIG_VIEWS = (CALLER_CONFIG, DEFAULT_CONFIG)
|
||||
SCAN_TIMEOUT = 60
|
||||
# ref and remote names come from repositories an agent may write: one named
|
||||
# like --output=<path> would otherwise make rev-list create that file
|
||||
END_OF_OPTIONS = "--end-of-options"
|
||||
_STRICT_ENV: contextvars.ContextVar[bool] = contextvars.ContextVar(
|
||||
"pkgmgr_git_strict_env", default=False
|
||||
)
|
||||
|
||||
|
||||
def _is_not_repo_error(stderr: str) -> bool:
|
||||
@@ -63,9 +78,61 @@ def _is_not_repo_error(stderr: str) -> bool:
|
||||
return "not a git repository" in msg
|
||||
|
||||
|
||||
def _scan_env() -> dict[str, str]:
|
||||
env = {key: value for key, value in os.environ.items() if key not in SCAN_UNSET}
|
||||
return {**env, **SCAN_ENV}
|
||||
@contextmanager
|
||||
def strict_env() -> Iterator[None]:
|
||||
token = _STRICT_ENV.set(True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_STRICT_ENV.reset(token)
|
||||
|
||||
|
||||
def _strict_keeps(key: str, caller: bool) -> bool:
|
||||
return key in STRICT_KEEP or (
|
||||
caller and CONFIG_READ_KEEP.fullmatch(key) is not None
|
||||
)
|
||||
|
||||
|
||||
def _passwd_home() -> str | None:
|
||||
try:
|
||||
return pwd.getpwuid(os.getuid()).pw_dir
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
|
||||
def _scan_env(strict: bool = False, view: str | None = None) -> dict[str, str]:
|
||||
"""
|
||||
Build the environment of a scan or strict git call.
|
||||
|
||||
Args:
|
||||
strict: drop every inherited `GIT_*` variable but STRICT_KEEP.
|
||||
view: None, CALLER_CONFIG or DEFAULT_CONFIG, as run takes it.
|
||||
|
||||
Returns:
|
||||
The inherited environment without SCAN_UNSET, plus SCAN_ENV; for a
|
||||
config view with the system config; for DEFAULT_CONFIG also without
|
||||
any `GIT_*` but STRICT_KEEP and XDG_CONFIG_HOME, HOME set to the
|
||||
passwd home (unset without a passwd entry).
|
||||
"""
|
||||
caller = view == CALLER_CONFIG
|
||||
scrub = strict or view == DEFAULT_CONFIG
|
||||
env = {
|
||||
key: value
|
||||
for key, value in os.environ.items()
|
||||
if key not in SCAN_UNSET
|
||||
and not (scrub and key.startswith("GIT_") and not _strict_keeps(key, caller))
|
||||
}
|
||||
env = {**env, **SCAN_ENV}
|
||||
if view is None:
|
||||
return env
|
||||
del env["GIT_CONFIG_NOSYSTEM"]
|
||||
if view == DEFAULT_CONFIG:
|
||||
env.pop("XDG_CONFIG_HOME", None)
|
||||
env.pop("HOME", None)
|
||||
home = _passwd_home()
|
||||
if home:
|
||||
env["HOME"] = home
|
||||
return env
|
||||
|
||||
|
||||
def run(
|
||||
@@ -75,6 +142,7 @@ def run(
|
||||
preview: bool = False,
|
||||
scan: bool = False,
|
||||
input_text: str | None = None,
|
||||
config_view: str | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
Run a Git command and return its stdout as a stripped string.
|
||||
@@ -85,9 +153,17 @@ def run(
|
||||
preview: print the command instead of running it.
|
||||
scan: read a repository an agent may have written: no fsmonitor, hook,
|
||||
pager, lazy fetch, replace object, system config or prompt, stdin
|
||||
closed, a timeout.
|
||||
closed, a timeout. Inside strict_env() every call, scan or not,
|
||||
also runs without any inherited `GIT_*` variable but
|
||||
`GIT_CEILING_DIRECTORIES`, which only narrows discovery.
|
||||
input_text: text fed to stdin, e.g. for `cat-file --batch-check`;
|
||||
replaces the closed stdin of scan mode.
|
||||
config_view: for a pure config read, the config it sees, both with
|
||||
the system config: CALLER_CONFIG also keeps, inside strict_env(),
|
||||
`GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_PARAMETERS`,
|
||||
`GIT_CONFIG_COUNT` and its `GIT_CONFIG_KEY_<n>` and
|
||||
`GIT_CONFIG_VALUE_<n>`; DEFAULT_CONFIG reads the default system
|
||||
and passwd-home global config whatever the environment says.
|
||||
|
||||
Raises GitRunError (or a subclass) if execution fails or times out.
|
||||
"""
|
||||
@@ -98,10 +174,15 @@ def run(
|
||||
print(f"[PREVIEW] Would run in {cwd!r}: {cmd_str}")
|
||||
return ""
|
||||
|
||||
strict = _STRICT_ENV.get()
|
||||
hardened: dict = (
|
||||
{"env": _scan_env(), "stdin": subprocess.DEVNULL, "timeout": SCAN_TIMEOUT}
|
||||
{
|
||||
"env": _scan_env(strict, config_view),
|
||||
"stdin": subprocess.DEVNULL,
|
||||
"timeout": SCAN_TIMEOUT,
|
||||
}
|
||||
if scan
|
||||
else {}
|
||||
else ({"env": _scan_env(True, config_view)} if strict else {})
|
||||
)
|
||||
if input_text is not None:
|
||||
hardened.pop("stdin", None)
|
||||
|
||||
@@ -9,11 +9,59 @@ import yaml
|
||||
from pkgmgr.core.repository.paths import resolve_repo_paths
|
||||
|
||||
|
||||
def version_literal(name: str) -> re.Pattern[str]:
|
||||
"""
|
||||
Args:
|
||||
name: the module attribute holding the version, e.g. __version__.
|
||||
|
||||
Returns:
|
||||
A pattern whose groups are the assignment up to the opening quote, the
|
||||
version and the closing quote of `name = "X.Y.Z"`.
|
||||
"""
|
||||
return re.compile(rf"""(?m)^(\s*{re.escape(name)}\s*=\s*["'])([^"']+)(["'])""")
|
||||
|
||||
|
||||
def dynamic_version_source(pyproject_path: str, data: dict) -> tuple[str, str] | None:
|
||||
"""
|
||||
Args:
|
||||
pyproject_path: the pyproject.toml file.
|
||||
data: its parsed content.
|
||||
|
||||
Returns:
|
||||
(module file, attribute name) that setuptools reads the version from
|
||||
when [project].dynamic lists version and [tool.setuptools.dynamic]
|
||||
sets version = {attr = "pkg.module.NAME"}, with
|
||||
[tool.setuptools].package-dir applied; None otherwise.
|
||||
"""
|
||||
project = data.get("project") or {}
|
||||
if "version" not in project.get("dynamic", []):
|
||||
return None
|
||||
setuptools = (data.get("tool") or {}).get("setuptools") or {}
|
||||
attr = ((setuptools.get("dynamic") or {}).get("version") or {}).get("attr")
|
||||
if not isinstance(attr, str) or "." not in attr:
|
||||
return None
|
||||
module, _, name = attr.rpartition(".")
|
||||
parts = module.split(".")
|
||||
dirs = setuptools.get("package-dir") or {}
|
||||
if parts[0] in dirs:
|
||||
base = os.path.join(dirs[parts[0]], *parts[1:])
|
||||
else:
|
||||
base = os.path.join(dirs.get("", ""), *parts)
|
||||
root = os.path.dirname(os.path.abspath(pyproject_path))
|
||||
for candidate in (f"{base}.py", os.path.join(base, "__init__.py")):
|
||||
path = os.path.join(root, candidate)
|
||||
if os.path.isfile(path):
|
||||
return path, name
|
||||
return None
|
||||
|
||||
|
||||
def read_pyproject_version(repo_dir: str) -> str | None:
|
||||
"""
|
||||
Read the version from pyproject.toml in repo_dir, if present.
|
||||
|
||||
Expects a PEP 621-style [project] table with a 'version' field.
|
||||
Expects a PEP 621-style [project] table with a 'version' field, or a
|
||||
dynamic version that setuptools reads from a module attribute
|
||||
(dynamic_version_source()).
|
||||
"""
|
||||
paths = resolve_repo_paths(repo_dir)
|
||||
path = paths.pyproject_toml
|
||||
@@ -30,7 +78,14 @@ def read_pyproject_version(repo_dir: str) -> str | None:
|
||||
data = tomllib.load(f)
|
||||
project = data.get("project") or {}
|
||||
version = project.get("version")
|
||||
return str(version).strip() if version else None
|
||||
if version:
|
||||
return str(version).strip()
|
||||
source = dynamic_version_source(path, data)
|
||||
if source is None:
|
||||
return None
|
||||
with open(source[0], encoding="utf-8") as f:
|
||||
match = version_literal(source[1]).search(f.read())
|
||||
return match.group(2).strip() if match else None
|
||||
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
|
||||
return None
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,17 +6,18 @@ import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc
|
||||
from pkgmgr.actions.branch import gc, gc_forge
|
||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||
from pkgmgr.cli.commands.branch import handle_branch
|
||||
from pkgmgr.cli.parser import create_parser
|
||||
from pkgmgr.core.credentials.types import NoCredentialsError
|
||||
|
||||
GIT_ENV = {
|
||||
**os.environ,
|
||||
GITHUB_URL = "https://github.com/example/demo.git"
|
||||
AUTHOR = {
|
||||
"GIT_AUTHOR_NAME": "t",
|
||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
||||
"GIT_COMMITTER_NAME": "t",
|
||||
@@ -28,7 +29,7 @@ def git(cwd: str, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=cwd,
|
||||
env=GIT_ENV,
|
||||
env={**os.environ, **AUTHOR},
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
@@ -46,7 +47,16 @@ def docker_available() -> bool:
|
||||
class GcFixture:
|
||||
def setUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self._tmp.cleanup)
|
||||
self.root = os.path.realpath(self._tmp.name)
|
||||
self.addCleanup(os.chdir, os.getcwd())
|
||||
os.chdir(self.root)
|
||||
home = os.path.join(self.root, "home")
|
||||
os.makedirs(home)
|
||||
scratch = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
patcher = patch.dict(os.environ, {**scratch, "HOME": home}, clear=True)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.origin = os.path.join(self.root, "origin.git")
|
||||
self.repo = os.path.join(self.root, "repo")
|
||||
git(self.root, "init", "--bare", "-b", "main", self.origin)
|
||||
@@ -81,9 +91,6 @@ class GcFixture:
|
||||
merged_heads={self.squashed_sha: 7}, open_heads={"wip": 3}
|
||||
)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self._tmp.cleanup()
|
||||
|
||||
def _commit(self, name: str) -> None:
|
||||
with open(os.path.join(self.repo, f"{name}.txt"), "w") as fh:
|
||||
fh.write(name)
|
||||
@@ -241,6 +248,80 @@ class TestBranchGc(GcFixture, unittest.TestCase):
|
||||
self.assertEqual(items["merged"].skip, "forge unavailable")
|
||||
self.assertIsNone(items["squashed"].merged_by)
|
||||
|
||||
def _github_without_token(self) -> None:
|
||||
git(self.repo, "branch", "local-done", "merged")
|
||||
git(self.repo, "checkout", "-b", "local-wip", "main")
|
||||
self._commit("local-wip")
|
||||
git(self.repo, "checkout", "main")
|
||||
git(self.repo, "branch", "--track", "tracked", "origin/merged")
|
||||
git(self.repo, "push", "origin", "merged:refs/heads/remote-done")
|
||||
git(self.repo, "remote", "set-url", "origin", GITHUB_URL)
|
||||
|
||||
def _cleanup_without_token(self, apply: bool) -> tuple[int, dict]:
|
||||
out = io.StringIO()
|
||||
with (
|
||||
patch.dict(os.environ, {"GIT_ALLOW_PROTOCOL": "file"}),
|
||||
patch.object(gc, "host_pid_namespace", return_value=True),
|
||||
patch.object(gc, "list_compose_containers", return_value=[]),
|
||||
patch.object(gc, "_process_cwds", return_value={}),
|
||||
patch.object(gc_forge, "TokenResolver") as resolver,
|
||||
patch.object(gc_forge, "HttpClient") as http,
|
||||
redirect_stdout(out),
|
||||
redirect_stderr(io.StringIO()),
|
||||
):
|
||||
resolver.return_value.get_token.side_effect = NoCredentialsError("none")
|
||||
code = gc.cleanup(
|
||||
[self.repo],
|
||||
scope="branch",
|
||||
apply=apply,
|
||||
as_json=True,
|
||||
include=[],
|
||||
exclude=[],
|
||||
merged_into=[],
|
||||
sizes=False,
|
||||
min_age=None,
|
||||
hooks={},
|
||||
)
|
||||
resolver.return_value.get_token.assert_called_once()
|
||||
http.assert_not_called()
|
||||
return code, json.loads(out.getvalue())["repos"][0]
|
||||
|
||||
def test_local_only_merged_branch_needs_no_forge(self) -> None:
|
||||
self._github_without_token()
|
||||
code, plan = self._cleanup_without_token(apply=False)
|
||||
items = {i["branch"]: i for i in plan["items"] if i["branch"]}
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("forge unavailable: no GitHub token (none)", plan["warnings"])
|
||||
self.assertIsNone(items["local-done"]["skip"])
|
||||
self.assertEqual(items["local-done"]["merged_by"], "ancestor")
|
||||
self.assertEqual(items["local-done"]["actions"], ["local-branch"])
|
||||
self.assertEqual(items["remote-done"]["state"], "merged-clean")
|
||||
self.assertEqual(items["tracked"]["state"], "merged-clean")
|
||||
self.assertEqual(items["local-wip"]["state"], "unmerged")
|
||||
for name in ("merged", "remote-done", "tracked", "local-wip", "squashed"):
|
||||
with self.subTest(branch=name):
|
||||
self.assertEqual(items[name]["skip"], "forge unavailable")
|
||||
|
||||
def test_apply_without_token_deletes_only_the_local_only_merged_branch(
|
||||
self,
|
||||
) -> None:
|
||||
self._github_without_token()
|
||||
before = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
||||
code, plan = self._cleanup_without_token(apply=True)
|
||||
after = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(
|
||||
[(i["branch"], i["result"]) for i in plan["items"] if i["result"]],
|
||||
[("local-done", "done")],
|
||||
)
|
||||
self.assertEqual(before - after, {"refs/heads/local-done"})
|
||||
self.assertEqual(after - before, set())
|
||||
self.assertEqual(
|
||||
git(self.origin, "branch", "--list", "remote-done"), "remote-done"
|
||||
)
|
||||
|
||||
def test_stale_metadata_is_listed_not_pruned(self) -> None:
|
||||
stub = os.path.join(self.repo, ".git", "worktrees", "stub")
|
||||
os.makedirs(stub)
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -160,6 +161,27 @@ class TestReview(unittest.TestCase):
|
||||
self.assertNotIn("big 11</td>", html)
|
||||
self.assertIn("20 more lines not shown", html)
|
||||
|
||||
def test_toolbar_buttons_are_labelled_icons(self) -> None:
|
||||
html = self._render("page.html", None, [])
|
||||
|
||||
for key, label in (("expand", "Expand all"), ("collapse", "Collapse all")):
|
||||
with self.subTest(button=key):
|
||||
button = re.search(
|
||||
rf'<button type="button" id="{key}-all"([^>]*)>(.*?)</button>',
|
||||
html,
|
||||
re.DOTALL,
|
||||
)
|
||||
self.assertIsNotNone(button)
|
||||
attrs, inner = button.groups()
|
||||
self.assertIn(f'title="{label}"', attrs)
|
||||
self.assertIn(f'aria-label="{label}"', attrs)
|
||||
self.assertRegex(
|
||||
inner, rf'^<svg class="bi bi-arrows-{key}"[^>]* aria-hidden="true"'
|
||||
)
|
||||
self.assertEqual(re.sub(r"<[^>]+>", "", inner).strip(), "")
|
||||
self.assertNotIn("<link", html)
|
||||
self.assertNotIn("<img", html)
|
||||
|
||||
def test_errors_exit_two(self) -> None:
|
||||
plain = os.path.join(self.root, "plain")
|
||||
os.makedirs(plain)
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import ExitStack, redirect_stderr, redirect_stdout
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc
|
||||
from pkgmgr.core.git import run
|
||||
|
||||
AUTHOR = {
|
||||
"GIT_AUTHOR_NAME": "t",
|
||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
||||
"GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
||||
}
|
||||
MERGED = 12
|
||||
REGISTRATIONS = 40
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("git"), "git builds the repository under test")
|
||||
class TestHeldBranchesReadOnce(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = os.path.realpath(tmp.name)
|
||||
self.addCleanup(os.chdir, os.getcwd())
|
||||
os.chdir(self.root)
|
||||
home = os.path.join(self.root, "home")
|
||||
os.makedirs(home)
|
||||
clean = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
patcher = patch.dict(os.environ, {**clean, **AUTHOR, "HOME": home}, clear=True)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.repo = os.path.join(self.root, "repo")
|
||||
self._shape()
|
||||
|
||||
def git(self, *args: str) -> str:
|
||||
return run(["-c", "commit.gpgsign=false", *args], cwd=self.repo)
|
||||
|
||||
def _write(self, path: str, text: str) -> None:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(text)
|
||||
|
||||
def _shape(self) -> None:
|
||||
origin = os.path.join(self.root, "origin.git")
|
||||
run(["init", "-q", "--bare", "-b", "main", origin], cwd=self.root)
|
||||
run(["init", "-q", "-b", "main", self.repo], cwd=self.root)
|
||||
self.git("remote", "add", "origin", origin)
|
||||
self._write(os.path.join(self.repo, "c1"), "c1")
|
||||
self.git("add", "c1")
|
||||
self.git("commit", "-q", "-m", "c1")
|
||||
self.git("checkout", "-q", "-b", "side")
|
||||
self._write(os.path.join(self.repo, "f1"), "f1")
|
||||
self.git("add", "f1")
|
||||
self.git("commit", "-q", "-m", "f1")
|
||||
f1 = self.git("rev-parse", "HEAD")
|
||||
self.git("checkout", "-q", "main")
|
||||
self.git("merge", "-q", "--no-ff", "-m", "m1", "side")
|
||||
self.git("branch", "-q", "-D", "side")
|
||||
self.git("push", "-q", "origin", "main")
|
||||
self.git("fetch", "-q", "origin")
|
||||
self.git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
|
||||
for index in range(MERGED):
|
||||
self.git("branch", f"merged-{index:03d}", f1)
|
||||
self.git("symbolic-ref", "refs/heads/alias", "refs/heads/merged-001")
|
||||
base = os.path.join(self.repo, ".git", "worktrees")
|
||||
for index in range(REGISTRATIONS):
|
||||
reg = os.path.join(base, f"wt{index:03d}")
|
||||
head = "ref: refs/heads/merged-002\n" if index == 7 else f"{f1}\n"
|
||||
self._write(os.path.join(reg, "HEAD"), head)
|
||||
self._write(os.path.join(reg, "commondir"), "../..\n")
|
||||
self._write(
|
||||
os.path.join(reg, "gitdir"), f"{self.root}/gone/wt{index:03d}/.git\n"
|
||||
)
|
||||
self._write(
|
||||
os.path.join(base, "wt011", "rebase-merge", "head-name"),
|
||||
"refs/heads/merged-003\n",
|
||||
)
|
||||
self._write(os.path.join(self.repo, ".git", "BISECT_START"), "merged-004\n")
|
||||
|
||||
def _run(self, *, cached: bool, apply: bool) -> tuple[dict, int]:
|
||||
out = io.StringIO()
|
||||
with ExitStack() as stack:
|
||||
held = stack.enter_context(
|
||||
patch.object(gc, "_held_branches", wraps=gc._held_branches)
|
||||
)
|
||||
if not cached:
|
||||
stack.enter_context(
|
||||
patch.object(gc, "cache", side_effect=lambda func: func)
|
||||
)
|
||||
stack.enter_context(
|
||||
patch.object(gc, "host_pid_namespace", return_value=True)
|
||||
)
|
||||
stack.enter_context(patch.object(gc, "_process_cwds", return_value={}))
|
||||
stack.enter_context(redirect_stdout(out))
|
||||
stack.enter_context(redirect_stderr(io.StringIO()))
|
||||
code = gc.cleanup(
|
||||
[self.repo],
|
||||
scope="local",
|
||||
apply=apply,
|
||||
as_json=True,
|
||||
include=[],
|
||||
exclude=[],
|
||||
merged_into=[],
|
||||
sizes=False,
|
||||
min_age=None,
|
||||
hooks={},
|
||||
)
|
||||
self.assertEqual(code, 0)
|
||||
return json.loads(out.getvalue()), held.call_count
|
||||
|
||||
def _items(self, plan: dict) -> dict:
|
||||
return {i["branch"]: i for i in plan["repos"][0]["items"]}
|
||||
|
||||
def test_one_read_gives_the_plan_of_one_read_per_branch(self) -> None:
|
||||
per_branch, old_reads = self._run(cached=False, apply=False)
|
||||
once, new_reads = self._run(cached=True, apply=False)
|
||||
|
||||
self.assertEqual(once, per_branch)
|
||||
self.assertEqual(new_reads, 1)
|
||||
self.assertGreaterEqual(old_reads, MERGED - 1)
|
||||
items = self._items(once)
|
||||
self.assertIn("symbolic ref", items["alias"]["skip"])
|
||||
self.assertIn("target of symbolic ref", items["merged-001"]["skip"])
|
||||
self.assertIn("checked out in", items["merged-002"]["skip"])
|
||||
self.assertIn("rebase in progress", items["merged-003"]["skip"])
|
||||
self.assertIn("bisect in progress", items["merged-004"]["skip"])
|
||||
deletable = sorted(n for n, i in items.items() if i["actions"])
|
||||
free = [0, *range(5, MERGED)]
|
||||
self.assertEqual(deletable, [f"merged-{i:03d}" for i in free])
|
||||
|
||||
def test_branch_held_after_the_plan_is_not_deleted(self) -> None:
|
||||
rebuilt: list[str] = []
|
||||
rebuild = gc._rebuild
|
||||
|
||||
def pin_before_first_recheck(*args: object) -> object:
|
||||
if not rebuilt:
|
||||
rebuilt.append(
|
||||
self.git("symbolic-ref", "refs/tags/pin", "refs/heads/merged-005")
|
||||
)
|
||||
return rebuild(*args)
|
||||
|
||||
with patch.object(gc, "_rebuild", side_effect=pin_before_first_recheck):
|
||||
plan, reads = self._run(cached=True, apply=True)
|
||||
|
||||
items = self._items(plan)
|
||||
self.assertGreater(reads, 1)
|
||||
self.assertEqual(
|
||||
items["merged-005"]["result"],
|
||||
"skipped: changed since plan (target of symbolic ref refs/tags/pin)",
|
||||
)
|
||||
self.assertIn("merged-005", self.git("for-each-ref", "refs/heads"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,124 @@
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import ExitStack
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from pkgmgr.actions.publish.workflow import publish
|
||||
|
||||
|
||||
class TestPublishWorkflowChildren(unittest.TestCase):
|
||||
def publish_with(self, mirror: str, environ: dict) -> tuple[list, str]:
|
||||
"""
|
||||
Args:
|
||||
mirror: the PyPI project URL of the mirrors file.
|
||||
environ: extra environment variables of the pkgmgr process;
|
||||
"{repo}" in a value becomes the repository directory.
|
||||
|
||||
Returns:
|
||||
The recorded subprocess.run calls and the repository directory,
|
||||
whose dist is a symlink to a foreign directory with an old
|
||||
artifact.
|
||||
"""
|
||||
repo_dir = tempfile.mkdtemp()
|
||||
foreign = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, repo_dir)
|
||||
self.addCleanup(shutil.rmtree, foreign)
|
||||
with open(os.path.join(foreign, "example-0.9.0.tar.gz"), "w"):
|
||||
pass
|
||||
os.symlink(foreign, os.path.join(repo_dir, "dist"))
|
||||
|
||||
def run(argv, *_args, **kwargs):
|
||||
if argv[2] == "build" and "--help" not in argv:
|
||||
if "--outdir" in argv:
|
||||
out = argv[argv.index("--outdir") + 1]
|
||||
else:
|
||||
out = os.path.join(kwargs["cwd"], "dist")
|
||||
with open(os.path.join(out, "example-1.0.0.tar.gz"), "w"):
|
||||
pass
|
||||
return kwargs
|
||||
|
||||
module = "pkgmgr.actions.publish.workflow"
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(
|
||||
patch(f"{module}.read_mirrors_file", return_value={"pypi": mirror})
|
||||
)
|
||||
stack.enter_context(
|
||||
patch(f"{module}.head_semver_tags", return_value=["v1.0.0"])
|
||||
)
|
||||
resolver = stack.enter_context(patch(f"{module}.TokenResolver"))
|
||||
mock_run = stack.enter_context(
|
||||
patch(f"{module}.subprocess.run", side_effect=run)
|
||||
)
|
||||
stack.enter_context(
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
name: value.format(repo=repo_dir)
|
||||
for name, value in environ.items()
|
||||
},
|
||||
)
|
||||
)
|
||||
resolver.return_value.get_token.return_value = MagicMock(token="t")
|
||||
publish(repo={}, repo_dir=repo_dir, interactive=False, allow_prompt=False)
|
||||
return mock_run.call_args_list, repo_dir
|
||||
|
||||
def test_every_child_runs_under_the_current_interpreter(self):
|
||||
calls, _ = self.publish_with("https://pypi.org/project/example/", {})
|
||||
argvs = [call.args[0] for call in calls]
|
||||
self.assertEqual(
|
||||
[argv[2] for argv in argvs], ["build", "twine", "build", "twine"]
|
||||
)
|
||||
self.assertEqual({argv[0] for argv in argvs}, {sys.executable})
|
||||
|
||||
def test_children_never_run_in_the_repository(self):
|
||||
calls, repo_dir = self.publish_with("https://pypi.org/project/example/", {})
|
||||
cwds = {call.kwargs["cwd"] for call in calls}
|
||||
self.assertEqual(len(cwds), 1)
|
||||
self.assertNotEqual(os.path.realpath(cwds.pop()), os.path.realpath(repo_dir))
|
||||
|
||||
def test_only_the_fresh_build_is_uploaded(self):
|
||||
calls, repo_dir = self.publish_with("https://pypi.org/project/example/", {})
|
||||
upload = calls[-1].args[0]
|
||||
self.assertEqual(
|
||||
[os.path.basename(path) for path in upload if path.endswith(".tar.gz")],
|
||||
["example-1.0.0.tar.gz"],
|
||||
)
|
||||
self.assertEqual(calls[2].args[0][-1], repo_dir)
|
||||
|
||||
def test_no_pkgmgr_variable_reaches_a_child(self):
|
||||
calls, _ = self.publish_with(
|
||||
"https://pypi.org/project/example/",
|
||||
{"PKGMGR_PYPI_TOKEN": "secret", "PKGMGR_GITHUB_TOKEN": "secret"},
|
||||
)
|
||||
for call in calls:
|
||||
self.assertFalse(
|
||||
[name for name in call.kwargs["env"] if name.startswith("PKGMGR_")]
|
||||
)
|
||||
self.assertEqual(calls[-1].kwargs["env"]["TWINE_PASSWORD"], "t")
|
||||
|
||||
def test_no_repository_path_stays_on_the_children_pythonpath(self):
|
||||
calls, _ = self.publish_with(
|
||||
"https://pypi.org/project/example/",
|
||||
{"PYTHONPATH": os.pathsep.join(["{repo}", "{repo}/src", "/opt/keep"])},
|
||||
)
|
||||
self.assertEqual(
|
||||
{call.kwargs["env"]["PYTHONPATH"] for call in calls}, {"/opt/keep"}
|
||||
)
|
||||
|
||||
def test_the_upload_goes_to_the_host_of_the_mirror(self):
|
||||
for mirror, url in (
|
||||
("https://pypi.org/project/example/", "https://upload.pypi.org/legacy/"),
|
||||
("https://test.pypi.org/project/example/", "https://test.pypi.org/legacy/"),
|
||||
):
|
||||
with self.subTest(mirror=mirror):
|
||||
calls, _ = self.publish_with(mirror, {})
|
||||
upload = calls[-1].args[0]
|
||||
self.assertIn("--non-interactive", upload)
|
||||
self.assertEqual(upload[upload.index("--repository-url") + 1], url)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -140,6 +140,75 @@ class TestUpdatePyprojectVersion(unittest.TestCase):
|
||||
|
||||
self.assertEqual(content, original)
|
||||
|
||||
def write_dynamic_attr_project(self, tmpdir: str, module: str) -> str:
|
||||
with open(os.path.join(tmpdir, "pyproject.toml"), "w", encoding="utf-8") as f:
|
||||
f.write(
|
||||
textwrap.dedent(
|
||||
"""
|
||||
[project]
|
||||
name = "quality"
|
||||
dynamic = ["version"]
|
||||
|
||||
[tool.setuptools]
|
||||
package-dir = {"" = "src"}
|
||||
|
||||
[tool.setuptools.dynamic]
|
||||
version = {attr = "quality.__version__"}
|
||||
"""
|
||||
).lstrip()
|
||||
)
|
||||
os.makedirs(os.path.join(tmpdir, "src", "quality"))
|
||||
path = os.path.join(tmpdir, "src", "quality", "__init__.py")
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(module)
|
||||
return path
|
||||
|
||||
def test_a_dynamic_attr_version_is_bumped_in_its_module_and_read_back(self) -> None:
|
||||
from pkgmgr.core.version.source import read_pyproject_version
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
module = self.write_dynamic_attr_project(
|
||||
tmpdir, '"""Quality."""\n\n__version__ = "0.1.0"\n'
|
||||
)
|
||||
with open(os.path.join(tmpdir, "pyproject.toml"), encoding="utf-8") as f:
|
||||
before = f.read()
|
||||
self.assertEqual(read_pyproject_version(tmpdir), "0.1.0")
|
||||
|
||||
update_pyproject_version(
|
||||
os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=False
|
||||
)
|
||||
|
||||
with open(module, encoding="utf-8") as f:
|
||||
self.assertEqual(f.read(), '"""Quality."""\n\n__version__ = "0.2.0"\n')
|
||||
with open(os.path.join(tmpdir, "pyproject.toml"), encoding="utf-8") as f:
|
||||
self.assertEqual(f.read(), before)
|
||||
self.assertEqual(read_pyproject_version(tmpdir), "0.2.0")
|
||||
|
||||
def test_a_dynamic_attr_version_preview_writes_nothing(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
module = self.write_dynamic_attr_project(tmpdir, "__version__ = '0.1.0'\n")
|
||||
|
||||
update_pyproject_version(
|
||||
os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=True
|
||||
)
|
||||
|
||||
with open(module, encoding="utf-8") as f:
|
||||
self.assertEqual(f.read(), "__version__ = '0.1.0'\n")
|
||||
|
||||
def test_a_dynamic_attr_module_without_the_literal_raises(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
self.write_dynamic_attr_project(
|
||||
tmpdir,
|
||||
"from importlib.metadata import version\n__version__ = version('quality')\n",
|
||||
)
|
||||
|
||||
with self.assertRaises(RuntimeError) as cm:
|
||||
update_pyproject_version(
|
||||
os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=False
|
||||
)
|
||||
|
||||
self.assertIn("Missing __version__ literal", str(cm.exception))
|
||||
|
||||
def test_update_pyproject_version_missing_file_is_skipped(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
path = os.path.join(tmpdir, "pyproject.toml")
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import pwd
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from pkgmgr.core.git.errors import GitRunError
|
||||
from pkgmgr.core.git.run import run
|
||||
from pkgmgr.core.git.run import CALLER_CONFIG, DEFAULT_CONFIG, run, strict_env
|
||||
|
||||
|
||||
class TestGitRun(unittest.TestCase):
|
||||
@@ -55,6 +59,98 @@ class TestGitRun(unittest.TestCase):
|
||||
self.assertNotIn("stdin", kwargs)
|
||||
self.assertIn("timeout", kwargs)
|
||||
|
||||
OVERRIDES = (
|
||||
"GIT_DIR",
|
||||
"GIT_WORK_TREE",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_CONFIG",
|
||||
"GIT_CEILING_DIRECTORIES",
|
||||
"GIT_CONFIG_GLOBAL",
|
||||
"GIT_CONFIG_SYSTEM",
|
||||
"GIT_CONFIG_PARAMETERS",
|
||||
"GIT_CONFIG_COUNT",
|
||||
"GIT_CONFIG_KEY_0",
|
||||
"GIT_CONFIG_VALUE_0",
|
||||
"GIT_CONFIG_KEY_X",
|
||||
)
|
||||
CONFIG_READ = (
|
||||
"GIT_CEILING_DIRECTORIES",
|
||||
"GIT_CONFIG_COUNT",
|
||||
"GIT_CONFIG_GLOBAL",
|
||||
"GIT_CONFIG_KEY_0",
|
||||
"GIT_CONFIG_PARAMETERS",
|
||||
"GIT_CONFIG_SYSTEM",
|
||||
"GIT_CONFIG_VALUE_0",
|
||||
)
|
||||
|
||||
def _env(
|
||||
self, scan: bool, strict: bool, view: str | None = None
|
||||
) -> dict[str, str] | None:
|
||||
completed = MagicMock()
|
||||
completed.stdout = ""
|
||||
planted = {
|
||||
**dict.fromkeys(self.OVERRIDES, "/elsewhere"),
|
||||
"HOME": "/elsewhere",
|
||||
"XDG_CONFIG_HOME": "/elsewhere",
|
||||
}
|
||||
with (
|
||||
patch.dict("os.environ", planted),
|
||||
patch(
|
||||
"pkgmgr.core.git.run.subprocess.run", return_value=completed
|
||||
) as mock_run,
|
||||
):
|
||||
if strict:
|
||||
with strict_env():
|
||||
run(["status"], scan=scan, config_view=view)
|
||||
else:
|
||||
run(["status"], scan=scan, config_view=view)
|
||||
return mock_run.call_args.kwargs.get("env")
|
||||
|
||||
def _kept(self, env: dict[str, str]) -> list[str]:
|
||||
return sorted(name for name in self.OVERRIDES if name in env)
|
||||
|
||||
def test_scan_drops_repository_overrides_from_the_environment(self) -> None:
|
||||
unset = ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")
|
||||
for view in (None, CALLER_CONFIG):
|
||||
with self.subTest(view=view):
|
||||
env = self._env(scan=True, strict=False, view=view)
|
||||
|
||||
self.assertEqual(
|
||||
self._kept(env),
|
||||
sorted(name for name in self.OVERRIDES if name not in unset),
|
||||
)
|
||||
self.assertEqual(env.get("GIT_CONFIG_NOSYSTEM"), None if view else "1")
|
||||
self.assertIsNone(self._env(scan=False, strict=False, view=view))
|
||||
|
||||
def test_strict_env_keeps_only_the_ceiling(self) -> None:
|
||||
for scan in (True, False):
|
||||
with self.subTest(scan=scan):
|
||||
env = self._env(scan=scan, strict=True)
|
||||
|
||||
self.assertEqual(self._kept(env), ["GIT_CEILING_DIRECTORIES"])
|
||||
self.assertEqual(env.get("GIT_CONFIG_NOSYSTEM"), "1")
|
||||
|
||||
def test_strict_caller_config_also_keeps_the_config_variables(self) -> None:
|
||||
for scan in (True, False):
|
||||
with self.subTest(scan=scan):
|
||||
env = self._env(scan=scan, strict=True, view=CALLER_CONFIG)
|
||||
|
||||
self.assertEqual(self._kept(env), list(self.CONFIG_READ))
|
||||
self.assertIsNone(env.get("GIT_CONFIG_NOSYSTEM"))
|
||||
self.assertEqual(env.get("HOME"), "/elsewhere")
|
||||
|
||||
def test_default_config_ignores_the_environment(self) -> None:
|
||||
home = pwd.getpwuid(os.getuid()).pw_dir
|
||||
for strict in (True, False):
|
||||
with self.subTest(strict=strict):
|
||||
env = self._env(scan=True, strict=strict, view=DEFAULT_CONFIG)
|
||||
|
||||
self.assertEqual(self._kept(env), ["GIT_CEILING_DIRECTORIES"])
|
||||
self.assertIsNone(env.get("GIT_CONFIG_NOSYSTEM"))
|
||||
self.assertEqual(env.get("HOME"), home)
|
||||
self.assertFalse("XDG_CONFIG_HOME" in env)
|
||||
|
||||
def test_failure_raises_giterror_with_details(self) -> None:
|
||||
# Build a CalledProcessError with stdout/stderr populated
|
||||
import subprocess as sp
|
||||
|
||||
Reference in new issue
Block a user