Compare commits
32
Commits
No files matched your search
@@ -0,0 +1,19 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Only the latest release receives security fixes. Fixes land on `main` and ship
|
||||
with the next release; the `stable` tag and the published container images
|
||||
follow the highest released version.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please do not report security issues in a public issue or pull request.
|
||||
|
||||
Report them privately through either channel:
|
||||
|
||||
- GitHub: [report a vulnerability](https://github.com/kevinveenbirkenbach/package-manager/security/advisories/new)
|
||||
- Email: Kevin Veen-Birkenbach, [kevin@veen.world](mailto:kevin@veen.world), [veen.world](https://veen.world)
|
||||
|
||||
Include the affected version, the steps to reproduce, and the impact you
|
||||
expect.
|
||||
@@ -23,14 +23,3 @@ updates:
|
||||
patterns: ["*"]
|
||||
labels:
|
||||
- "dependencies"
|
||||
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
groups:
|
||||
docker:
|
||||
applies-to: version-updates
|
||||
patterns: ["*"]
|
||||
labels:
|
||||
- "dependencies"
|
||||
@@ -71,4 +71,4 @@ jobs:
|
||||
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
|
||||
uses: infinito-nexus/quality/.github/workflows/quality.yml@2eaac6f644eb4c47102bd8cc353635c71af5dab9 # v1.2.0
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
security-events: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Run hadolint (produce SARIF)
|
||||
id: hadolint
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
|
||||
- name: Upload analysis results to GitHub
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||
with:
|
||||
sarif_file: hadolint-results.sarif
|
||||
wait-for-processing: true
|
||||
|
||||
@@ -8,7 +8,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
lint-python:
|
||||
uses: infinito-nexus/quality/.github/workflows/tool.yml@003eed66dd51592c3312a7c21ae429abead54d6f # v0.2.0
|
||||
uses: infinito-nexus/quality/.github/workflows/tool.yml@2eaac6f644eb4c47102bd8cc353635c71af5dab9 # v1.2.0
|
||||
with:
|
||||
tool: ruff
|
||||
args: check src tests
|
||||
@@ -10,7 +10,7 @@ jobs:
|
||||
lint-shell:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install ShellCheck
|
||||
run: sudo apt-get update && sudo apt-get install -y shellcheck
|
||||
- name: Run ShellCheck
|
||||
|
||||
@@ -8,6 +8,10 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
mark-stable:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -19,7 +23,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true # We need tags and main history for version comparison
|
||||
|
||||
@@ -8,9 +8,12 @@ on:
|
||||
- cron: "0 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
if: ${{ github.event_name != 'workflow_run' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository) }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
@@ -21,7 +24,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository (with tags)
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -54,7 +57,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout ${{ matrix.release.version }}
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ matrix.release.sha }}
|
||||
|
||||
@@ -96,7 +99,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout ${{ matrix.release.version }}
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ matrix.release.sha }}
|
||||
|
||||
|
||||
@@ -24,18 +24,18 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v4.2.2
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run analysis
|
||||
uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0
|
||||
uses: ossf/scorecard-action@23f22cd43608bae7a1f1fa2603d7314dee9538a5 # v2.6.0
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
publish_results: true
|
||||
|
||||
- name: Upload to code-scanning
|
||||
uses: github/codeql-action/upload-sarif@v4
|
||||
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -3,6 +3,9 @@ name: CodeQL Advanced
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Check security
|
||||
@@ -23,10 +26,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4
|
||||
uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
@@ -42,6 +45,6 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4
|
||||
uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||
with:
|
||||
category: "/language:${{ matrix.language }}"
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Show commit SHA
|
||||
run: git rev-parse HEAD
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
DISTRO: ${{ matrix.distro }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
@@ -18,13 +18,13 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@v23
|
||||
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
|
||||
|
||||
- name: Update flake.lock and open a pull request
|
||||
uses: DeterminateSystems/update-flake-lock@v29
|
||||
uses: DeterminateSystems/update-flake-lock@da03c0f078bc4b2c37ee4f7e072d34bf8f188bb3 # v29
|
||||
with:
|
||||
pr-title: "chore(deps): update flake.lock"
|
||||
pr-labels: |
|
||||
|
||||
@@ -1,5 +1,36 @@
|
||||
# Changelog
|
||||
|
||||
## [2.6.0] - 2026-12-02
|
||||
|
||||
Added:
|
||||
|
||||
- GC: *gc --risk low* plans and applies cleanups by risk level and owner
|
||||
- Release: *--expect-tree* refuses a release whose HEAD tree changed
|
||||
- Security: *.github/SECURITY.md* with private vulnerability reporting
|
||||
|
||||
Changed:
|
||||
|
||||
- Push: signs and pushes from a private bare repository, not the checkout
|
||||
- Push: URL credentials are redacted in every error and preview line
|
||||
- Release: untracked release inputs abort an *--expect-tree* release
|
||||
- CI: GitHub actions pinned by SHA; workflow tokens default to read-only
|
||||
|
||||
Fixed:
|
||||
|
||||
- Release: a nested clone releases itself, never the main checkout
|
||||
- Release: tracked changes are refused before any version bump
|
||||
- Release: a setuptools dynamic attr version is bumped in its module
|
||||
- Publish: builds with the pkgmgr interpreter in a private directory
|
||||
- GC: owner status, mounts and docker state are rechecked before deletes
|
||||
- GC: worktree holds win over a missing forge token
|
||||
- Branch: held branches are read once per cleanup plan
|
||||
- Security: the 32 open CodeQL alerts are closed
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Push refuses an origin whose URL is a local path or plain http
|
||||
- Push ignores http and credential settings in the repository git config
|
||||
|
||||
## [2.5.0] - 2026-11-13
|
||||
|
||||
Added:
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
rec {
|
||||
pkgmgr = pyPkgs.buildPythonApplication {
|
||||
pname = "package-manager";
|
||||
version = "2.5.0";
|
||||
version = "2.6.0";
|
||||
|
||||
# Use the git repo as source
|
||||
src = ./.;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Maintainer: Kevin Veen-Birkenbach <info@veen.world>
|
||||
|
||||
pkgname=package-manager
|
||||
pkgver=2.5.0
|
||||
pkgver=2.6.0
|
||||
pkgrel=1
|
||||
pkgdesc="Local-flake wrapper for Kevin's package-manager (Nix-based)."
|
||||
arch=('any')
|
||||
|
||||
@@ -1,3 +1,36 @@
|
||||
package-manager (2.6.0-1) unstable; urgency=medium
|
||||
|
||||
Added:
|
||||
|
||||
- GC: *gc --risk low* plans and applies cleanups by risk level and owner
|
||||
- Release: *--expect-tree* refuses a release whose HEAD tree changed
|
||||
- Security: *.github/SECURITY.md* with private vulnerability reporting
|
||||
|
||||
Changed:
|
||||
|
||||
- Push: signs and pushes from a private bare repository, not the checkout
|
||||
- Push: URL credentials are redacted in every error and preview line
|
||||
- Release: untracked release inputs abort an *--expect-tree* release
|
||||
- CI: GitHub actions pinned by SHA; workflow tokens default to read-only
|
||||
|
||||
Fixed:
|
||||
|
||||
- Release: a nested clone releases itself, never the main checkout
|
||||
- Release: tracked changes are refused before any version bump
|
||||
- Release: a setuptools dynamic attr version is bumped in its module
|
||||
- Publish: builds with the pkgmgr interpreter in a private directory
|
||||
- GC: owner status, mounts and docker state are rechecked before deletes
|
||||
- GC: worktree holds win over a missing forge token
|
||||
- Branch: held branches are read once per cleanup plan
|
||||
- Security: the 32 open CodeQL alerts are closed
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Push refuses an origin whose URL is a local path or plain http
|
||||
- Push ignores http and credential settings in the repository git config
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Wed, 02 Dec 2026 12:08:23 +0000
|
||||
|
||||
package-manager (2.5.0-1) unstable; urgency=medium
|
||||
|
||||
Added:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Name: package-manager
|
||||
Version: 2.5.0
|
||||
Version: 2.6.0
|
||||
Release: 1%{?dist}
|
||||
Summary: Wrapper that runs Kevin's package-manager via Nix flake
|
||||
|
||||
@@ -74,6 +74,36 @@ echo ">>> package-manager removed. Nix itself was not removed."
|
||||
/usr/lib/package-manager/
|
||||
|
||||
%changelog
|
||||
* Wed Dec 02 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.6.0-1
|
||||
- Added:
|
||||
|
||||
- - GC: *gc --risk low* plans and applies cleanups by risk level and owner
|
||||
- - Release: *--expect-tree* refuses a release whose HEAD tree changed
|
||||
- - Security: *.github/SECURITY.md* with private vulnerability reporting
|
||||
|
||||
- Changed:
|
||||
|
||||
- - Push: signs and pushes from a private bare repository, not the checkout
|
||||
- - Push: URL credentials are redacted in every error and preview line
|
||||
- - Release: untracked release inputs abort an *--expect-tree* release
|
||||
- - CI: GitHub actions pinned by SHA; workflow tokens default to read-only
|
||||
|
||||
- Fixed:
|
||||
|
||||
- - Release: a nested clone releases itself, never the main checkout
|
||||
- - Release: tracked changes are refused before any version bump
|
||||
- - Release: a setuptools dynamic attr version is bumped in its module
|
||||
- - Publish: builds with the pkgmgr interpreter in a private directory
|
||||
- - GC: owner status, mounts and docker state are rechecked before deletes
|
||||
- - GC: worktree holds win over a missing forge token
|
||||
- - Branch: held branches are read once per cleanup plan
|
||||
- - Security: the 32 open CodeQL alerts are closed
|
||||
|
||||
- Upgrade notes:
|
||||
|
||||
- - Push refuses an origin whose URL is a local path or plain http
|
||||
- - Push ignores http and credential settings in the repository git config
|
||||
|
||||
* Fri Nov 13 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.5.0-1
|
||||
- Added:
|
||||
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "kpmx"
|
||||
version = "2.5.0"
|
||||
version = "2.6.0"
|
||||
description = "Kevin's package-manager tool (pkgmgr)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if [ -f /etc/os-release ]; then
|
||||
# shellcheck source=/dev/null
|
||||
. /etc/os-release
|
||||
fi
|
||||
|
||||
echo "Running tests inside distro: ${ID:-unknown}"
|
||||
|
||||
if [ -f "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh" ]; then
|
||||
# shellcheck source=/dev/null
|
||||
. "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh"
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.nix-profile/etc/profile.d/nix.sh" ]; then
|
||||
# shellcheck source=/dev/null
|
||||
. "$HOME/.nix-profile/etc/profile.d/nix.sh"
|
||||
fi
|
||||
|
||||
PATH="/nix/var/nix/profiles/default/bin:$HOME/.nix-profile/bin:$PATH"
|
||||
|
||||
command -v nix >/dev/null || {
|
||||
echo "ERROR: nix not found."
|
||||
exit 1
|
||||
}
|
||||
|
||||
bash scripts/test/container/safe-directory.sh
|
||||
|
||||
nix develop .#default --no-write-lock-file -c \
|
||||
python3 -m unittest discover \
|
||||
-s /opt/src/pkgmgr/tests/e2e \
|
||||
-p "$TEST_PATTERN"
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Param: IMAGE ($1) - the image name shown in the missing-nix error.
|
||||
# Param: PKGMGR_DISTRO ($2) - the distro shown in the missing-nix error.
|
||||
IMAGE="$1"
|
||||
PKGMGR_DISTRO="$2"
|
||||
|
||||
bash scripts/test/container/safe-directory.sh
|
||||
|
||||
echo ">>> preflight: nix must exist in image"
|
||||
if ! command -v nix >/dev/null 2>&1; then
|
||||
echo "NO_NIX"
|
||||
echo "ERROR: nix not found in image ${IMAGE} (PKGMGR_DISTRO=${PKGMGR_DISTRO})"
|
||||
echo "HINT: Ensure Nix is installed during image build for this distro."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ">>> nix version"
|
||||
nix --version
|
||||
|
||||
if [[ -f /opt/src/pkgmgr/scripts/nix/lib/retry_403.sh ]]; then
|
||||
# shellcheck source=/dev/null
|
||||
source /opt/src/pkgmgr/scripts/nix/lib/retry_403.sh
|
||||
elif [[ -f ./scripts/nix/lib/retry_403.sh ]]; then
|
||||
# shellcheck source=/dev/null
|
||||
source ./scripts/nix/lib/retry_403.sh
|
||||
else
|
||||
echo "ERROR: retry helper not found: scripts/nix/lib/retry_403.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ">>> nix flake show"
|
||||
run_with_github_403_retry nix flake show . --no-write-lock-file >/dev/null
|
||||
|
||||
echo ">>> nix build .#default"
|
||||
run_with_github_403_retry nix build .#default --no-link --no-write-lock-file
|
||||
|
||||
echo ">>> nix run .#pkgmgr -- --help"
|
||||
run_with_github_403_retry nix run .#pkgmgr -- --help --no-write-lock-file
|
||||
|
||||
echo ">>> OK: Nix flake-only test succeeded."
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
echo "[test-env-virtual] Installing pkgmgr (distro package)..."
|
||||
make install
|
||||
|
||||
echo "[test-env-virtual] Setting up Python venv..."
|
||||
make setup-venv
|
||||
|
||||
echo "[test-env-virtual] Activating venv..."
|
||||
# shellcheck source=/dev/null
|
||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
||||
|
||||
echo "[test-env-virtual] Using pkgmgr from:"
|
||||
command -v pkgmgr
|
||||
pkgmgr --help
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if command -v git >/dev/null 2>&1; then
|
||||
git config --global --add safe.directory /opt/src/pkgmgr || true
|
||||
git config --global --add safe.directory /opt/src/pkgmgr/.git || true
|
||||
git config --global --add safe.directory "*" || true
|
||||
fi
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
|
||||
# Param: suite ($1) - the test folder to discover, tests/unit or tests/integration.
|
||||
suite="$1"
|
||||
|
||||
git config --global --add safe.directory /opt/src/pkgmgr || true
|
||||
nix develop .#default --no-write-lock-file -c \
|
||||
python3 -m unittest discover \
|
||||
-s "$suite" \
|
||||
-t /opt/src/pkgmgr \
|
||||
-p "$TEST_PATTERN"
|
||||
@@ -14,48 +14,4 @@ docker run --rm \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
--workdir /opt/src/pkgmgr \
|
||||
"pkgmgr-${PKGMGR_DISTRO}" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
|
||||
# Load distro info
|
||||
if [ -f /etc/os-release ]; then
|
||||
. /etc/os-release
|
||||
fi
|
||||
|
||||
echo "Running tests inside distro: ${ID:-unknown}"
|
||||
|
||||
# Load Nix environment if available
|
||||
if [ -f "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh" ]; then
|
||||
. "/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh"
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.nix-profile/etc/profile.d/nix.sh" ]; then
|
||||
. "$HOME/.nix-profile/etc/profile.d/nix.sh"
|
||||
fi
|
||||
|
||||
PATH="/nix/var/nix/profiles/default/bin:$HOME/.nix-profile/bin:$PATH"
|
||||
|
||||
command -v nix >/dev/null || {
|
||||
echo "ERROR: nix not found."
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Mark the mounted repository as safe to avoid Git ownership errors.
|
||||
# Newer Git (e.g. on Ubuntu) complains about the gitdir (/opt/src/pkgmgr/.git),
|
||||
# older versions about the worktree (/opt/src/pkgmgr). Nix turns "." into the
|
||||
# flake input "git+file:///opt/src/pkgmgr", which then uses Git under the hood.
|
||||
if command -v git >/dev/null 2>&1; then
|
||||
# Worktree path
|
||||
git config --global --add safe.directory /opt/src/pkgmgr || true
|
||||
# Gitdir path shown in the "dubious ownership" error
|
||||
git config --global --add safe.directory /opt/src/pkgmgr/.git || true
|
||||
# Ephemeral CI containers: allow all paths as a last resort
|
||||
git config --global --add safe.directory "*" || true
|
||||
fi
|
||||
|
||||
# Run the E2E tests inside the Nix development shell
|
||||
nix develop .#default --no-write-lock-file -c \
|
||||
python3 -m unittest discover \
|
||||
-s /opt/src/pkgmgr/tests/e2e \
|
||||
-p "$TEST_PATTERN"
|
||||
'
|
||||
bash -l scripts/test/container/e2e.sh
|
||||
@@ -16,48 +16,4 @@ docker run --rm \
|
||||
-e REINSTALL_PKGMGR=1 \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
"${IMAGE}" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
|
||||
if command -v git >/dev/null 2>&1; then
|
||||
git config --global --add safe.directory /opt/src/pkgmgr || true
|
||||
git config --global --add safe.directory /opt/src/pkgmgr/.git || true
|
||||
git config --global --add safe.directory "*" || true
|
||||
fi
|
||||
|
||||
echo ">>> preflight: nix must exist in image"
|
||||
if ! command -v nix >/dev/null 2>&1; then
|
||||
echo "NO_NIX"
|
||||
echo "ERROR: nix not found in image '"${IMAGE}"' (PKGMGR_DISTRO='"${PKGMGR_DISTRO}"')"
|
||||
echo "HINT: Ensure Nix is installed during image build for this distro."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ">>> nix version"
|
||||
nix --version
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Retry helper for GitHub API rate-limit (HTTP 403)
|
||||
# ------------------------------------------------------------
|
||||
if [[ -f /opt/src/pkgmgr/scripts/nix/lib/retry_403.sh ]]; then
|
||||
# shellcheck source=./scripts/nix/lib/retry_403.sh
|
||||
source /opt/src/pkgmgr/scripts/nix/lib/retry_403.sh
|
||||
elif [[ -f ./scripts/nix/lib/retry_403.sh ]]; then
|
||||
# shellcheck source=./scripts/nix/lib/retry_403.sh
|
||||
source ./scripts/nix/lib/retry_403.sh
|
||||
else
|
||||
echo "ERROR: retry helper not found: scripts/nix/lib/retry_403.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ">>> nix flake show"
|
||||
run_with_github_403_retry nix flake show . --no-write-lock-file >/dev/null
|
||||
|
||||
echo ">>> nix build .#default"
|
||||
run_with_github_403_retry nix build .#default --no-link --no-write-lock-file
|
||||
|
||||
echo ">>> nix run .#pkgmgr -- --help"
|
||||
run_with_github_403_retry nix run .#pkgmgr -- --help --no-write-lock-file
|
||||
|
||||
echo ">>> OK: Nix flake-only test succeeded."
|
||||
'
|
||||
bash -l scripts/test/container/env/nix.sh "${IMAGE}" "${PKGMGR_DISTRO}"
|
||||
@@ -12,31 +12,13 @@ echo "[test-env-virtual] Inspect image metadata:"
|
||||
docker image inspect "${IMAGE}" | sed -n '1,40p'
|
||||
echo
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Run VENV-based pkgmgr test inside container
|
||||
# ------------------------------------------------------------
|
||||
if OUTPUT=$(docker run --rm \
|
||||
-e REINSTALL_PKGMGR=1 \
|
||||
-v "$(pwd):/opt/src/pkgmgr" \
|
||||
-w /opt/src/pkgmgr \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
"${IMAGE}" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
|
||||
echo "[test-env-virtual] Installing pkgmgr (distro package)..."
|
||||
make install
|
||||
|
||||
echo "[test-env-virtual] Setting up Python venv..."
|
||||
make setup-venv
|
||||
|
||||
echo "[test-env-virtual] Activating venv..."
|
||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
||||
|
||||
echo "[test-env-virtual] Using pkgmgr from:"
|
||||
command -v pkgmgr
|
||||
pkgmgr --help
|
||||
' 2>&1); then
|
||||
bash -l scripts/test/container/env/virtual.sh 2>&1); then
|
||||
|
||||
echo "$OUTPUT"
|
||||
echo
|
||||
|
||||
@@ -14,12 +14,4 @@ docker run --rm \
|
||||
-e TEST_PATTERN="${TEST_PATTERN}" \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
"pkgmgr-${PKGMGR_DISTRO}" \
|
||||
bash -lc '
|
||||
set -e;
|
||||
git config --global --add safe.directory /opt/src/pkgmgr || true;
|
||||
nix develop .#default --no-write-lock-file -c \
|
||||
python3 -m unittest discover \
|
||||
-s tests/integration \
|
||||
-t /opt/src/pkgmgr \
|
||||
-p "$TEST_PATTERN";
|
||||
'
|
||||
bash -l scripts/test/container/unittest.sh tests/integration
|
||||
@@ -14,12 +14,4 @@ docker run --rm \
|
||||
-e TEST_PATTERN="${TEST_PATTERN}" \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
"pkgmgr-${PKGMGR_DISTRO}" \
|
||||
bash -lc '
|
||||
set -e;
|
||||
git config --global --add safe.directory /opt/src/pkgmgr || true;
|
||||
nix develop .#default --no-write-lock-file -c \
|
||||
python3 -m unittest discover \
|
||||
-s tests/unit \
|
||||
-t /opt/src/pkgmgr \
|
||||
-p "$TEST_PATTERN";
|
||||
'
|
||||
bash -l scripts/test/container/unittest.sh tests/unit
|
||||
@@ -65,6 +65,7 @@ REFUSAL = (
|
||||
)
|
||||
SCOPES = ("worktree", "branch", "all", "purge", "local")
|
||||
NOT_LINKED = "not a linked worktree of this repository"
|
||||
FORGE_UNAVAILABLE = "forge unavailable"
|
||||
NO_REMOTE_DEFAULT = (
|
||||
"refused: no remote-tracking default (origin, else the only remote: "
|
||||
"refs/remotes/<remote>/HEAD, main or master, resolving inside "
|
||||
@@ -466,13 +467,13 @@ def _in_line(repo: Repo, sha: str) -> str | None:
|
||||
def _merged_by(repo: Repo, sha: str) -> str | None:
|
||||
if sha not in repo.first_parent and _is_ancestor(sha, repo.default, repo.repo):
|
||||
return "ancestor"
|
||||
number = repo.forge.merged_heads.get(sha)
|
||||
if number:
|
||||
return f"pr#{number}"
|
||||
line = _in_line(repo, sha)
|
||||
if line:
|
||||
return f"line:{line}"
|
||||
return "patch" if _patch_merged(repo, sha) else None
|
||||
if _patch_merged(repo, sha):
|
||||
return "patch"
|
||||
number = repo.forge.merged_heads.get(sha)
|
||||
return f"pr#{number}" if number else None
|
||||
|
||||
|
||||
def _patch_merged(repo: Repo, sha: str) -> bool:
|
||||
@@ -518,24 +519,22 @@ def human_size(size: int) -> str:
|
||||
return f"{value / 1024:.1f}T"
|
||||
|
||||
|
||||
def _needs_forge(item: Item, tree: Worktree | None) -> bool:
|
||||
def _forge_skip(repo: Repo, item: Item, tree: Worktree | None) -> str | None:
|
||||
"""
|
||||
Whether deciding the item needs the forge's PR and protection facts.
|
||||
|
||||
Args:
|
||||
repo: the planned repository with its forge facts.
|
||||
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.
|
||||
FORGE_UNAVAILABLE when the forge was not read, except for a branch that
|
||||
no worktree holds, without upstream and remote branch, merged into the
|
||||
default by ancestry; None otherwise.
|
||||
"""
|
||||
return not (
|
||||
tree is None
|
||||
and item.merged_by == "ancestor"
|
||||
and item.upstream is None
|
||||
and not item.remotes
|
||||
)
|
||||
if not repo.forge.unavailable:
|
||||
return None
|
||||
local = tree is None and item.upstream is None and not item.remotes
|
||||
return None if local and item.merged_by == "ancestor" else FORGE_UNAVAILABLE
|
||||
|
||||
|
||||
def _skip(
|
||||
@@ -548,10 +547,9 @@ 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 and _needs_forge(item, tree):
|
||||
return "forge unavailable"
|
||||
forge = _forge_skip(repo, item, tree)
|
||||
if tree is None:
|
||||
return None
|
||||
return forge
|
||||
if tree.main:
|
||||
return "checked out in main worktree"
|
||||
if repo.scope == "local":
|
||||
@@ -576,7 +574,7 @@ def _skip(
|
||||
lock = _lock_skip(tree.locked, repo.host_ns)
|
||||
if lock:
|
||||
return lock
|
||||
return _busy(cwds, tree.path)
|
||||
return _busy(cwds, tree.path) or forge
|
||||
|
||||
|
||||
def _remote_refusal(unsafe: list[str], item: Item) -> str | None:
|
||||
@@ -746,7 +744,7 @@ def _build(
|
||||
)
|
||||
item.skip = _skip(repo, item, tree, checkout, cwds)
|
||||
if (
|
||||
item.skip is None
|
||||
item.skip in (None, FORGE_UNAVAILABLE)
|
||||
and repo.min_age is not None
|
||||
and item.last_activity
|
||||
and (time.time() - item.last_activity) / 3600 < repo.min_age
|
||||
@@ -813,24 +811,6 @@ def _local_actions(
|
||||
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
|
||||
the refs the branch tip must be an ancestor of.
|
||||
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 []
|
||||
hold = held().get(item.branch)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from pkgmgr.actions.mirror.url_utils import parse_repo_from_git_url
|
||||
@@ -12,6 +13,8 @@ from pkgmgr.core.remote_provisioning.http.errors import HttpError
|
||||
GITHUB_HOST = "github.com"
|
||||
GITHUB_API = "https://api.github.com"
|
||||
PAGE_SIZE = 100
|
||||
TIMEOUT_S = 10
|
||||
BUDGET_S = 60
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -46,10 +49,14 @@ def github_slugs(remote_urls: dict[str, str]) -> list[tuple[str, str]]:
|
||||
return slugs
|
||||
|
||||
|
||||
def _pages(http: HttpClient, headers: dict[str, str], url: str) -> list[dict]:
|
||||
def _pages(
|
||||
http: HttpClient, headers: dict[str, str], url: str, deadline: float
|
||||
) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
if time.monotonic() > deadline:
|
||||
raise HttpError(status=0, message=f"budget of {BUDGET_S}s exceeded")
|
||||
resp = http.request_json(
|
||||
"GET", f"{url}&per_page={PAGE_SIZE}&page={page}", headers=headers
|
||||
)
|
||||
@@ -94,7 +101,8 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
|
||||
The facts, or facts whose unavailable names the failing repository.
|
||||
"""
|
||||
facts = ForgeFacts()
|
||||
http = HttpClient(timeout_s=30)
|
||||
http = HttpClient(timeout_s=TIMEOUT_S)
|
||||
deadline = time.monotonic() + BUDGET_S
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
@@ -103,14 +111,17 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
|
||||
for owner, name in slugs:
|
||||
base = f"{GITHUB_API}/repos/{owner}/{name}"
|
||||
try:
|
||||
for pr in _pages(http, headers, f"{base}/pulls?state=all"):
|
||||
for pr in _pages(http, headers, f"{base}/pulls?state=all", deadline):
|
||||
if pr["merged_at"]:
|
||||
facts.merged_heads[pr["head"]["sha"]] = pr["number"]
|
||||
elif pr["state"] == "open":
|
||||
facts.open_heads[pr["head"]["ref"]] = pr["number"]
|
||||
for branch in _pages(http, headers, f"{base}/branches?protected=true"):
|
||||
for branch in _pages(
|
||||
http, headers, f"{base}/branches?protected=true", deadline
|
||||
):
|
||||
facts.protected.add(branch["name"])
|
||||
except (HttpError, ValueError, KeyError, TypeError) as exc:
|
||||
facts.unavailable = f"GitHub API failed for {owner}/{name}: {exc}"
|
||||
return facts
|
||||
return ForgeFacts(
|
||||
unavailable=f"GitHub API failed for {owner}/{name}: {exc}"
|
||||
)
|
||||
return facts
|
||||
@@ -21,39 +21,12 @@ def _common_dir(cwd: str) -> str:
|
||||
|
||||
|
||||
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:
|
||||
@@ -72,16 +45,6 @@ def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
|
||||
|
||||
|
||||
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 []
|
||||
@@ -89,26 +52,6 @@ def _git_dirs(repo_root: str) -> list[str]:
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -50,17 +50,15 @@ def _cache_path(owner: str, name: str) -> str:
|
||||
return os.path.join(base, "pkgmgr", "forge", owner, f"{name}.json")
|
||||
|
||||
|
||||
def secret_service_token() -> tuple[str | None, str | None]:
|
||||
"""
|
||||
Read the GitHub token from the Secret Service without unlocking it.
|
||||
class SecretServiceUnavailable(Exception):
|
||||
pass
|
||||
|
||||
Returns:
|
||||
(token, None), or (None, why no token is available).
|
||||
"""
|
||||
|
||||
def _secret_service_token() -> str:
|
||||
try:
|
||||
import secretstorage
|
||||
except ImportError:
|
||||
return None, "secretstorage not installed"
|
||||
except ImportError as exc:
|
||||
raise SecretServiceUnavailable("secretstorage not installed") from exc
|
||||
key = build_keyring_key("github", GITHUB_HOST, None)
|
||||
try:
|
||||
connection = secretstorage.dbus_init()
|
||||
@@ -72,14 +70,21 @@ def secret_service_token() -> tuple[str | None, str | None]:
|
||||
)
|
||||
unlocked = [item for item in items if not item.is_locked()]
|
||||
if not items:
|
||||
return None, "no GitHub token in the Secret Service"
|
||||
raise SecretServiceUnavailable("no GitHub token in the Secret Service")
|
||||
if not unlocked:
|
||||
return None, "Secret Service locked"
|
||||
return unlocked[0].get_secret().decode(), None
|
||||
raise SecretServiceUnavailable("Secret Service locked")
|
||||
return unlocked[0].get_secret().decode()
|
||||
finally:
|
||||
connection.close()
|
||||
except (secretstorage.exceptions.SecretStorageException, OSError) as exc:
|
||||
return None, f"Secret Service unavailable: {exc}"
|
||||
raise SecretServiceUnavailable(f"Secret Service unavailable: {exc}") from exc
|
||||
|
||||
|
||||
def _forge_access() -> tuple[str | None, str | None]:
|
||||
try:
|
||||
return _secret_service_token(), None
|
||||
except SecretServiceUnavailable as exc:
|
||||
return None, str(exc)
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -315,7 +320,7 @@ def branch_tree(
|
||||
"""
|
||||
known = list(dict.fromkeys(os.path.realpath(d) for d in repo_dirs))
|
||||
orphans = [d for d in _shared_owners(worktrees_root) if d not in known]
|
||||
token, reason = secret_service_token()
|
||||
token, reason = _forge_access()
|
||||
host_ns = gc.host_pid_namespace()
|
||||
containers = gc.list_compose_containers()
|
||||
data = {
|
||||
@@ -357,7 +362,7 @@ def refresh_tree_entry(repo_root: str) -> None:
|
||||
if not os.path.isfile(path) or not gc.host_pid_namespace():
|
||||
return
|
||||
root = os.path.realpath(repo_root)
|
||||
token, reason = secret_service_token()
|
||||
token, reason = _forge_access()
|
||||
fresh = _scan(root, True, token, reason, gc.list_compose_containers(), True)
|
||||
with _locked(path):
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
from .levels import LEVELS
|
||||
from .plan import RiskRequest, risk_cleanup
|
||||
|
||||
__all__ = ["LEVELS", "RiskRequest", "risk_cleanup"]
|
||||
@@ -0,0 +1,204 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
|
||||
from pkgmgr.actions.branch.gc import COMPOSE_PROJECT, _describe, _docker
|
||||
|
||||
from .levels import DAY_S, HIGH, IDLE_DAYS, LOW, MEDIUM, item
|
||||
|
||||
DF_VERBOSE = ["system", "df", "--verbose", "--format", "{{json .}}"]
|
||||
DANGLING = ["image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true"]
|
||||
STOPPED = ("exited", "dead")
|
||||
UNITS = {"": 1, "k": 10**3, "m": 10**6, "g": 10**9, "t": 10**12, "p": 10**15}
|
||||
SIZE = re.compile(r"([0-9.]+)\s*([kKmMgGtTpP]?)B")
|
||||
STAMP = re.compile(r"(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)(?:\.(\d+))? ([+-]\d{4})")
|
||||
|
||||
|
||||
def parse_size(text: object) -> int | None:
|
||||
match = SIZE.fullmatch(str(text or "").strip())
|
||||
if not match:
|
||||
return None
|
||||
return int(float(match.group(1)) * UNITS[match.group(2).lower()])
|
||||
|
||||
|
||||
def parse_time(text: object) -> float | None:
|
||||
match = STAMP.match(str(text or "").strip())
|
||||
if not match:
|
||||
return None
|
||||
clock, fraction, zone = match.groups()
|
||||
micro = (fraction or "")[:6].ljust(6, "0")
|
||||
return datetime.strptime(
|
||||
f"{clock}.{micro} {zone}", "%Y-%m-%d %H:%M:%S.%f %z"
|
||||
).timestamp()
|
||||
|
||||
|
||||
def _project(labels: object) -> str | None:
|
||||
for pair in str(labels or "").split(","):
|
||||
key, _, value = pair.partition("=")
|
||||
if key == COMPOSE_PROJECT:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _volumes(rows: list[dict]) -> list[dict]:
|
||||
items = []
|
||||
for row in rows:
|
||||
links = int(row["Links"]) if str(row.get("Links")).isdigit() else None
|
||||
unused = links == 0
|
||||
items.append(
|
||||
item(
|
||||
"volume",
|
||||
str(row["Name"]),
|
||||
MEDIUM if unused else HIGH,
|
||||
"unused volume: its data is lost"
|
||||
if unused
|
||||
else "volume in use by a container",
|
||||
size_bytes=parse_size(row.get("Size")),
|
||||
compose_project=_project(row.get("Labels")),
|
||||
links=links,
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _images(rows: list[dict], dangling: set[str]) -> list[dict]:
|
||||
items = []
|
||||
for row in rows:
|
||||
if str(row.get("Containers")) != "0":
|
||||
continue
|
||||
loose = row["ID"] in dangling
|
||||
items.append(
|
||||
item(
|
||||
"image",
|
||||
str(row["ID"]),
|
||||
LOW if loose else MEDIUM,
|
||||
"dangling image without containers" if loose else "unused tagged image",
|
||||
size_bytes=parse_size(row.get("UniqueSize")),
|
||||
repository=row.get("Repository"),
|
||||
tag=row.get("Tag"),
|
||||
created_at=row.get("CreatedAt"),
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _cache(rows: list[dict], now: float) -> list[dict]:
|
||||
items = []
|
||||
for row in rows:
|
||||
if str(row.get("InUse")).lower() != "false":
|
||||
continue
|
||||
used = parse_time(row.get("LastUsedAt")) or parse_time(row.get("CreatedAt"))
|
||||
idle = used is not None and now - used > IDLE_DAYS * DAY_S
|
||||
items.append(
|
||||
item(
|
||||
"build-cache",
|
||||
str(row["ID"]),
|
||||
LOW if idle else MEDIUM,
|
||||
f"build cache idle > {IDLE_DAYS} days"
|
||||
if idle
|
||||
else f"build cache used within {IDLE_DAYS} days",
|
||||
size_bytes=parse_size(row.get("Size")),
|
||||
last_used_since=row.get("LastUsedSince"),
|
||||
last_used_at=used,
|
||||
shared=str(row.get("Shared")).lower() == "true",
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _containers(rows: list[dict]) -> list[dict]:
|
||||
items = []
|
||||
for row in rows:
|
||||
if row.get("State") not in STOPPED:
|
||||
continue
|
||||
volumes = str(row.get("LocalVolumes"))
|
||||
bare = volumes == "0"
|
||||
items.append(
|
||||
item(
|
||||
"container",
|
||||
str(row["ID"]),
|
||||
LOW if bare else MEDIUM,
|
||||
"stopped container without volumes"
|
||||
if bare
|
||||
else f"stopped container with {volumes} local volumes",
|
||||
names=row.get("Names"),
|
||||
image=row.get("Image"),
|
||||
compose_project=_project(row.get("Labels")),
|
||||
status=row.get("Status"),
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def docker_items(now: float) -> tuple[list[dict], list[str]]:
|
||||
"""
|
||||
Args:
|
||||
now: epoch seconds the build cache idle time is measured against.
|
||||
|
||||
Returns:
|
||||
Every volume, unused image, idle build cache record and stopped
|
||||
container with its risk, read without changing anything, and
|
||||
warnings when docker is missing, fails or prints no JSON.
|
||||
"""
|
||||
try:
|
||||
data = json.loads(_docker(DF_VERBOSE))
|
||||
dangling = set(_docker(DANGLING).split())
|
||||
except FileNotFoundError:
|
||||
return [], ["docker unavailable: not installed"]
|
||||
except subprocess.CalledProcessError as exc:
|
||||
return [], [f"docker unavailable: {_describe(exc)}"]
|
||||
except ValueError:
|
||||
return [], ["docker system df --verbose: output is not JSON"]
|
||||
return [
|
||||
*_volumes(data.get("Volumes") or []),
|
||||
*_images(data.get("Images") or [], dangling),
|
||||
*_cache(data.get("BuildCache") or [], now),
|
||||
*_containers(data.get("Containers") or []),
|
||||
], []
|
||||
|
||||
|
||||
def delete_docker(entry: dict, now: float) -> str:
|
||||
"""
|
||||
Args:
|
||||
entry: a low image, build-cache or container item of the plan.
|
||||
now: as docker_items takes it.
|
||||
|
||||
Returns:
|
||||
done, or skipped with the reason: an item that docker no longer
|
||||
lists as low right before its delete, or a kind that is never low.
|
||||
|
||||
Raises:
|
||||
subprocess.CalledProcessError: when docker refuses the delete.
|
||||
RuntimeError: when docker cannot be read again before the delete.
|
||||
"""
|
||||
name = entry["name"]
|
||||
fresh, warnings = docker_items(now)
|
||||
if warnings:
|
||||
raise RuntimeError(f"revalidation failed: {'; '.join(warnings)}")
|
||||
if not any(
|
||||
i["kind"] == entry["kind"] and i["name"] == name and i["risk"] == LOW
|
||||
for i in fresh
|
||||
):
|
||||
return "skipped: changed since plan"
|
||||
if entry["kind"] == "image":
|
||||
_docker(["image", "rm", name])
|
||||
elif entry["kind"] == "build-cache":
|
||||
_docker(
|
||||
[
|
||||
"builder",
|
||||
"prune",
|
||||
"--force",
|
||||
"--filter",
|
||||
f"id={name}",
|
||||
"--filter",
|
||||
f"until={IDLE_DAYS * 24}h",
|
||||
]
|
||||
)
|
||||
elif entry["kind"] == "container":
|
||||
_docker(["container", "rm", name])
|
||||
else:
|
||||
return f"skipped: {entry['kind']} is never deleted as low"
|
||||
return "done"
|
||||
@@ -0,0 +1,174 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
from pkgmgr.actions.branch.gc import (
|
||||
FORGE_UNAVAILABLE,
|
||||
Item,
|
||||
Repo,
|
||||
_git,
|
||||
_rebuild,
|
||||
execute,
|
||||
prepare,
|
||||
)
|
||||
from pkgmgr.actions.worktree.hooks import FINI_HOOK
|
||||
|
||||
from .levels import HIGH, LOW, MEDIUM, item
|
||||
|
||||
LOCAL_PROOF = ("ancestor", "patch")
|
||||
TREE_STEPS = (f"hook:{FINI_HOOK}", "worktree")
|
||||
|
||||
|
||||
def _pushed(repo: Repo, head: str | None) -> bool:
|
||||
if not head:
|
||||
return False
|
||||
count = _git(["rev-list", "--count", head, "--not", "--remotes"], repo.repo)
|
||||
return count == "0"
|
||||
|
||||
|
||||
def pr_state(repo: Repo, it: Item) -> str:
|
||||
"""
|
||||
Args:
|
||||
repo: the planned repository with its forge facts.
|
||||
it: one of its items.
|
||||
|
||||
Returns:
|
||||
unknown when the forge was not read, else open #N, merged #N or none.
|
||||
"""
|
||||
if repo.forge.unavailable:
|
||||
return "unknown"
|
||||
number = repo.forge.open_heads.get(it.branch) if it.branch else None
|
||||
if number:
|
||||
return f"open #{number}"
|
||||
shas = [it.local_sha, it.head, *it.remotes.values()]
|
||||
merged = [repo.forge.merged_heads[s] for s in shas if s in repo.forge.merged_heads]
|
||||
return f"merged #{merged[0]}" if merged else "none"
|
||||
|
||||
|
||||
def classify(repo: Repo, it: Item) -> tuple[str, str]:
|
||||
"""
|
||||
Args:
|
||||
repo: the planned repository.
|
||||
it: one of its items, planned with scope `all` or `worktree`.
|
||||
|
||||
Returns:
|
||||
The risk and why. Low only for a linked worktree merged into the
|
||||
default branch by ancestry or patch id, without staged, unstaged or
|
||||
untracked change, whose head is on a remote, without compose stack
|
||||
and with nothing but the forge's absence holding it.
|
||||
"""
|
||||
return _state_verdict(it) or _tree_verdict(repo, it)
|
||||
|
||||
|
||||
def _state_verdict(it: Item) -> tuple[str, str] | None:
|
||||
if it.state == "protected":
|
||||
return HIGH, it.reason
|
||||
if it.state == "stale":
|
||||
return MEDIUM, "stale worktree metadata"
|
||||
if it.state == "dirty":
|
||||
return HIGH, it.reason
|
||||
if it.worktree is None:
|
||||
if it.state == "merged-clean":
|
||||
return MEDIUM, f"merged branch ({it.reason}): branches are never low"
|
||||
return HIGH, it.reason
|
||||
if it.state != "merged-clean":
|
||||
if it.unpushed:
|
||||
return HIGH, f"{it.reason}; {it.unpushed} commits on no remote"
|
||||
return MEDIUM, it.reason
|
||||
return None
|
||||
|
||||
|
||||
def _tree_verdict(repo: Repo, it: Item) -> tuple[str, str]:
|
||||
if it.merged_by not in LOCAL_PROOF or it.merged_into != repo.default:
|
||||
return MEDIUM, f"merged by {it.merged_by}, not locally into {repo.default}"
|
||||
if it.worktree_state != "clean" or any((it.staged, it.unstaged, it.untracked)):
|
||||
return HIGH, "worktree has changes"
|
||||
if it.compose_projects:
|
||||
return MEDIUM, f"compose stack {', '.join(it.compose_projects)}"
|
||||
if it.skip not in (None, FORGE_UNAVAILABLE):
|
||||
return MEDIUM, it.skip
|
||||
if "worktree" not in it.actions:
|
||||
return MEDIUM, "no worktree removal planned"
|
||||
if not _pushed(repo, it.head):
|
||||
return MEDIUM, "head is on no remote"
|
||||
return LOW, f"merged into {repo.default} by {it.merged_by}, clean, pushed"
|
||||
|
||||
|
||||
def _entry(repo: Repo, it: Item) -> dict:
|
||||
risk, reason = classify(repo, it)
|
||||
linked = it.worktree is not None and it.worktree != repo.repo
|
||||
kind = "stale" if it.state == "stale" else "worktree" if linked else "branch"
|
||||
return item(
|
||||
kind,
|
||||
it.worktree if linked or not it.branch else it.branch,
|
||||
risk,
|
||||
reason,
|
||||
size_bytes=it.size_bytes,
|
||||
repo=repo.repo,
|
||||
branch=it.branch,
|
||||
head=it.head,
|
||||
state=it.state,
|
||||
merged_by=it.merged_by,
|
||||
merged_into=it.merged_into,
|
||||
staged=it.staged,
|
||||
unstaged=it.unstaged,
|
||||
untracked=it.untracked,
|
||||
compose_projects=it.compose_projects,
|
||||
pr=pr_state(repo, it),
|
||||
skip=it.skip,
|
||||
steps=[a for a in it.actions if a in TREE_STEPS] if risk == LOW else [],
|
||||
)
|
||||
|
||||
|
||||
def git_items(
|
||||
repo_roots: list[str], include: list[str], exclude: list[str], options: dict
|
||||
) -> tuple[list[tuple[Repo, Item, dict]], list[str], bool] | None:
|
||||
"""
|
||||
Args:
|
||||
repo_roots: main worktree roots of the repositories to scan, each
|
||||
planned with scope `all`.
|
||||
include: only items whose branch or worktree path matches one of these.
|
||||
exclude: drop items whose branch or worktree path matches one of these.
|
||||
options: the plan_repo keyword options but scope.
|
||||
|
||||
Returns:
|
||||
(repository, item, plan entry) per chosen item, the warnings and
|
||||
whether this runs in the host PID namespace; None for an unknown
|
||||
include.
|
||||
"""
|
||||
prepared = prepare(repo_roots, include, exclude, {**options, "scope": "all"})
|
||||
if prepared is None:
|
||||
return None
|
||||
repos, host_ns, chosen = prepared
|
||||
warnings = [f"{repo.repo}: {w}" for repo in repos for w in repo.warnings]
|
||||
entries = [
|
||||
(repo, it, _entry(repo, it))
|
||||
for repo in repos
|
||||
for it in repo.items
|
||||
if chosen(it)
|
||||
]
|
||||
return entries, warnings, host_ns
|
||||
|
||||
|
||||
def delete_worktree(repo: Repo, it: Item) -> str:
|
||||
"""
|
||||
Args:
|
||||
repo: the planned repository.
|
||||
it: the low worktree item as planned; planned again with scope
|
||||
`worktree`, so its branch stays, and removed only while low.
|
||||
|
||||
Returns:
|
||||
The result execute settles, or skipped when it changed since the plan.
|
||||
|
||||
Raises:
|
||||
RuntimeError: when execute settles no result.
|
||||
"""
|
||||
tree_repo = replace(repo, scope="worktree")
|
||||
fresh = _rebuild(tree_repo, it)
|
||||
risk, reason = classify(tree_repo, fresh)
|
||||
if risk != LOW or fresh.head != it.head or fresh.worktree != it.worktree:
|
||||
return f"skipped: changed since plan ({reason})"
|
||||
execute(tree_repo, fresh)
|
||||
if fresh.result is None:
|
||||
raise RuntimeError(f"execute settled no result for {it.worktree}")
|
||||
return fresh.result
|
||||
@@ -0,0 +1,36 @@
|
||||
from __future__ import annotations
|
||||
|
||||
LOW = "low"
|
||||
MEDIUM = "medium"
|
||||
HIGH = "high"
|
||||
LEVELS = (LOW, MEDIUM, HIGH)
|
||||
DAY_S = 86400
|
||||
IDLE_DAYS = 7
|
||||
TMP_AGE_S = DAY_S
|
||||
|
||||
|
||||
def rank(level: str) -> int:
|
||||
return LEVELS.index(level)
|
||||
|
||||
|
||||
def item(kind: str, name: str, risk: str, reason: str, **facts: object) -> dict:
|
||||
"""
|
||||
Args:
|
||||
kind: worktree, branch, stale, image, build-cache, container, volume or tmp.
|
||||
name: what the item deletes: a path, branch, docker id or volume name.
|
||||
risk: one of LEVELS.
|
||||
reason: why the item has that risk.
|
||||
facts: kind-specific fields; size_bytes is read by the totals.
|
||||
|
||||
Returns:
|
||||
One plan item; result stays None until an apply sets it.
|
||||
"""
|
||||
return {
|
||||
"kind": kind,
|
||||
"name": name,
|
||||
"risk": risk,
|
||||
"reason": reason,
|
||||
"size_bytes": None,
|
||||
**facts,
|
||||
"result": None,
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from pkgmgr.actions.branch.gc import (
|
||||
REFUSAL,
|
||||
_describe,
|
||||
_process_cwds,
|
||||
host_pid_namespace,
|
||||
human_size,
|
||||
)
|
||||
|
||||
from .docker_items import delete_docker, docker_items
|
||||
from .git_items import delete_worktree, git_items
|
||||
from .levels import LEVELS, LOW, rank
|
||||
from .tmp_items import delete_tmp, read_owners, tmp_items
|
||||
|
||||
DOCKER_KINDS = ("image", "build-cache", "container")
|
||||
NO_HOST_NS = "process and lock checks unavailable: not in the host PID namespace"
|
||||
INCLUDE_ONLY_GIT = (
|
||||
"--branch selects git items only; docker and scratch items stay out of the plan"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RiskRequest:
|
||||
"""
|
||||
Args:
|
||||
level: print the git, docker and scratch items up to this risk;
|
||||
apply needs `low`.
|
||||
apply: delete exactly the low items of the same plan, each
|
||||
re-checked right before.
|
||||
as_json: print the plan as JSON instead of text lines.
|
||||
owners_file: optional JSON object of scratch path -> task status.
|
||||
include: only git items whose branch or worktree path matches; when
|
||||
set, docker and scratch items are neither planned nor deleted.
|
||||
exclude: drop git items whose branch or worktree path matches.
|
||||
merged_into: integration lines (refs) that also count as merged.
|
||||
sizes: measure each worktree's disk usage into the plan.
|
||||
min_age: skip git items younger than this many hours.
|
||||
hooks: pinned hooks by managed repository root realpath.
|
||||
tmp_root: the scratch directory whose direct children are listed.
|
||||
"""
|
||||
|
||||
level: str
|
||||
apply: bool
|
||||
as_json: bool
|
||||
owners_file: str | None
|
||||
include: list[str]
|
||||
exclude: list[str]
|
||||
merged_into: list[str]
|
||||
sizes: bool
|
||||
min_age: float | None
|
||||
hooks: dict[str, dict[str, list[str]]]
|
||||
tmp_root: str
|
||||
|
||||
|
||||
def _totals(entries: list[dict]) -> dict:
|
||||
return {
|
||||
level: {
|
||||
"count": sum(e["risk"] == level for e in entries),
|
||||
"size_bytes": sum(
|
||||
e["size_bytes"]
|
||||
for e in entries
|
||||
if e["risk"] == level and e["size_bytes"] is not None
|
||||
),
|
||||
}
|
||||
for level in LEVELS
|
||||
}
|
||||
|
||||
|
||||
def _render(plan: dict) -> str:
|
||||
lines = [f"== gc plan (risk up to {plan['risk']})"]
|
||||
for entry in plan["items"]:
|
||||
size = "-" if entry["size_bytes"] is None else human_size(entry["size_bytes"])
|
||||
line = (
|
||||
f"{entry['risk'].upper():<6} {entry['kind']:<11} {size:>8} "
|
||||
f"{entry['name']} {entry['reason']}"
|
||||
)
|
||||
lines.append(f"{line} -> {entry['result']}" if entry["result"] else line)
|
||||
lines += [
|
||||
f"TOTAL {level}: {t['count']} items, {human_size(t['size_bytes'])}"
|
||||
for level, t in plan["totals"].items()
|
||||
]
|
||||
lines += [f"WARN {warning}" for warning in plan["warnings"]]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _delete(
|
||||
entry: dict,
|
||||
git_by_name: dict,
|
||||
owners_file: str | None,
|
||||
now: float,
|
||||
) -> str:
|
||||
try:
|
||||
if entry["kind"] in DOCKER_KINDS:
|
||||
return delete_docker(entry, now)
|
||||
if entry["kind"] == "tmp":
|
||||
return delete_tmp(
|
||||
entry, read_owners(owners_file), now, _process_cwds()
|
||||
)
|
||||
if entry["kind"] == "worktree":
|
||||
repo, it = git_by_name[(entry["repo"], entry["name"])]
|
||||
return delete_worktree(repo, it)
|
||||
except (subprocess.CalledProcessError, OSError, RuntimeError, ValueError) as exc:
|
||||
return f"failed: {_describe(exc)}"
|
||||
return f"skipped: {entry['kind']} is never deleted as low"
|
||||
|
||||
|
||||
def _refusal(request: RiskRequest, host_ns: bool) -> str | None:
|
||||
if request.apply and request.level != LOW:
|
||||
return "Refusing: --apply removes only low items; use --risk low"
|
||||
if request.apply and not host_ns:
|
||||
return REFUSAL
|
||||
return None
|
||||
|
||||
|
||||
def _git_options(request: RiskRequest) -> dict:
|
||||
return {
|
||||
"merged_into": request.merged_into,
|
||||
"sizes": request.sizes,
|
||||
"min_age": request.min_age,
|
||||
"activity": False,
|
||||
"hooks": request.hooks,
|
||||
}
|
||||
|
||||
|
||||
def _host_items(
|
||||
request: RiskRequest, owners: dict[str, str], now: float, host_ns: bool
|
||||
) -> tuple[list[dict], list[str]]:
|
||||
notes = [] if host_ns else [NO_HOST_NS]
|
||||
if request.include:
|
||||
return [], [*notes, INCLUDE_ONLY_GIT]
|
||||
docker, docker_warnings = docker_items(now)
|
||||
cwds = _process_cwds() if host_ns else {}
|
||||
scratch = tmp_items(request.tmp_root, owners, now, cwds)
|
||||
return [*docker, *scratch], [*notes, *docker_warnings]
|
||||
|
||||
|
||||
def _apply(
|
||||
entries: list[dict], git: list, owners_file: str | None, now: float
|
||||
) -> None:
|
||||
git_by_name = {(e["repo"], e["name"]): (repo, it) for repo, it, e in git}
|
||||
for entry in entries:
|
||||
if entry["risk"] == LOW:
|
||||
entry["result"] = _delete(entry, git_by_name, owners_file, now)
|
||||
print(
|
||||
f"[gc] {entry['kind']} {entry['name']}: {entry['result']}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
|
||||
def _report(
|
||||
request: RiskRequest,
|
||||
host_ns: bool,
|
||||
now: float,
|
||||
entries: list[dict],
|
||||
warnings: list[str],
|
||||
) -> int:
|
||||
plan = {
|
||||
"host_pid_namespace": host_ns,
|
||||
"risk": request.level,
|
||||
"generated_at": now,
|
||||
"totals": _totals(entries),
|
||||
"items": [e for e in entries if rank(e["risk"]) <= rank(request.level)],
|
||||
"warnings": warnings,
|
||||
}
|
||||
print(json.dumps(plan, indent=2) if request.as_json else _render(plan))
|
||||
failed = any((e["result"] or "").startswith("failed") for e in entries)
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
def risk_cleanup(repo_roots: list[str], request: RiskRequest) -> int:
|
||||
"""
|
||||
Args:
|
||||
repo_roots: main worktree roots of the repositories to scan.
|
||||
request: what to plan, print and apply.
|
||||
|
||||
Returns:
|
||||
2 when refused, 1 when an applied item failed, else 0.
|
||||
|
||||
Raises:
|
||||
ValueError: for a level outside LEVELS.
|
||||
"""
|
||||
if request.level not in LEVELS:
|
||||
raise ValueError(f"unknown risk {request.level!r}")
|
||||
host_ns = host_pid_namespace()
|
||||
refusal = _refusal(request, host_ns)
|
||||
if refusal:
|
||||
print(refusal, file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
owners = read_owners(request.owners_file)
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f"Refusing: owner file: {_describe(exc)}", file=sys.stderr)
|
||||
return 2
|
||||
now = time.time()
|
||||
planned = git_items(
|
||||
repo_roots, request.include, request.exclude, _git_options(request)
|
||||
)
|
||||
if planned is None:
|
||||
return 2
|
||||
git, git_warnings, _ = planned
|
||||
host, host_warnings = _host_items(request, owners, now, host_ns)
|
||||
entries = [*(entry for _, _, entry in git), *host]
|
||||
if request.apply:
|
||||
_apply(entries, git, request.owners_file, now)
|
||||
return _report(request, host_ns, now, entries, [*git_warnings, *host_warnings])
|
||||
@@ -0,0 +1,179 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
|
||||
from pkgmgr.actions.branch.gc import _busy
|
||||
from pkgmgr.actions.branch.nofollow import canonical, remove_tree
|
||||
from pkgmgr.actions.gc.report.walk import TreeStats, walk
|
||||
|
||||
from .levels import HIGH, LOW, MEDIUM, TMP_AGE_S, item
|
||||
|
||||
ENDED = ("done", "stopped")
|
||||
MOUNTINFO = "/proc/self/mountinfo"
|
||||
OCTAL = re.compile(r"\\([0-7]{3})")
|
||||
|
||||
|
||||
def read_owners(path: str | None) -> dict[str, str]:
|
||||
"""
|
||||
Args:
|
||||
path: a JSON object of absolute path -> task status, or None.
|
||||
|
||||
Returns:
|
||||
Normalised absolute path -> lower-case status; empty without a file.
|
||||
|
||||
Raises:
|
||||
OSError: when the file cannot be read.
|
||||
ValueError: when it is not such a JSON object.
|
||||
"""
|
||||
if not path:
|
||||
return {}
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
if not isinstance(data, dict) or not all(
|
||||
isinstance(k, str) and isinstance(v, str) for k, v in data.items()
|
||||
):
|
||||
raise ValueError(f"{path}: expected a JSON object of path -> status")
|
||||
return {os.path.abspath(k): v.lower() for k, v in data.items()}
|
||||
|
||||
|
||||
def _measure(path: str, st: os.stat_result) -> tuple[TreeStats | None, int, float]:
|
||||
if not stat.S_ISDIR(st.st_mode):
|
||||
return None, st.st_blocks * 512, st.st_mtime
|
||||
stats = walk(path)
|
||||
return stats, stats.size_bytes, max(stats.newest_mtime, st.st_mtime)
|
||||
|
||||
|
||||
def _mount_hold(path: str) -> tuple[str, str] | None:
|
||||
try:
|
||||
with open(MOUNTINFO, encoding="utf-8", errors="surrogateescape") as fh:
|
||||
points = [OCTAL.sub(_char, line.split()[4]) for line in fh]
|
||||
except (OSError, IndexError):
|
||||
return MEDIUM, "mount table unreadable"
|
||||
if any(p == path or p.startswith(path + os.sep) for p in points):
|
||||
return MEDIUM, "is or holds a mount point"
|
||||
return None
|
||||
|
||||
|
||||
def _char(match: re.Match) -> str:
|
||||
return chr(int(match.group(1), 8))
|
||||
|
||||
|
||||
def _contents(path: str, stats: TreeStats, cwds: dict) -> tuple[str, str] | None:
|
||||
if stats.foreign_entries or stats.unreadable:
|
||||
return MEDIUM, "holds foreign or unreadable entries"
|
||||
busy = _busy(cwds, path)
|
||||
return (MEDIUM, busy) if busy else None
|
||||
|
||||
|
||||
def _held(
|
||||
path: str, stats: TreeStats | None, status: str | None, cwds: dict
|
||||
) -> tuple[str, str] | None:
|
||||
if stats is not None and os.path.lexists(os.path.join(path, ".git")):
|
||||
return HIGH, "holds a git checkout: remove it as a worktree"
|
||||
if status is not None and status not in ENDED:
|
||||
return HIGH, f"owner task is {status}"
|
||||
mounted = _mount_hold(path)
|
||||
if mounted:
|
||||
return mounted
|
||||
return _contents(path, stats, cwds) if stats is not None else None
|
||||
|
||||
|
||||
def _settled(status: str | None, age: float) -> tuple[str, str]:
|
||||
if age <= TMP_AGE_S:
|
||||
return MEDIUM, "changed within 24 h"
|
||||
if status is None:
|
||||
return MEDIUM, "no owner task known"
|
||||
return LOW, f"owner task {status}, unchanged for 24 h"
|
||||
|
||||
|
||||
def _verdict(
|
||||
path: str, st: os.stat_result, owners: dict[str, str], now: float, cwds: dict
|
||||
) -> tuple[str, str, int, float]:
|
||||
stats, size, newest = _measure(path, st)
|
||||
status = owners.get(path)
|
||||
risk, reason = _held(path, stats, status, cwds) or _settled(status, now - newest)
|
||||
return risk, reason, size, newest
|
||||
|
||||
|
||||
def tmp_items(
|
||||
root: str, owners: dict[str, str], now: float, cwds: dict[int, str]
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Args:
|
||||
root: the scratch directory, /tmp on a host; only its direct
|
||||
children the current user owns are listed.
|
||||
owners: absolute path -> task status from read_owners.
|
||||
now: epoch seconds the 24 h age is measured against.
|
||||
cwds: pid -> working directory of the host's processes.
|
||||
|
||||
Returns:
|
||||
One item per regular file or directory, never a symlink, socket or
|
||||
foreign entry: low only when its owner task is done or stopped and
|
||||
nothing in it changed for 24 h.
|
||||
"""
|
||||
items = []
|
||||
base = os.path.realpath(root)
|
||||
try:
|
||||
names = sorted(os.listdir(base))
|
||||
except OSError:
|
||||
return []
|
||||
for name in names:
|
||||
path = os.path.join(base, name)
|
||||
try:
|
||||
st = os.lstat(path)
|
||||
except OSError:
|
||||
continue
|
||||
if st.st_uid != os.getuid() or not (
|
||||
stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)
|
||||
):
|
||||
continue
|
||||
risk, reason, size, newest = _verdict(path, st, owners, now, cwds)
|
||||
items.append(
|
||||
item(
|
||||
"tmp",
|
||||
path,
|
||||
risk,
|
||||
reason,
|
||||
size_bytes=size,
|
||||
newest_mtime=newest,
|
||||
owner_status=owners.get(path),
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def delete_tmp(
|
||||
entry: dict, owners: dict[str, str], now: float, cwds: dict[int, str]
|
||||
) -> str:
|
||||
"""
|
||||
Args:
|
||||
entry: a low tmp item of the plan, deleted only while still low.
|
||||
owners: as tmp_items takes them.
|
||||
now: as tmp_items takes it.
|
||||
cwds: as tmp_items takes them, read again before the delete.
|
||||
|
||||
Returns:
|
||||
The result: done, or skipped with the reason.
|
||||
|
||||
Raises:
|
||||
OSError: when the delete fails.
|
||||
"""
|
||||
path = entry["name"]
|
||||
if not canonical(path):
|
||||
return "skipped: path is not canonical"
|
||||
st = os.lstat(path)
|
||||
if st.st_uid != os.getuid():
|
||||
return "skipped: no longer owned by this user"
|
||||
risk, reason, _, _ = _verdict(path, st, owners, now, cwds)
|
||||
if risk != LOW:
|
||||
return f"skipped: changed since plan ({reason})"
|
||||
if stat.S_ISDIR(st.st_mode):
|
||||
remove_tree(path)
|
||||
elif stat.S_ISREG(st.st_mode):
|
||||
os.unlink(path)
|
||||
else:
|
||||
return "skipped: no longer a file or directory"
|
||||
return "done"
|
||||
@@ -161,7 +161,6 @@ class InstallationPipeline:
|
||||
else:
|
||||
repo.pop("command", None)
|
||||
|
||||
state = new_state
|
||||
return
|
||||
|
||||
if attempted:
|
||||
|
||||
@@ -131,6 +131,23 @@ When `--close` is enabled:
|
||||
|
||||
---
|
||||
|
||||
## Audited Tree (`--expect-tree <sha>`)
|
||||
|
||||
Pins the release to an audited tree:
|
||||
|
||||
- After the pull (`fetch` + `pull --ff-only`) and before any file is written,
|
||||
`git rev-parse HEAD^{tree}` must equal the given full sha
|
||||
- Any other tree, also one a push brought in after the audit, aborts the
|
||||
release with a non-zero exit before any release file is written; the
|
||||
pull already ran and is not reverted, so HEAD and tracked files may
|
||||
have moved
|
||||
- A release input (pyproject, changelogs, flake, packaging or Cargo
|
||||
files) that exists but is untracked is not part of the audited tree,
|
||||
so it aborts the release the same way
|
||||
- With `--retry` the check runs before anything is pushed
|
||||
|
||||
---
|
||||
|
||||
## Execution Flow (ASCII Diagram)
|
||||
|
||||
```
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from .options import ReleaseOptions
|
||||
from .workflow import release
|
||||
|
||||
__all__ = ["release"]
|
||||
__all__ = ["ReleaseOptions", "release"]
|
||||
@@ -41,6 +41,37 @@ def ensure_clean_and_synced(*, preview: bool = False) -> None:
|
||||
pull_ff_only(preview=preview)
|
||||
|
||||
|
||||
def ensure_head_tree(expected: str | None) -> None:
|
||||
if expected is None:
|
||||
return
|
||||
actual = run(["rev-parse", "HEAD^{tree}"])
|
||||
if actual != expected:
|
||||
raise RuntimeError(
|
||||
f"HEAD tree {actual} is not the expected tree {expected}; "
|
||||
"refusing to release an unaudited tree"
|
||||
)
|
||||
|
||||
|
||||
def ensure_inputs_tracked(expected: str | None, files: list[str]) -> None:
|
||||
"""
|
||||
Args:
|
||||
expected: the audited tree sha, or None to skip the check.
|
||||
files: existing files the release writes or stages.
|
||||
|
||||
Raises:
|
||||
RuntimeError: one of the files is not tracked, so its content is
|
||||
not part of the audited tree.
|
||||
"""
|
||||
if expected is None or not files:
|
||||
return
|
||||
untracked = run(["ls-files", "--others", "--", *files])
|
||||
if untracked:
|
||||
raise RuntimeError(
|
||||
f"Release inputs not in the audited tree {expected}:\n{untracked}\n"
|
||||
"refusing to release unaudited content"
|
||||
)
|
||||
|
||||
|
||||
def _parse_v_tag(tag: str) -> tuple[int, ...] | None:
|
||||
"""
|
||||
Parse tags like 'v1.2.3' into (1, 2, 3).
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReleaseOptions:
|
||||
"""
|
||||
Args:
|
||||
expect_tree: full tree sha HEAD must match after the pull, or None.
|
||||
pyproject_path: pyproject.toml of the repository to release.
|
||||
changelog_path: Markdown changelog to extend.
|
||||
release_type: semver part to bump (major, minor, patch).
|
||||
message: release message for the changelogs and the tag.
|
||||
preview: only print what would change.
|
||||
force: skip the interactive preview and the branch deletion prompt.
|
||||
close: delete the current branch after the release.
|
||||
retry: re-deploy the existing HEAD release instead of bumping.
|
||||
"""
|
||||
|
||||
expect_tree: str | None
|
||||
pyproject_path: str = "pyproject.toml"
|
||||
changelog_path: str = "CHANGELOG.md"
|
||||
release_type: str = "patch"
|
||||
message: str | None = None
|
||||
preview: bool = False
|
||||
force: bool = False
|
||||
close: bool = False
|
||||
retry: bool = False
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
from pkgmgr.actions.branch import close_branch
|
||||
from pkgmgr.actions.repository.push import (
|
||||
@@ -12,7 +13,7 @@ from pkgmgr.actions.repository.push import (
|
||||
from pkgmgr.core.git import GitRunError
|
||||
from pkgmgr.core.git.commands import add, commit, tag_annotated
|
||||
from pkgmgr.core.git.queries import get_current_branch
|
||||
from pkgmgr.core.repository.paths import resolve_repo_paths
|
||||
from pkgmgr.core.repository.paths import RepoPaths, resolve_repo_paths
|
||||
|
||||
from .files import (
|
||||
update_cargo_version,
|
||||
@@ -26,87 +27,91 @@ from .files import (
|
||||
)
|
||||
from .git_ops import (
|
||||
ensure_clean_and_synced,
|
||||
ensure_head_tree,
|
||||
ensure_inputs_tracked,
|
||||
is_highest_version_tag,
|
||||
update_latest_tag,
|
||||
)
|
||||
from .options import ReleaseOptions
|
||||
from .package_name import resolve_package_name
|
||||
from .prompts import confirm_proceed_release, should_delete_branch
|
||||
from .retry import retry_release
|
||||
from .versioning import bump_semver, determine_current_version
|
||||
|
||||
MAIN_BRANCHES = ("main", "master")
|
||||
CARGO_FILES = ("Cargo.toml", "Cargo.lock")
|
||||
|
||||
def _release_impl(
|
||||
pyproject_path: str = "pyproject.toml",
|
||||
changelog_path: str = "CHANGELOG.md",
|
||||
release_type: str = "patch",
|
||||
message: str | None = None,
|
||||
preview: bool = False,
|
||||
close: bool = False,
|
||||
force: bool = False,
|
||||
) -> None:
|
||||
# Determine current branch early
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Prepared:
|
||||
branch: str
|
||||
version: str
|
||||
tag: str
|
||||
tag_message: str
|
||||
files: list[str]
|
||||
|
||||
|
||||
def _current_branch() -> str:
|
||||
try:
|
||||
branch = get_current_branch() or "main"
|
||||
return get_current_branch() or "main"
|
||||
except GitRunError:
|
||||
branch = "main"
|
||||
print(f"Releasing on branch: {branch}")
|
||||
return "main"
|
||||
|
||||
refuse_unsafe_config(".")
|
||||
# Pull BEFORE making any modifications
|
||||
ensure_clean_and_synced(preview=preview)
|
||||
|
||||
repo_root = os.path.dirname(os.path.abspath(pyproject_path))
|
||||
current_ver = determine_current_version(repo_root)
|
||||
new_ver = bump_semver(current_ver, release_type)
|
||||
new_ver_str = str(new_ver)
|
||||
new_tag = new_ver.to_tag(with_prefix=True)
|
||||
def _existing(files: list[str | None]) -> list[str]:
|
||||
return [p for p in files if isinstance(p, str) and p and os.path.exists(p)]
|
||||
|
||||
mode = "PREVIEW" if preview else "REAL"
|
||||
print(f"Release mode: {mode}")
|
||||
print(f"Current version: {current_ver}")
|
||||
print(f"New version: {new_ver_str} ({release_type})")
|
||||
|
||||
paths = resolve_repo_paths(repo_root)
|
||||
|
||||
# --- Update versioned files ------------------------------------------------
|
||||
|
||||
update_pyproject_version(pyproject_path, new_ver_str, preview=preview)
|
||||
|
||||
changelog_message = update_changelog(
|
||||
changelog_path,
|
||||
new_ver_str,
|
||||
message=message,
|
||||
preview=preview,
|
||||
def _release_files(
|
||||
options: ReleaseOptions, paths: RepoPaths, extra: list[str]
|
||||
) -> list[str]:
|
||||
return _existing(
|
||||
[
|
||||
options.pyproject_path,
|
||||
options.changelog_path,
|
||||
paths.flake_nix,
|
||||
paths.arch_pkgbuild,
|
||||
paths.rpm_spec,
|
||||
paths.debian_changelog,
|
||||
*extra,
|
||||
]
|
||||
)
|
||||
|
||||
update_flake_version(paths.flake_nix, new_ver_str, preview=preview)
|
||||
|
||||
cargo_files = update_cargo_version(repo_root, new_ver_str, preview=preview)
|
||||
def _next_version(options: ReleaseOptions, repo_root: str):
|
||||
current_ver = determine_current_version(repo_root)
|
||||
new_ver = bump_semver(current_ver, options.release_type)
|
||||
print(f"Release mode: {'PREVIEW' if options.preview else 'REAL'}")
|
||||
print(f"Current version: {current_ver}")
|
||||
print(f"New version: {new_ver} ({options.release_type})")
|
||||
return new_ver
|
||||
|
||||
|
||||
def _update_packaging_versions(paths: RepoPaths, version: str, preview: bool) -> None:
|
||||
if paths.arch_pkgbuild:
|
||||
update_pkgbuild_version(paths.arch_pkgbuild, new_ver_str, preview=preview)
|
||||
update_pkgbuild_version(paths.arch_pkgbuild, version, preview=preview)
|
||||
else:
|
||||
print(
|
||||
"[INFO] No PKGBUILD found (packaging/arch/PKGBUILD or PKGBUILD). Skipping."
|
||||
)
|
||||
|
||||
if paths.rpm_spec:
|
||||
update_spec_version(paths.rpm_spec, new_ver_str, preview=preview)
|
||||
update_spec_version(paths.rpm_spec, version, preview=preview)
|
||||
else:
|
||||
print("[INFO] No RPM spec file found. Skipping spec version update.")
|
||||
|
||||
effective_message: str | None = message
|
||||
if isinstance(changelog_message, str) and changelog_message.strip():
|
||||
effective_message = changelog_message.strip()
|
||||
|
||||
def _update_packaging_changelogs(
|
||||
paths: RepoPaths, version: str, message: str | None, preview: bool
|
||||
) -> None:
|
||||
package_name = resolve_package_name(paths)
|
||||
|
||||
if paths.debian_changelog:
|
||||
update_debian_changelog(
|
||||
paths.debian_changelog,
|
||||
package_name=package_name,
|
||||
new_version=new_ver_str,
|
||||
message=effective_message,
|
||||
new_version=version,
|
||||
message=message,
|
||||
preview=preview,
|
||||
)
|
||||
else:
|
||||
@@ -116,152 +121,150 @@ def _release_impl(
|
||||
update_spec_changelog(
|
||||
spec_path=paths.rpm_spec,
|
||||
package_name=package_name,
|
||||
new_version=new_ver_str,
|
||||
message=effective_message,
|
||||
new_version=version,
|
||||
message=message,
|
||||
preview=preview,
|
||||
)
|
||||
|
||||
# --- Git commit / tag / push ----------------------------------------------
|
||||
|
||||
commit_msg = f"Release version {new_ver_str}"
|
||||
tag_msg = effective_message or commit_msg
|
||||
def _update_files(
|
||||
options: ReleaseOptions, repo_root: str, paths: RepoPaths, version: str
|
||||
) -> tuple[str | None, list[str]]:
|
||||
"""
|
||||
Returns:
|
||||
The effective release message and the Cargo files that were updated.
|
||||
"""
|
||||
preview = options.preview
|
||||
update_pyproject_version(options.pyproject_path, version, preview=preview)
|
||||
changelog_message = update_changelog(
|
||||
options.changelog_path,
|
||||
version,
|
||||
message=options.message,
|
||||
preview=preview,
|
||||
)
|
||||
update_flake_version(paths.flake_nix, version, preview=preview)
|
||||
cargo_files = update_cargo_version(repo_root, version, preview=preview)
|
||||
_update_packaging_versions(paths, version, preview)
|
||||
|
||||
files_to_add = [
|
||||
pyproject_path,
|
||||
changelog_path,
|
||||
paths.flake_nix,
|
||||
paths.arch_pkgbuild,
|
||||
paths.rpm_spec,
|
||||
paths.debian_changelog,
|
||||
*cargo_files,
|
||||
]
|
||||
existing_files = [
|
||||
p for p in files_to_add if isinstance(p, str) and p and os.path.exists(p)
|
||||
]
|
||||
message = options.message
|
||||
if isinstance(changelog_message, str) and changelog_message.strip():
|
||||
message = changelog_message.strip()
|
||||
|
||||
if preview:
|
||||
add(existing_files, preview=True)
|
||||
commit(commit_msg, all=True, preview=True)
|
||||
sign_unpushed(".", preview=True)
|
||||
tag_annotated(new_tag, tag_msg, preview=True)
|
||||
push_branch(".", [], sign=True, refs=(new_tag,), preview=True)
|
||||
_update_packaging_changelogs(paths, version, message, preview)
|
||||
return message, cargo_files
|
||||
|
||||
if is_highest_version_tag(new_tag):
|
||||
update_latest_tag(new_tag, preview=True)
|
||||
|
||||
def _prepare(options: ReleaseOptions, branch: str) -> _Prepared:
|
||||
repo_root = os.path.dirname(os.path.abspath(options.pyproject_path))
|
||||
paths = resolve_repo_paths(repo_root)
|
||||
cargo_inputs = [os.path.join(repo_root, name) for name in CARGO_FILES]
|
||||
ensure_inputs_tracked(
|
||||
options.expect_tree, _release_files(options, paths, cargo_inputs)
|
||||
)
|
||||
new_ver = _next_version(options, repo_root)
|
||||
version = str(new_ver)
|
||||
message, cargo_files = _update_files(options, repo_root, paths, version)
|
||||
return _Prepared(
|
||||
branch=branch,
|
||||
version=version,
|
||||
tag=new_ver.to_tag(with_prefix=True),
|
||||
tag_message=message or f"Release version {version}",
|
||||
files=_release_files(options, paths, cargo_files),
|
||||
)
|
||||
|
||||
|
||||
def _commit_tag_push(prepared: _Prepared, preview: bool) -> None:
|
||||
add(prepared.files, preview=preview)
|
||||
commit(f"Release version {prepared.version}", all=True, preview=preview)
|
||||
sign_unpushed(".", preview=preview)
|
||||
tag_annotated(prepared.tag, prepared.tag_message, preview=preview)
|
||||
push_branch(".", [], sign=True, refs=(prepared.tag,), preview=preview)
|
||||
|
||||
|
||||
def _finish_preview(prepared: _Prepared, options: ReleaseOptions) -> None:
|
||||
tag = prepared.tag
|
||||
if is_highest_version_tag(tag):
|
||||
update_latest_tag(tag, preview=True)
|
||||
else:
|
||||
print(f"[PREVIEW] Skipping 'latest' update (tag {tag} is not the highest).")
|
||||
|
||||
branch = prepared.branch
|
||||
if options.close and branch not in MAIN_BRANCHES:
|
||||
if options.force:
|
||||
print(f"[PREVIEW] Would delete branch {branch} (forced).")
|
||||
else:
|
||||
print(
|
||||
f"[PREVIEW] Skipping 'latest' update (tag {new_tag} is not the highest)."
|
||||
f"[PREVIEW] Would ask whether to delete branch {branch} after release."
|
||||
)
|
||||
|
||||
if close and branch not in ("main", "master"):
|
||||
if force:
|
||||
print(f"[PREVIEW] Would delete branch {branch} (forced).")
|
||||
else:
|
||||
print(
|
||||
f"[PREVIEW] Would ask whether to delete branch {branch} after release."
|
||||
)
|
||||
return
|
||||
|
||||
add(existing_files, preview=False)
|
||||
commit(commit_msg, all=True, preview=False)
|
||||
sign_unpushed(".", preview=False)
|
||||
tag_annotated(new_tag, tag_msg, preview=False)
|
||||
|
||||
push_branch(".", [], sign=True, refs=(new_tag,), preview=False)
|
||||
|
||||
# Update 'latest' only if this is the highest version tag
|
||||
def _move_latest(tag: str) -> None:
|
||||
try:
|
||||
if is_highest_version_tag(new_tag):
|
||||
update_latest_tag(new_tag, preview=False)
|
||||
if is_highest_version_tag(tag):
|
||||
update_latest_tag(tag, preview=False)
|
||||
else:
|
||||
print(
|
||||
f"[INFO] Skipping 'latest' update (tag {new_tag} is not the highest)."
|
||||
)
|
||||
print(f"[INFO] Skipping 'latest' update (tag {tag} is not the highest).")
|
||||
except GitRunError as exc:
|
||||
print(f"[WARN] Failed to update floating 'latest' tag for {new_tag}: {exc}")
|
||||
print(f"[WARN] Failed to update floating 'latest' tag for {tag}: {exc}")
|
||||
print("'latest' tag was not updated.")
|
||||
|
||||
print(f"Release {new_ver_str} completed.")
|
||||
|
||||
if close:
|
||||
if branch in ("main", "master"):
|
||||
print(
|
||||
f"[INFO] close=True but current branch is {branch}; skipping branch deletion."
|
||||
)
|
||||
return
|
||||
|
||||
if not should_delete_branch(force=force):
|
||||
print(f"[INFO] Branch deletion declined. Keeping branch {branch}.")
|
||||
return
|
||||
|
||||
print(f"[INFO] Deleting branch {branch} after successful release...")
|
||||
try:
|
||||
close_branch(name=branch, base_branch="main", cwd=".")
|
||||
except (RuntimeError, GitRunError) as exc:
|
||||
print(f"[WARN] Failed to close branch {branch} automatically: {exc}")
|
||||
|
||||
|
||||
def release(
|
||||
pyproject_path: str = "pyproject.toml",
|
||||
changelog_path: str = "CHANGELOG.md",
|
||||
release_type: str = "patch",
|
||||
message: str | None = None,
|
||||
preview: bool = False,
|
||||
force: bool = False,
|
||||
close: bool = False,
|
||||
retry: bool = False,
|
||||
) -> None:
|
||||
if retry:
|
||||
retry_release(pyproject_path=pyproject_path, preview=preview)
|
||||
return
|
||||
|
||||
if preview:
|
||||
_release_impl(
|
||||
pyproject_path=pyproject_path,
|
||||
changelog_path=changelog_path,
|
||||
release_type=release_type,
|
||||
message=message,
|
||||
preview=True,
|
||||
close=close,
|
||||
force=force,
|
||||
def _close_released_branch(branch: str, force: bool) -> None:
|
||||
if branch in MAIN_BRANCHES:
|
||||
print(
|
||||
f"[INFO] close=True but current branch is {branch}; skipping branch deletion."
|
||||
)
|
||||
return
|
||||
|
||||
# If force or non-interactive: no preview+confirmation step
|
||||
if force or (not sys.stdin.isatty()):
|
||||
_release_impl(
|
||||
pyproject_path=pyproject_path,
|
||||
changelog_path=changelog_path,
|
||||
release_type=release_type,
|
||||
message=message,
|
||||
preview=False,
|
||||
close=close,
|
||||
force=force,
|
||||
)
|
||||
if not should_delete_branch(force=force):
|
||||
print(f"[INFO] Branch deletion declined. Keeping branch {branch}.")
|
||||
return
|
||||
|
||||
print(f"[INFO] Deleting branch {branch} after successful release...")
|
||||
try:
|
||||
close_branch(name=branch, base_branch="main", cwd=".")
|
||||
except (RuntimeError, GitRunError) as exc:
|
||||
print(f"[WARN] Failed to close branch {branch} automatically: {exc}")
|
||||
|
||||
|
||||
def _release_impl(options: ReleaseOptions) -> None:
|
||||
branch = _current_branch()
|
||||
print(f"Releasing on branch: {branch}")
|
||||
|
||||
refuse_unsafe_config(".")
|
||||
ensure_clean_and_synced(preview=options.preview)
|
||||
ensure_head_tree(options.expect_tree)
|
||||
|
||||
prepared = _prepare(options, branch)
|
||||
_commit_tag_push(prepared, options.preview)
|
||||
|
||||
if options.preview:
|
||||
_finish_preview(prepared, options)
|
||||
return
|
||||
|
||||
_move_latest(prepared.tag)
|
||||
print(f"Release {prepared.version} completed.")
|
||||
|
||||
if options.close:
|
||||
_close_released_branch(branch, options.force)
|
||||
|
||||
|
||||
def release(options: ReleaseOptions) -> None:
|
||||
if options.retry:
|
||||
ensure_head_tree(options.expect_tree)
|
||||
retry_release(pyproject_path=options.pyproject_path, preview=options.preview)
|
||||
return
|
||||
|
||||
if options.preview or options.force or not sys.stdin.isatty():
|
||||
_release_impl(options)
|
||||
return
|
||||
|
||||
print("[INFO] Running preview before actual release...\n")
|
||||
_release_impl(
|
||||
pyproject_path=pyproject_path,
|
||||
changelog_path=changelog_path,
|
||||
release_type=release_type,
|
||||
message=message,
|
||||
preview=True,
|
||||
close=close,
|
||||
force=force,
|
||||
)
|
||||
_release_impl(replace(options, preview=True))
|
||||
|
||||
if not confirm_proceed_release():
|
||||
print()
|
||||
return
|
||||
|
||||
print("\n[INFO] Running REAL release...\n")
|
||||
_release_impl(
|
||||
pyproject_path=pyproject_path,
|
||||
changelog_path=changelog_path,
|
||||
release_type=release_type,
|
||||
message=message,
|
||||
preview=False,
|
||||
close=close,
|
||||
force=force,
|
||||
)
|
||||
_release_impl(options)
|
||||
@@ -0,0 +1,392 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from pkgmgr.core.git import GitRunError, run
|
||||
from pkgmgr.core.git.run import DEFAULT_CONFIG, SCAN_FLAGS, _scan_env
|
||||
|
||||
PUSH_SCHEMES = ("https", "ssh")
|
||||
_SCP_URL = re.compile(
|
||||
r"[A-Za-z0-9_][A-Za-z0-9._-]*@(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9A-Fa-f:.]+\]):\S+"
|
||||
)
|
||||
_URL_USERINFO = re.compile(r"(?<=://)[^/?#\s]*@")
|
||||
TRUSTED_FLAGS = (
|
||||
*SCAN_FLAGS,
|
||||
"-c",
|
||||
"protocol.allow=never",
|
||||
*(
|
||||
arg
|
||||
for scheme in PUSH_SCHEMES
|
||||
for arg in ("-c", f"protocol.{scheme}.allow=always")
|
||||
),
|
||||
"-c",
|
||||
"transfer.bundleURI=false",
|
||||
"-c",
|
||||
"submodule.recurse=false",
|
||||
"-c",
|
||||
"fetch.recurseSubmodules=false",
|
||||
)
|
||||
_FILE_PROTOCOL = ("-c", "protocol.file.allow=always")
|
||||
CHECKOUT_FETCH_FLAGS = (
|
||||
"-c",
|
||||
"protocol.allow=never",
|
||||
*_FILE_PROTOCOL,
|
||||
"-c",
|
||||
"fetch.bundleURI=",
|
||||
"-c",
|
||||
"transfer.bundleURI=false",
|
||||
"-c",
|
||||
"core.alternateRefsCommand=true",
|
||||
"-c",
|
||||
"submodule.recurse=false",
|
||||
"-c",
|
||||
"fetch.recurseSubmodules=false",
|
||||
)
|
||||
|
||||
|
||||
class PushRefusedError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Target:
|
||||
repo_dir: str
|
||||
tdir: str
|
||||
branch: str
|
||||
head: str
|
||||
remote: str
|
||||
fetch_url: str
|
||||
push_urls: tuple[str, ...]
|
||||
|
||||
@property
|
||||
def branch_ref(self) -> str:
|
||||
return f"refs/heads/{self.branch}"
|
||||
|
||||
|
||||
def try_git(repo_dir: str, *args: str) -> str | None:
|
||||
try:
|
||||
return run(list(args), cwd=repo_dir, scan=True)
|
||||
except GitRunError:
|
||||
return None
|
||||
|
||||
|
||||
def _config_all(repo_dir: str, key: str) -> list[str]:
|
||||
values = try_git(repo_dir, "config", "-z", "--get-all", key)
|
||||
return values.split("\0")[:-1] if values else []
|
||||
|
||||
|
||||
def file_url(path: str) -> str:
|
||||
return Path(os.path.abspath(path)).as_uri()
|
||||
|
||||
|
||||
def redact_urls(text: str) -> str:
|
||||
"""
|
||||
Args:
|
||||
text: a diagnostic that may name remote URLs.
|
||||
|
||||
Returns:
|
||||
The text with the userinfo of every scheme URL, which may carry a
|
||||
password or token, replaced by `***`.
|
||||
|
||||
"""
|
||||
return _URL_USERINFO.sub("***@", text)
|
||||
|
||||
|
||||
def trusted_env(extra: dict[str, str]) -> dict[str, str]:
|
||||
"""
|
||||
Args:
|
||||
extra: variables set on top, e.g. the author of a re-signed commit.
|
||||
|
||||
Returns:
|
||||
The environment of every git call in the temporary repository: no
|
||||
inherited `GIT_*` variable, the system and passwd-home global config,
|
||||
no replace objects, prompts and askpass helpers left to that config.
|
||||
|
||||
"""
|
||||
env = _scan_env(False, DEFAULT_CONFIG)
|
||||
env.pop("GIT_TERMINAL_PROMPT", None)
|
||||
env.pop("GIT_ASKPASS", None)
|
||||
return {**env, **extra}
|
||||
|
||||
|
||||
def _tgit_run(tdir: str, args: tuple[str, ...], local: bool) -> bytes:
|
||||
"""
|
||||
Args:
|
||||
tdir: the temporary bare repository.
|
||||
args: the git arguments.
|
||||
local: also allow the file protocol, for transfers with the checkout.
|
||||
|
||||
Returns:
|
||||
The raw stdout.
|
||||
|
||||
Raises:
|
||||
GitRunError: git failed.
|
||||
|
||||
"""
|
||||
cmd = [
|
||||
"git",
|
||||
f"--git-dir={tdir}",
|
||||
*TRUSTED_FLAGS,
|
||||
*(_FILE_PROTOCOL if local else ()),
|
||||
*args,
|
||||
]
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
cwd=tdir,
|
||||
env=trusted_env({}),
|
||||
input=b"",
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise GitRunError(
|
||||
redact_urls(
|
||||
f"Git command failed in {tdir!r}: {' '.join(cmd)}\n"
|
||||
f"Exit code: {result.returncode}\n"
|
||||
f"STDERR:\n{os.fsdecode(result.stderr)}"
|
||||
)
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def tgit_bytes(tdir: str, *args: str) -> bytes:
|
||||
return _tgit_run(tdir, args, False)
|
||||
|
||||
|
||||
def tgit(tdir: str, *args: str) -> str:
|
||||
return os.fsdecode(_tgit_run(tdir, args, False)).strip()
|
||||
|
||||
|
||||
def tgit_local(tdir: str, *args: str) -> str:
|
||||
return os.fsdecode(_tgit_run(tdir, args, True)).strip()
|
||||
|
||||
|
||||
def _ttry(tdir: str, *args: str) -> str | None:
|
||||
try:
|
||||
return tgit(tdir, *args) or None
|
||||
except GitRunError:
|
||||
return None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def trusted_repo(repo_dir: str) -> Iterator[str]:
|
||||
tdir = tempfile.mkdtemp(prefix="pkgmgr-push-")
|
||||
try:
|
||||
object_format = try_git(repo_dir, "config", "--get", "extensions.objectFormat")
|
||||
tgit(
|
||||
tdir,
|
||||
"init",
|
||||
"--quiet",
|
||||
"--bare",
|
||||
"--template=",
|
||||
*((f"--object-format={object_format}",) if object_format else ()),
|
||||
)
|
||||
yield tdir
|
||||
finally:
|
||||
shutil.rmtree(tdir, ignore_errors=True)
|
||||
|
||||
|
||||
def _scheme_url_allowed(url: str) -> bool:
|
||||
if url.split("://", 1)[0] not in PUSH_SCHEMES:
|
||||
return False
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
host = parts.hostname or ""
|
||||
user = parts.username or ""
|
||||
except ValueError:
|
||||
return False
|
||||
return bool(host) and not host.startswith("-") and not user.startswith("-")
|
||||
|
||||
|
||||
def url_allowed(url: str) -> bool:
|
||||
if any(ch.isspace() or not ch.isprintable() for ch in url):
|
||||
return False
|
||||
if "://" not in url:
|
||||
return _SCP_URL.fullmatch(url) is not None
|
||||
return _scheme_url_allowed(url)
|
||||
|
||||
|
||||
def _listed_head(repo_dir: str, tdir: str) -> tuple[str, str]:
|
||||
symrefs: dict[str, str] = {}
|
||||
refs: dict[str, str] = {}
|
||||
listed = tgit_local(tdir, "ls-remote", "--symref", "--", file_url(repo_dir))
|
||||
for line in listed.splitlines():
|
||||
value, _, name = line.partition("\t")
|
||||
if value.startswith("ref: "):
|
||||
symrefs[name] = value[len("ref: ") :]
|
||||
else:
|
||||
refs[name] = value
|
||||
target = symrefs.get("HEAD", "")
|
||||
if "HEAD" not in refs or not target.startswith("refs/heads/"):
|
||||
raise PushRefusedError(f"{repo_dir}: detached HEAD, nothing to push")
|
||||
return target[len("refs/heads/") :], refs["HEAD"]
|
||||
|
||||
|
||||
def _push_remote(repo_dir: str, branch: str) -> str:
|
||||
return (
|
||||
try_git(repo_dir, "config", "--get", f"branch.{branch}.pushRemote")
|
||||
or try_git(repo_dir, "config", "--get", "remote.pushDefault")
|
||||
or try_git(repo_dir, "config", "--get", f"branch.{branch}.remote")
|
||||
or "origin"
|
||||
)
|
||||
|
||||
|
||||
def open_target(repo_dir: str, tdir: str) -> Target:
|
||||
"""
|
||||
Args:
|
||||
repo_dir: the checkout, read through upload-pack and `git config`.
|
||||
tdir: the temporary bare repository.
|
||||
|
||||
Returns:
|
||||
The checkout's current branch, its HEAD and the push remote's URLs.
|
||||
|
||||
Raises:
|
||||
PushRefusedError: detached HEAD, no URL, or a URL that is not https,
|
||||
ssh or user@host:path.
|
||||
|
||||
"""
|
||||
branch, head = _listed_head(repo_dir, tdir)
|
||||
remote = _push_remote(repo_dir, branch)
|
||||
urls = _config_all(repo_dir, f"remote.{remote}.url")
|
||||
if not urls:
|
||||
raise PushRefusedError(f"{repo_dir}: remote {remote} has no URL")
|
||||
push_urls = tuple(_config_all(repo_dir, f"remote.{remote}.pushurl") or urls)
|
||||
for url in (urls[0], *push_urls):
|
||||
if not url_allowed(url):
|
||||
raise PushRefusedError(
|
||||
f"{repo_dir}: remote {remote} URL {redact_urls(repr(url))} is not "
|
||||
"https, ssh or user@host:path; local paths and other transports are "
|
||||
"not pushed to"
|
||||
)
|
||||
return Target(repo_dir, tdir, branch, head, remote, urls[0], push_urls)
|
||||
|
||||
|
||||
def copy_head(target: Target, *, tags: bool) -> None:
|
||||
tgit_local(
|
||||
target.tdir,
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"--no-write-fetch-head",
|
||||
"--no-recurse-submodules",
|
||||
"--",
|
||||
file_url(target.repo_dir),
|
||||
target.head,
|
||||
*(("+refs/tags/*:refs/tags/*",) if tags else ()),
|
||||
)
|
||||
|
||||
|
||||
def fetch_heads(
|
||||
target: Target, url: str, names: list[str], prefix: str
|
||||
) -> dict[str, str]:
|
||||
wanted = [f"refs/heads/{name}" for name in dict.fromkeys(names)]
|
||||
listed = tgit(target.tdir, "ls-remote", "--", url, *wanted).splitlines()
|
||||
present = {ln.partition("\t")[2] for ln in listed} & set(wanted)
|
||||
if not present:
|
||||
return {}
|
||||
tgit(
|
||||
target.tdir,
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"--no-write-fetch-head",
|
||||
"--no-recurse-submodules",
|
||||
"--",
|
||||
url,
|
||||
*(f"+{ref}:{prefix}/{ref}" for ref in sorted(present)),
|
||||
)
|
||||
return {
|
||||
ref[len("refs/heads/") :]: tgit(
|
||||
target.tdir, "rev-parse", "--verify", "--quiet", f"{prefix}/{ref}"
|
||||
)
|
||||
for ref in present
|
||||
}
|
||||
|
||||
|
||||
def _upstream_branch(target: Target) -> tuple[str, str] | None:
|
||||
remote = try_git(
|
||||
target.repo_dir, "config", "--get", f"branch.{target.branch}.remote"
|
||||
)
|
||||
merge = try_git(target.repo_dir, "config", "--get", f"branch.{target.branch}.merge")
|
||||
if not remote or remote == "." or not (merge or "").startswith("refs/heads/"):
|
||||
return None
|
||||
return remote, merge[len("refs/heads/") :]
|
||||
|
||||
|
||||
def _upstream_tip(target: Target) -> tuple[str | None, str | None]:
|
||||
upstream = _upstream_branch(target)
|
||||
if upstream is None:
|
||||
return None, None
|
||||
remote, name = upstream
|
||||
if remote == target.remote:
|
||||
return name, None
|
||||
urls = _config_all(target.repo_dir, f"remote.{remote}.url")
|
||||
if not urls or not url_allowed(urls[0]):
|
||||
return None, None
|
||||
try:
|
||||
return None, fetch_heads(target, urls[0], [name], "refs/pkgmgr/upstream").get(
|
||||
name
|
||||
)
|
||||
except GitRunError:
|
||||
return None, None
|
||||
|
||||
|
||||
def bases(target: Target) -> tuple[str | None, list[str | None]]:
|
||||
"""
|
||||
Returns:
|
||||
The push remote's tip of the branch, and the candidate bases in order:
|
||||
that tip, the upstream's tip, then the remote's main and master.
|
||||
|
||||
"""
|
||||
upstream_name, upstream_sha = _upstream_tip(target)
|
||||
names = [
|
||||
target.branch,
|
||||
*([upstream_name] if upstream_name else []),
|
||||
"main",
|
||||
"master",
|
||||
]
|
||||
tips = fetch_heads(target, target.fetch_url, names, "refs/pkgmgr/base")
|
||||
upstream = tips.get(upstream_name) if upstream_name else upstream_sha
|
||||
return tips.get(target.branch), [
|
||||
tips.get(target.branch),
|
||||
upstream,
|
||||
tips.get("main"),
|
||||
tips.get("master"),
|
||||
]
|
||||
|
||||
|
||||
def unpushed_signatures(
|
||||
target: Target, candidates: list[str | None]
|
||||
) -> tuple[str, dict[str, str]]:
|
||||
"""
|
||||
Args:
|
||||
target: the copied checkout.
|
||||
candidates: bases as `bases` returns them; the first with a merge base wins.
|
||||
|
||||
Returns:
|
||||
The merge base, and the `%G?` signature status of every commit after it.
|
||||
|
||||
Raises:
|
||||
PushRefusedError: no candidate shares history with HEAD.
|
||||
|
||||
"""
|
||||
for tip in candidates:
|
||||
base = tip and _ttry(target.tdir, "merge-base", target.head, tip)
|
||||
if base:
|
||||
lines = tgit(
|
||||
target.tdir, "log", "--format=%H %G?", f"{base}..{target.head}"
|
||||
).splitlines()
|
||||
return base, dict(line.split() for line in lines)
|
||||
raise PushRefusedError(
|
||||
f"{target.repo_dir}: no {target.remote}/{target.branch}, no upstream and no "
|
||||
f"{target.remote}/main or {target.remote}/master to sign against"
|
||||
)
|
||||
@@ -7,8 +7,13 @@ from typing import Any
|
||||
from pkgmgr.core.git.queries import get_repo_root
|
||||
|
||||
try:
|
||||
from jinja2 import Environment, FileSystemLoader, StrictUndefined
|
||||
except ImportError as exc: # pragma: no cover
|
||||
from jinja2 import (
|
||||
Environment,
|
||||
FileSystemLoader,
|
||||
StrictUndefined,
|
||||
select_autoescape,
|
||||
)
|
||||
except ImportError as exc: # pragma: no cover
|
||||
Environment = None # type: ignore
|
||||
FileSystemLoader = None # type: ignore
|
||||
StrictUndefined = None # type: ignore
|
||||
@@ -41,7 +46,18 @@ class TemplateRenderer:
|
||||
env = Environment(
|
||||
loader=FileSystemLoader(self.templates_dir),
|
||||
undefined=StrictUndefined,
|
||||
autoescape=False,
|
||||
autoescape=select_autoescape(
|
||||
enabled_extensions=(
|
||||
"html",
|
||||
"htm",
|
||||
"xml",
|
||||
"html.j2",
|
||||
"htm.j2",
|
||||
"xml.j2",
|
||||
),
|
||||
default_for_string=False,
|
||||
default=False,
|
||||
),
|
||||
keep_trailing_newline=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from pkgmgr.actions.repository._parallel import (
|
||||
@@ -9,25 +12,42 @@ from pkgmgr.actions.repository._parallel import (
|
||||
resolve_repos,
|
||||
run_on_repos,
|
||||
)
|
||||
from pkgmgr.actions.repository._trusted import (
|
||||
CHECKOUT_FETCH_FLAGS,
|
||||
TRUSTED_FLAGS,
|
||||
PushRefusedError,
|
||||
Target,
|
||||
bases,
|
||||
copy_head,
|
||||
fetch_heads,
|
||||
file_url,
|
||||
open_target,
|
||||
redact_urls,
|
||||
tgit,
|
||||
tgit_bytes,
|
||||
trusted_env,
|
||||
trusted_repo,
|
||||
try_git,
|
||||
unpushed_signatures,
|
||||
)
|
||||
from pkgmgr.core.git import GitRunError, run
|
||||
from pkgmgr.core.git.queries import UNSAFE_CONFIG, local_config
|
||||
from pkgmgr.core.git.run import SCAN_FLAGS
|
||||
|
||||
Repository = dict[str, Any]
|
||||
|
||||
# Re-signing opens pinentry; parallel pushes must not ask for the passphrase at once.
|
||||
_SIGN_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class PushRefusedError(RuntimeError):
|
||||
"""Raised when a push would ship unsigned commits or overwrite a mirror."""
|
||||
_AUTHOR = re.compile(rb"(.*?) <([^>]*)> (\d+) ([+-]\d{4})")
|
||||
|
||||
|
||||
def _try_git(repo_dir: str, *args: str) -> str | None:
|
||||
try:
|
||||
return run(list(args), cwd=repo_dir)
|
||||
except GitRunError:
|
||||
return None
|
||||
@dataclass(frozen=True)
|
||||
class _Push:
|
||||
extra_args: tuple[str, ...]
|
||||
refs: tuple[str, ...]
|
||||
rewrite: bool
|
||||
preview: bool
|
||||
old_tip: str | None
|
||||
|
||||
|
||||
def refuse_unsafe_config(repo_dir: str) -> None:
|
||||
@@ -38,9 +58,10 @@ def refuse_unsafe_config(repo_dir: str) -> None:
|
||||
Raises:
|
||||
PushRefusedError: the repository's own config, which an agent may have
|
||||
written, sets a key that makes git run a program or reroute the push.
|
||||
Filter drivers stay allowed on purpose: git-lfs and git-crypt need
|
||||
them locally, so a clean filter can still run in the amend's index
|
||||
refresh, as it did before.
|
||||
Signing and pushing never read that config, so this is only an early
|
||||
refusal; filter drivers stay allowed because git-lfs and git-crypt
|
||||
need them locally.
|
||||
|
||||
"""
|
||||
unsafe = local_config(repo_dir, UNSAFE_CONFIG)
|
||||
if unsafe:
|
||||
@@ -50,142 +71,171 @@ def refuse_unsafe_config(repo_dir: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _push_target(repo_dir: str) -> tuple[str, str]:
|
||||
refuse_unsafe_config(repo_dir)
|
||||
branch = run(["rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_dir)
|
||||
if branch == "HEAD":
|
||||
raise PushRefusedError(f"{repo_dir}: detached HEAD, nothing to push")
|
||||
remote = (
|
||||
_try_git(repo_dir, "config", "--get", f"branch.{branch}.pushRemote")
|
||||
or _try_git(repo_dir, "config", "--get", "remote.pushDefault")
|
||||
or _try_git(repo_dir, "config", "--get", f"branch.{branch}.remote")
|
||||
or "origin"
|
||||
)
|
||||
return branch, remote
|
||||
def _head_commit(target: Target) -> tuple[list[str], dict[str, str], bytes]:
|
||||
"""
|
||||
Args:
|
||||
target: the copied checkout.
|
||||
|
||||
Returns:
|
||||
The `git commit-tree` arguments that rebuild HEAD (encoding, tree,
|
||||
parents), its author as environment variables, and its message.
|
||||
|
||||
Raises:
|
||||
PushRefusedError: HEAD has no tree or no parseable author.
|
||||
|
||||
"""
|
||||
fields, message = _commit_fields(target)
|
||||
author = _AUTHOR.fullmatch((fields.get(b"author") or [b""])[0])
|
||||
if not fields.get(b"tree") or author is None:
|
||||
raise PushRefusedError(
|
||||
f"{target.repo_dir}: cannot parse HEAD {target.head[:10]}"
|
||||
)
|
||||
name, email, stamp, zone = (os.fsdecode(part) for part in author.groups())
|
||||
args = [
|
||||
"-c",
|
||||
"i18n.commitEncoding="
|
||||
+ os.fsdecode((fields.get(b"encoding") or [b"UTF-8"])[0]),
|
||||
"commit-tree",
|
||||
os.fsdecode(fields[b"tree"][0]),
|
||||
*(arg for p in fields.get(b"parent", []) for arg in ("-p", os.fsdecode(p))),
|
||||
]
|
||||
env = {
|
||||
"GIT_AUTHOR_NAME": name,
|
||||
"GIT_AUTHOR_EMAIL": email,
|
||||
"GIT_AUTHOR_DATE": f"@{stamp} {zone}",
|
||||
}
|
||||
return args, env, message
|
||||
|
||||
|
||||
def _unpushed_signatures(
|
||||
repo_dir: str, remote: str, branch: str
|
||||
) -> tuple[str, dict[str, str]]:
|
||||
for ref in (
|
||||
f"refs/remotes/{remote}/{branch}",
|
||||
"@{u}",
|
||||
f"refs/remotes/{remote}/main",
|
||||
f"refs/remotes/{remote}/master",
|
||||
):
|
||||
base = _try_git(repo_dir, "merge-base", "HEAD", ref)
|
||||
if base:
|
||||
lines = run(
|
||||
["log", "--format=%H %G?", f"{base}..HEAD"], cwd=repo_dir
|
||||
).splitlines()
|
||||
return base, dict(line.split() for line in lines)
|
||||
raise PushRefusedError(
|
||||
f"{repo_dir}: no {remote}/{branch}, no upstream and no {remote}/main or "
|
||||
f"{remote}/master to sign against"
|
||||
def _commit_fields(target: Target) -> tuple[dict[bytes, list[bytes]], bytes]:
|
||||
header, _, message = tgit_bytes(
|
||||
target.tdir, "cat-file", "commit", target.head
|
||||
).partition(b"\n\n")
|
||||
fields: dict[bytes, list[bytes]] = {}
|
||||
for line in header.split(b"\n"):
|
||||
key, _, value = line.partition(b" ")
|
||||
fields.setdefault(key, []).append(value)
|
||||
return fields, message
|
||||
|
||||
|
||||
def _sign_head(target: Target) -> str:
|
||||
args, author, message = _head_commit(target)
|
||||
cmd = ["git", f"--git-dir={target.tdir}", *TRUSTED_FLAGS, *args, "-S"]
|
||||
with _SIGN_LOCK:
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
cwd=target.tdir,
|
||||
env=trusted_env(author),
|
||||
input=message,
|
||||
stdout=subprocess.PIPE,
|
||||
check=False,
|
||||
)
|
||||
signed = os.fsdecode(result.stdout).strip()
|
||||
if result.returncode != 0 or not signed:
|
||||
raise PushRefusedError(
|
||||
f"{target.repo_dir}: signing HEAD {target.head[:10]} failed"
|
||||
)
|
||||
tgit(target.tdir, "update-ref", "refs/pkgmgr/signed", signed)
|
||||
return signed
|
||||
|
||||
|
||||
def _adopt(target: Target, signed: str) -> None:
|
||||
"""
|
||||
Args:
|
||||
target: the checkout and its temporary repository.
|
||||
signed: the signed commit; fetched into the checkout, then its branch
|
||||
moves there. That fetch still reads the checkout's config, so
|
||||
CHECKOUT_FETCH_FLAGS pins every key that would fetch from elsewhere
|
||||
or run a program, in case the refuse-list check is stale.
|
||||
|
||||
Raises:
|
||||
PushRefusedError: the branch moved away from HEAD while it was signed.
|
||||
|
||||
"""
|
||||
run(
|
||||
[
|
||||
*CHECKOUT_FETCH_FLAGS,
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"--no-write-fetch-head",
|
||||
"--no-recurse-submodules",
|
||||
"--upload-pack=git-upload-pack",
|
||||
"--",
|
||||
file_url(target.tdir),
|
||||
signed,
|
||||
],
|
||||
cwd=target.repo_dir,
|
||||
scan=True,
|
||||
)
|
||||
try:
|
||||
run(
|
||||
[
|
||||
"update-ref",
|
||||
"-m",
|
||||
"pkgmgr push: sign HEAD",
|
||||
target.branch_ref,
|
||||
signed,
|
||||
target.head,
|
||||
],
|
||||
cwd=target.repo_dir,
|
||||
scan=True,
|
||||
)
|
||||
except GitRunError as exc:
|
||||
raise PushRefusedError(
|
||||
f"{target.repo_dir}: {target.branch} moved away from {target.head[:10]} "
|
||||
f"while it was signed; left it where it is, signed {signed[:10]} is dropped"
|
||||
) from exc
|
||||
|
||||
|
||||
def sign_unpushed(repo_dir: str, *, preview: bool = False) -> None:
|
||||
"""
|
||||
Args:
|
||||
repo_dir: checkout whose current branch is signed.
|
||||
preview: print the fetch and the amend instead of running them.
|
||||
preview: read and check as usual, but print the signing instead of doing it.
|
||||
|
||||
"""
|
||||
branch, remote = _push_target(repo_dir)
|
||||
run(
|
||||
["fetch", "--quiet", "--no-recurse-submodules", "--", remote],
|
||||
cwd=repo_dir,
|
||||
preview=preview,
|
||||
)
|
||||
base, signatures = _unpushed_signatures(repo_dir, remote, branch)
|
||||
head = run(["rev-parse", "HEAD"], cwd=repo_dir)
|
||||
older = sum(1 for sha, s in signatures.items() if sha != head and s != "G")
|
||||
if older:
|
||||
print(
|
||||
f"[push] WARN {older} older unsigned commit(s) in {base[:10]}..HEAD~ of "
|
||||
f"{repo_dir} stay unsigned: signing them would rewrite history"
|
||||
)
|
||||
if signatures.get(head, "G") == "G":
|
||||
return
|
||||
if run(
|
||||
[
|
||||
*SCAN_FLAGS,
|
||||
"diff",
|
||||
"--cached",
|
||||
"--name-only",
|
||||
"--no-ext-diff",
|
||||
"--ignore-submodules=none",
|
||||
"HEAD",
|
||||
],
|
||||
cwd=repo_dir,
|
||||
):
|
||||
raise PushRefusedError(f"{repo_dir}: staged changes, cannot sign HEAD")
|
||||
|
||||
cmd = [
|
||||
"git",
|
||||
*SCAN_FLAGS,
|
||||
"commit",
|
||||
"--amend",
|
||||
"--no-edit",
|
||||
"--no-verify",
|
||||
"--allow-empty",
|
||||
"-S",
|
||||
]
|
||||
print(f"[push] Signing HEAD {head[:10]} in {repo_dir}")
|
||||
if preview:
|
||||
print(f"[PREVIEW] Would run in {repo_dir!r}: {' '.join(cmd)}")
|
||||
return
|
||||
with _SIGN_LOCK:
|
||||
result = subprocess.run(cmd, cwd=repo_dir, check=False)
|
||||
if result.returncode != 0:
|
||||
raise PushRefusedError(f"{repo_dir}: signing HEAD {head[:10]} failed")
|
||||
|
||||
|
||||
def _lease(
|
||||
repo_dir: str,
|
||||
url: str,
|
||||
branch_ref: str,
|
||||
tracking: str | None,
|
||||
keep: tuple[str, ...],
|
||||
preview: bool,
|
||||
) -> str:
|
||||
if tracking is not None:
|
||||
sha = _try_git(repo_dir, "rev-parse", "--verify", "--quiet", tracking) or ""
|
||||
else:
|
||||
listed = run(["ls-remote", "--", url, branch_ref], cwd=repo_dir).splitlines()
|
||||
sha = next(
|
||||
(ln.split()[0] for ln in listed if ln.split()[1:] == [branch_ref]), ""
|
||||
)
|
||||
if sha and not preview:
|
||||
run(
|
||||
[
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"--no-recurse-submodules",
|
||||
"--",
|
||||
url,
|
||||
branch_ref,
|
||||
],
|
||||
cwd=repo_dir,
|
||||
refuse_unsafe_config(repo_dir)
|
||||
with trusted_repo(repo_dir) as tdir:
|
||||
target = open_target(repo_dir, tdir)
|
||||
copy_head(target, tags=False)
|
||||
_tip, candidates = bases(target)
|
||||
base, signatures = unpushed_signatures(target, candidates)
|
||||
head = target.head
|
||||
older = sum(1 for sha, s in signatures.items() if sha != head and s != "G")
|
||||
if older:
|
||||
print(
|
||||
f"[push] WARN {older} older unsigned commit(s) in {base[:10]}..HEAD~ of "
|
||||
f"{repo_dir} stay unsigned: signing them would rewrite history"
|
||||
)
|
||||
if not sha or preview:
|
||||
return sha
|
||||
if signatures.get(head, "G") == "G":
|
||||
return
|
||||
print(f"[push] Signing HEAD {head[:10]} in {repo_dir}")
|
||||
if preview:
|
||||
print(
|
||||
f"[PREVIEW] Would re-sign {head[:10]} with git commit-tree -S in a "
|
||||
f"temporary repository and move {target.branch_ref} of {repo_dir!r} to it"
|
||||
)
|
||||
return
|
||||
_adopt(target, _sign_head(target))
|
||||
|
||||
|
||||
def _refuse_lost(target: Target, url: str, sha: str, keep: tuple[str, ...]) -> None:
|
||||
lost: set[str] | None = None
|
||||
for tip in keep:
|
||||
plus = {
|
||||
line[2:]
|
||||
for line in run(["cherry", tip, sha], cwd=repo_dir).splitlines()
|
||||
for line in tgit(target.tdir, "cherry", tip, sha).splitlines()
|
||||
if line.startswith("+")
|
||||
}
|
||||
lost = plus if lost is None else lost & plus
|
||||
if lost:
|
||||
raise PushRefusedError(
|
||||
f"{url}: {len(lost)} commit(s) exist only there, not overwritten: "
|
||||
f"{redact_urls(url)}: {len(lost)} commit(s) exist only there, "
|
||||
"not overwritten: "
|
||||
f"{' '.join(s[:10] for s in sorted(lost))}; "
|
||||
"pass --rewrite for a deliberate history rewrite"
|
||||
)
|
||||
return sha
|
||||
|
||||
|
||||
def push_branch(
|
||||
@@ -198,13 +248,6 @@ def push_branch(
|
||||
preview: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Push the current branch to every pushurl of its push remote, each with its own lease.
|
||||
|
||||
The fetch URL is leased against the remote-tracking ref, every other
|
||||
pushurl against its own branch tip; each only after `git cherry` shows it
|
||||
holds no commit the new tip lacks. A mirror failure is reported after the
|
||||
others were pushed; a canonical failure stops before any mirror.
|
||||
|
||||
Args:
|
||||
repo_dir: checkout whose current branch is pushed.
|
||||
extra_args: flags appended to every `git push`.
|
||||
@@ -213,73 +256,134 @@ def push_branch(
|
||||
rewrite: replace commits of the old canonical tip; the fetch URL skips
|
||||
the cherry check, mirrors only refuse commits the old tip never had.
|
||||
preview: print the pushes instead of running them.
|
||||
"""
|
||||
branch, remote = _push_target(repo_dir)
|
||||
head = run(["rev-parse", "HEAD"], cwd=repo_dir)
|
||||
if sign:
|
||||
_base, signatures = _unpushed_signatures(repo_dir, remote, branch)
|
||||
if not preview and signatures.get(head, "G") != "G":
|
||||
raise PushRefusedError(
|
||||
f"{repo_dir}: HEAD {head[:10]} is unsigned; run `pkgmgr push` to sign it"
|
||||
)
|
||||
|
||||
fetch_url = run(["remote", "get-url", "--", remote], cwd=repo_dir)
|
||||
push_urls = run(
|
||||
["remote", "get-url", "--push", "--all", "--", remote], cwd=repo_dir
|
||||
).splitlines()
|
||||
branch_ref = f"refs/heads/{branch}"
|
||||
tracking = f"refs/remotes/{remote}/{branch}"
|
||||
old_tip = _try_git(repo_dir, "rev-parse", "--verify", "--quiet", tracking)
|
||||
if fetch_url not in push_urls:
|
||||
print(
|
||||
f"[push] WARN {remote}: fetch URL is no pushurl; every URL is leased "
|
||||
"as a mirror, tracking ref and upstream stay untouched"
|
||||
"""
|
||||
refuse_unsafe_config(repo_dir)
|
||||
with trusted_repo(repo_dir) as tdir:
|
||||
target = open_target(repo_dir, tdir)
|
||||
copy_head(target, tags=True)
|
||||
old_tip = _old_tip(target, sign, preview)
|
||||
plan = _Push(tuple(extra_args), refs, rewrite, preview, old_tip)
|
||||
if target.fetch_url not in target.push_urls:
|
||||
print(
|
||||
f"[push] WARN {target.remote}: fetch URL is no pushurl; every URL is "
|
||||
"leased as a mirror, tracking ref and upstream stay untouched"
|
||||
)
|
||||
failed: list[str] = []
|
||||
ordered = sorted(target.push_urls, key=lambda u: u != target.fetch_url)
|
||||
for index, url in enumerate(ordered):
|
||||
if not _push_url(target, plan, index, url):
|
||||
failed.append(url)
|
||||
if failed:
|
||||
raise PushRefusedError(
|
||||
f"{repo_dir}: push failed for {redact_urls(', '.join(failed))}"
|
||||
)
|
||||
|
||||
failed: list[str] = []
|
||||
for url in sorted(push_urls, key=lambda u: u != fetch_url):
|
||||
if url == fetch_url:
|
||||
keep: tuple[str, ...] = () if rewrite else (head,)
|
||||
else:
|
||||
keep = (head, old_tip) if rewrite and old_tip else (head,)
|
||||
try:
|
||||
expect = _lease(
|
||||
repo_dir,
|
||||
url,
|
||||
branch_ref,
|
||||
tracking if url == fetch_url else None,
|
||||
keep,
|
||||
preview,
|
||||
)
|
||||
run(
|
||||
[
|
||||
"push",
|
||||
"--follow-tags",
|
||||
"--no-recurse-submodules",
|
||||
f"--force-with-lease={branch_ref}:{expect}",
|
||||
*extra_args,
|
||||
"--",
|
||||
url,
|
||||
branch_ref,
|
||||
*refs,
|
||||
],
|
||||
cwd=repo_dir,
|
||||
preview=preview,
|
||||
)
|
||||
except (GitRunError, PushRefusedError) as exc:
|
||||
if url == fetch_url:
|
||||
raise
|
||||
print(f"[push] FAILED {url}\n{exc}")
|
||||
failed.append(url)
|
||||
continue
|
||||
print(f"[push] {url} <- {branch} {head[:10]}")
|
||||
if url == fetch_url and not preview:
|
||||
run(["update-ref", tracking, head], cwd=repo_dir)
|
||||
if not _try_git(repo_dir, "rev-parse", "--abbrev-ref", "@{u}"):
|
||||
run(["branch", f"--set-upstream-to={remote}/{branch}"], cwd=repo_dir)
|
||||
|
||||
if failed:
|
||||
raise PushRefusedError(f"{repo_dir}: push failed for {', '.join(failed)}")
|
||||
def _old_tip(target: Target, sign: bool, preview: bool) -> str | None:
|
||||
"""
|
||||
Args:
|
||||
target: the copied checkout.
|
||||
sign: also refuse an unpushed, unsigned HEAD.
|
||||
preview: skip that refusal.
|
||||
|
||||
Returns:
|
||||
The canonical URL's branch tip, or None when it has no such branch.
|
||||
|
||||
"""
|
||||
if not sign:
|
||||
return fetch_heads(
|
||||
target, target.fetch_url, [target.branch], "refs/pkgmgr/base"
|
||||
).get(target.branch)
|
||||
old_tip, candidates = bases(target)
|
||||
_base, signatures = unpushed_signatures(target, candidates)
|
||||
if not preview and target.head in signatures and signatures[target.head] != "G":
|
||||
raise PushRefusedError(
|
||||
f"{target.repo_dir}: HEAD {target.head[:10]} is unsigned; "
|
||||
"run `pkgmgr push` to sign it"
|
||||
)
|
||||
return old_tip
|
||||
|
||||
|
||||
def _lease(target: Target, plan: _Push, index: int, url: str) -> str:
|
||||
if url == target.fetch_url:
|
||||
return plan.old_tip or ""
|
||||
tips = fetch_heads(target, url, [target.branch], f"refs/pkgmgr/lease/{index}")
|
||||
return tips.get(target.branch) or ""
|
||||
|
||||
|
||||
def _keep(target: Target, plan: _Push, canonical: bool) -> tuple[str, ...]:
|
||||
if canonical:
|
||||
return () if plan.rewrite else (target.head,)
|
||||
if plan.rewrite and plan.old_tip:
|
||||
return (target.head, plan.old_tip)
|
||||
return (target.head,)
|
||||
|
||||
|
||||
def _push_url(target: Target, plan: _Push, index: int, url: str) -> bool:
|
||||
"""
|
||||
Args:
|
||||
target: the copied checkout.
|
||||
plan: the push options and the canonical URL's old tip.
|
||||
index: position of the URL, naming its lease ref.
|
||||
url: the URL pushed to.
|
||||
|
||||
Returns:
|
||||
False when a mirror failed; the failure is printed.
|
||||
|
||||
Raises:
|
||||
GitRunError, PushRefusedError: the canonical URL failed.
|
||||
|
||||
"""
|
||||
canonical = url == target.fetch_url
|
||||
try:
|
||||
expect = _lease(target, plan, index, url)
|
||||
if expect and not plan.preview:
|
||||
_refuse_lost(target, url, expect, _keep(target, plan, canonical))
|
||||
cmd = [
|
||||
"push",
|
||||
"--follow-tags",
|
||||
"--no-recurse-submodules",
|
||||
"--no-verify",
|
||||
f"--force-with-lease={target.branch_ref}:{expect}",
|
||||
*plan.extra_args,
|
||||
"--",
|
||||
url,
|
||||
f"{target.head}:{target.branch_ref}",
|
||||
*plan.refs,
|
||||
]
|
||||
if plan.preview:
|
||||
print(
|
||||
f"[PREVIEW] Would run in a temporary copy of {target.repo_dir!r}: "
|
||||
f"git {redact_urls(' '.join(cmd))}"
|
||||
)
|
||||
else:
|
||||
tgit(target.tdir, *cmd)
|
||||
except (GitRunError, PushRefusedError) as exc:
|
||||
if canonical:
|
||||
raise
|
||||
print(f"[push] FAILED {redact_urls(url)}\n{exc}")
|
||||
return False
|
||||
print(f"[push] {redact_urls(url)} <- {target.branch} {target.head[:10]}")
|
||||
if canonical and not plan.preview:
|
||||
_track(target)
|
||||
return True
|
||||
|
||||
|
||||
def _track(target: Target) -> None:
|
||||
tracking = f"refs/remotes/{target.remote}/{target.branch}"
|
||||
run(["update-ref", tracking, target.head], cwd=target.repo_dir, scan=True)
|
||||
upstream = f"{target.branch}@{{upstream}}"
|
||||
if not try_git(target.repo_dir, "rev-parse", "--abbrev-ref", upstream):
|
||||
run(
|
||||
[
|
||||
"branch",
|
||||
f"--set-upstream-to={target.remote}/{target.branch}",
|
||||
target.branch,
|
||||
],
|
||||
cwd=target.repo_dir,
|
||||
scan=True,
|
||||
)
|
||||
|
||||
|
||||
def _push_one(
|
||||
@@ -302,9 +406,6 @@ def push_repo_dirs(
|
||||
jobs: int = 1,
|
||||
rewrite: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Sign and push each ``(identifier, repo_dir)``, optionally in parallel.
|
||||
"""
|
||||
run_on_repos(
|
||||
repos,
|
||||
lambda rd: _push_one(rd, extra_args, sign, rewrite, preview),
|
||||
@@ -323,9 +424,6 @@ def push_in_parallel(
|
||||
jobs: int = 1,
|
||||
rewrite: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Sign and push each selected repository, optionally in parallel.
|
||||
"""
|
||||
push_repo_dirs(
|
||||
resolve_repos(selected_repos, repositories_base_dir, all_repos),
|
||||
extra_args,
|
||||
|
||||
@@ -5,6 +5,7 @@ import sys
|
||||
from typing import Any
|
||||
|
||||
from pkgmgr.actions.publish import publish as run_publish
|
||||
from pkgmgr.actions.release import ReleaseOptions
|
||||
from pkgmgr.actions.release import release as run_release
|
||||
from pkgmgr.cli.context import CLIContext
|
||||
from pkgmgr.core.git import GitRunError, run
|
||||
@@ -48,6 +49,79 @@ def release_at_cwd(args, ctx: CLIContext, selected: list[Repository]) -> None:
|
||||
handle_release(args, ctx, _at_cwd_checkout(args, selected))
|
||||
|
||||
|
||||
def _release_options(args) -> ReleaseOptions:
|
||||
return ReleaseOptions(
|
||||
pyproject_path="pyproject.toml",
|
||||
changelog_path="CHANGELOG.md",
|
||||
release_type=args.release_type or "patch",
|
||||
message=args.message or None,
|
||||
preview=getattr(args, "preview", False),
|
||||
force=getattr(args, "force", False),
|
||||
close=getattr(args, "close", False),
|
||||
retry=bool(getattr(args, "retry", False)),
|
||||
expect_tree=getattr(args, "expect_tree", None),
|
||||
)
|
||||
|
||||
|
||||
def _resolve_repo_dir(ctx: CLIContext, repo: Repository, identifier: str) -> str | None:
|
||||
"""
|
||||
Returns:
|
||||
The repository's existing directory, or None after a skip warning.
|
||||
"""
|
||||
try:
|
||||
repo_dir = repo.get("directory") or get_repo_dir(
|
||||
ctx.repositories_base_dir, repo
|
||||
)
|
||||
except (AttributeError, KeyError, TypeError) as exc:
|
||||
print(
|
||||
f"[WARN] Skipping repository {identifier}: failed to resolve directory: {exc}"
|
||||
)
|
||||
return None
|
||||
|
||||
if not os.path.isdir(repo_dir):
|
||||
print(f"[WARN] Skipping repository {identifier}: directory missing.")
|
||||
return None
|
||||
return repo_dir
|
||||
|
||||
|
||||
def _release_type_usable(args, identifier: str) -> bool:
|
||||
retry = bool(getattr(args, "retry", False))
|
||||
if retry and args.release_type:
|
||||
print(
|
||||
f"[WARN] Ignoring release_type '{args.release_type}' for {identifier} — --retry skips version bumps."
|
||||
)
|
||||
if not retry and not args.release_type:
|
||||
print(
|
||||
f"[WARN] Skipping {identifier}: release_type is required unless --retry is set."
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _release_repo(args, repo: Repository, repo_dir: str, identifier: str) -> None:
|
||||
options = _release_options(args)
|
||||
action_label = "retry-release" if options.retry else "release"
|
||||
print(f"[pkgmgr] Running {action_label} for repository {identifier}...")
|
||||
|
||||
cwd_before = os.getcwd()
|
||||
try:
|
||||
os.chdir(repo_dir)
|
||||
run_release(options)
|
||||
|
||||
if not getattr(args, "no_publish", False):
|
||||
print(f"[pkgmgr] Running publish for repository {identifier}...")
|
||||
is_tty = sys.stdin.isatty()
|
||||
run_publish(
|
||||
repo=repo,
|
||||
repo_dir=repo_dir,
|
||||
preview=options.preview,
|
||||
interactive=is_tty,
|
||||
allow_prompt=is_tty,
|
||||
)
|
||||
finally:
|
||||
os.chdir(cwd_before)
|
||||
|
||||
|
||||
def handle_release(
|
||||
args,
|
||||
ctx: CLIContext,
|
||||
@@ -66,60 +140,7 @@ def handle_release(
|
||||
|
||||
for repo in selected:
|
||||
identifier = get_repo_identifier(repo, ctx.all_repositories)
|
||||
|
||||
try:
|
||||
repo_dir = repo.get("directory") or get_repo_dir(
|
||||
ctx.repositories_base_dir, repo
|
||||
)
|
||||
except (AttributeError, KeyError, TypeError) as exc:
|
||||
print(
|
||||
f"[WARN] Skipping repository {identifier}: failed to resolve directory: {exc}"
|
||||
)
|
||||
repo_dir = _resolve_repo_dir(ctx, repo, identifier)
|
||||
if repo_dir is None or not _release_type_usable(args, identifier):
|
||||
continue
|
||||
|
||||
if not os.path.isdir(repo_dir):
|
||||
print(f"[WARN] Skipping repository {identifier}: directory missing.")
|
||||
continue
|
||||
|
||||
retry = bool(getattr(args, "retry", False))
|
||||
if retry and args.release_type:
|
||||
print(
|
||||
f"[WARN] Ignoring release_type '{args.release_type}' for {identifier} — --retry skips version bumps."
|
||||
)
|
||||
if not retry and not args.release_type:
|
||||
print(
|
||||
f"[WARN] Skipping {identifier}: release_type is required unless --retry is set."
|
||||
)
|
||||
continue
|
||||
|
||||
action_label = "retry-release" if retry else "release"
|
||||
print(f"[pkgmgr] Running {action_label} for repository {identifier}...")
|
||||
|
||||
cwd_before = os.getcwd()
|
||||
try:
|
||||
os.chdir(repo_dir)
|
||||
|
||||
run_release(
|
||||
pyproject_path="pyproject.toml",
|
||||
changelog_path="CHANGELOG.md",
|
||||
release_type=args.release_type or "patch",
|
||||
message=args.message or None,
|
||||
preview=getattr(args, "preview", False),
|
||||
force=getattr(args, "force", False),
|
||||
close=getattr(args, "close", False),
|
||||
retry=retry,
|
||||
)
|
||||
|
||||
if not getattr(args, "no_publish", False):
|
||||
print(f"[pkgmgr] Running publish for repository {identifier}...")
|
||||
is_tty = sys.stdin.isatty()
|
||||
run_publish(
|
||||
repo=repo,
|
||||
repo_dir=repo_dir,
|
||||
preview=getattr(args, "preview", False),
|
||||
interactive=is_tty,
|
||||
allow_prompt=is_tty,
|
||||
)
|
||||
|
||||
finally:
|
||||
os.chdir(cwd_before)
|
||||
_release_repo(args, repo, repo_dir, identifier)
|
||||
@@ -3,9 +3,11 @@ from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from pkgmgr.actions.branch.gc import main_repo_root
|
||||
from pkgmgr.actions.gc.report import disk_report, render_text
|
||||
from pkgmgr.actions.gc.risk import RiskRequest, risk_cleanup
|
||||
from pkgmgr.actions.worktree.flow_actions import (
|
||||
worktree_flow_clear,
|
||||
worktree_flow_set,
|
||||
@@ -118,7 +120,28 @@ def handle_worktree(args, ctx: CLIContext) -> None:
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def _risk_request(args, ctx: CLIContext) -> RiskRequest:
|
||||
return RiskRequest(
|
||||
level=args.risk,
|
||||
apply=args.apply,
|
||||
as_json=args.json,
|
||||
owners_file=args.owners,
|
||||
hooks=pinned_hooks(ctx),
|
||||
min_age=args.min_age,
|
||||
tmp_root=tempfile.gettempdir(),
|
||||
**scan_options(args),
|
||||
)
|
||||
|
||||
|
||||
def handle_gc(args, ctx: CLIContext) -> None:
|
||||
if args.risk:
|
||||
if args.report:
|
||||
print("--risk cannot be combined with --report", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
sys.exit(risk_cleanup(scan_repo_roots(args, ctx), _risk_request(args, ctx)))
|
||||
if args.owners:
|
||||
print("--owners only with --risk", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
if not args.report:
|
||||
run_cleanup(args, ctx, "all")
|
||||
if args.apply:
|
||||
|
||||
@@ -2,6 +2,8 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
from pkgmgr.actions.gc.risk.levels import LEVELS
|
||||
|
||||
from .branch_cmd import add_apply_options, add_min_age_option, add_scan_options
|
||||
|
||||
|
||||
@@ -16,6 +18,11 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
|
||||
add_apply_options(gc)
|
||||
add_scan_options(gc)
|
||||
add_min_age_option(gc)
|
||||
_add_report_options(gc)
|
||||
_add_risk_options(gc)
|
||||
|
||||
|
||||
def _add_report_options(gc: argparse.ArgumentParser) -> None:
|
||||
gc.add_argument(
|
||||
"--report",
|
||||
action="store_true",
|
||||
@@ -44,3 +51,26 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
|
||||
action="store_true",
|
||||
help="With --report: also read `docker system df`",
|
||||
)
|
||||
|
||||
|
||||
def _add_risk_options(gc: argparse.ArgumentParser) -> None:
|
||||
gc.add_argument(
|
||||
"--risk",
|
||||
choices=LEVELS,
|
||||
help=(
|
||||
"Plan branches, worktrees, docker volumes, unused images, idle build "
|
||||
"cache, stopped containers and /tmp entries with a risk class each "
|
||||
"and print the items up to RISK; --apply removes exactly the low "
|
||||
"items of that plan and needs --risk low; with --branch only the "
|
||||
"matching git items are planned"
|
||||
),
|
||||
)
|
||||
gc.add_argument(
|
||||
"--owners",
|
||||
metavar="FILE",
|
||||
help=(
|
||||
"With --risk: JSON object of /tmp path -> owner task status; only "
|
||||
"an entry whose task is done or stopped and that is unchanged for "
|
||||
"24 h is low"
|
||||
),
|
||||
)
|
||||
@@ -5,20 +5,7 @@ import argparse
|
||||
from .common import add_identifier_arguments
|
||||
|
||||
|
||||
def add_release_subparser(
|
||||
subparsers: argparse._SubParsersAction,
|
||||
) -> None:
|
||||
"""
|
||||
Register the release command.
|
||||
"""
|
||||
release_parser = subparsers.add_parser(
|
||||
"release",
|
||||
help=(
|
||||
"Create a release for repository/ies by incrementing version "
|
||||
"and updating the changelog."
|
||||
),
|
||||
)
|
||||
|
||||
def _add_version_arguments(release_parser: argparse.ArgumentParser) -> None:
|
||||
release_parser.add_argument(
|
||||
"release_type",
|
||||
nargs="?",
|
||||
@@ -36,8 +23,8 @@ def add_release_subparser(
|
||||
help="Optional release message to add to the changelog and tag.",
|
||||
)
|
||||
|
||||
add_identifier_arguments(release_parser)
|
||||
|
||||
def _add_flow_arguments(release_parser: argparse.ArgumentParser) -> None:
|
||||
release_parser.add_argument(
|
||||
"--close",
|
||||
action="store_true",
|
||||
@@ -52,8 +39,7 @@ def add_release_subparser(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Skip the interactive preview+confirmation step and run the "
|
||||
"release directly."
|
||||
"Run the release directly, without the interactive preview and its prompt."
|
||||
),
|
||||
)
|
||||
|
||||
@@ -63,6 +49,19 @@ def add_release_subparser(
|
||||
help="Do not run publish automatically after a successful release.",
|
||||
)
|
||||
|
||||
|
||||
def _add_safety_arguments(release_parser: argparse.ArgumentParser) -> None:
|
||||
release_parser.add_argument(
|
||||
"--expect-tree",
|
||||
metavar="TREE",
|
||||
default=None,
|
||||
help=(
|
||||
"Refuse to release unless HEAD's tree (git rev-parse HEAD^{tree}) "
|
||||
"equals this full sha after the pull and before any file is "
|
||||
"written; with --retry, before anything is pushed."
|
||||
),
|
||||
)
|
||||
|
||||
release_parser.add_argument(
|
||||
"--retry",
|
||||
action="store_true",
|
||||
@@ -74,3 +73,19 @@ def add_release_subparser(
|
||||
"post-tag push or PyPI upload failed mid-flight."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def add_release_subparser(
|
||||
subparsers: argparse._SubParsersAction,
|
||||
) -> None:
|
||||
release_parser = subparsers.add_parser(
|
||||
"release",
|
||||
help=(
|
||||
"Create a release for repository/ies by incrementing version "
|
||||
"and updating the changelog."
|
||||
),
|
||||
)
|
||||
_add_version_arguments(release_parser)
|
||||
add_identifier_arguments(release_parser)
|
||||
_add_flow_arguments(release_parser)
|
||||
_add_safety_arguments(release_parser)
|
||||
@@ -68,7 +68,7 @@ def create_ink(
|
||||
# Mark local repo scripts as executable if needed
|
||||
try:
|
||||
if os.path.realpath(command).startswith(os.path.realpath(repo_dir)):
|
||||
os.chmod(command, 0o755)
|
||||
os.chmod(command, 0o700)
|
||||
except OSError as e:
|
||||
if not quiet:
|
||||
print(f"Failed to set permissions on '{command}': {e}")
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
# src/pkgmgr/core/remote_provisioning/http/client.py
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import ssl
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from .errors import HttpError
|
||||
|
||||
ALLOWED_SCHEMES = frozenset({"http", "https"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HttpResponse:
|
||||
@@ -31,6 +35,11 @@ class HttpClient:
|
||||
headers: dict[str, str] | None = None,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> HttpResponse:
|
||||
scheme = urllib.parse.urlsplit(url).scheme
|
||||
if scheme not in ALLOWED_SCHEMES:
|
||||
raise HttpError(
|
||||
status=0, message=f"unsupported URL scheme {scheme!r}", body=""
|
||||
)
|
||||
data: bytes | None = None
|
||||
final_headers: dict[str, str] = dict(headers or {})
|
||||
|
||||
@@ -41,7 +50,9 @@ class HttpClient:
|
||||
req = urllib.request.Request(url=url, data=data, method=method.upper())
|
||||
for k, v in final_headers.items():
|
||||
req.add_header(k, v)
|
||||
return self._send(req)
|
||||
|
||||
def _send(self, req: urllib.request.Request) -> HttpResponse:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
req,
|
||||
@@ -49,21 +60,32 @@ class HttpClient:
|
||||
context=ssl.create_default_context(),
|
||||
) as resp:
|
||||
raw = resp.read().decode("utf-8", errors="replace")
|
||||
|
||||
parsed: dict[str, Any] | None = None
|
||||
if raw:
|
||||
try:
|
||||
loaded = json.loads(raw)
|
||||
parsed = loaded if isinstance(loaded, dict) else None
|
||||
except json.JSONDecodeError:
|
||||
parsed = None
|
||||
|
||||
return HttpResponse(status=int(resp.status), text=raw, json=parsed)
|
||||
return HttpResponse(
|
||||
status=int(resp.status), text=raw, json=_json_object(raw)
|
||||
)
|
||||
except urllib.error.HTTPError as exc:
|
||||
try:
|
||||
body = exc.read().decode("utf-8", errors="replace")
|
||||
except (OSError, ValueError):
|
||||
body = ""
|
||||
raise HttpError(status=int(exc.code), message=str(exc), body=body) from exc
|
||||
except urllib.error.URLError as exc:
|
||||
raise HttpError(status=0, message=str(exc), body="") from exc
|
||||
raise HttpError(
|
||||
status=int(exc.code), message=str(exc), body=_error_body(exc)
|
||||
) from exc
|
||||
except (OSError, http.client.HTTPException) as exc:
|
||||
message = str(exc) or type(exc).__name__
|
||||
raise HttpError(status=0, message=message, body="") from exc
|
||||
|
||||
|
||||
def _json_object(raw: str) -> dict[str, Any] | None:
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
loaded = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return loaded if isinstance(loaded, dict) else None
|
||||
|
||||
|
||||
def _error_body(exc: urllib.error.HTTPError) -> str:
|
||||
try:
|
||||
return exc.read().decode("utf-8", errors="replace")
|
||||
except http.client.IncompleteRead as truncated:
|
||||
return truncated.partial.decode("utf-8", errors="replace")
|
||||
except (OSError, ValueError):
|
||||
return ""
|
||||
@@ -1,6 +1,7 @@
|
||||
# src/pkgmgr/core/remote_provisioning/providers/github.py
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
from typing import Any
|
||||
|
||||
from ..http.client import HttpClient
|
||||
@@ -103,7 +104,7 @@ class GitHubProvider(RemoteProvider):
|
||||
user_url = f"{api}/user/repos"
|
||||
|
||||
# Try org first, then fall back to user creation.
|
||||
try:
|
||||
with contextlib.suppress(HttpError):
|
||||
resp = self._http.request_json(
|
||||
"POST", org_url, headers=self._headers(token), payload=payload
|
||||
)
|
||||
@@ -114,8 +115,6 @@ class GitHubProvider(RemoteProvider):
|
||||
message="Repository created (org).",
|
||||
url=str(html_url) if html_url else None,
|
||||
)
|
||||
except HttpError:
|
||||
pass
|
||||
|
||||
resp = self._http.request_json(
|
||||
"POST", user_url, headers=self._headers(token), payload=payload
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
@@ -127,7 +128,7 @@ def get_installed_nix_profile_version(*candidates: str) -> InstalledVersion | No
|
||||
# Preferred: JSON output
|
||||
rc, out, _ = _run_nix(["nix", "profile", "list", "--json"])
|
||||
if rc == 0 and out.strip():
|
||||
try:
|
||||
with contextlib.suppress(json.JSONDecodeError, AttributeError):
|
||||
data = json.loads(out)
|
||||
elements = data.get("elements") or data.get("items") or {}
|
||||
if isinstance(elements, dict):
|
||||
@@ -145,8 +146,6 @@ def get_installed_nix_profile_version(*candidates: str) -> InstalledVersion | No
|
||||
guess = _extract_version_from_store_path(sp)
|
||||
if guess:
|
||||
return InstalledVersion(name=name, version=guess)
|
||||
except (json.JSONDecodeError, AttributeError):
|
||||
pass
|
||||
|
||||
# Fallback: text mode
|
||||
rc, out, _ = _run_nix(["nix", "profile", "list"])
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# src/pkgmgr/core/version/source.py
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
|
||||
@@ -259,14 +260,12 @@ def read_ansible_galaxy_version(repo_dir: str) -> str | None:
|
||||
"""
|
||||
galaxy_yml = os.path.join(repo_dir, "galaxy.yml")
|
||||
if os.path.isfile(galaxy_yml):
|
||||
try:
|
||||
with contextlib.suppress(OSError, UnicodeDecodeError, yaml.YAMLError):
|
||||
with open(galaxy_yml, encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
version = data.get("version")
|
||||
if isinstance(version, str) and version.strip():
|
||||
return version.strip()
|
||||
except (OSError, UnicodeDecodeError, yaml.YAMLError):
|
||||
pass
|
||||
|
||||
meta_yml = os.path.join(repo_dir, "meta", "main.yml")
|
||||
if os.path.isfile(meta_yml):
|
||||
|
||||
@@ -74,17 +74,17 @@ class TestIntegrationReleaseCommand(unittest.TestCase):
|
||||
self._run_pkgmgr(["release", "patch", "--preview"])
|
||||
|
||||
mock_run_release.assert_called_once()
|
||||
_args, kwargs = mock_run_release.call_args
|
||||
options = mock_run_release.call_args.args[0]
|
||||
|
||||
# CLI wiring
|
||||
self.assertEqual(kwargs.get("release_type"), "patch")
|
||||
self.assertEqual(options.release_type, "patch")
|
||||
self.assertTrue(
|
||||
kwargs.get("preview"),
|
||||
options.preview,
|
||||
"preview should be True when --preview is used",
|
||||
)
|
||||
# Default: no --close → close=False
|
||||
self.assertFalse(
|
||||
kwargs.get("close"),
|
||||
options.close,
|
||||
"close must be False when --close is not given",
|
||||
)
|
||||
|
||||
@@ -116,17 +116,17 @@ class TestIntegrationReleaseCommand(unittest.TestCase):
|
||||
self._run_pkgmgr(["release", "minor", "--preview", "--close"])
|
||||
|
||||
mock_run_release.assert_called_once()
|
||||
_args, kwargs = mock_run_release.call_args
|
||||
options = mock_run_release.call_args.args[0]
|
||||
|
||||
# CLI wiring
|
||||
self.assertEqual(kwargs.get("release_type"), "minor")
|
||||
self.assertEqual(options.release_type, "minor")
|
||||
self.assertTrue(
|
||||
kwargs.get("preview"),
|
||||
options.preview,
|
||||
"preview should be True when --preview is used",
|
||||
)
|
||||
# With --close → close=True
|
||||
self.assertTrue(
|
||||
kwargs.get("close"),
|
||||
options.close,
|
||||
"close must be True when --close is given",
|
||||
)
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
|
||||
docker = os.path.join(self.bin, "docker")
|
||||
with open(docker, "w", encoding="utf-8") as fh:
|
||||
fh.write(FAILING_DOCKER.format(python=sys.executable))
|
||||
os.chmod(docker, 0o755)
|
||||
os.chmod(docker, 0o700)
|
||||
self.docker_log = os.path.join(self.root, "docker.log")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
@@ -159,7 +159,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
|
||||
patch.object(gc_forge, "TokenResolver") as resolver,
|
||||
patch.object(gc_forge, "HttpClient") as http,
|
||||
patch.object(
|
||||
tree, "secret_service_token", return_value=(None, "test")
|
||||
tree, "_forge_access", return_value=(None, "test")
|
||||
) as secret,
|
||||
):
|
||||
resolver.return_value.get_token.side_effect = NoCredentialsError("none")
|
||||
@@ -1688,7 +1688,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
|
||||
path = os.path.join(hooks, name)
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(MARKING_HOOK.format(marker=marker))
|
||||
os.chmod(path, 0o755)
|
||||
os.chmod(path, 0o700)
|
||||
|
||||
run = self._cleanup("local", apply=True)
|
||||
|
||||
|
||||
@@ -4,36 +4,16 @@ import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from contextlib import redirect_stdout
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc, gc_forge
|
||||
from pkgmgr.actions.branch import gc
|
||||
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
|
||||
|
||||
GITHUB_URL = "https://github.com/example/demo.git"
|
||||
AUTHOR = {
|
||||
"GIT_AUTHOR_NAME": "t",
|
||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
||||
"GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
||||
}
|
||||
|
||||
|
||||
def git(cwd: str, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=cwd,
|
||||
env={**os.environ, **AUTHOR},
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
from tests.support.git_sandbox import git, isolated_root, origin_and_repo
|
||||
|
||||
|
||||
def docker_available() -> bool:
|
||||
@@ -46,24 +26,8 @@ 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)
|
||||
git(self.root, "init", "-b", "main", self.repo)
|
||||
git(self.repo, "remote", "add", "origin", self.origin)
|
||||
self._commit("init")
|
||||
git(self.repo, "push", "-u", "origin", "main")
|
||||
self.root = isolated_root(self, {})
|
||||
self.origin, self.repo = origin_and_repo(self.root)
|
||||
|
||||
self._branch_with_commit("merged")
|
||||
git(self.repo, "merge", "--no-ff", "-m", "merge merged", "merged")
|
||||
@@ -153,185 +117,6 @@ class GcFixture:
|
||||
|
||||
|
||||
class TestBranchGc(GcFixture, unittest.TestCase):
|
||||
def test_classifies_every_branch(self) -> None:
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["main"].state, "protected")
|
||||
self.assertEqual(items["merged"].state, "merged-clean")
|
||||
self.assertEqual(items["merged"].merged_by, "ancestor")
|
||||
self.assertEqual(
|
||||
items["merged"].actions,
|
||||
["worktree", "local-branch", "remote-branch:origin"],
|
||||
)
|
||||
self.assertTrue(items["merged"].eligible)
|
||||
self.assertEqual(items["squashed"].merged_by, "pr#7")
|
||||
self.assertTrue(items["squashed"].eligible)
|
||||
self.assertEqual(items["fresh"].state, "unmerged")
|
||||
self.assertEqual(items["fresh"].reason, "no own commits")
|
||||
self.assertEqual(items["wip"].state, "unmerged")
|
||||
self.assertEqual(items["wip"].skip, "open-pr #3")
|
||||
self.assertEqual(items["dirty"].state, "dirty")
|
||||
|
||||
def test_merged_into_counts_commits_in_an_integration_line(self) -> None:
|
||||
self._integration_line()
|
||||
before = self._items(self._plan(host_ns=True, cwds={}))
|
||||
self.assertEqual(before["feat"].state, "unmerged")
|
||||
self.assertIsNone(before["feat"].merged_into)
|
||||
|
||||
for ref in ("line", "origin/line"):
|
||||
with self.subTest(ref=ref):
|
||||
items = self._items(
|
||||
self._plan(host_ns=True, cwds={}, merged_into=[ref])
|
||||
)
|
||||
self.assertEqual(items["feat"].state, "merged-clean")
|
||||
self.assertEqual(items["feat"].merged_by, f"line:{ref}")
|
||||
self.assertEqual(items["feat"].merged_into, ref)
|
||||
self.assertTrue(items["feat"].eligible)
|
||||
self.assertEqual(items["line"].state, "protected")
|
||||
self.assertEqual(items["start"].state, "unmerged")
|
||||
self.assertEqual(items["merged"].merged_into, "origin/main")
|
||||
|
||||
def test_unknown_merged_into_ref_is_a_warning(self) -> None:
|
||||
plan = self._plan(host_ns=True, cwds={}, merged_into=["no-such-line"])
|
||||
|
||||
self.assertIn("merged-into ref no-such-line not found", plan.warnings)
|
||||
self.assertEqual(self._items(plan)["merged"].state, "merged-clean")
|
||||
|
||||
def test_sizes_and_min_age(self) -> None:
|
||||
items = self._items(self._plan(host_ns=True, cwds={}, sizes=True))
|
||||
self.assertGreater(items["merged"].size_bytes, 0)
|
||||
self.assertIsNone(items["squashed"].size_bytes)
|
||||
self.assertIn("size ", gc._line(items["merged"]))
|
||||
|
||||
young = self._items(self._plan(host_ns=True, cwds={}, min_age=1000))
|
||||
self.assertEqual(young["merged"].skip, "younger than 1000 h")
|
||||
self.assertFalse(young["merged"].eligible)
|
||||
old = self._items(self._plan(host_ns=True, cwds={}, min_age=0))
|
||||
self.assertIsNone(old["merged"].skip)
|
||||
|
||||
def test_busy_worktree_is_skipped(self) -> None:
|
||||
cwds = {4242: os.path.join(self.merged_wt, "sub")}
|
||||
items = self._items(self._plan(host_ns=True, cwds=cwds))
|
||||
|
||||
self.assertTrue(items["merged"].skip.startswith("process: pid 4242"))
|
||||
self.assertFalse(items["merged"].eligible)
|
||||
|
||||
def test_lock_with_live_pid_is_skipped(self) -> None:
|
||||
self._lock(f"claude agent x (pid {os.getpid()} on host)")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, f"lock: pid {os.getpid()} alive")
|
||||
|
||||
def test_lock_with_dead_pid_is_overridden(self) -> None:
|
||||
self._lock("claude agent x (pid 999999999 on host)")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertIsNone(items["locked"].skip)
|
||||
self.assertTrue(items["locked"].eligible)
|
||||
|
||||
def test_lock_outside_host_namespace_is_unknown(self) -> None:
|
||||
self._lock("claude agent x (pid 999999999 on host)")
|
||||
items = self._items(self._plan(host_ns=False, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, "lock: liveness unknown")
|
||||
|
||||
def test_lock_without_pid_is_respected(self) -> None:
|
||||
self._lock("manual hold")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, "lock: manual hold")
|
||||
|
||||
def test_forge_unavailable_skips_everything(self) -> None:
|
||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
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)
|
||||
open(os.path.join(stub, "commondir"), "w").close()
|
||||
plan = self._plan(host_ns=True, cwds={})
|
||||
|
||||
stale = [i for i in plan.items if i.state == "stale"]
|
||||
self.assertEqual([i.worktree for i in stale], [stub])
|
||||
self.assertTrue(os.path.isdir(stub))
|
||||
|
||||
def test_execute_removes_worktree_and_branches(self) -> None:
|
||||
plan = self._plan(host_ns=True, cwds={})
|
||||
item = self._items(plan)["merged"]
|
||||
@@ -534,7 +319,7 @@ class TestBranchGc(GcFixture, unittest.TestCase):
|
||||
hook = os.path.join(self.repo, ".git", "hooks", "reference-transaction")
|
||||
with open(hook, "w") as fh:
|
||||
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
||||
os.chmod(hook, 0o755)
|
||||
os.chmod(hook, 0o700)
|
||||
plan = self._plan(host_ns=True, cwds={})
|
||||
item = self._items(plan)["merged"]
|
||||
|
||||
|
||||
@@ -110,7 +110,7 @@ class TestBranchTree(unittest.TestCase):
|
||||
patch.object(gc, "_process_cwds", return_value={}),
|
||||
patch.object(
|
||||
tree,
|
||||
"secret_service_token",
|
||||
"_forge_access",
|
||||
return_value=(None, "Secret Service locked"),
|
||||
),
|
||||
]
|
||||
@@ -389,7 +389,7 @@ class TestBranchTree(unittest.TestCase):
|
||||
open_heads={},
|
||||
)
|
||||
with (
|
||||
patch.object(tree, "secret_service_token", return_value=("t0ken", None)),
|
||||
patch.object(tree, "_forge_access", return_value=("t0ken", None)),
|
||||
patch.object(tree, "facts_with_token", return_value=facts) as live,
|
||||
):
|
||||
first = self._by_branch(self._entry())
|
||||
@@ -408,7 +408,7 @@ class TestBranchTree(unittest.TestCase):
|
||||
(False, "Secret Service locked"),
|
||||
)
|
||||
self.assertEqual(data["repos"][0]["forge"], "cached")
|
||||
with patch.object(tree, "secret_service_token", return_value=("t0ken", None)):
|
||||
with patch.object(tree, "_forge_access", return_value=("t0ken", None)):
|
||||
self.assertTrue(json.loads(self._tree())["delete_ready"])
|
||||
|
||||
def test_an_unwritable_cache_keeps_the_scan_and_names_it(self) -> None:
|
||||
@@ -417,7 +417,7 @@ class TestBranchTree(unittest.TestCase):
|
||||
self._write(self.root, "cache-is-a-file", "")
|
||||
with (
|
||||
patch.dict(os.environ, {"XDG_CACHE_HOME": blocker}),
|
||||
patch.object(tree, "secret_service_token", return_value=("t0ken", None)),
|
||||
patch.object(tree, "_forge_access", return_value=("t0ken", None)),
|
||||
patch.object(tree, "facts_with_token", return_value=ForgeFacts()),
|
||||
):
|
||||
entry = self._entry()
|
||||
|
||||
@@ -22,7 +22,7 @@ class TestBranchTreeFlow(GcFixture, unittest.TestCase):
|
||||
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(tree, "secret_service_token", return_value=(None, "locked")),
|
||||
patch.object(tree, "_forge_access", return_value=(None, "locked")),
|
||||
):
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
@@ -164,7 +164,7 @@ class TestInstalledVersionDegradation(unittest.TestCase):
|
||||
self.assertIsNone(get_installed_python_version("kpmx"))
|
||||
|
||||
def test_non_json_nix_profile_output_falls_back_to_text_mode(self) -> None:
|
||||
import pkgmgr.core.version.installed as mod
|
||||
from pkgmgr.core.version import installed as mod
|
||||
|
||||
with (
|
||||
patch.object(mod.shutil, "which", return_value="/usr/bin/nix"),
|
||||
@@ -173,7 +173,7 @@ class TestInstalledVersionDegradation(unittest.TestCase):
|
||||
self.assertIsNone(mod.get_installed_nix_profile_version("pkgmgr"))
|
||||
|
||||
def test_json_list_instead_of_object_is_tolerated(self) -> None:
|
||||
import pkgmgr.core.version.installed as mod
|
||||
from pkgmgr.core.version import installed as mod
|
||||
|
||||
# Valid JSON, wrong shape: data.get() raises AttributeError on a list.
|
||||
with (
|
||||
@@ -566,7 +566,7 @@ class TestReleaseFileWriteDegradation(unittest.TestCase):
|
||||
self.assertIn("Could not read spec file for changelog update", buf.getvalue())
|
||||
|
||||
def test_unwritable_spec_changelog_is_reported(self) -> None:
|
||||
import pkgmgr.actions.release.files.rpm_changelog as mod
|
||||
from pkgmgr.actions.release.files import rpm_changelog as mod
|
||||
|
||||
path = _write(
|
||||
os.path.join(self.dir, "pkg.spec"),
|
||||
|
||||
@@ -4,7 +4,6 @@ import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import pkgmgr.actions.install as install_module
|
||||
from pkgmgr.actions.install import install_repos
|
||||
from pkgmgr.actions.install.installers.base import BaseInstaller
|
||||
|
||||
|
||||
@@ -141,7 +140,7 @@ class TestInstallReposIntegration(unittest.TestCase):
|
||||
old_installers = install_module.INSTALLERS
|
||||
install_module.INSTALLERS = [DummyInstaller()]
|
||||
try:
|
||||
install_repos(
|
||||
install_module.install_repos(
|
||||
selected_repos=selected_repos,
|
||||
repositories_base_dir=tmp_base,
|
||||
bin_dir=tmp_bin,
|
||||
|
||||
@@ -129,7 +129,7 @@ class TestIntegrationMirrorProbeDetailAndProvision(unittest.TestCase):
|
||||
]
|
||||
|
||||
def probe_side_effect(url: str, cwd: str = "."):
|
||||
if "github.com" in url:
|
||||
if url == "git@github.com:alice/repo.git":
|
||||
# show "empty repo reachable" note; setup_cmd prints [OK] and does not print reason for ok
|
||||
return (
|
||||
True,
|
||||
@@ -180,7 +180,7 @@ class TestIntegrationMirrorProbeDetailAndProvision(unittest.TestCase):
|
||||
]
|
||||
|
||||
def probe_side_effect(url: str, cwd: str = "."):
|
||||
if "github.com" in url:
|
||||
if url == "git@github.com:alice/repo.git":
|
||||
return True, ""
|
||||
return False, "(exit 128) fatal: Could not read from remote repository."
|
||||
|
||||
|
||||
@@ -6,10 +6,11 @@ import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from contextlib import redirect_stdout, suppress
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.release.options import ReleaseOptions
|
||||
from pkgmgr.actions.release.retry import retry_release
|
||||
from pkgmgr.actions.release.workflow import _release_impl
|
||||
from pkgmgr.actions.repository.push import (
|
||||
@@ -21,50 +22,94 @@ from pkgmgr.cli.context import CLIContext
|
||||
from pkgmgr.cli.parser import create_parser
|
||||
from pkgmgr.cli.proxy import maybe_handle_proxy
|
||||
|
||||
_REAL_RUN = subprocess.run
|
||||
GIT = shutil.which("git")
|
||||
SSH_KEYGEN = shutil.which("ssh-keygen")
|
||||
|
||||
|
||||
def git(cwd: str, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", *args], cwd=cwd, check=True, capture_output=True, text=True
|
||||
return _REAL_RUN(
|
||||
[GIT, *args], cwd=cwd, check=True, capture_output=True, text=True
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("ssh-keygen"), "ssh-keygen signs the commits")
|
||||
class TestPushMirrorLeases(unittest.TestCase):
|
||||
def keygen(path: Path) -> None:
|
||||
_REAL_RUN(
|
||||
[SSH_KEYGEN, "-q", "-t", "ed25519", "-N", "", "-f", str(path)],
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
def ssh_url(path: str) -> str:
|
||||
return f"t@localhost:{path}"
|
||||
|
||||
|
||||
@unittest.skipUnless(GIT and SSH_KEYGEN, "git and ssh-keygen sign the commits")
|
||||
class SignedRemotesCase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self._tmp.cleanup)
|
||||
root = Path(os.path.realpath(self._tmp.name))
|
||||
self.root = str(root)
|
||||
key = root / "key"
|
||||
subprocess.run(
|
||||
["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)],
|
||||
check=True,
|
||||
)
|
||||
self.key = root / "key"
|
||||
keygen(self.key)
|
||||
(root / "allowed").write_text(f"t@example.org {(root / 'key.pub').read_text()}")
|
||||
(root / "gitconfig").write_text(
|
||||
self.gitconfig = root / ".gitconfig"
|
||||
self._write_gitconfig(root)
|
||||
self.env = {
|
||||
**{
|
||||
key: value
|
||||
for key, value in os.environ.items()
|
||||
if key not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")
|
||||
},
|
||||
"GIT_CONFIG_GLOBAL": str(self.gitconfig),
|
||||
"GIT_CONFIG_NOSYSTEM": "1",
|
||||
}
|
||||
for patcher in (
|
||||
patch.dict(os.environ, self.env, clear=True),
|
||||
patch("pkgmgr.core.git.run._passwd_home", return_value=self.root),
|
||||
):
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self._init_remotes(root)
|
||||
|
||||
def _write_gitconfig(self, root: Path) -> None:
|
||||
fakessh = root / "fakessh"
|
||||
fakessh.write_text(
|
||||
"#!/bin/sh\n"
|
||||
"shift $(($# - 1))\n"
|
||||
f'exec env -i PATH="$PATH" HOME={root} sh -c "$1"\n'
|
||||
)
|
||||
fakessh.chmod(0o755)
|
||||
self.gitconfig.write_text(
|
||||
"[user]\n\tname = t\n\temail = t@example.org\n"
|
||||
f"\tsigningkey = {key}\n"
|
||||
f"\tsigningkey = {self.key}\n"
|
||||
"[gpg]\n\tformat = ssh\n"
|
||||
f'[gpg "ssh"]\n\tallowedSignersFile = {root / "allowed"}\n'
|
||||
"[commit]\n\tgpgsign = false\n"
|
||||
"[init]\n\tdefaultBranch = main\n"
|
||||
f"[core]\n\tsshCommand = {fakessh}\n"
|
||||
"[ssh]\n\tvariant = simple\n"
|
||||
)
|
||||
env = patch.dict(
|
||||
os.environ,
|
||||
{"GIT_CONFIG_GLOBAL": str(root / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1"},
|
||||
)
|
||||
env.start()
|
||||
self.addCleanup(env.stop)
|
||||
|
||||
def _init_remotes(self, root: Path) -> None:
|
||||
self.canonical = str(root / "canonical.git")
|
||||
self.mirror = str(root / "mirror.git")
|
||||
self.repo = str(root / "repo")
|
||||
git(self.root, "init", "-q", "--bare", self.canonical)
|
||||
git(self.root, "init", "-q", "--bare", self.mirror)
|
||||
git(self.root, "init", "-q", self.repo)
|
||||
git(self.repo, "remote", "add", "origin", self.canonical)
|
||||
git(self.repo, "remote", "set-url", "--add", "--push", "origin", self.canonical)
|
||||
git(self.repo, "remote", "set-url", "--add", "--push", "origin", self.mirror)
|
||||
git(self.repo, "remote", "add", "origin", ssh_url(self.canonical))
|
||||
for bare in (self.canonical, self.mirror):
|
||||
git(
|
||||
self.repo,
|
||||
"remote",
|
||||
"set-url",
|
||||
"--add",
|
||||
"--push",
|
||||
"origin",
|
||||
ssh_url(bare),
|
||||
)
|
||||
self.init = self._commit("init")
|
||||
git(self.repo, "push", "-q", self.canonical, "main")
|
||||
git(self.repo, "push", "-q", self.mirror, "main")
|
||||
@@ -78,6 +123,17 @@ class TestPushMirrorLeases(unittest.TestCase):
|
||||
git(cwd, "commit", "-q", *flags, "-m", name)
|
||||
return git(cwd, "rev-parse", "HEAD")
|
||||
|
||||
def _tip(self, bare: str, ref: str = "refs/heads/main") -> str:
|
||||
return _REAL_RUN(
|
||||
[GIT, "rev-parse", "--verify", "--quiet", ref],
|
||||
cwd=bare,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
class TestPushMirrorLeases(SignedRemotesCase):
|
||||
def _push(self, rewrite: bool = False) -> str:
|
||||
with redirect_stdout(io.StringIO()) as out:
|
||||
sign_unpushed(self.repo)
|
||||
@@ -102,15 +158,6 @@ class TestPushMirrorLeases(unittest.TestCase):
|
||||
|
||||
self.assertEqual(cm.exception.code, 0)
|
||||
|
||||
def _tip(self, bare: str, ref: str = "refs/heads/main") -> str:
|
||||
return subprocess.run(
|
||||
["git", "rev-parse", "--verify", "--quiet", ref],
|
||||
cwd=bare,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
|
||||
def _assert_shipped_signed(self) -> None:
|
||||
head = git(self.repo, "rev-parse", "HEAD")
|
||||
self.assertEqual(self._tip(self.canonical), head)
|
||||
@@ -226,7 +273,7 @@ class TestPushMirrorLeases(unittest.TestCase):
|
||||
git(self.repo, "fetch", "-q", "origin")
|
||||
self._commit("new")
|
||||
upstream = subprocess.run(
|
||||
["git", "rev-parse", "--abbrev-ref", "@{u}"],
|
||||
[GIT, "rev-parse", "--abbrev-ref", "@{u}"],
|
||||
cwd=self.repo,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
@@ -302,12 +349,24 @@ class TestPushMirrorLeases(unittest.TestCase):
|
||||
head = git(self.repo, "rev-parse", "HEAD")
|
||||
git(self.repo, "config", "diff.ignoreSubmodules", "all")
|
||||
git(self.repo, "update-index", "--add", "--cacheinfo", f"160000,{head},sub")
|
||||
tree = git(self.repo, "rev-parse", "HEAD^{tree}")
|
||||
|
||||
with self.assertRaises(PushRefusedError) as cm:
|
||||
self._push()
|
||||
self._push()
|
||||
|
||||
self.assertIn("staged changes", str(cm.exception))
|
||||
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), head)
|
||||
self._assert_shipped_signed()
|
||||
self.assertNotEqual(git(self.repo, "rev-parse", "HEAD"), head)
|
||||
self.assertEqual(git(self.repo, "rev-parse", "HEAD^{tree}"), tree)
|
||||
self.assertEqual(
|
||||
git(
|
||||
self.repo,
|
||||
"diff",
|
||||
"--cached",
|
||||
"--name-only",
|
||||
"--ignore-submodules=none",
|
||||
"HEAD",
|
||||
),
|
||||
"sub",
|
||||
)
|
||||
|
||||
def test_unstaged_edit_stays_out_of_the_signed_head(self) -> None:
|
||||
self._commit("feature")
|
||||
@@ -339,10 +398,8 @@ class TestPushMirrorLeases(unittest.TestCase):
|
||||
hooks_fire = marker.exists()
|
||||
marker.unlink(missing_ok=True)
|
||||
|
||||
try:
|
||||
with suppress(PushRefusedError):
|
||||
self._push()
|
||||
except PushRefusedError:
|
||||
pass
|
||||
|
||||
self.assertFalse(marker.exists(), f"config hooks fire on commit: {hooks_fire}")
|
||||
|
||||
@@ -364,7 +421,7 @@ class TestPushMirrorLeases(unittest.TestCase):
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
def test_remote_named_like_an_option_is_pushed(self) -> None:
|
||||
git(self.repo, "config", "remote.-r.url", self.canonical)
|
||||
git(self.repo, "config", "remote.-r.url", ssh_url(self.canonical))
|
||||
git(self.repo, "config", "remote.-r.fetch", "+refs/heads/*:refs/remotes/-r/*")
|
||||
git(self.repo, "config", "branch.main.pushRemote", "-r")
|
||||
git(self.repo, "fetch", "-q", "--", "-r")
|
||||
@@ -383,7 +440,11 @@ class TestPushMirrorLeases(unittest.TestCase):
|
||||
|
||||
with redirect_stdout(io.StringIO()), self.assertRaises(PushRefusedError):
|
||||
_release_impl(
|
||||
pyproject_path=os.path.join(self.repo, "pyproject.toml"), force=True
|
||||
ReleaseOptions(
|
||||
pyproject_path=os.path.join(self.repo, "pyproject.toml"),
|
||||
force=True,
|
||||
expect_tree=None,
|
||||
)
|
||||
)
|
||||
|
||||
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), head)
|
||||
|
||||
@@ -14,7 +14,6 @@ from collections.abc import Sequence
|
||||
from unittest.mock import patch
|
||||
|
||||
import pkgmgr.actions.install as install_mod
|
||||
from pkgmgr.actions.install import install_repos
|
||||
from pkgmgr.actions.install.installers.makefile import MakefileInstaller
|
||||
from pkgmgr.actions.install.installers.nix import NixFlakeInstaller
|
||||
from pkgmgr.actions.install.installers.os_packages.arch_pkgbuild import (
|
||||
@@ -89,7 +88,7 @@ class TestRecursiveCapabilitiesIntegration(unittest.TestCase):
|
||||
),
|
||||
patch.object(install_mod, "clone_repos"),
|
||||
):
|
||||
install_repos(
|
||||
install_mod.install_repos(
|
||||
selected_repos=selected_repos,
|
||||
repositories_base_dir=self.tmp_root,
|
||||
bin_dir=self.bin_dir,
|
||||
|
||||
@@ -131,7 +131,7 @@ class TestReleaseCwdCheckout(unittest.TestCase):
|
||||
with (
|
||||
patch(
|
||||
"pkgmgr.cli.commands.release.run_release",
|
||||
side_effect=lambda **_kwargs: seen.append(os.getcwd()),
|
||||
side_effect=lambda *_args, **_kwargs: seen.append(os.getcwd()),
|
||||
),
|
||||
redirect_stdout(io.StringIO()),
|
||||
):
|
||||
|
||||
@@ -14,7 +14,7 @@ class TestIntegrationReposCreatePreview(unittest.TestCase):
|
||||
try:
|
||||
repos_mod = importlib.import_module("pkgmgr.cli.commands.repos")
|
||||
except ImportError as exc:
|
||||
self.skipTest(f"CLI module not available: {exc}")
|
||||
raise unittest.SkipTest(f"CLI module not available: {exc}") from exc
|
||||
|
||||
handle = getattr(repos_mod, "handle_repos_command", None)
|
||||
if handle is None:
|
||||
|
||||
@@ -58,7 +58,7 @@ class ReviewRepoCase(unittest.TestCase):
|
||||
|
||||
def _trap(self, path: str, tail: str) -> str:
|
||||
write(path, f"#!/bin/sh\ntouch '{self.marker}'\n{tail}\n".encode())
|
||||
os.chmod(path, 0o755)
|
||||
os.chmod(path, 0o700)
|
||||
return path
|
||||
|
||||
def _assert_fires(self, *args: str) -> None:
|
||||
|
||||
@@ -331,7 +331,7 @@ class TestWorktreeUp(WorktreeFixture, unittest.TestCase):
|
||||
script = os.path.join(self.repo, name)
|
||||
with open(script, "w") as fh:
|
||||
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
||||
os.chmod(script, 0o755)
|
||||
os.chmod(script, 0o700)
|
||||
git(self.repo, "add", name)
|
||||
git(self.repo, "commit", "-m", name)
|
||||
git(self.repo, "push", "origin", "main")
|
||||
@@ -370,7 +370,7 @@ class TestWorktreeUp(WorktreeFixture, unittest.TestCase):
|
||||
fake = os.path.join(planted, "true")
|
||||
with open(fake, "w") as fh:
|
||||
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
||||
os.chmod(fake, 0o755)
|
||||
os.chmod(fake, 0o700)
|
||||
if os.getuid() == 0:
|
||||
os.chown(planted, 65534, 65534)
|
||||
os.chown(fake, 65534, 65534)
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,81 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
AUTHOR = {
|
||||
"GIT_AUTHOR_NAME": "t",
|
||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
||||
"GIT_COMMITTER_NAME": "t",
|
||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
||||
}
|
||||
|
||||
|
||||
def git(cwd: str, *args: str) -> str:
|
||||
"""
|
||||
Args:
|
||||
cwd: the repository to run in.
|
||||
args: the git arguments; signing stays off and AUTHOR applies.
|
||||
|
||||
Returns:
|
||||
The stripped standard output.
|
||||
"""
|
||||
return subprocess.run(
|
||||
["git", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=cwd,
|
||||
env={**os.environ, **AUTHOR},
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def origin_and_repo(root: str) -> tuple[str, str]:
|
||||
"""
|
||||
Args:
|
||||
root: the directory that holds both repositories.
|
||||
|
||||
Returns:
|
||||
The paths of the bare `origin.git` and of `repo`, whose `main`
|
||||
tracks origin and carries one pushed commit adding `init.txt`.
|
||||
"""
|
||||
origin = os.path.join(root, "origin.git")
|
||||
repo = os.path.join(root, "repo")
|
||||
git(root, "init", "--bare", "-b", "main", origin)
|
||||
git(root, "init", "-b", "main", repo)
|
||||
git(repo, "remote", "add", "origin", origin)
|
||||
with open(os.path.join(repo, "init.txt"), "w") as fh:
|
||||
fh.write("init")
|
||||
git(repo, "add", "init.txt")
|
||||
git(repo, "commit", "-m", "init")
|
||||
git(repo, "push", "-u", "origin", "main")
|
||||
return origin, repo
|
||||
|
||||
|
||||
def isolated_root(case: unittest.TestCase, env: dict[str, str]) -> str:
|
||||
"""
|
||||
Args:
|
||||
case: the test whose cleanups remove the directory and restore the
|
||||
working directory and environment.
|
||||
env: variables set over the environment, from which every GIT_*
|
||||
variable is dropped.
|
||||
|
||||
Returns:
|
||||
The realpath of a fresh temporary directory, now the working
|
||||
directory, whose empty `home` child is HOME.
|
||||
"""
|
||||
scratch = tempfile.TemporaryDirectory()
|
||||
case.addCleanup(scratch.cleanup)
|
||||
root = os.path.realpath(scratch.name)
|
||||
case.addCleanup(os.chdir, os.getcwd())
|
||||
os.chdir(root)
|
||||
home = os.path.join(root, "home")
|
||||
os.makedirs(home)
|
||||
kept = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||
environ = patch.dict(os.environ, {**kept, **env, "HOME": home}, clear=True)
|
||||
environ.start()
|
||||
case.addCleanup(environ.stop)
|
||||
return root
|
||||
@@ -4,51 +4,27 @@ 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
|
||||
from pkgmgr.core.git import run
|
||||
from tests.support.git_sandbox import AUTHOR, isolated_root
|
||||
|
||||
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")
|
||||
@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, "HOME": home}, clear=True)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.root = isolated_root(self, AUTHOR)
|
||||
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()
|
||||
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)
|
||||
@@ -57,8 +33,8 @@ class TestHeldBranchesReadOnce(unittest.TestCase):
|
||||
|
||||
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)
|
||||
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")
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc
|
||||
|
||||
SHA = "a" * 40
|
||||
|
||||
|
||||
def _repo(merged_heads: dict[str, int]) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
first_parent=set(),
|
||||
default="origin/main",
|
||||
repo="/repo",
|
||||
forge=SimpleNamespace(merged_heads=merged_heads),
|
||||
)
|
||||
|
||||
|
||||
class TestMergedByOrder(unittest.TestCase):
|
||||
def _merged_by(self, *, line, patch_merged, merged_heads):
|
||||
with (
|
||||
patch.object(gc, "_is_ancestor", return_value=False),
|
||||
patch.object(gc, "_in_line", return_value=line),
|
||||
patch.object(gc, "_patch_merged", return_value=patch_merged),
|
||||
):
|
||||
return gc._merged_by(_repo(merged_heads), SHA)
|
||||
|
||||
def test_line_wins_over_forge(self):
|
||||
self.assertEqual(
|
||||
self._merged_by(line="release", patch_merged=False, merged_heads={SHA: 7}),
|
||||
"line:release",
|
||||
)
|
||||
|
||||
def test_patch_wins_over_forge(self):
|
||||
self.assertEqual(
|
||||
self._merged_by(line=None, patch_merged=True, merged_heads={SHA: 7}),
|
||||
"patch",
|
||||
)
|
||||
|
||||
def test_forge_only_when_git_has_no_evidence(self):
|
||||
self.assertEqual(
|
||||
self._merged_by(line=None, patch_merged=False, merged_heads={SHA: 7}),
|
||||
"pr#7",
|
||||
)
|
||||
|
||||
def test_unmerged_without_any_evidence(self):
|
||||
self.assertIsNone(
|
||||
self._merged_by(line=None, patch_merged=False, merged_heads={})
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,202 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc, gc_forge
|
||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||
from pkgmgr.core.credentials.types import NoCredentialsError
|
||||
from tests.integration.test_branch_gc import GcFixture
|
||||
from tests.support.git_sandbox import git
|
||||
|
||||
GITHUB_URL = "https://github.com/example/demo.git"
|
||||
|
||||
|
||||
class TestBranchGcPlan(GcFixture, unittest.TestCase):
|
||||
def test_classifies_every_branch(self) -> None:
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["main"].state, "protected")
|
||||
self.assertEqual(items["merged"].state, "merged-clean")
|
||||
self.assertEqual(items["merged"].merged_by, "ancestor")
|
||||
self.assertEqual(
|
||||
items["merged"].actions,
|
||||
["worktree", "local-branch", "remote-branch:origin"],
|
||||
)
|
||||
self.assertTrue(items["merged"].eligible)
|
||||
self.assertEqual(items["squashed"].merged_by, "pr#7")
|
||||
self.assertTrue(items["squashed"].eligible)
|
||||
self.assertEqual(items["fresh"].state, "unmerged")
|
||||
self.assertEqual(items["fresh"].reason, "no own commits")
|
||||
self.assertEqual(items["wip"].state, "unmerged")
|
||||
self.assertEqual(items["wip"].skip, "open-pr #3")
|
||||
self.assertEqual(items["dirty"].state, "dirty")
|
||||
|
||||
def test_merged_into_counts_commits_in_an_integration_line(self) -> None:
|
||||
self._integration_line()
|
||||
before = self._items(self._plan(host_ns=True, cwds={}))
|
||||
self.assertEqual(before["feat"].state, "unmerged")
|
||||
self.assertIsNone(before["feat"].merged_into)
|
||||
|
||||
for ref in ("line", "origin/line"):
|
||||
with self.subTest(ref=ref):
|
||||
items = self._items(
|
||||
self._plan(host_ns=True, cwds={}, merged_into=[ref])
|
||||
)
|
||||
self.assertEqual(items["feat"].state, "merged-clean")
|
||||
self.assertEqual(items["feat"].merged_by, f"line:{ref}")
|
||||
self.assertEqual(items["feat"].merged_into, ref)
|
||||
self.assertTrue(items["feat"].eligible)
|
||||
self.assertEqual(items["line"].state, "protected")
|
||||
self.assertEqual(items["start"].state, "unmerged")
|
||||
self.assertEqual(items["merged"].merged_into, "origin/main")
|
||||
|
||||
def test_unknown_merged_into_ref_is_a_warning(self) -> None:
|
||||
plan = self._plan(host_ns=True, cwds={}, merged_into=["no-such-line"])
|
||||
|
||||
self.assertIn("merged-into ref no-such-line not found", plan.warnings)
|
||||
self.assertEqual(self._items(plan)["merged"].state, "merged-clean")
|
||||
|
||||
def test_sizes_and_min_age(self) -> None:
|
||||
items = self._items(self._plan(host_ns=True, cwds={}, sizes=True))
|
||||
self.assertGreater(items["merged"].size_bytes, 0)
|
||||
self.assertIsNone(items["squashed"].size_bytes)
|
||||
self.assertIn("size ", gc._line(items["merged"]))
|
||||
|
||||
young = self._items(self._plan(host_ns=True, cwds={}, min_age=1000))
|
||||
self.assertEqual(young["merged"].skip, "younger than 1000 h")
|
||||
self.assertFalse(young["merged"].eligible)
|
||||
old = self._items(self._plan(host_ns=True, cwds={}, min_age=0))
|
||||
self.assertIsNone(old["merged"].skip)
|
||||
|
||||
def test_busy_worktree_is_skipped(self) -> None:
|
||||
cwds = {4242: os.path.join(self.merged_wt, "sub")}
|
||||
items = self._items(self._plan(host_ns=True, cwds=cwds))
|
||||
|
||||
self.assertTrue(items["merged"].skip.startswith("process: pid 4242"))
|
||||
self.assertFalse(items["merged"].eligible)
|
||||
|
||||
def test_lock_with_live_pid_is_skipped(self) -> None:
|
||||
self._lock(f"claude agent x (pid {os.getpid()} on host)")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, f"lock: pid {os.getpid()} alive")
|
||||
|
||||
def test_lock_with_dead_pid_is_overridden(self) -> None:
|
||||
self._lock("claude agent x (pid 999999999 on host)")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertIsNone(items["locked"].skip)
|
||||
self.assertTrue(items["locked"].eligible)
|
||||
|
||||
def test_lock_outside_host_namespace_is_unknown(self) -> None:
|
||||
self._lock("claude agent x (pid 999999999 on host)")
|
||||
items = self._items(self._plan(host_ns=False, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, "lock: liveness unknown")
|
||||
|
||||
def test_lock_without_pid_is_respected(self) -> None:
|
||||
self._lock("manual hold")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
self.assertEqual(items["locked"].skip, "lock: manual hold")
|
||||
|
||||
def test_forge_unavailable_skips_everything(self) -> None:
|
||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||
|
||||
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, "_docker", 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)
|
||||
open(os.path.join(stub, "commondir"), "w").close()
|
||||
plan = self._plan(host_ns=True, cwds={})
|
||||
|
||||
stale = [i for i in plan.items if i.state == "stale"]
|
||||
self.assertEqual([i.worktree for i in stale], [stub])
|
||||
self.assertTrue(os.path.isdir(stub))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -31,7 +31,7 @@ def item(locked: bool, secret: bytes = b"t0ken") -> MagicMock:
|
||||
class TestSecretServiceToken(unittest.TestCase):
|
||||
def _token(self, module: types.ModuleType) -> tuple[str | None, str | None]:
|
||||
with patch.dict(sys.modules, {"secretstorage": module}):
|
||||
return tree.secret_service_token()
|
||||
return tree._forge_access()
|
||||
|
||||
def test_a_locked_item_is_never_unlocked(self) -> None:
|
||||
locked = item(True)
|
||||
|
||||
@@ -4,9 +4,8 @@ import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
from pkgmgr.actions.code_scanning import (
|
||||
CodeScanningError,
|
||||
@@ -52,11 +51,13 @@ class TestDownloadCodeScanning(unittest.TestCase):
|
||||
def test_writes_alerts_summary_and_analyses(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
with (
|
||||
mock.patch(
|
||||
unittest.mock.patch(
|
||||
"pkgmgr.actions.code_scanning.shutil.which",
|
||||
return_value="/usr/bin/gh",
|
||||
),
|
||||
mock.patch("pkgmgr.actions.code_scanning._gh", side_effect=_fake_gh),
|
||||
unittest.mock.patch(
|
||||
"pkgmgr.actions.code_scanning._gh", side_effect=_fake_gh
|
||||
),
|
||||
):
|
||||
result = download_code_scanning(output_dir=tmp)
|
||||
|
||||
@@ -74,10 +75,12 @@ class TestDownloadCodeScanning(unittest.TestCase):
|
||||
|
||||
def test_default_output_dir_uses_repo_name(self) -> None:
|
||||
with (
|
||||
mock.patch(
|
||||
unittest.mock.patch(
|
||||
"pkgmgr.actions.code_scanning.shutil.which", return_value="/usr/bin/gh"
|
||||
),
|
||||
mock.patch("pkgmgr.actions.code_scanning._gh", side_effect=_fake_gh),
|
||||
unittest.mock.patch(
|
||||
"pkgmgr.actions.code_scanning._gh", side_effect=_fake_gh
|
||||
),
|
||||
):
|
||||
result = download_code_scanning()
|
||||
self.addCleanup(shutil.rmtree, "/tmp/pkgmgr-cs-test", ignore_errors=True)
|
||||
@@ -88,7 +91,9 @@ class TestDownloadCodeScanning(unittest.TestCase):
|
||||
|
||||
def test_errors_when_gh_missing(self) -> None:
|
||||
with (
|
||||
mock.patch("pkgmgr.actions.code_scanning.shutil.which", return_value=None),
|
||||
unittest.mock.patch(
|
||||
"pkgmgr.actions.code_scanning.shutil.which", return_value=None
|
||||
),
|
||||
self.assertRaises(CodeScanningError),
|
||||
):
|
||||
download_code_scanning(output_dir="/tmp/should-not-be-created")
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,270 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc
|
||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||
from pkgmgr.actions.gc.risk import docker_items, plan
|
||||
from tests.support.git_sandbox import git, isolated_root, origin_and_repo
|
||||
|
||||
DAY = 86400
|
||||
REAL_RUN = subprocess.run
|
||||
DANGLING_ID = "sha256:" + "d" * 64
|
||||
TAGGED_ID = "sha256:" + "a" * 64
|
||||
USED_ID = "sha256:" + "u" * 64
|
||||
OLD_CACHE = "oldcache0000000000000000a"
|
||||
NEW_CACHE = "newcache0000000000000000b"
|
||||
BUSY_CACHE = "busycache000000000000000c"
|
||||
BARE_CONTAINER = "c" * 64
|
||||
VOLUME_CONTAINER = "v" * 64
|
||||
RUNNING_CONTAINER = "r" * 64
|
||||
IMAGES = (
|
||||
(DANGLING_ID, "0", "<none>", "<none>", "1.5GB"),
|
||||
(TAGGED_ID, "0", "app", "old", "200MB"),
|
||||
(USED_ID, "2", "app", "live", "300MB"),
|
||||
)
|
||||
CACHES = (
|
||||
(OLD_CACHE, "false", "265MB", 8, "8 days ago"),
|
||||
(NEW_CACHE, "false", "10kB", 2, "2 days ago"),
|
||||
(BUSY_CACHE, "true", "1GB", 30, "4 weeks ago"),
|
||||
)
|
||||
CONTAINERS = (
|
||||
(
|
||||
BARE_CONTAINER,
|
||||
"exited",
|
||||
"0",
|
||||
"bare",
|
||||
"Exited (0)",
|
||||
"com.docker.compose.project=demo,x=y",
|
||||
),
|
||||
(VOLUME_CONTAINER, "exited", "1", "withvol", "Exited (1)", ""),
|
||||
(RUNNING_CONTAINER, "running", "0", "live", "Up", ""),
|
||||
)
|
||||
VOLUMES = [
|
||||
{
|
||||
"Name": "demo_data",
|
||||
"Links": "0",
|
||||
"Size": "2GB",
|
||||
"Labels": "com.docker.compose.project=demo",
|
||||
},
|
||||
{"Name": "live_data", "Links": "1", "Size": "1GB", "Labels": ""},
|
||||
]
|
||||
OWNERS = {
|
||||
"old-done.log": "done",
|
||||
"old-stopped": "Stopped",
|
||||
"new-done.log": "done",
|
||||
"old-running.log": "running",
|
||||
"checkout": "done",
|
||||
}
|
||||
SCRATCH_FILES = ("old-done.log", "new-done.log", "old-running.log", "old-unknown.log")
|
||||
OLD_SCRATCH = ("old-done.log", "old-stopped", "old-running.log", "old-unknown.log")
|
||||
|
||||
|
||||
def stamp(epoch: float) -> str:
|
||||
moment = datetime.fromtimestamp(epoch, tz=timezone.utc)
|
||||
return moment.strftime("%Y-%m-%d %H:%M:%S.%f") + "123 +0000 UTC"
|
||||
|
||||
|
||||
def docker_df(now: float) -> dict:
|
||||
return {
|
||||
"Images": [
|
||||
{
|
||||
"ID": image_id,
|
||||
"Containers": containers,
|
||||
"Repository": repository,
|
||||
"Tag": tag,
|
||||
"UniqueSize": size,
|
||||
"CreatedAt": stamp(now),
|
||||
}
|
||||
for image_id, containers, repository, tag, size in IMAGES
|
||||
],
|
||||
"BuildCache": [
|
||||
{
|
||||
"ID": cache_id,
|
||||
"InUse": in_use,
|
||||
"Size": size,
|
||||
"LastUsedAt": stamp(now - days * DAY),
|
||||
"LastUsedSince": since,
|
||||
}
|
||||
for cache_id, in_use, size, days, since in CACHES
|
||||
],
|
||||
"Containers": [
|
||||
{
|
||||
"ID": container_id,
|
||||
"State": state,
|
||||
"LocalVolumes": volumes,
|
||||
"Names": names,
|
||||
"Image": "app:live",
|
||||
"Status": status,
|
||||
"Labels": labels,
|
||||
}
|
||||
for container_id, state, volumes, names, status, labels in CONTAINERS
|
||||
],
|
||||
"Volumes": VOLUMES,
|
||||
}
|
||||
|
||||
|
||||
class FakeDocker:
|
||||
def __init__(self, now: float) -> None:
|
||||
self.calls: list[list[str]] = []
|
||||
self.df = json.dumps(docker_df(now))
|
||||
|
||||
def __call__(self, args: list[str]) -> str:
|
||||
self.calls.append(list(args))
|
||||
if args == docker_items.DF_VERBOSE:
|
||||
return self.df
|
||||
if args == docker_items.DANGLING:
|
||||
return DANGLING_ID + "\n"
|
||||
return ""
|
||||
|
||||
def writes(self) -> list[list[str]]:
|
||||
reads = (docker_items.DF_VERBOSE, docker_items.DANGLING)
|
||||
return [call for call in self.calls if call not in reads]
|
||||
|
||||
|
||||
def inside(path: str, root: str) -> bool:
|
||||
return path == root or path.startswith(root + os.sep)
|
||||
|
||||
|
||||
def write(path: str, text: str) -> None:
|
||||
with open(path, "w") as fh:
|
||||
fh.write(text)
|
||||
|
||||
|
||||
class RiskPlanFixture:
|
||||
def setUp(self) -> None:
|
||||
self.root = isolated_root(self, {"GIT_ALLOW_PROTOCOL": "file"})
|
||||
self.commands: list[list[str]] = []
|
||||
self._start(patch("subprocess.run", self._guarded_run))
|
||||
self._repos()
|
||||
self._scratch()
|
||||
self.now = time.time()
|
||||
self.docker = FakeDocker(self.now)
|
||||
self.forge = ForgeFacts()
|
||||
self.containers = [gc.Container("stackproj", self.wt["stack"], "img")]
|
||||
self.host_ns = True
|
||||
self.include: list[str] = []
|
||||
|
||||
def _start(self, patcher) -> None:
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def _guarded_run(self, cmd, *args, **kwargs):
|
||||
argv = [str(part) for part in cmd]
|
||||
self.commands.append(argv)
|
||||
if os.path.basename(argv[0]) not in ("git", "du"):
|
||||
raise AssertionError(f"unexpected command outside the mocks: {argv}")
|
||||
cwd = os.path.realpath(kwargs.get("cwd") or os.getcwd())
|
||||
for path in [cwd, *(a for a in argv[1:] if a.startswith("/"))]:
|
||||
if not inside(os.path.realpath(path), self.root):
|
||||
raise AssertionError(f"{argv} reaches {path} outside {self.root}")
|
||||
return REAL_RUN(cmd, *args, **kwargs)
|
||||
|
||||
def _commit(self, cwd: str, name: str) -> None:
|
||||
write(os.path.join(cwd, f"{name}.txt"), name)
|
||||
git(cwd, "add", f"{name}.txt")
|
||||
git(cwd, "commit", "-m", name)
|
||||
|
||||
def _branch(self, name: str, *, push: bool, merge: bool = False) -> None:
|
||||
git(self.repo, "checkout", "-b", name, "main")
|
||||
self._commit(self.repo, name)
|
||||
if push:
|
||||
git(self.repo, "push", "origin", name)
|
||||
git(self.repo, "checkout", "main")
|
||||
if merge:
|
||||
git(self.repo, "merge", "--no-ff", "-m", f"merge {name}", name)
|
||||
git(self.repo, "push", "origin", "main")
|
||||
|
||||
def _repos(self) -> None:
|
||||
self.origin, self.repo = origin_and_repo(self.root)
|
||||
self._branch("cherry", push=False)
|
||||
for name in ("done", "stack", "old"):
|
||||
self._branch(name, push=True, merge=True)
|
||||
git(self.repo, "branch", "dirty", "done")
|
||||
self._branch("pushed", push=True)
|
||||
self._branch("wip", push=False)
|
||||
git(self.repo, "cherry-pick", "cherry")
|
||||
git(self.repo, "push", "origin", "main")
|
||||
git(self.repo, "remote", "set-head", "origin", "main")
|
||||
self.wt = {}
|
||||
for name in ("done", "dirty", "stack", "pushed", "wip", "cherry"):
|
||||
self.wt[name] = os.path.join(self.root, f"wt-{name}")
|
||||
git(self.repo, "worktree", "add", self.wt[name], name)
|
||||
write(os.path.join(self.wt["dirty"], "untracked.txt"), "x")
|
||||
|
||||
def _old(self, path: str) -> None:
|
||||
old = time.time() - 2 * DAY
|
||||
for base, dirs, files in os.walk(path):
|
||||
for name in [*dirs, *files]:
|
||||
os.utime(os.path.join(base, name), (old, old))
|
||||
os.utime(path, (old, old))
|
||||
|
||||
def _scratch(self) -> None:
|
||||
self.tmp = os.path.join(self.root, "scratch")
|
||||
os.makedirs(self.tmp)
|
||||
self.t = {
|
||||
name: os.path.join(self.tmp, name)
|
||||
for name in (*SCRATCH_FILES, "old-stopped", "checkout")
|
||||
}
|
||||
for name in SCRATCH_FILES:
|
||||
write(self.t[name], name)
|
||||
os.makedirs(os.path.join(self.t["old-stopped"], "deep"))
|
||||
write(os.path.join(self.t["old-stopped"], "deep", "x.log"), "x")
|
||||
os.makedirs(self.t["checkout"])
|
||||
write(os.path.join(self.t["checkout"], ".git"), "gitdir: /nowhere\n")
|
||||
for name in (*OLD_SCRATCH, "checkout"):
|
||||
self._old(self.t[name])
|
||||
os.symlink(self.t["old-done.log"], os.path.join(self.tmp, "link"))
|
||||
self.owners = os.path.join(self.root, "owners.json")
|
||||
with open(self.owners, "w") as fh:
|
||||
json.dump({self.t[name]: status for name, status in OWNERS.items()}, fh)
|
||||
|
||||
def request(self, level: str, apply: bool) -> plan.RiskRequest:
|
||||
return plan.RiskRequest(
|
||||
level=level,
|
||||
apply=apply,
|
||||
as_json=True,
|
||||
owners_file=self.owners,
|
||||
include=self.include,
|
||||
exclude=[],
|
||||
merged_into=[],
|
||||
sizes=False,
|
||||
min_age=None,
|
||||
hooks={},
|
||||
tmp_root=self.tmp,
|
||||
)
|
||||
|
||||
def run_gc(self, level: str, apply: bool = False) -> tuple[int, dict, str]:
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
no_gc_docker = AssertionError("gc must not call docker for low items")
|
||||
with (
|
||||
patch.object(gc, "host_pid_namespace", return_value=self.host_ns),
|
||||
patch.object(plan, "host_pid_namespace", return_value=self.host_ns),
|
||||
patch.object(gc, "_process_cwds", return_value={}),
|
||||
patch.object(plan, "_process_cwds", return_value={}),
|
||||
patch.object(gc, "list_compose_containers", return_value=self.containers),
|
||||
patch.object(gc, "fetch_forge_facts", return_value=self.forge),
|
||||
patch.object(gc, "_docker", side_effect=no_gc_docker),
|
||||
patch.object(docker_items, "_docker", side_effect=self.docker),
|
||||
redirect_stdout(out),
|
||||
redirect_stderr(err),
|
||||
):
|
||||
code = plan.risk_cleanup([self.repo], self.request(level, apply))
|
||||
printed = json.loads(out.getvalue()) if out.getvalue().strip() else {}
|
||||
return code, printed, err.getvalue()
|
||||
|
||||
def risks(self, printed: dict) -> dict[str, str]:
|
||||
return {entry["name"]: entry["risk"] for entry in printed["items"]}
|
||||
|
||||
def entry(self, printed: dict, name: str) -> dict:
|
||||
return next(e for e in printed["items"] if e["name"] == name)
|
||||
|
||||
def refs(self, cwd: str) -> str:
|
||||
return git(cwd, "for-each-ref", "--format=%(refname) %(objectname)")
|
||||
@@ -0,0 +1,224 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.gc.risk import git_items, plan, tmp_items
|
||||
from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
|
||||
BARE_CONTAINER,
|
||||
DANGLING_ID,
|
||||
OLD_CACHE,
|
||||
RiskPlanFixture,
|
||||
write,
|
||||
)
|
||||
|
||||
|
||||
class TestApplyLow(RiskPlanFixture, unittest.TestCase):
|
||||
def test_apply_deletes_exactly_the_low_items(self) -> None:
|
||||
repo_refs, origin_refs = self.refs(self.repo), self.refs(self.origin)
|
||||
tmp_before = set(os.listdir(self.tmp))
|
||||
_, low_plan, _ = self.run_gc(level="low")
|
||||
self.docker.calls.clear()
|
||||
self.commands.clear()
|
||||
|
||||
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(sorted(self.risks(printed)), sorted(self.risks(low_plan)))
|
||||
self.assertEqual({e["result"] for e in printed["items"]}, {"done"})
|
||||
self.assertFalse(os.path.exists(self.wt["done"]))
|
||||
for name in ("dirty", "stack", "pushed", "wip", "cherry"):
|
||||
self.assertTrue(os.path.isdir(self.wt[name]), name)
|
||||
self.assertEqual(self.refs(self.repo), repo_refs)
|
||||
self.assertEqual(self.refs(self.origin), origin_refs)
|
||||
self.assertEqual(
|
||||
tmp_before - set(os.listdir(self.tmp)), {"old-done.log", "old-stopped"}
|
||||
)
|
||||
self.assertEqual(
|
||||
self.docker.writes(),
|
||||
[
|
||||
["image", "rm", DANGLING_ID],
|
||||
[
|
||||
"builder",
|
||||
"prune",
|
||||
"--force",
|
||||
"--filter",
|
||||
f"id={OLD_CACHE}",
|
||||
"--filter",
|
||||
"until=168h",
|
||||
],
|
||||
["container", "rm", BARE_CONTAINER],
|
||||
],
|
||||
)
|
||||
for argv in self.commands:
|
||||
self.assertFalse({"push", "-D", "update-ref"} & set(argv), argv)
|
||||
|
||||
def test_branch_filter_applies_to_its_git_items_only(self) -> None:
|
||||
tmp_before = sorted(os.listdir(self.tmp))
|
||||
self.include = ["done"]
|
||||
|
||||
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(
|
||||
[(e["name"], e["result"]) for e in printed["items"]],
|
||||
[(self.wt["done"], "done")],
|
||||
)
|
||||
self.assertIn(plan.INCLUDE_ONLY_GIT, printed["warnings"])
|
||||
self.assertEqual(self.docker.calls, [])
|
||||
self.assertEqual(sorted(os.listdir(self.tmp)), tmp_before)
|
||||
for name in ("dirty", "stack", "pushed", "wip", "cherry"):
|
||||
self.assertTrue(os.path.isdir(self.wt[name]), name)
|
||||
|
||||
def test_worktree_changed_after_plan_is_skipped(self) -> None:
|
||||
real_rebuild = git_items._rebuild
|
||||
|
||||
def dirty_then_rebuild(repo, item):
|
||||
with open(os.path.join(self.wt["done"], "late.txt"), "w") as fh:
|
||||
fh.write("late")
|
||||
return real_rebuild(repo, item)
|
||||
|
||||
with patch.object(git_items, "_rebuild", side_effect=dirty_then_rebuild):
|
||||
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||
done = self.entry(printed, self.wt["done"])
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(done["result"].startswith("skipped: changed since plan"))
|
||||
self.assertTrue(os.path.isfile(os.path.join(self.wt["done"], "late.txt")))
|
||||
|
||||
def test_negative_control_refusals_delete_nothing(self) -> None:
|
||||
repo_refs = self.refs(self.repo)
|
||||
tmp_before = sorted(os.listdir(self.tmp))
|
||||
for level, host_ns in (("medium", True), ("high", True), ("low", False)):
|
||||
with self.subTest(level=level, host_ns=host_ns):
|
||||
self.docker.calls.clear()
|
||||
self.host_ns = host_ns
|
||||
code, printed, err = self.run_gc(level=level, apply=True)
|
||||
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(printed, {})
|
||||
self.assertIn("Refusing", err)
|
||||
self.assertEqual(self.docker.calls, [])
|
||||
self.assertTrue(os.path.isdir(self.wt["done"]))
|
||||
self.assertEqual(self.refs(self.repo), repo_refs)
|
||||
self.assertEqual(sorted(os.listdir(self.tmp)), tmp_before)
|
||||
|
||||
def test_bad_owner_file_is_refused(self) -> None:
|
||||
with open(self.owners, "w") as fh:
|
||||
fh.write("[1, 2]")
|
||||
code, printed, err = self.run_gc(level="low", apply=True)
|
||||
|
||||
self.assertEqual((code, printed), (2, {}))
|
||||
self.assertIn("owner file", err)
|
||||
self.assertTrue(os.path.isdir(self.wt["done"]))
|
||||
self.assertTrue(os.path.isfile(self.t["old-done.log"]))
|
||||
|
||||
def _after_plan(self, change) -> tuple[int, dict]:
|
||||
real_apply = plan._apply
|
||||
|
||||
def change_then_apply(*args):
|
||||
change()
|
||||
return real_apply(*args)
|
||||
|
||||
with patch.object(plan, "_apply", side_effect=change_then_apply):
|
||||
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||
return code, printed
|
||||
|
||||
def test_owner_status_changed_after_plan_keeps_the_scratch(self) -> None:
|
||||
running = json.dumps({self.t["old-stopped"]: "running"})
|
||||
|
||||
code, printed = self._after_plan(lambda: write(self.owners, running))
|
||||
stopped = self.entry(printed, self.t["old-stopped"])
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(
|
||||
stopped["result"], "skipped: changed since plan (owner task is running)"
|
||||
)
|
||||
self.assertTrue(os.path.isdir(self.t["old-stopped"]))
|
||||
|
||||
def test_owner_file_gone_after_plan_fails_and_keeps_the_scratch(self) -> None:
|
||||
code, printed = self._after_plan(lambda: os.unlink(self.owners))
|
||||
|
||||
self.assertEqual(code, 1)
|
||||
for name in ("old-stopped", "old-done.log"):
|
||||
self.assertTrue(
|
||||
self.entry(printed, self.t[name])["result"].startswith("failed:"), name
|
||||
)
|
||||
self.assertTrue(os.path.lexists(self.t[name]), name)
|
||||
|
||||
def test_docker_items_no_longer_low_after_plan_are_kept(self) -> None:
|
||||
def nothing_low() -> None:
|
||||
df = json.loads(self.docker.df)
|
||||
for row in df["Containers"]:
|
||||
row["LocalVolumes"] = "1"
|
||||
for row in df["BuildCache"]:
|
||||
row["InUse"] = "true"
|
||||
self.docker.df = json.dumps(df)
|
||||
self.docker.calls.clear()
|
||||
|
||||
code, printed = self._after_plan(nothing_low)
|
||||
changed = {
|
||||
e["name"]: e["result"]
|
||||
for e in printed["items"]
|
||||
if e["kind"] in ("build-cache", "container")
|
||||
}
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(
|
||||
changed,
|
||||
dict.fromkeys((OLD_CACHE, BARE_CONTAINER), "skipped: changed since plan"),
|
||||
)
|
||||
self.assertEqual(self.docker.writes(), [["image", "rm", DANGLING_ID]])
|
||||
|
||||
def test_docker_unreadable_after_plan_fails_and_deletes_nothing(self) -> None:
|
||||
def docker_gone() -> None:
|
||||
self.docker.df = "not json"
|
||||
self.docker.calls.clear()
|
||||
|
||||
code, printed = self._after_plan(docker_gone)
|
||||
results = [
|
||||
e["result"]
|
||||
for e in printed["items"]
|
||||
if e["kind"] in ("image", "build-cache", "container")
|
||||
]
|
||||
|
||||
self.assertEqual(code, 1)
|
||||
self.assertTrue(results)
|
||||
for result in results:
|
||||
self.assertTrue(result.startswith("failed: revalidation failed"), result)
|
||||
self.assertEqual(self.docker.writes(), [])
|
||||
|
||||
def test_non_utf8_mount_elsewhere_keeps_the_plan_working(self) -> None:
|
||||
table = os.path.join(self.root, "mountinfo")
|
||||
with open(table, "wb") as fh:
|
||||
fh.write(b"36 35 98:0 / /mnt/\xff rw - ext4 /dev/x rw\n")
|
||||
|
||||
with patch.object(tmp_items, "MOUNTINFO", table):
|
||||
code, printed, _ = self.run_gc(level="low")
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(self.risks(printed).get(self.t["old-stopped"]), "low")
|
||||
|
||||
def test_mount_at_or_below_scratch_is_never_low(self) -> None:
|
||||
stopped = self.t["old-stopped"]
|
||||
table = os.path.join(self.root, "mountinfo")
|
||||
for point in (stopped, os.path.join(stopped, "deep"), None):
|
||||
with self.subTest(point=point):
|
||||
if point is None:
|
||||
table_path = os.path.join(self.root, "absent")
|
||||
else:
|
||||
escaped = point.replace(" ", "\\040")
|
||||
write(table, f"36 35 98:0 / {escaped} rw - ext4 /dev/x rw\n")
|
||||
table_path = table
|
||||
with patch.object(tmp_items, "MOUNTINFO", table_path):
|
||||
code, printed, _ = self.run_gc(level="low", apply=True)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
self.assertNotIn(stopped, self.risks(printed))
|
||||
self.assertTrue(os.path.isdir(stopped))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,186 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stderr
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||
from pkgmgr.actions.gc.risk import plan
|
||||
from pkgmgr.cli.commands.worktree import handle_gc
|
||||
from pkgmgr.cli.parser import create_parser
|
||||
from tests.support.git_sandbox import git
|
||||
from tests.unit.pkgmgr.actions.gc.risk.risk_fixture import (
|
||||
BARE_CONTAINER,
|
||||
BUSY_CACHE,
|
||||
DANGLING_ID,
|
||||
NEW_CACHE,
|
||||
OLD_CACHE,
|
||||
RUNNING_CONTAINER,
|
||||
TAGGED_ID,
|
||||
USED_ID,
|
||||
VOLUME_CONTAINER,
|
||||
RiskPlanFixture,
|
||||
)
|
||||
|
||||
|
||||
class TestRiskRules(RiskPlanFixture, unittest.TestCase):
|
||||
def test_git_rules(self) -> None:
|
||||
code, printed, _ = self.run_gc(level="high")
|
||||
risks = self.risks(printed)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
expected = {
|
||||
self.wt["done"]: "low",
|
||||
self.wt["dirty"]: "high",
|
||||
self.wt["wip"]: "high",
|
||||
self.wt["pushed"]: "medium",
|
||||
self.wt["stack"]: "medium",
|
||||
self.wt["cherry"]: "medium",
|
||||
"old": "medium",
|
||||
"main": "high",
|
||||
}
|
||||
for name, risk in expected.items():
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(risks[name], risk)
|
||||
done = self.entry(printed, self.wt["done"])
|
||||
self.assertEqual(done["steps"], ["worktree"])
|
||||
self.assertEqual(done["pr"], "none")
|
||||
cherry = self.entry(printed, self.wt["cherry"])
|
||||
self.assertEqual(cherry["reason"], "head is on no remote")
|
||||
|
||||
def test_local_proof_needs_no_forge(self) -> None:
|
||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
done = self.entry(printed, self.wt["done"])
|
||||
|
||||
self.assertEqual(done["risk"], "low")
|
||||
self.assertEqual(done["pr"], "unknown")
|
||||
self.assertEqual(done["skip"], "forge unavailable")
|
||||
|
||||
def test_forge_absence_never_hides_a_worktree_hold(self) -> None:
|
||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||
git(self.repo, "worktree", "lock", "--reason", "kept", self.wt["done"])
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
done = self.entry(printed, self.wt["done"])
|
||||
|
||||
self.assertEqual((done["risk"], done["skip"]), ("medium", "lock: kept"))
|
||||
|
||||
def test_open_pull_request_is_not_low(self) -> None:
|
||||
self.forge = ForgeFacts(open_heads={"done": 9})
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
done = self.entry(printed, self.wt["done"])
|
||||
|
||||
self.assertEqual((done["risk"], done["pr"]), ("medium", "open #9"))
|
||||
|
||||
def test_docker_rules(self) -> None:
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
risks = self.risks(printed)
|
||||
|
||||
self.assertEqual(risks[DANGLING_ID], "low")
|
||||
self.assertEqual(risks[TAGGED_ID], "medium")
|
||||
self.assertEqual(risks[OLD_CACHE], "low")
|
||||
self.assertEqual(risks[NEW_CACHE], "medium")
|
||||
self.assertEqual(risks[BARE_CONTAINER], "low")
|
||||
self.assertEqual(risks[VOLUME_CONTAINER], "medium")
|
||||
self.assertEqual(risks["demo_data"], "medium")
|
||||
self.assertEqual(risks["live_data"], "high")
|
||||
for absent in (USED_ID, BUSY_CACHE, RUNNING_CONTAINER):
|
||||
self.assertNotIn(absent, risks)
|
||||
volume = self.entry(printed, "demo_data")
|
||||
self.assertEqual(
|
||||
(volume["compose_project"], volume["links"], volume["size_bytes"]),
|
||||
("demo", 0, 2 * 10**9),
|
||||
)
|
||||
image = self.entry(printed, DANGLING_ID)
|
||||
self.assertEqual(image["size_bytes"], 1_500_000_000)
|
||||
|
||||
def test_tmp_rules(self) -> None:
|
||||
_, printed, _ = self.run_gc(level="high")
|
||||
risks = self.risks(printed)
|
||||
|
||||
self.assertEqual(risks[self.t["old-done.log"]], "low")
|
||||
self.assertEqual(risks[self.t["old-stopped"]], "low")
|
||||
self.assertEqual(risks[self.t["new-done.log"]], "medium")
|
||||
self.assertEqual(risks[self.t["old-unknown.log"]], "medium")
|
||||
self.assertEqual(risks[self.t["old-running.log"]], "high")
|
||||
self.assertEqual(risks[self.t["checkout"]], "high")
|
||||
self.assertNotIn(os.path.join(self.tmp, "link"), risks)
|
||||
|
||||
def test_risk_low_plan_lists_only_low_items(self) -> None:
|
||||
_, printed, _ = self.run_gc(level="low")
|
||||
|
||||
self.assertEqual(
|
||||
sorted(self.risks(printed)),
|
||||
sorted(
|
||||
[
|
||||
self.wt["done"],
|
||||
DANGLING_ID,
|
||||
OLD_CACHE,
|
||||
BARE_CONTAINER,
|
||||
self.t["old-done.log"],
|
||||
self.t["old-stopped"],
|
||||
]
|
||||
),
|
||||
)
|
||||
self.assertEqual(printed["totals"]["low"]["count"], 6)
|
||||
|
||||
|
||||
class TestRiskCli(unittest.TestCase):
|
||||
def _gc(self, *argv: str) -> tuple[int, object]:
|
||||
args = create_parser("test").parse_args(["gc", *argv])
|
||||
ctx = SimpleNamespace(config_merged={"worktree_hooks": {}, "repositories": []})
|
||||
with (
|
||||
patch("pkgmgr.cli.commands.worktree.scan_repo_roots", return_value=["/r"]),
|
||||
patch("pkgmgr.cli.commands.worktree.risk_cleanup", return_value=0) as run,
|
||||
patch("pkgmgr.cli.commands.worktree.run_cleanup") as legacy,
|
||||
redirect_stderr(io.StringIO()),
|
||||
self.assertRaises(SystemExit) as stop,
|
||||
):
|
||||
handle_gc(args, ctx)
|
||||
legacy.assert_not_called()
|
||||
return stop.exception.code, run
|
||||
|
||||
def test_cli_forwards_risk_flags(self) -> None:
|
||||
code, run = self._gc(
|
||||
"--risk",
|
||||
"low",
|
||||
"--apply",
|
||||
"--json",
|
||||
"--owners",
|
||||
"/o.json",
|
||||
"--merged-into",
|
||||
"origin/main",
|
||||
"--sizes",
|
||||
)
|
||||
|
||||
self.assertEqual(code, 0)
|
||||
run.assert_called_once_with(
|
||||
["/r"],
|
||||
plan.RiskRequest(
|
||||
level="low",
|
||||
apply=True,
|
||||
as_json=True,
|
||||
owners_file="/o.json",
|
||||
include=[],
|
||||
exclude=[],
|
||||
merged_into=["origin/main"],
|
||||
sizes=True,
|
||||
min_age=None,
|
||||
hooks={},
|
||||
tmp_root=tempfile.gettempdir(),
|
||||
),
|
||||
)
|
||||
|
||||
def test_cli_refuses_risk_with_report(self) -> None:
|
||||
code, run = self._gc("--risk", "low", "--report")
|
||||
|
||||
self.assertEqual(code, 2)
|
||||
run.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -26,11 +26,6 @@ class TestMakefileInstaller(unittest.TestCase):
|
||||
)
|
||||
self.installer = MakefileInstaller()
|
||||
|
||||
# @patch("os.path.exists", return_value=True)
|
||||
# def test_supports_true_when_makefile_exists(self, mock_exists):
|
||||
# self.assertTrue(self.installer.supports(self.ctx))
|
||||
# mock_exists.assert_called_with(os.path.join(self.ctx.repo_dir, "Makefile"))
|
||||
|
||||
@patch("os.path.exists", return_value=False)
|
||||
def test_supports_false_when_makefile_missing(self, mock_exists):
|
||||
self.assertFalse(self.installer.supports(self.ctx))
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from unittest import mock
|
||||
import unittest.mock
|
||||
|
||||
from pkgmgr.actions.release.files.editor import _open_editor_for_changelog
|
||||
|
||||
|
||||
class TestOpenEditorForChangelog(unittest.TestCase):
|
||||
def _buffer(self, **kwargs: object) -> str:
|
||||
"""Returns: what the editor was handed, with the editor itself a no-op."""
|
||||
def _edit(self, **kwargs: object) -> tuple[str, str]:
|
||||
"""Returns: what the editor was handed and the kept entry, editor a no-op."""
|
||||
seen: dict[str, str] = {}
|
||||
|
||||
def record(argv: list[str]) -> int:
|
||||
@@ -16,11 +15,14 @@ class TestOpenEditorForChangelog(unittest.TestCase):
|
||||
seen["text"] = handle.read()
|
||||
return 0
|
||||
|
||||
with mock.patch(
|
||||
with unittest.mock.patch(
|
||||
"pkgmgr.actions.release.files.editor.subprocess.call", side_effect=record
|
||||
):
|
||||
_open_editor_for_changelog(**kwargs)
|
||||
return seen["text"]
|
||||
kept = _open_editor_for_changelog(**kwargs)
|
||||
return seen["text"], kept
|
||||
|
||||
def _buffer(self, **kwargs: object) -> str:
|
||||
return self._edit(**kwargs)[0]
|
||||
|
||||
def test_the_rejection_reaches_the_editor_the_entry_is_fixed_in(self) -> None:
|
||||
text = self._buffer(
|
||||
@@ -37,19 +39,7 @@ class TestOpenEditorForChangelog(unittest.TestCase):
|
||||
self.assertTrue(line.startswith(";"), line)
|
||||
|
||||
def test_a_finding_never_lands_in_the_entry(self) -> None:
|
||||
seen: dict[str, str] = {}
|
||||
|
||||
def rewrite(argv: list[str]) -> int:
|
||||
with open(argv[1], encoding="utf-8") as handle:
|
||||
seen["text"] = handle.read()
|
||||
return 0
|
||||
|
||||
with mock.patch(
|
||||
"pkgmgr.actions.release.files.editor.subprocess.call", side_effect=rewrite
|
||||
):
|
||||
kept = _open_editor_for_changelog(
|
||||
initial_message="- a bullet", findings=["MD036 somewhere"]
|
||||
)
|
||||
_, kept = self._edit(initial_message="- a bullet", findings=["MD036 somewhere"])
|
||||
self.assertEqual(kept, "- a bullet")
|
||||
|
||||
def test_without_findings_the_header_stays_as_it_was(self) -> None:
|
||||
|
||||
@@ -14,6 +14,7 @@ from __future__ import annotations
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.release.options import ReleaseOptions
|
||||
from pkgmgr.actions.release.retry import retry_release
|
||||
from pkgmgr.actions.release.workflow import release
|
||||
from pkgmgr.core.git import GitRunError
|
||||
@@ -25,7 +26,7 @@ class TestReleaseRetry(unittest.TestCase):
|
||||
def test_retry_routes_to_retry_release_only(
|
||||
self, mock_release_impl, mock_retry_release
|
||||
) -> None:
|
||||
release(retry=True, preview=False)
|
||||
release(ReleaseOptions(retry=True, expect_tree=None))
|
||||
|
||||
mock_retry_release.assert_called_once()
|
||||
mock_release_impl.assert_not_called()
|
||||
@@ -36,7 +37,7 @@ class TestReleaseRetry(unittest.TestCase):
|
||||
def test_retry_preview_passthrough(
|
||||
self, mock_release_impl, mock_retry_release
|
||||
) -> None:
|
||||
release(retry=True, preview=True)
|
||||
release(ReleaseOptions(retry=True, preview=True, expect_tree=None))
|
||||
|
||||
mock_retry_release.assert_called_once()
|
||||
mock_release_impl.assert_not_called()
|
||||
@@ -50,12 +51,15 @@ class TestReleaseRetry(unittest.TestCase):
|
||||
# release_type/message/close/force must NOT trigger the full release flow
|
||||
# when retry=True.
|
||||
release(
|
||||
retry=True,
|
||||
release_type="major",
|
||||
message="ignored body",
|
||||
preview=False,
|
||||
force=True,
|
||||
close=True,
|
||||
ReleaseOptions(
|
||||
retry=True,
|
||||
release_type="major",
|
||||
message="ignored body",
|
||||
preview=False,
|
||||
force=True,
|
||||
close=True,
|
||||
expect_tree=None,
|
||||
)
|
||||
)
|
||||
|
||||
mock_retry_release.assert_called_once()
|
||||
|
||||
@@ -1,66 +1,154 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.release.workflow import release
|
||||
from pkgmgr.actions.release.git_ops import ensure_head_tree
|
||||
from pkgmgr.actions.release.options import ReleaseOptions
|
||||
from pkgmgr.actions.release.workflow import _release_impl, release
|
||||
|
||||
TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
|
||||
OTHER = "0" * 40
|
||||
WORKFLOW = "pkgmgr.actions.release.workflow"
|
||||
GIT_OPS_RUN = "pkgmgr.actions.release.git_ops.run"
|
||||
|
||||
|
||||
class TestWorkflowReleaseEntryPoint(unittest.TestCase):
|
||||
@patch("pkgmgr.actions.release.workflow._release_impl")
|
||||
@patch(f"{WORKFLOW}._release_impl")
|
||||
def test_release_preview_calls_impl_preview_only(self, mock_impl) -> None:
|
||||
release(preview=True, force=False, close=False)
|
||||
release(ReleaseOptions(preview=True, expect_tree=None))
|
||||
|
||||
mock_impl.assert_called_once()
|
||||
kwargs = mock_impl.call_args.kwargs
|
||||
self.assertTrue(kwargs["preview"])
|
||||
self.assertFalse(kwargs["force"])
|
||||
options = mock_impl.call_args.args[0]
|
||||
self.assertTrue(options.preview)
|
||||
self.assertFalse(options.force)
|
||||
|
||||
@patch("pkgmgr.actions.release.workflow._release_impl")
|
||||
@patch("pkgmgr.actions.release.workflow.sys.stdin.isatty", return_value=False)
|
||||
@patch(f"{WORKFLOW}._release_impl")
|
||||
@patch(f"{WORKFLOW}.sys.stdin.isatty", return_value=False)
|
||||
def test_release_non_interactive_runs_real_without_confirmation(
|
||||
self, _mock_isatty, mock_impl
|
||||
) -> None:
|
||||
release(preview=False, force=False, close=False)
|
||||
release(ReleaseOptions(expect_tree=None))
|
||||
|
||||
mock_impl.assert_called_once()
|
||||
kwargs = mock_impl.call_args.kwargs
|
||||
self.assertFalse(kwargs["preview"])
|
||||
self.assertFalse(mock_impl.call_args.args[0].preview)
|
||||
|
||||
@patch("pkgmgr.actions.release.workflow._release_impl")
|
||||
@patch(f"{WORKFLOW}._release_impl")
|
||||
def test_release_force_runs_real_without_confirmation(self, mock_impl) -> None:
|
||||
release(preview=False, force=True, close=False)
|
||||
release(ReleaseOptions(force=True, expect_tree=None))
|
||||
|
||||
mock_impl.assert_called_once()
|
||||
kwargs = mock_impl.call_args.kwargs
|
||||
self.assertFalse(kwargs["preview"])
|
||||
self.assertTrue(kwargs["force"])
|
||||
options = mock_impl.call_args.args[0]
|
||||
self.assertFalse(options.preview)
|
||||
self.assertTrue(options.force)
|
||||
|
||||
@patch("pkgmgr.actions.release.workflow._release_impl")
|
||||
@patch(
|
||||
"pkgmgr.actions.release.workflow.confirm_proceed_release", return_value=False
|
||||
)
|
||||
@patch("pkgmgr.actions.release.workflow.sys.stdin.isatty", return_value=True)
|
||||
@patch(f"{WORKFLOW}._release_impl")
|
||||
@patch(f"{WORKFLOW}.confirm_proceed_release", return_value=False)
|
||||
@patch(f"{WORKFLOW}.sys.stdin.isatty", return_value=True)
|
||||
def test_release_interactive_decline_runs_only_preview(
|
||||
self, _mock_isatty, _mock_confirm, mock_impl
|
||||
) -> None:
|
||||
release(preview=False, force=False, close=False)
|
||||
release(ReleaseOptions(expect_tree=None))
|
||||
|
||||
# interactive path: preview first, then decline => only one call
|
||||
self.assertEqual(mock_impl.call_count, 1)
|
||||
self.assertTrue(mock_impl.call_args_list[0].kwargs["preview"])
|
||||
self.assertTrue(mock_impl.call_args_list[0].args[0].preview)
|
||||
|
||||
@patch("pkgmgr.actions.release.workflow._release_impl")
|
||||
@patch("pkgmgr.actions.release.workflow.confirm_proceed_release", return_value=True)
|
||||
@patch("pkgmgr.actions.release.workflow.sys.stdin.isatty", return_value=True)
|
||||
@patch(f"{WORKFLOW}._release_impl")
|
||||
@patch(f"{WORKFLOW}.confirm_proceed_release", return_value=True)
|
||||
@patch(f"{WORKFLOW}.sys.stdin.isatty", return_value=True)
|
||||
def test_release_interactive_accept_runs_preview_then_real(
|
||||
self, _mock_isatty, _mock_confirm, mock_impl
|
||||
) -> None:
|
||||
release(preview=False, force=False, close=False)
|
||||
release(ReleaseOptions(expect_tree=None))
|
||||
|
||||
self.assertEqual(mock_impl.call_count, 2)
|
||||
self.assertTrue(mock_impl.call_args_list[0].kwargs["preview"])
|
||||
self.assertFalse(mock_impl.call_args_list[1].kwargs["preview"])
|
||||
self.assertTrue(mock_impl.call_args_list[0].args[0].preview)
|
||||
self.assertFalse(mock_impl.call_args_list[1].args[0].preview)
|
||||
|
||||
@patch(f"{WORKFLOW}._release_impl")
|
||||
@patch(f"{WORKFLOW}.confirm_proceed_release", return_value=True)
|
||||
@patch(f"{WORKFLOW}.sys.stdin.isatty", return_value=True)
|
||||
def test_release_passes_expect_tree_to_preview_and_real(
|
||||
self, _mock_isatty, _mock_confirm, mock_impl
|
||||
) -> None:
|
||||
release(ReleaseOptions(expect_tree=TREE))
|
||||
|
||||
self.assertEqual(
|
||||
[c.args[0].expect_tree for c in mock_impl.call_args_list], [TREE, TREE]
|
||||
)
|
||||
|
||||
|
||||
class TestReleaseExpectTree(unittest.TestCase):
|
||||
def test_tree_mismatch_after_pull_stops_before_any_write(self) -> None:
|
||||
with (
|
||||
patch(f"{WORKFLOW}.get_current_branch", return_value="main"),
|
||||
patch(f"{WORKFLOW}.refuse_unsafe_config"),
|
||||
patch(f"{WORKFLOW}.ensure_clean_and_synced") as mock_sync,
|
||||
patch(f"{WORKFLOW}.update_pyproject_version") as mock_write,
|
||||
patch(GIT_OPS_RUN, return_value=OTHER) as mock_run,
|
||||
redirect_stdout(io.StringIO()),
|
||||
self.assertRaises(RuntimeError) as cm,
|
||||
):
|
||||
_release_impl(ReleaseOptions(force=True, expect_tree=TREE))
|
||||
|
||||
mock_sync.assert_called_once()
|
||||
mock_run.assert_called_once_with(["rev-parse", "HEAD^{tree}"])
|
||||
mock_write.assert_not_called()
|
||||
self.assertIn(TREE, str(cm.exception))
|
||||
|
||||
def test_untracked_release_input_stops_before_any_write(self) -> None:
|
||||
workdir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(workdir.cleanup)
|
||||
pyproject = os.path.join(workdir.name, "pyproject.toml")
|
||||
flake = os.path.join(workdir.name, "flake.nix")
|
||||
for path in (pyproject, flake):
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
handle.write("")
|
||||
options = ReleaseOptions(
|
||||
pyproject_path=pyproject,
|
||||
changelog_path=os.path.join(workdir.name, "CHANGELOG.md"),
|
||||
force=True,
|
||||
expect_tree=TREE,
|
||||
)
|
||||
|
||||
with (
|
||||
patch(f"{WORKFLOW}.get_current_branch", return_value="main"),
|
||||
patch(f"{WORKFLOW}.refuse_unsafe_config"),
|
||||
patch(f"{WORKFLOW}.ensure_clean_and_synced"),
|
||||
patch(f"{WORKFLOW}.update_pyproject_version") as mock_write,
|
||||
patch(GIT_OPS_RUN, side_effect=[TREE, "flake.nix"]) as mock_run,
|
||||
redirect_stdout(io.StringIO()),
|
||||
self.assertRaises(RuntimeError) as cm,
|
||||
):
|
||||
_release_impl(options)
|
||||
|
||||
mock_run.assert_called_with(["ls-files", "--others", "--", pyproject, flake])
|
||||
mock_write.assert_not_called()
|
||||
self.assertIn("flake.nix", str(cm.exception))
|
||||
|
||||
@patch(f"{WORKFLOW}.retry_release")
|
||||
@patch(GIT_OPS_RUN, return_value=OTHER)
|
||||
def test_retry_with_other_tree_pushes_nothing(self, _mock_run, mock_retry) -> None:
|
||||
with self.assertRaises(RuntimeError):
|
||||
release(ReleaseOptions(retry=True, expect_tree=TREE))
|
||||
|
||||
mock_retry.assert_not_called()
|
||||
|
||||
@patch(GIT_OPS_RUN, return_value=TREE)
|
||||
def test_matching_tree_passes(self, mock_run) -> None:
|
||||
ensure_head_tree(TREE)
|
||||
|
||||
mock_run.assert_called_once_with(["rev-parse", "HEAD^{tree}"])
|
||||
|
||||
@patch(GIT_OPS_RUN)
|
||||
def test_no_expected_tree_reads_nothing(self, mock_run) -> None:
|
||||
ensure_head_tree(None)
|
||||
|
||||
mock_run.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.repository.create.templates import TemplateRenderer
|
||||
|
||||
|
||||
class TestTemplateAutoescape(unittest.TestCase):
|
||||
def _render(self, names: list[str]) -> dict[str, str]:
|
||||
with tempfile.TemporaryDirectory() as tpl, tempfile.TemporaryDirectory() as out:
|
||||
for name in names:
|
||||
with open(os.path.join(tpl, name), "w", encoding="utf-8") as fh:
|
||||
fh.write("{{ value }}")
|
||||
with patch.object(
|
||||
TemplateRenderer, "_resolve_templates_dir", return_value=tpl
|
||||
):
|
||||
TemplateRenderer().render(
|
||||
repo_dir=out, context={"value": "<b>"}, preview=False
|
||||
)
|
||||
rendered = {}
|
||||
for name in names:
|
||||
with open(os.path.join(out, name[:-3]), encoding="utf-8") as fh:
|
||||
rendered[name[:-3]] = fh.read()
|
||||
return rendered
|
||||
|
||||
def test_markup_templates_escape_and_others_stay_raw(self) -> None:
|
||||
rendered = self._render(
|
||||
["page.html.j2", "page.htm.j2", "feed.xml.j2", "README.md.j2"]
|
||||
)
|
||||
self.assertEqual(rendered["page.html"], "<b>")
|
||||
self.assertEqual(rendered["page.htm"], "<b>")
|
||||
self.assertEqual(rendered["feed.xml"], "<b>")
|
||||
self.assertEqual(rendered["README.md"], "<b>")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,364 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from contextlib import redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.repository import push as push_module
|
||||
from pkgmgr.actions.repository.push import (
|
||||
PushRefusedError,
|
||||
push_branch,
|
||||
sign_unpushed,
|
||||
)
|
||||
from tests.integration.test_push_mirror_leases import (
|
||||
_REAL_RUN,
|
||||
GIT,
|
||||
SignedRemotesCase,
|
||||
git,
|
||||
keygen,
|
||||
)
|
||||
|
||||
|
||||
def _push_sids(events: list[dict]) -> set[str]:
|
||||
return {
|
||||
e["sid"] for e in events if e["event"] == "cmd_name" and e.get("name") == "push"
|
||||
}
|
||||
|
||||
|
||||
def _repo_param(event: dict, prefixes: tuple[str, ...]) -> bool:
|
||||
return (
|
||||
event["event"] == "def_param"
|
||||
and event.get("scope") in ("local", "worktree")
|
||||
and event["param"].startswith(prefixes)
|
||||
)
|
||||
|
||||
|
||||
class TestPushTrustedGitdir(SignedRemotesCase):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
self.marker = Path(self.root, "marker")
|
||||
self.trace = Path(self.root, "trace.json")
|
||||
|
||||
def _push(self) -> str:
|
||||
with redirect_stdout(io.StringIO()) as out:
|
||||
sign_unpushed(self.repo)
|
||||
push_branch(self.repo, [], sign=True)
|
||||
return out.getvalue()
|
||||
|
||||
def _plant(self) -> str:
|
||||
return f"touch {self.marker}"
|
||||
|
||||
def _hook(self, directory: Path, *names: str) -> None:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
for name in names:
|
||||
hook = directory / name
|
||||
hook.write_text(f"#!/bin/sh\n{self._plant()}\n")
|
||||
hook.chmod(0o755)
|
||||
|
||||
def _canonical_signature(self) -> str:
|
||||
return _REAL_RUN(
|
||||
[GIT, "log", "-1", "--format=%G?", "refs/heads/main"],
|
||||
cwd=self.canonical,
|
||||
env={**self.env, "GIT_NO_REPLACE_OBJECTS": "1"},
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout.strip()
|
||||
|
||||
def _assert_landed(self) -> None:
|
||||
head = git(self.repo, "rev-parse", "HEAD")
|
||||
self.assertEqual(self._tip(self.canonical), head)
|
||||
self.assertEqual(self._tip(self.mirror), head)
|
||||
self.assertEqual(self._canonical_signature(), "G")
|
||||
|
||||
def _assert_nothing_ran(self) -> None:
|
||||
self.assertFalse(self.marker.exists(), "a planted program ran")
|
||||
|
||||
def _trace_repo_config(self, prefixes: tuple[str, ...]) -> None:
|
||||
with self.gitconfig.open("a") as fh:
|
||||
fh.write(
|
||||
f"[trace2]\n\teventTarget = {self.trace}\n"
|
||||
f"\tconfigParams = {','.join(p + '*' for p in prefixes)}\n"
|
||||
)
|
||||
|
||||
def _repo_config_seen_by_push(self, prefixes: tuple[str, ...]) -> list[str]:
|
||||
events = [json.loads(line) for line in self.trace.read_text().splitlines()]
|
||||
pushes = _push_sids(events)
|
||||
self.assertTrue(pushes, "no push was traced")
|
||||
return [
|
||||
f"{e['param']}={e['value']}"
|
||||
for e in events
|
||||
if e["sid"] in pushes and _repo_param(e, prefixes)
|
||||
]
|
||||
|
||||
def _push_with_config_planted_after_check(self, check: int) -> int:
|
||||
self._commit("feature")
|
||||
real = push_module.local_config
|
||||
calls: list[str] = []
|
||||
|
||||
def check_then_plant(path: str, pattern: str) -> list[str]:
|
||||
found = real(path, pattern)
|
||||
calls.append(path)
|
||||
if len(calls) == check:
|
||||
git(self.repo, "config", "core.sshCommand", f"{self._plant()}; false #")
|
||||
git(self.repo, "config", "core.fsmonitor", self._plant())
|
||||
return found
|
||||
|
||||
with patch.object(push_module, "local_config", check_then_plant):
|
||||
self._push()
|
||||
return len(calls)
|
||||
|
||||
def test_vector1_repository_hooks_never_run(self) -> None:
|
||||
hooks = (
|
||||
"pre-push",
|
||||
"reference-transaction",
|
||||
"post-commit",
|
||||
"post-rewrite",
|
||||
"post-index-change",
|
||||
)
|
||||
for name, hook_dir in (
|
||||
("hooks", Path(self.repo, ".git", "hooks")),
|
||||
("hooks-path", Path(self.root, "planted-hooks")),
|
||||
):
|
||||
with self.subTest(hook_dir=str(hook_dir)):
|
||||
self._commit(name)
|
||||
self._hook(hook_dir, *hooks)
|
||||
if name == "hooks-path":
|
||||
git(self.repo, "config", "core.hooksPath", str(hook_dir))
|
||||
|
||||
self._push()
|
||||
|
||||
self._assert_nothing_ran()
|
||||
self._assert_landed()
|
||||
shutil.rmtree(hook_dir)
|
||||
|
||||
def test_vector2_filter_driver_never_runs(self) -> None:
|
||||
Path(self.repo, ".gitattributes").write_text("*.txt filter=probe\n")
|
||||
git(self.repo, "config", "filter.probe.clean", f"{self._plant()}; cat")
|
||||
git(self.repo, "config", "filter.probe.smudge", "cat")
|
||||
git(self.repo, "add", ".gitattributes")
|
||||
self._commit("feature")
|
||||
stamp = Path(self.repo, "feature.txt").stat().st_mtime + 10
|
||||
os.utime(Path(self.repo, "feature.txt"), (stamp, stamp))
|
||||
self.marker.unlink()
|
||||
|
||||
self._push()
|
||||
|
||||
self._assert_nothing_ran()
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector3_core_worktree_elsewhere_is_never_read(self) -> None:
|
||||
self._commit("feature")
|
||||
elsewhere = Path(self.root, "elsewhere")
|
||||
elsewhere.mkdir()
|
||||
(elsewhere / ".gitattributes").write_text("* filter=probe\n")
|
||||
(elsewhere / "feature.txt").write_text("feature")
|
||||
git(self.repo, "config", "filter.probe.clean", f"{self._plant()}; cat")
|
||||
git(self.repo, "config", "core.worktree", str(elsewhere))
|
||||
|
||||
self._push()
|
||||
|
||||
self._assert_nothing_ran()
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector4_repository_credential_config_never_reaches_the_push(
|
||||
self,
|
||||
) -> None:
|
||||
self._trace_repo_config(("credential.",))
|
||||
for key, value in (
|
||||
("credential.protectProtocol", "false"),
|
||||
("credential.username", "planted"),
|
||||
("credential.useHttpPath", "true"),
|
||||
("credential.https://example.org.username", "planted"),
|
||||
):
|
||||
git(self.repo, "config", key, value)
|
||||
self._commit("feature")
|
||||
|
||||
self._push()
|
||||
|
||||
self.assertEqual(self._repo_config_seen_by_push(("credential.",)), [])
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector5_bundle_uri_is_never_fetched(self) -> None:
|
||||
other = os.path.join(self.root, "other")
|
||||
git(self.root, "init", "-q", other)
|
||||
self._commit("planted", other)
|
||||
bundle = os.path.join(self.root, "planted.bundle")
|
||||
git(other, "bundle", "create", bundle, "main")
|
||||
git(self.repo, "config", "fetch.bundleURI", bundle)
|
||||
git(self.repo, "config", "transfer.bundleURI", "true")
|
||||
self._commit("feature")
|
||||
|
||||
self._push()
|
||||
|
||||
self.assertEqual(git(self.repo, "for-each-ref", "refs/bundles/"), "")
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector6_repository_http_config_never_reaches_the_push(self) -> None:
|
||||
self._trace_repo_config(("http.",))
|
||||
for key, value in (
|
||||
("http.curloptResolve", "localhost:443:127.0.0.2"),
|
||||
("http.delegation", "always"),
|
||||
("http.proxySSLCert", f"{self.root}/planted.pem"),
|
||||
("http.proxySSLKey", f"{self.root}/planted.key"),
|
||||
("http.proxySSLCAInfo", f"{self.root}/planted.ca"),
|
||||
):
|
||||
git(self.repo, "config", key, value)
|
||||
self._commit("feature")
|
||||
|
||||
self._push()
|
||||
|
||||
self.assertEqual(self._repo_config_seen_by_push(("http.",)), [])
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector7_merge_driver_never_runs(self) -> None:
|
||||
Path(self.repo, ".gitattributes").write_text("* merge=probe\n")
|
||||
git(self.repo, "add", ".gitattributes")
|
||||
git(self.repo, "config", "merge.probe.driver", f"{self._plant()}; false")
|
||||
git(self.repo, "config", "merge.probe.name", "probe")
|
||||
self._commit("feature")
|
||||
|
||||
self._push()
|
||||
|
||||
self._assert_nothing_ran()
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector8_submodule_configs_are_never_read(self) -> None:
|
||||
upstream = os.path.join(self.root, "sub-upstream")
|
||||
git(self.root, "init", "-q", upstream)
|
||||
self._commit("sub", upstream)
|
||||
git(
|
||||
self.repo,
|
||||
"-c",
|
||||
"protocol.file.allow=always",
|
||||
"submodule",
|
||||
"add",
|
||||
"-q",
|
||||
upstream,
|
||||
"sub",
|
||||
)
|
||||
git(self.repo, "commit", "-q", "-m", "add sub")
|
||||
modules = Path(self.repo, ".git", "modules", "sub")
|
||||
self._hook(
|
||||
modules / "hooks",
|
||||
"pre-push",
|
||||
"reference-transaction",
|
||||
"post-commit",
|
||||
"post-checkout",
|
||||
"pre-commit",
|
||||
)
|
||||
git(str(modules), "config", "filter.probe.clean", f"{self._plant()}; cat")
|
||||
git(str(modules), "config", "core.fsmonitor", self._plant())
|
||||
Path(self.repo, "sub", ".gitattributes").write_text("* filter=probe\n")
|
||||
stamp = Path(self.repo, "sub", "sub.txt").stat().st_mtime + 10
|
||||
os.utime(Path(self.repo, "sub", "sub.txt"), (stamp, stamp))
|
||||
for key, value in (
|
||||
("submodule.recurse", "true"),
|
||||
("push.recurseSubmodules", "on-demand"),
|
||||
("fetch.recurseSubmodules", "yes"),
|
||||
("diff.ignoreSubmodules", "none"),
|
||||
("status.submoduleSummary", "true"),
|
||||
("diff.submodule", "diff"),
|
||||
):
|
||||
git(self.repo, "config", key, value)
|
||||
self._commit("feature")
|
||||
|
||||
self._push()
|
||||
|
||||
self._assert_nothing_ran()
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector9_replace_ref_never_fakes_a_good_signature(self) -> None:
|
||||
unsigned = self._commit("feature")
|
||||
tree = git(self.repo, "rev-parse", "HEAD^{tree}")
|
||||
forged = git(
|
||||
self.repo, "commit-tree", tree, "-p", self.init, "-S", "-m", "forged"
|
||||
)
|
||||
git(self.repo, "replace", unsigned, forged)
|
||||
self.assertEqual(git(self.repo, "log", "-1", "--format=%G?", unsigned), "G")
|
||||
|
||||
self._push()
|
||||
|
||||
self.assertNotEqual(self._tip(self.canonical), unsigned)
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector9_repository_allowed_signers_never_fake_a_good_signature(
|
||||
self,
|
||||
) -> None:
|
||||
planted_key = Path(self.root, "planted-key")
|
||||
keygen(planted_key)
|
||||
allowed = Path(self.root, "planted-allowed")
|
||||
allowed.write_text(f"t@example.org {Path(f'{planted_key}.pub').read_text()}")
|
||||
git(self.repo, "config", "gpg.ssh.allowedSignersFile", str(allowed))
|
||||
git(self.repo, "config", "user.signingKey", str(planted_key))
|
||||
Path(self.repo, "feature.txt").write_text("feature")
|
||||
git(self.repo, "add", "feature.txt")
|
||||
git(self.repo, "commit", "-q", "-S", "-m", "feature")
|
||||
planted = git(self.repo, "rev-parse", "HEAD")
|
||||
self.assertEqual(git(self.repo, "log", "-1", "--format=%G?"), "G")
|
||||
|
||||
self._push()
|
||||
|
||||
self.assertNotEqual(self._tip(self.canonical), planted)
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector10_config_planted_after_the_sign_check_is_refused(self) -> None:
|
||||
with self.assertRaises(PushRefusedError) as cm:
|
||||
self._push_with_config_planted_after_check(1)
|
||||
|
||||
self.assertIn("core.sshcommand", str(cm.exception))
|
||||
self._assert_nothing_ran()
|
||||
self.assertEqual(self._tip(self.canonical), self.init)
|
||||
self.assertEqual(self._tip(self.mirror), self.init)
|
||||
|
||||
def test_vector10_config_planted_after_the_push_check_never_runs(self) -> None:
|
||||
checks = self._push_with_config_planted_after_check(2)
|
||||
|
||||
self.assertGreaterEqual(checks, 2, "the config was never planted")
|
||||
self._assert_nothing_ran()
|
||||
self._assert_landed()
|
||||
|
||||
def test_vector10_branch_moved_while_signing_is_kept(self) -> None:
|
||||
self._commit("feature")
|
||||
moved: list[str] = []
|
||||
|
||||
def race(cmd, *args, **kwargs):
|
||||
if not moved and ("commit-tree" in cmd or "--amend" in cmd):
|
||||
moved.append(self._commit("racing"))
|
||||
return _REAL_RUN(cmd, *args, **kwargs)
|
||||
|
||||
with (
|
||||
patch("subprocess.run", side_effect=race),
|
||||
self.assertRaises(PushRefusedError),
|
||||
):
|
||||
self._push()
|
||||
|
||||
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), moved[0])
|
||||
self.assertEqual(self._tip(self.canonical), self.init)
|
||||
self.assertEqual(self._tip(self.mirror), self.init)
|
||||
|
||||
def test_local_and_foreign_push_urls_are_refused(self) -> None:
|
||||
self._commit("feature")
|
||||
for url in (
|
||||
self.mirror,
|
||||
f"file://{self.mirror}",
|
||||
f"ext::sh -c touch% {self.marker}",
|
||||
"t@-oProxyCommand=x:path",
|
||||
"ssh://-oProxyCommand=x/path",
|
||||
"http://localhost/x.git",
|
||||
):
|
||||
with self.subTest(url=url):
|
||||
git(self.repo, "config", "--unset-all", "remote.origin.pushurl")
|
||||
git(self.repo, "config", "--add", "remote.origin.pushurl", url)
|
||||
|
||||
with (
|
||||
self.assertRaises(PushRefusedError),
|
||||
redirect_stdout(io.StringIO()),
|
||||
):
|
||||
push_branch(self.repo, [], sign=False)
|
||||
|
||||
self.assertEqual(self._tip(self.mirror), self.init)
|
||||
@@ -0,0 +1,118 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from pkgmgr.actions.repository import _trusted
|
||||
from pkgmgr.actions.repository import push as push_module
|
||||
from pkgmgr.core.git import GitRunError
|
||||
|
||||
GIT = shutil.which("git")
|
||||
CREDENTIAL = "pw-value"
|
||||
OID = "a" * 40
|
||||
|
||||
|
||||
def _target(branch: str) -> _trusted.Target:
|
||||
return _trusted.Target(
|
||||
repo_dir="/nonexistent/repo",
|
||||
tdir="/nonexistent/tdir",
|
||||
branch=branch,
|
||||
head=OID,
|
||||
remote="origin",
|
||||
fetch_url="t@localhost:canonical.git",
|
||||
push_urls=("t@localhost:canonical.git",),
|
||||
)
|
||||
|
||||
|
||||
class TestTrustedReviewFixes(unittest.TestCase):
|
||||
@unittest.skipUnless(GIT, "git reads the config")
|
||||
def test_config_value_with_a_newline_stays_one_value(self) -> None:
|
||||
value = "https://a.example/x\nhttps://b.example/y"
|
||||
env = {
|
||||
key: val
|
||||
for key, val in os.environ.items()
|
||||
if key not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as repo:
|
||||
subprocess.run([GIT, "init", "-q", repo], check=True, env=env)
|
||||
subprocess.run(
|
||||
[GIT, "config", "--add", "remote.origin.pushurl", value],
|
||||
cwd=repo,
|
||||
check=True,
|
||||
env=env,
|
||||
)
|
||||
|
||||
values = _trusted._config_all(repo, "remote.origin.pushurl")
|
||||
|
||||
self.assertEqual(values, [value])
|
||||
|
||||
def test_file_url_percent_encodes_the_path(self) -> None:
|
||||
self.assertEqual(
|
||||
_trusted.file_url("/srv/repo%20name"), "file:///srv/repo%2520name"
|
||||
)
|
||||
|
||||
def test_failed_trusted_call_redacts_url_userinfo(self) -> None:
|
||||
failed = subprocess.CompletedProcess([], 128, b"", b"fatal: refused")
|
||||
url = f"https://user:{CREDENTIAL}@example.org/x.git"
|
||||
|
||||
with (
|
||||
patch.object(_trusted.subprocess, "run", return_value=failed),
|
||||
self.assertRaises(GitRunError) as cm,
|
||||
):
|
||||
_trusted.tgit("/nonexistent/tdir", "ls-remote", "--", url)
|
||||
|
||||
self.assertNotIn(CREDENTIAL, str(cm.exception))
|
||||
self.assertIn("https://***@example.org/x.git", str(cm.exception))
|
||||
|
||||
def test_failed_mirror_line_redacts_url_userinfo(self) -> None:
|
||||
plan = push_module._Push((), (), False, False, None)
|
||||
url = f"https://user:{CREDENTIAL}@example.org/mirror.git"
|
||||
refused = _trusted.PushRefusedError("lease failed")
|
||||
|
||||
with (
|
||||
patch.object(push_module, "_lease", side_effect=refused),
|
||||
redirect_stdout(io.StringIO()) as out,
|
||||
):
|
||||
pushed = push_module._push_url(_target("main"), plan, 1, url)
|
||||
|
||||
self.assertFalse(pushed)
|
||||
self.assertNotIn(CREDENTIAL, out.getvalue())
|
||||
|
||||
def test_ls_remote_line_without_a_tab_lists_no_ref(self) -> None:
|
||||
with patch.object(
|
||||
_trusted, "tgit", return_value=f"{OID} refs/heads/main"
|
||||
) as fake:
|
||||
tips = _trusted.fetch_heads(
|
||||
_target("main"), "t@localhost:x.git", ["main"], "refs/x"
|
||||
)
|
||||
|
||||
self.assertEqual(tips, {})
|
||||
fake.assert_called_once()
|
||||
|
||||
def test_track_uses_the_validated_branch(self) -> None:
|
||||
run = MagicMock(return_value="")
|
||||
target = _target("feature")
|
||||
|
||||
with (
|
||||
patch.object(push_module, "run", run),
|
||||
patch.object(push_module, "try_git", return_value=None) as probe,
|
||||
):
|
||||
push_module._track(target)
|
||||
|
||||
probe.assert_called_once_with(
|
||||
target.repo_dir, "rev-parse", "--abbrev-ref", "feature@{upstream}"
|
||||
)
|
||||
self.assertEqual(
|
||||
run.call_args_list[-1].args[0],
|
||||
["branch", "--set-upstream-to=origin/feature", "feature"],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -16,6 +16,8 @@ import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import call, patch
|
||||
|
||||
from pkgmgr.actions.release import ReleaseOptions
|
||||
|
||||
|
||||
class TestReleaseCommand(unittest.TestCase):
|
||||
"""
|
||||
@@ -100,14 +102,17 @@ class TestReleaseCommand(unittest.TestCase):
|
||||
|
||||
# And run_release should be invoked once with the expected parameters.
|
||||
mock_run_release.assert_called_once_with(
|
||||
pyproject_path="pyproject.toml",
|
||||
changelog_path="CHANGELOG.md",
|
||||
release_type="minor",
|
||||
message="Close branch after minor release",
|
||||
preview=False,
|
||||
force=True,
|
||||
close=True,
|
||||
retry=False,
|
||||
ReleaseOptions(
|
||||
pyproject_path="pyproject.toml",
|
||||
changelog_path="CHANGELOG.md",
|
||||
release_type="minor",
|
||||
message="Close branch after minor release",
|
||||
preview=False,
|
||||
force=True,
|
||||
close=True,
|
||||
retry=False,
|
||||
expect_tree=None,
|
||||
)
|
||||
)
|
||||
|
||||
@patch("pkgmgr.cli.commands.release.os.path.isdir", return_value=True)
|
||||
@@ -143,20 +148,25 @@ class TestReleaseCommand(unittest.TestCase):
|
||||
"patch",
|
||||
"dummy-id",
|
||||
"--preview",
|
||||
"--expect-tree",
|
||||
"4b825dc642cb6eb9a060e54bf8d69288fbee4904",
|
||||
]
|
||||
args = self._parse_release_args(argv)
|
||||
|
||||
handle_release(args, ctx, selected)
|
||||
|
||||
mock_run_release.assert_called_once_with(
|
||||
pyproject_path="pyproject.toml",
|
||||
changelog_path="CHANGELOG.md",
|
||||
release_type="patch",
|
||||
message=None,
|
||||
preview=True,
|
||||
force=False,
|
||||
close=False,
|
||||
retry=False,
|
||||
ReleaseOptions(
|
||||
pyproject_path="pyproject.toml",
|
||||
changelog_path="CHANGELOG.md",
|
||||
release_type="patch",
|
||||
message=None,
|
||||
preview=True,
|
||||
force=False,
|
||||
close=False,
|
||||
retry=False,
|
||||
expect_tree="4b825dc642cb6eb9a060e54bf8d69288fbee4904",
|
||||
)
|
||||
)
|
||||
|
||||
@patch("pkgmgr.cli.commands.release.run_release")
|
||||
|
||||
@@ -19,10 +19,9 @@ import os
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
import unittest.mock
|
||||
from contextlib import redirect_stdout
|
||||
from typing import Any
|
||||
from unittest import mock
|
||||
|
||||
from pkgmgr import cli
|
||||
|
||||
@@ -71,7 +70,7 @@ class TestCliVersion(unittest.TestCase):
|
||||
}
|
||||
|
||||
# Patch load_config so cli.main() does not read real config files
|
||||
self._patch_load_config = mock.patch(
|
||||
self._patch_load_config = unittest.mock.patch(
|
||||
"pkgmgr.cli.load_config", return_value=_fake_config()
|
||||
)
|
||||
self.mock_load_config = self._patch_load_config.start()
|
||||
@@ -79,7 +78,7 @@ class TestCliVersion(unittest.TestCase):
|
||||
# Patch the "current directory" selection used by dispatch_command().
|
||||
# This matches the new behaviour: without explicit identifiers,
|
||||
# version uses _select_repo_for_current_directory(ctx).
|
||||
self._patch_select_repo_for_current_directory = mock.patch(
|
||||
self._patch_select_repo_for_current_directory = unittest.mock.patch(
|
||||
"pkgmgr.cli.dispatch._select_repo_for_current_directory",
|
||||
return_value=[self._fake_repo],
|
||||
)
|
||||
@@ -165,7 +164,7 @@ class TestCliVersion(unittest.TestCase):
|
||||
self._write_pyproject("1.2.3")
|
||||
|
||||
# Arrange: mock git tags used by handle_version
|
||||
with mock.patch(
|
||||
with unittest.mock.patch(
|
||||
"pkgmgr.cli.commands.version.get_tags",
|
||||
return_value=["v1.2.0", "v1.2.3", "v1.0.0"],
|
||||
):
|
||||
@@ -197,7 +196,7 @@ class TestCliVersion(unittest.TestCase):
|
||||
self._write_pyproject("1.2.4")
|
||||
|
||||
# Arrange: mock git tags (latest is 1.2.3)
|
||||
with mock.patch(
|
||||
with unittest.mock.patch(
|
||||
"pkgmgr.cli.commands.version.get_tags",
|
||||
return_value=["v1.2.3"],
|
||||
):
|
||||
@@ -225,7 +224,7 @@ class TestCliVersion(unittest.TestCase):
|
||||
self._write_pyproject("0.0.1")
|
||||
|
||||
# Arrange: no tags returned
|
||||
with mock.patch(
|
||||
with unittest.mock.patch(
|
||||
"pkgmgr.cli.commands.version.get_tags",
|
||||
return_value=[],
|
||||
):
|
||||
|
||||
@@ -79,7 +79,7 @@ class TestCreateInk(unittest.TestCase):
|
||||
command_path = os.path.join(repo_dir, "main.sh")
|
||||
with open(command_path, "w", encoding="utf-8") as f:
|
||||
f.write("#!/bin/sh\necho mytool\n")
|
||||
os.chmod(command_path, 0o755)
|
||||
os.chmod(command_path, 0o700)
|
||||
|
||||
repo = {
|
||||
"command": command_path,
|
||||
|
||||
@@ -149,7 +149,7 @@ class TestGitRun(unittest.TestCase):
|
||||
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)
|
||||
self.assertNotIn("XDG_CONFIG_HOME", env)
|
||||
|
||||
def test_failure_raises_giterror_with_details(self) -> None:
|
||||
# Build a CalledProcessError with stdout/stderr populated
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import io
|
||||
import unittest
|
||||
import urllib.error
|
||||
from typing import NoReturn
|
||||
from unittest.mock import patch
|
||||
|
||||
from pkgmgr.actions.branch import gc_forge
|
||||
from pkgmgr.core.remote_provisioning.http.client import HttpClient
|
||||
from pkgmgr.core.remote_provisioning.http.errors import HttpError
|
||||
|
||||
TRUNCATED = (
|
||||
b"HTTP/1.1 200 OK\r\nContent-Length: 4096\r\n"
|
||||
b"Content-Type: application/json\r\n\r\n"
|
||||
b'[{"number": 1, "merged_at": null'
|
||||
)
|
||||
|
||||
|
||||
class TruncatedSocket:
|
||||
def __init__(self, payload: bytes) -> None:
|
||||
self._file = io.BytesIO(payload)
|
||||
|
||||
def makefile(self, *_args, **_kwargs):
|
||||
return self._file
|
||||
|
||||
|
||||
def truncated_response(*_args, **_kwargs) -> http.client.HTTPResponse:
|
||||
response = http.client.HTTPResponse(TruncatedSocket(TRUNCATED))
|
||||
response.begin()
|
||||
return response
|
||||
|
||||
|
||||
class TruncatedBody(io.BytesIO):
|
||||
def read(self, *_args) -> bytes:
|
||||
raise http.client.IncompleteRead(b'{"message": "Bad', 64)
|
||||
|
||||
|
||||
def truncated_error(*_args, **_kwargs) -> NoReturn:
|
||||
raise urllib.error.HTTPError(
|
||||
"https://example.org/x",
|
||||
502,
|
||||
"Bad Gateway",
|
||||
http.client.HTTPMessage(),
|
||||
TruncatedBody(),
|
||||
)
|
||||
|
||||
|
||||
class TestTruncatedResponse(unittest.TestCase):
|
||||
def test_truncated_error_body_keeps_status_and_partial_body(self) -> None:
|
||||
with (
|
||||
patch("urllib.request.urlopen", side_effect=truncated_error),
|
||||
self.assertRaises(HttpError) as caught,
|
||||
):
|
||||
HttpClient(timeout_s=1).request_json("GET", "https://example.org/x")
|
||||
|
||||
self.assertEqual(caught.exception.status, 502)
|
||||
self.assertEqual(caught.exception.body, '{"message": "Bad')
|
||||
|
||||
def test_incomplete_read_becomes_http_error(self) -> None:
|
||||
with (
|
||||
patch("urllib.request.urlopen", side_effect=truncated_response),
|
||||
self.assertRaises(HttpError) as caught,
|
||||
):
|
||||
HttpClient(timeout_s=1).request_json("GET", "https://example.org/x")
|
||||
|
||||
self.assertEqual(caught.exception.status, 0)
|
||||
self.assertIn("IncompleteRead", str(caught.exception))
|
||||
|
||||
def test_read_timeout_becomes_http_error(self) -> None:
|
||||
with (
|
||||
patch("urllib.request.urlopen", side_effect=TimeoutError()),
|
||||
self.assertRaises(HttpError) as caught,
|
||||
):
|
||||
HttpClient(timeout_s=1).request_json("GET", "https://example.org/x")
|
||||
|
||||
self.assertEqual(str(caught.exception), "TimeoutError")
|
||||
|
||||
def test_non_http_scheme_is_refused_before_any_request(self) -> None:
|
||||
with (
|
||||
patch("urllib.request.urlopen") as urlopen,
|
||||
self.assertRaises(HttpError) as caught,
|
||||
):
|
||||
HttpClient(timeout_s=1).request_json("GET", "file:///etc/passwd")
|
||||
|
||||
urlopen.assert_not_called()
|
||||
self.assertIn("unsupported URL scheme 'file'", str(caught.exception))
|
||||
|
||||
def test_forge_facts_degrade_to_unavailable_instead_of_crashing(self) -> None:
|
||||
with patch("urllib.request.urlopen", side_effect=truncated_response):
|
||||
facts = gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||
|
||||
self.assertIn("GitHub API failed for owner/repo", facts.unavailable)
|
||||
self.assertEqual((facts.merged_heads, facts.open_heads), ({}, {}))
|
||||
|
||||
def test_forge_budget_stops_paging(self) -> None:
|
||||
with (
|
||||
patch.object(gc_forge, "BUDGET_S", -1),
|
||||
patch("urllib.request.urlopen") as urlopen,
|
||||
):
|
||||
facts = gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||
|
||||
urlopen.assert_not_called()
|
||||
self.assertIn("budget", facts.unavailable)
|
||||
|
||||
def test_forge_requests_use_the_short_timeout(self) -> None:
|
||||
with (
|
||||
patch.object(gc_forge, "HttpClient", wraps=HttpClient) as client,
|
||||
patch("urllib.request.urlopen", side_effect=truncated_response),
|
||||
):
|
||||
gc_forge.facts_with_token([("owner", "repo")], "token")
|
||||
|
||||
client.assert_called_once_with(timeout_s=gc_forge.TIMEOUT_S)
|
||||
self.assertLessEqual(gc_forge.TIMEOUT_S, 10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user