Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
235a43225b | ||
|
|
2c70837d00 | ||
|
|
83297dab67 | ||
|
|
bd32cf9fab | ||
|
|
eff95a8003 | ||
|
|
d94492e306 | ||
|
|
39843ab627 | ||
|
|
5e08847286 | ||
|
|
d416fc79e9 | ||
|
|
e017af0cd1 | ||
|
|
9421f69ea9 |
No files matched your search
@@ -0,0 +1 @@
|
||||
* @kevinveenbirkenbach
|
||||
+20
-7
@@ -5,19 +5,32 @@ updates:
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "00:00"
|
||||
rebase-strategy: "auto"
|
||||
open-pull-requests-limit: 0
|
||||
groups:
|
||||
pip-security:
|
||||
applies-to: security-updates
|
||||
patterns: ["*"]
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "python"
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "00:00"
|
||||
groups:
|
||||
github-actions:
|
||||
applies-to: version-updates
|
||||
patterns: ["*"]
|
||||
labels:
|
||||
- "dependencies"
|
||||
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
docker:
|
||||
applies-to: version-updates
|
||||
patterns: ["*"]
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "ci"
|
||||
@@ -46,15 +46,10 @@ jobs:
|
||||
contents: read
|
||||
uses: ./.github/workflows/test-e2e.yml
|
||||
|
||||
test-virgin-user:
|
||||
test-virgin:
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/test-virgin-user.yml
|
||||
|
||||
test-virgin-root:
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/test-virgin-root.yml
|
||||
uses: ./.github/workflows/test-virgin.yml
|
||||
|
||||
lint-shell:
|
||||
permissions:
|
||||
|
||||
@@ -64,7 +64,7 @@ jobs:
|
||||
use: true
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
@@ -106,7 +106,7 @@ jobs:
|
||||
use: true
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Scorecard supply-chain security
|
||||
|
||||
on:
|
||||
branch_protection_rule:
|
||||
schedule:
|
||||
- cron: '00 00 * * *'
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
|
||||
concurrency:
|
||||
group: scorecard-${{ github.repository }}-${{ github.ref_name }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
name: Scorecard analysis
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.repository.default_branch == github.ref_name
|
||||
permissions:
|
||||
security-events: write
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run analysis
|
||||
uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
publish_results: true
|
||||
|
||||
- name: Upload to code-scanning
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -1,56 +0,0 @@
|
||||
name: Test Virgin Root
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-virgin-root:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
distro: [arch, debian, ubuntu, fedora, centos]
|
||||
env:
|
||||
NIX_CONFIG: |
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
- name: Pull base image (${{ matrix.distro }})
|
||||
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest"
|
||||
|
||||
- name: Virgin ${{ matrix.distro }} pkgmgr test (root)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
docker run --rm \
|
||||
-v "$PWD":/opt/src/pkgmgr \
|
||||
-v pkgmgr_repos:/root/Repositories \
|
||||
-v pkgmgr_pip_cache:/root/.cache/pip \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
-w /opt/src/pkgmgr \
|
||||
"ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
|
||||
git config --global --add safe.directory /opt/src/pkgmgr
|
||||
|
||||
make install
|
||||
make setup
|
||||
|
||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
||||
|
||||
pkgmgr update pkgmgr --clone-mode shallow --no-verification
|
||||
pkgmgr version pkgmgr
|
||||
|
||||
echo ">>> Running Nix-based: nix run .#pkgmgr -- version pkgmgr"
|
||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
||||
'
|
||||
@@ -1,68 +0,0 @@
|
||||
name: Test Virgin User
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-virgin-user:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
distro: [arch, debian, ubuntu, fedora, centos]
|
||||
env:
|
||||
NIX_CONFIG: |
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
- name: Pull base image (${{ matrix.distro }})
|
||||
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest"
|
||||
|
||||
- name: Virgin ${{ matrix.distro }} pkgmgr test (user)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
docker run --rm \
|
||||
-v "$PWD":/opt/src/pkgmgr \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
-w /opt/src/pkgmgr \
|
||||
"ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
|
||||
make install
|
||||
|
||||
useradd -m dev
|
||||
echo "dev ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dev
|
||||
chmod 0440 /etc/sudoers.d/dev
|
||||
chown -R dev:dev /opt/src/pkgmgr
|
||||
|
||||
mkdir -p /nix/store /nix/var/nix /nix/var/log/nix /nix/var/nix/profiles
|
||||
chown -R dev:dev /nix
|
||||
chmod 0755 /nix
|
||||
chmod 1777 /nix/store
|
||||
sudo -H -u dev env \
|
||||
HOME=/home/dev \
|
||||
NIX_CONFIG="$NIX_CONFIG" \
|
||||
PKGMGR_DISABLE_NIX_FLAKE_INSTALLER=1 \
|
||||
bash -lc "
|
||||
set -euo pipefail
|
||||
cd /opt/src/pkgmgr
|
||||
make setup-venv
|
||||
. \"\$HOME/.venvs/pkgmgr/bin/activate\"
|
||||
|
||||
pkgmgr version pkgmgr
|
||||
|
||||
export NIX_REMOTE=local
|
||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
||||
"
|
||||
'
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Test Virgin
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-virgin:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
mode: [user, root]
|
||||
distro: [arch, debian, ubuntu, fedora, centos]
|
||||
env:
|
||||
NIX_CONFIG: |
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
MODE: ${{ matrix.mode }}
|
||||
DISTRO: ${{ matrix.distro }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
- name: Pull base image (${{ matrix.distro }})
|
||||
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${DISTRO}:latest"
|
||||
|
||||
- name: Virgin ${{ matrix.distro }} pkgmgr test (${{ matrix.mode }})
|
||||
run: bash scripts/test/virgin/run.sh "$MODE" "$DISTRO"
|
||||
Generated
+3
-3
@@ -2,11 +2,11 @@
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1771714954,
|
||||
"narHash": "sha256-nhZJPnBavtu40/L2aqpljrfUNb2rxmWTmSjK2c9UKds=",
|
||||
"lastModified": 1782847189,
|
||||
"narHash": "sha256-twXPFqFsrrY5r28Zh7Homgcp2gUMBgQ6WDS98Q/3xFI=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "afbbf774e2087c3d734266c22f96fca2e78d3620",
|
||||
"rev": "b6018f87da91d19d0ab4cf979885689b469cdd41",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd /opt/src/pkgmgr
|
||||
make setup-venv
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
||||
|
||||
pkgmgr version pkgmgr
|
||||
|
||||
export NIX_REMOTE=local
|
||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
git config --global --add safe.directory /opt/src/pkgmgr
|
||||
|
||||
make install
|
||||
make setup
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
||||
|
||||
pkgmgr update pkgmgr --clone-mode shallow --no-verification
|
||||
pkgmgr version pkgmgr
|
||||
|
||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
mode="$1"
|
||||
distro="$2"
|
||||
|
||||
case "$mode" in
|
||||
root) volumes=(-v pkgmgr_repos:/root/Repositories -v pkgmgr_pip_cache:/root/.cache/pip) ;;
|
||||
user) volumes=() ;;
|
||||
*)
|
||||
echo "usage: $0 root|user <distro>" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
docker run --rm \
|
||||
-v "$PWD":/opt/src/pkgmgr \
|
||||
"${volumes[@]}" \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
-w /opt/src/pkgmgr \
|
||||
"ghcr.io/kevinveenbirkenbach/base-${distro}:latest" \
|
||||
bash -l "scripts/test/virgin/${mode}.sh"
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
make install
|
||||
|
||||
useradd -m dev
|
||||
echo "dev ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dev
|
||||
chmod 0440 /etc/sudoers.d/dev
|
||||
chown -R dev:dev /opt/src/pkgmgr
|
||||
|
||||
mkdir -p /nix/store /nix/var/nix /nix/var/log/nix /nix/var/nix/profiles
|
||||
chown -R dev:dev /nix
|
||||
chmod 0755 /nix
|
||||
chmod 1777 /nix/store
|
||||
|
||||
sudo -H -u dev env \
|
||||
HOME=/home/dev \
|
||||
NIX_CONFIG="$NIX_CONFIG" \
|
||||
PKGMGR_DISABLE_NIX_FLAKE_INSTALLER=1 \
|
||||
bash -l /opt/src/pkgmgr/scripts/test/virgin/dev.sh
|
||||
+26
-142
@@ -8,6 +8,7 @@ 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
|
||||
@@ -28,6 +29,7 @@ from pkgmgr.core.git.run import (
|
||||
)
|
||||
|
||||
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]]]
|
||||
@@ -37,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.
|
||||
@@ -69,12 +72,6 @@ NO_REMOTE_DEFAULT = (
|
||||
)
|
||||
NOT_UTF8 = "refused: git output (ref, remote or path names) is not UTF-8"
|
||||
DEFAULT_NAMES = ("HEAD", "main", "master")
|
||||
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"),
|
||||
)
|
||||
DELETE_MERGED_KEY = r"^branch\..*\.deletemerged$"
|
||||
SHARED_STORES = ("refs", "packed-refs", "reftable", "logs", "logs/refs")
|
||||
WALKED_STORES = ("refs", "reftable", "logs/refs")
|
||||
@@ -263,10 +260,6 @@ def _config_read(args: list[str], cwd: str, view: str) -> str:
|
||||
return run(args, cwd=cwd, scan=True, config_view=view)
|
||||
|
||||
|
||||
def _common_dir(cwd: str) -> str:
|
||||
return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
|
||||
|
||||
|
||||
def _docker(args: list[str]) -> str:
|
||||
return subprocess.run(
|
||||
["docker", *args], check=True, capture_output=True, text=True
|
||||
@@ -665,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)
|
||||
)
|
||||
@@ -759,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
|
||||
@@ -771,10 +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)
|
||||
return _local_actions(repo, item, tree, snapshot[5])
|
||||
registrations = snapshot[4]
|
||||
tree_part: list[str] = []
|
||||
if tree:
|
||||
if (
|
||||
@@ -813,9 +807,13 @@ def _actions(
|
||||
return actions
|
||||
|
||||
|
||||
def _local_actions(repo: Repo, item: Item, tree: Worktree | None) -> list[str]:
|
||||
"""
|
||||
Settle the actions of an item planned with scope `local`.
|
||||
def _local_actions(
|
||||
repo: Repo,
|
||||
item: Item,
|
||||
tree: Worktree | None,
|
||||
held: Callable[[], dict[str, str]],
|
||||
) -> list[str]:
|
||||
"""Settle the actions of an item planned with scope `local`.
|
||||
|
||||
Args:
|
||||
repo: the planned repository; its default and merged-into lines are
|
||||
@@ -823,19 +821,26 @@ def _local_actions(repo: Repo, item: Item, tree: Worktree | None) -> list[str]:
|
||||
item: the classified item; a merged-clean one whose tip is an
|
||||
ancestor of none of them gets that as its skip.
|
||||
tree: the worktree holding its branch, or None.
|
||||
held: the snapshot's _held_branches of the repository, read on the
|
||||
first call and reused for every later item of that snapshot.
|
||||
|
||||
Returns:
|
||||
`local-branch` for a merged-clean local branch that no worktree,
|
||||
worktree registration, rebase, bisect or symbolic ref holds and whose
|
||||
tip is an ancestor of the default or a merged-into line, else
|
||||
nothing; never a worktree, stack or remote action.
|
||||
|
||||
"""
|
||||
if item.state != "merged-clean" or not item.local_sha or tree is not None:
|
||||
return []
|
||||
held = _held_branches(repo.repo).get(item.branch)
|
||||
if held:
|
||||
item.skip = item.skip or held
|
||||
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"]
|
||||
@@ -854,6 +859,7 @@ def _snapshot(repo: Repo) -> tuple[list[Worktree], Snapshot]:
|
||||
cwds,
|
||||
tracking,
|
||||
_registrations(repo.repo),
|
||||
cache(lambda: _held_branches(repo.repo)),
|
||||
)
|
||||
|
||||
|
||||
@@ -911,25 +917,6 @@ def _default_remote(remotes: list[str]) -> str | None:
|
||||
return remotes[0] if len(remotes) == 1 else None
|
||||
|
||||
|
||||
def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
|
||||
"""
|
||||
List the resolvable refs under a prefix with their symref targets.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
prefix: a ref prefix such as `refs/heads` or `refs/remotes/origin`.
|
||||
git_dir: the git common dir (shared refs plus the main worktree's own)
|
||||
or a `worktrees/<id>` dir whose refs to list, or "" for the refs
|
||||
as repo_root's worktree sees them.
|
||||
|
||||
Returns:
|
||||
Full ref name -> the ref it points to, or "" for a plain ref.
|
||||
"""
|
||||
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 _resolve_within(refs: dict[str, str], ref: str) -> str | None:
|
||||
"""
|
||||
Follow a ref's symref chain without leaving a set of refs.
|
||||
@@ -975,109 +962,6 @@ def _remote_default(repo_root: str, remotes: list[str]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
|
||||
"""
|
||||
Read the branch every worktree's HEAD names, on any ref backend.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
git_dirs: the git common dir first, then each `worktrees/<id>`.
|
||||
|
||||
Returns:
|
||||
Branch name -> skip reason, from `git --git-dir=<dir> symbolic-ref
|
||||
HEAD` for each of them, whatever its id.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when a HEAD is neither readable nor detached.
|
||||
"""
|
||||
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]:
|
||||
"""
|
||||
List the git dirs of every worktree of the repository.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
|
||||
Returns:
|
||||
The git common dir, then each entry of `<common>/worktrees/`, whatever
|
||||
its id and whether `git worktree list` shows it.
|
||||
"""
|
||||
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]:
|
||||
"""
|
||||
Find the local branches that something besides a listed worktree holds.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
|
||||
Returns:
|
||||
Branch name -> skip reason: a symbolic branch, the branch any symbolic
|
||||
ref under `refs/` (also a tag or remote-tracking one) or under the
|
||||
main worktree's or any registration's `refs/worktree/` names, the HEAD
|
||||
of the main repository and of every `worktrees/<id>` registration,
|
||||
also one `git worktree list` omits, each rebase-merge and rebase-apply
|
||||
head-name, an interactive rebase's update-refs and BISECT_START; all
|
||||
read through the git common dir, whichever worktree repo_root is.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when git cannot read a registration, symref or HEAD.
|
||||
OSError: when a state file exists but cannot be read.
|
||||
ValueError: when a state file is not UTF-8.
|
||||
"""
|
||||
git_dirs = _git_dirs(repo_root)
|
||||
held: dict[str, str] = {}
|
||||
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}"
|
||||
)
|
||||
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
|
||||
held.setdefault(branch, reason)
|
||||
for git_dir in git_dirs:
|
||||
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}"
|
||||
)
|
||||
return held
|
||||
|
||||
|
||||
def _lines(
|
||||
repo_root: str, refs: list[str], remotes: list[str], warnings: list[str]
|
||||
) -> tuple[dict[str, tuple[str, set[str]]], set[str]]:
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
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]:
|
||||
"""List the resolvable refs under a prefix with their symref targets.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
prefix: a ref prefix such as `refs/heads` or `refs/remotes/origin`.
|
||||
git_dir: the git common dir (shared refs plus the main worktree's own)
|
||||
or a `worktrees/<id>` dir whose refs to list, or "" for the refs
|
||||
as repo_root's worktree sees them.
|
||||
|
||||
Returns:
|
||||
Full ref name -> the ref it points to, or "" for a plain ref.
|
||||
|
||||
"""
|
||||
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]:
|
||||
"""Read the branch every worktree's HEAD names, on any ref backend.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
git_dirs: the git common dir first, then each `worktrees/<id>`.
|
||||
|
||||
Returns:
|
||||
Branch name -> skip reason, from `git --git-dir=<dir> symbolic-ref
|
||||
HEAD` for each of them, whatever its id.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when a HEAD is neither readable nor detached.
|
||||
|
||||
"""
|
||||
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]:
|
||||
"""List the git dirs of every worktree of the repository.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
|
||||
Returns:
|
||||
The git common dir, then each entry of `<common>/worktrees/`, whatever
|
||||
its id and whether `git worktree list` shows it.
|
||||
|
||||
"""
|
||||
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]:
|
||||
"""Find the local branches that something besides a listed worktree holds.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
|
||||
Returns:
|
||||
Branch name -> skip reason: a symbolic branch, the branch any symbolic
|
||||
ref under `refs/` (also a tag or remote-tracking one) or under the
|
||||
main worktree's or any registration's `refs/worktree/` names, the HEAD
|
||||
of the main repository and of every `worktrees/<id>` registration,
|
||||
also one `git worktree list` omits, each rebase-merge and rebase-apply
|
||||
head-name, an interactive rebase's update-refs and BISECT_START; all
|
||||
read through the git common dir, whichever worktree repo_root is.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when git cannot read a registration, symref or HEAD.
|
||||
OSError: when a state file exists but cannot be read.
|
||||
ValueError: when a state file is not UTF-8.
|
||||
|
||||
"""
|
||||
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}"
|
||||
)
|
||||
@@ -13,7 +13,7 @@ from contextlib import contextmanager, redirect_stderr, redirect_stdout
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc, gc_forge, tree
|
||||
from pkgmgr.actions.branch import gc, gc_forge, held, tree
|
||||
from pkgmgr.cli.commands.branch import handle_branch, scan_repo_roots
|
||||
from pkgmgr.cli.parser import create_parser
|
||||
from pkgmgr.core.credentials.types import NoCredentialsError
|
||||
@@ -1647,7 +1647,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
|
||||
|
||||
def test_failed_head_read_refuses_the_repository(self) -> None:
|
||||
heads = self._refs(self.repo, "refs/heads")
|
||||
real = gc._git
|
||||
real = held._git
|
||||
|
||||
def timed_out(args: list[str], cwd: str) -> str:
|
||||
if args[1:] == ["symbolic-ref", "--quiet", "HEAD"]:
|
||||
@@ -1656,7 +1656,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
|
||||
raise err
|
||||
return real(args, cwd)
|
||||
|
||||
with patch.object(gc, "_git", side_effect=timed_out):
|
||||
with patch.object(held, "_git", side_effect=timed_out):
|
||||
run = self._cleanup("local", apply=True)
|
||||
|
||||
self.assertEqual(run.code, 2)
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import ExitStack, redirect_stderr, redirect_stdout
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc
|
||||
|
||||
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
|
||||
GIT = shutil.which("git")
|
||||
|
||||
|
||||
@unittest.skipUnless(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, "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 subprocess.run(
|
||||
[GIT, "-c", "commit.gpgsign=false", *args],
|
||||
cwd=self.repo,
|
||||
env={**os.environ, **AUTHOR},
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
|
||||
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")
|
||||
subprocess.run([GIT, "init", "-q", "--bare", "-b", "main", origin], check=True)
|
||||
subprocess.run([GIT, "init", "-q", "-b", "main", self.repo], check=True)
|
||||
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()
|
||||
Reference in new issue
Block a user