Compare commits
No files matched your search
@@ -0,0 +1 @@
|
||||
* @kevinveenbirkenbach
|
||||
@@ -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.
|
||||
@@ -5,19 +5,21 @@ updates:
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "00:00"
|
||||
rebase-strategy: "auto"
|
||||
open-pull-requests-limit: 0
|
||||
groups:
|
||||
pip-security:
|
||||
applies-to: security-updates
|
||||
patterns: ["*"]
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "python"
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "00:00"
|
||||
groups:
|
||||
github-actions:
|
||||
applies-to: version-updates
|
||||
patterns: ["*"]
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "ci"
|
||||
@@ -46,15 +46,10 @@ jobs:
|
||||
contents: read
|
||||
uses: ./.github/workflows/test-e2e.yml
|
||||
|
||||
test-virgin-user:
|
||||
test-virgin:
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/test-virgin-user.yml
|
||||
|
||||
test-virgin-root:
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/test-virgin-root.yml
|
||||
uses: ./.github/workflows/test-virgin.yml
|
||||
|
||||
lint-shell:
|
||||
permissions:
|
||||
@@ -71,3 +66,9 @@ jobs:
|
||||
contents: read
|
||||
security-events: write
|
||||
uses: ./.github/workflows/lint-docker.yml
|
||||
|
||||
quality:
|
||||
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
|
||||
permissions:
|
||||
contents: read
|
||||
uses: infinito-nexus/quality/.github/workflows/quality.yml@2eaac6f644eb4c47102bd8cc353635c71af5dab9 # v1.2.0
|
||||
@@ -15,12 +15,12 @@ jobs:
|
||||
security-events: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Run hadolint (produce SARIF)
|
||||
id: hadolint
|
||||
continue-on-error: true
|
||||
uses: hadolint/hadolint-action@2332a7b74a6de0dda2e2221d575162eba76ba5e5
|
||||
uses: hadolint/hadolint-action@06be81baf89a55ffd0e24b8f04a4185738dd3387
|
||||
with:
|
||||
dockerfile: ./Dockerfile
|
||||
format: sarif
|
||||
@@ -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,19 +8,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
lint-python:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install ruff
|
||||
run: pip install ruff
|
||||
|
||||
- name: Run ruff
|
||||
run: |
|
||||
ruff check src tests
|
||||
uses: infinito-nexus/quality/.github/workflows/tool.yml@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@v4
|
||||
- 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@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-tags: true # We need tags and main history for version comparison
|
||||
|
||||
@@ -4,56 +4,121 @@ on:
|
||||
workflow_run:
|
||||
workflows: ["Mark stable commit"]
|
||||
types: [completed]
|
||||
schedule:
|
||||
- cron: "0 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
prepare:
|
||||
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:
|
||||
contents: read
|
||||
|
||||
outputs:
|
||||
releases: ${{ steps.info.outputs.releases }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository (with tags)
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Resolve the releases this run publishes
|
||||
id: info
|
||||
env:
|
||||
WORKFLOW_RUN_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
run: bash scripts/github/publish-containers/compute-publish-container-info.sh
|
||||
|
||||
build:
|
||||
needs: prepare
|
||||
if: ${{ needs.prepare.result == 'success' && needs.prepare.outputs.releases != '[]' }}
|
||||
name: Build ${{ matrix.distro }} ${{ matrix.release.version }} for ${{ matrix.target.platform }}
|
||||
runs-on: ${{ matrix.target.runner }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
distro: &distros [arch, debian, ubuntu, fedora, centos]
|
||||
target:
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-latest
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
release: ${{ fromJSON(needs.prepare.outputs.releases) }}
|
||||
|
||||
steps:
|
||||
- name: Checkout ${{ matrix.release.version }}
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ matrix.release.sha }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003
|
||||
with:
|
||||
use: true
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push ${{ matrix.distro }} ${{ matrix.release.version }} for ${{ matrix.target.platform }}
|
||||
env:
|
||||
OWNER: ${{ github.repository_owner }}
|
||||
VERSION: ${{ matrix.release.version }}
|
||||
PKGMGR_DISTRO: ${{ matrix.distro }}
|
||||
PLATFORM: ${{ matrix.target.platform }}
|
||||
run: bash scripts/github/publish-containers/publish-container-images.sh
|
||||
|
||||
merge:
|
||||
needs: [prepare, build]
|
||||
if: ${{ !cancelled() && needs.prepare.result == 'success' && needs.prepare.outputs.releases != '[]' }}
|
||||
name: Merge ${{ matrix.distro }} ${{ matrix.release.version }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
distro: *distros
|
||||
release: ${{ fromJSON(needs.prepare.outputs.releases) }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository (with tags)
|
||||
uses: actions/checkout@v4
|
||||
- name: Checkout ${{ matrix.release.version }}
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Checkout workflow_run commit and refresh tags
|
||||
env:
|
||||
WORKFLOW_RUN_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
run: bash scripts/github/publish-containers/checkout-workflow-run-commit.sh
|
||||
|
||||
- name: Check whether tagged commit is on main
|
||||
id: branch-check
|
||||
env:
|
||||
TARGET_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
run: bash scripts/github/common/check-tagged-commit-on-main.sh
|
||||
|
||||
- name: Compute version and stable flag
|
||||
id: info
|
||||
if: steps.branch-check.outputs.is_on_main == 'true'
|
||||
run: bash scripts/github/publish-containers/compute-publish-container-info.sh
|
||||
ref: ${{ matrix.release.sha }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
if: ${{ steps.info.outputs.should_publish == 'true' }}
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f
|
||||
uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003
|
||||
with:
|
||||
use: true
|
||||
|
||||
- name: Login to GHCR
|
||||
if: ${{ steps.info.outputs.should_publish == 'true' }}
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Publish all images
|
||||
if: ${{ steps.info.outputs.should_publish == 'true' }}
|
||||
- name: Join both platforms of ${{ matrix.distro }} ${{ matrix.release.version }} under its tags
|
||||
env:
|
||||
OWNER: ${{ github.repository_owner }}
|
||||
VERSION: ${{ steps.info.outputs.version }}
|
||||
IS_STABLE: ${{ steps.info.outputs.is_stable }}
|
||||
run: bash scripts/github/publish-containers/publish-container-images.sh
|
||||
VERSION: ${{ matrix.release.version }}
|
||||
ALIASES: ${{ matrix.release.aliases }}
|
||||
PKGMGR_DISTRO: ${{ matrix.distro }}
|
||||
run: bash scripts/github/publish-containers/merge-container-images.sh
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Scorecard supply-chain security
|
||||
|
||||
on:
|
||||
branch_protection_rule:
|
||||
schedule:
|
||||
- cron: '00 00 * * *'
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
|
||||
concurrency:
|
||||
group: scorecard-${{ github.repository }}-${{ github.ref_name }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions: read-all
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
name: Scorecard analysis
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.repository.default_branch == github.ref_name
|
||||
permissions:
|
||||
security-events: write
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run analysis
|
||||
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@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@v4
|
||||
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@v4
|
||||
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@v4
|
||||
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@v4
|
||||
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@v4
|
||||
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@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
name: Test Virgin Root
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-virgin-root:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
distro: [arch, debian, ubuntu, fedora, centos]
|
||||
env:
|
||||
NIX_CONFIG: |
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
- name: Pull base image (${{ matrix.distro }})
|
||||
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest"
|
||||
|
||||
- name: Virgin ${{ matrix.distro }} pkgmgr test (root)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
docker run --rm \
|
||||
-v "$PWD":/opt/src/pkgmgr \
|
||||
-v pkgmgr_repos:/root/Repositories \
|
||||
-v pkgmgr_pip_cache:/root/.cache/pip \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
-w /opt/src/pkgmgr \
|
||||
"ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
|
||||
git config --global --add safe.directory /opt/src/pkgmgr
|
||||
|
||||
make install
|
||||
make setup
|
||||
|
||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
||||
|
||||
pkgmgr update pkgmgr --clone-mode shallow --no-verification
|
||||
pkgmgr version pkgmgr
|
||||
|
||||
echo ">>> Running Nix-based: nix run .#pkgmgr -- version pkgmgr"
|
||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
||||
'
|
||||
@@ -1,68 +0,0 @@
|
||||
name: Test Virgin User
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-virgin-user:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
distro: [arch, debian, ubuntu, fedora, centos]
|
||||
env:
|
||||
NIX_CONFIG: |
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
- name: Pull base image (${{ matrix.distro }})
|
||||
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest"
|
||||
|
||||
- name: Virgin ${{ matrix.distro }} pkgmgr test (user)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
docker run --rm \
|
||||
-v "$PWD":/opt/src/pkgmgr \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
-w /opt/src/pkgmgr \
|
||||
"ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest" \
|
||||
bash -lc '
|
||||
set -euo pipefail
|
||||
|
||||
make install
|
||||
|
||||
useradd -m dev
|
||||
echo "dev ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dev
|
||||
chmod 0440 /etc/sudoers.d/dev
|
||||
chown -R dev:dev /opt/src/pkgmgr
|
||||
|
||||
mkdir -p /nix/store /nix/var/nix /nix/var/log/nix /nix/var/nix/profiles
|
||||
chown -R dev:dev /nix
|
||||
chmod 0755 /nix
|
||||
chmod 1777 /nix/store
|
||||
sudo -H -u dev env \
|
||||
HOME=/home/dev \
|
||||
NIX_CONFIG="$NIX_CONFIG" \
|
||||
PKGMGR_DISABLE_NIX_FLAKE_INSTALLER=1 \
|
||||
bash -lc "
|
||||
set -euo pipefail
|
||||
cd /opt/src/pkgmgr
|
||||
make setup-venv
|
||||
. \"\$HOME/.venvs/pkgmgr/bin/activate\"
|
||||
|
||||
pkgmgr version pkgmgr
|
||||
|
||||
export NIX_REMOTE=local
|
||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
||||
"
|
||||
'
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Test Virgin
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-virgin:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
mode: [user, root]
|
||||
distro: [arch, debian, ubuntu, fedora, centos]
|
||||
env:
|
||||
NIX_CONFIG: |
|
||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||
MODE: ${{ matrix.mode }}
|
||||
DISTRO: ${{ matrix.distro }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Show Docker version
|
||||
run: docker version
|
||||
|
||||
- name: Pull base image (${{ matrix.distro }})
|
||||
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${DISTRO}:latest"
|
||||
|
||||
- name: Virgin ${{ matrix.distro }} pkgmgr test (${{ matrix.mode }})
|
||||
run: bash scripts/test/virgin/run.sh "$MODE" "$DISTRO"
|
||||
@@ -18,13 +18,13 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@v16
|
||||
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
|
||||
|
||||
- name: Update flake.lock and open a pull request
|
||||
uses: DeterminateSystems/update-flake-lock@v24
|
||||
uses: DeterminateSystems/update-flake-lock@da03c0f078bc4b2c37ee4f7e072d34bf8f188bb3 # v29
|
||||
with:
|
||||
pr-title: "chore(deps): update flake.lock"
|
||||
pr-labels: |
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# Agent Instructions
|
||||
|
||||
## Scope against the skills repository
|
||||
|
||||
package-manager holds deterministic code that an operator can run on its own,
|
||||
without an agent: repository, branch, worktree, release, packaging and
|
||||
development tooling. Agent coordination (claims, messages, queues, scores,
|
||||
prompts, session data) belongs to the
|
||||
[skills repository](https://github.com/kevinveenbirkenbach/skills), whose skills
|
||||
stay thin wrappers that call `pkgmgr`.
|
||||
|
||||
- A new helper that a human could sensibly run alone goes here as a `pkgmgr`
|
||||
command, with its tests, never as a script inside a skill.
|
||||
- Output that an agent filters further (claims, busy agents, scores) is
|
||||
emitted as `--json`; the filtering stays in the skill.
|
||||
- When the split of a helper is unclear, the operator decides.
|
||||
|
||||
## Working copy
|
||||
|
||||
The installed `pkgmgr` may run straight from the main checkout, so a
|
||||
half-edited tree breaks it for everyone. Edit only in a worktree
|
||||
(`pkgmgr worktree up <branch>`), never in the main checkout.
|
||||
+201
@@ -1,5 +1,206 @@
|
||||
# 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:
|
||||
|
||||
- Branch: *cleanup --local* deletes merged branches only where git would
|
||||
- Review: expand and collapse are icon buttons with labels
|
||||
|
||||
Fixed:
|
||||
|
||||
- GC: merged local-only branches are removed without a forge token
|
||||
|
||||
## [2.4.0] - 2026-11-07
|
||||
|
||||
Added:
|
||||
|
||||
- Worktree: *worktree up* and *down* give each branch its own slot
|
||||
- Worktree: *worktree flow* keeps pull sources and push targets per worktree
|
||||
- Worktree: *up --pull* and *--push* record the flow; default is the base
|
||||
- Branch: *branch tree* writes a hardened meta-tree of all repositories
|
||||
- Branch: the tree carries each worktree's merge flow
|
||||
- GC: *gc --report* prints a read-only disk inventory
|
||||
- Review: a branch review renders as a local HTML page
|
||||
- Publish: releases rebuild nightly; stable follows the tested build
|
||||
|
||||
Changed:
|
||||
|
||||
- Push: signs only an unsigned HEAD instead of re-signing the whole range
|
||||
|
||||
Fixed:
|
||||
|
||||
- Push, release, gc: refuse a repository config that would run a program
|
||||
- Git: hooks named in the config no longer run in hardened git calls
|
||||
- Tests: the trusted PATH fixture comes from os.defpath, not the host
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Push: move repo-local sshCommand, credential helpers, hooks to global config
|
||||
|
||||
## [2.3.0] - 2026-11-01
|
||||
|
||||
Added:
|
||||
|
||||
- Branch: *gc --merged-into REF* treats items merged into REF as merged
|
||||
- Branch: *--merged-into* is repeatable, protects REF and works for *purge*
|
||||
- Branch: *--sizes* adds each worktree's disk usage to the plan
|
||||
- Branch: *--min-age HOURS* skips items with a commit or index that recent
|
||||
|
||||
## [2.2.0] - 2026-11-01
|
||||
|
||||
Added:
|
||||
|
||||
- Push: *--no-sign* pushes unsigned commits as they are; leases still apply
|
||||
- Push: *--rewrite* replaces commits a remote already has (amend, squash)
|
||||
|
||||
Changed:
|
||||
|
||||
- Push: *pkgmgr push* signs every unpushed unsigned commit before pushing
|
||||
- Push: each pushurl gets its own lease; mirrors no longer fail as stale
|
||||
- Push: a commit that exists only on a mirror stops the push, nothing lost
|
||||
- Push: without a selection it pushes the current checkout or worktree
|
||||
- Release: signs before tagging and pushes branch and tag like *pkgmgr push*
|
||||
|
||||
Fixed:
|
||||
|
||||
- Container: images build on native amd64 and arm64 runners, not QEMU
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Push: needs a working signing key; pass *--no-sign* to push unsigned
|
||||
- Container: no 2.1.0 or 2.1.1 image reached GHCR; notes below carry over
|
||||
- Release: a version file ahead of the newest tag now raises the next version
|
||||
- Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
## [2.1.1] - 2026-10-31
|
||||
|
||||
Fixed:
|
||||
|
||||
- Release: tool-only or dynamic-version pyproject.toml is skipped, no crash
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Container: no 2.1.0 image reached GHCR; the two notes below carry over
|
||||
- Release: a version file ahead of the newest tag now raises the next version
|
||||
- Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
## [2.1.0] - 2026-10-31
|
||||
|
||||
Added:
|
||||
|
||||
- Branch: *pkgmgr branch gc* removes merged clean branches, worktrees, stacks
|
||||
- Branch: *gc* only prints its plan; *--apply* acts, *--json* for scripts
|
||||
- Branch: *pkgmgr branch purge* deletes unmerged or dirty items after y/N
|
||||
- Release: Cargo.toml version and its Cargo.lock entry follow the release
|
||||
|
||||
Changed:
|
||||
|
||||
- Release: starts from the highest version in the tag and all version files
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Release: a version file ahead of the newest tag now raises the next version
|
||||
- Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
## [2.0.5] - 2026-10-29
|
||||
|
||||
Fixed:
|
||||
|
||||
- Config: *pkgmgr config edit* opens nano instead of aborting without a TTY
|
||||
- Config: *pkgmgr config edit* exits with the editor's code when it fails
|
||||
|
||||
## [2.0.4] - 2026-10-19
|
||||
|
||||
Fixed:
|
||||
|
||||
- CI: Python lint passes again on ruff 0.17 and still on 0.16
|
||||
- CI: actions bumped: *actions/checkout* v7, *hadolint-action* 3.5.0
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- 2.0.3 was never marked *stable* nor published to GHCR: its CI failed
|
||||
- Release: write list items with dash bullets when markdownlint-cli2 is absent
|
||||
|
||||
## [2.0.3] - 2026-10-18
|
||||
|
||||
Fixed:
|
||||
|
||||
- Release: the entry is linted inside the CHANGELOG.md it lands in
|
||||
- Release: a list marker that breaks the file's consistency is caught (MD004)
|
||||
- Release: findings the file already has are not blamed on the entry
|
||||
- Release: *--no-globs* keeps the target repo's other files out of the lint
|
||||
- Release: without markdownlint-cli2, list items must use dash bullets
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Release: write list items with dash bullets when markdownlint-cli2 is absent
|
||||
|
||||
## [2.0.2] - 2026-10-01
|
||||
|
||||
Fixes a release flow that could reject every entry written for it.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A heading in a changelog message became bold, which markdown-lint reads
|
||||
back as a heading and refuses with MD036
|
||||
- Since the editor reopens on failure, no structured entry could ever pass
|
||||
- Headings now move below the release heading they are filed under
|
||||
- The lint findings reached nobody: the editor took over the terminal in the
|
||||
same breath they were printed
|
||||
- They are held until Enter and repeated inside the editor, above the text
|
||||
- The Makefile installer accepted install-* as proof of an install target but
|
||||
always ran plain make install
|
||||
- A repository with install-python and no install died on "No rule to make
|
||||
target" instead of being skipped
|
||||
|
||||
### Tests
|
||||
|
||||
- transform and lint were covered separately, so a transform producing lint
|
||||
errors went unseen; one test now runs the first through the second
|
||||
- Three tests were checking behaviour the code had already left behind
|
||||
|
||||
### Dependencies
|
||||
|
||||
- docker/login-action 3.7.0 to 4.6.0, setup-buildx-action 3.12.0 to 4.4.0
|
||||
- actions/setup-python 5 to 7
|
||||
- DeterminateSystems nix-installer-action 16 to 23, update-flake-lock 24 to 29
|
||||
|
||||
### Upgrading
|
||||
|
||||
- Nothing to do; a changelog entry written with headings now keeps them
|
||||
|
||||
## [2.0.1] - 2026-09-18
|
||||
|
||||
* A release no longer ends *CHANGELOG.md* on a blank line, which is MD012.
|
||||
|
||||
@@ -70,6 +70,90 @@ versioning features it can drive **end-to-end workflows**:
|
||||
|
||||
---
|
||||
|
||||
### Worktrees and garbage collection
|
||||
|
||||
| Command | Does |
|
||||
| --- | --- |
|
||||
| `pkgmgr worktree up <branch> [--base REF] [--path DIR] [--pull REF ...] [--push BRANCH ...]` | Checks the branch out under `<directories.worktrees>/<host>/<owner>/<repo>/<branch>` or at `--path`, assigns a free slot, records the merge flow and runs the pinned `worktree-init` hook |
|
||||
| `pkgmgr worktree flow [PATH] [--json]` | Shows the merge flow of the worktree at `PATH` (default: `.`) |
|
||||
| `pkgmgr worktree flow set [PATH] (--pull REF ... \| --no-pull) (--push BRANCH ... \| --no-push) [--json]` | Replaces both lists of the merge flow |
|
||||
| `pkgmgr worktree flow clear [PATH] [--json]` | Removes the merge flow |
|
||||
| `pkgmgr worktree cleanup [--apply]` | Removes clean worktrees whose commits are merged or pushed: pinned `worktree-fini` hook, compose stack, checkout; the branch stays |
|
||||
| `pkgmgr branch cleanup [--apply]` | Removes merged branches that no worktree holds, locally and on the remotes |
|
||||
| `pkgmgr branch cleanup --local [--apply] [--json] [--merged-into REF]...` | Deletes only local branches whose tip is an ancestor of the remote-tracking default or of a `--merged-into` REF, each with `git update-ref --no-deref -d` against the planned sha and then its `branch.<name>` section in the repository's own config file (`git config --file <git common dir>/config`; a section it cannot remove is noted on the done item), also when the branch has an upstream or remote copy. Every git call of `--local` runs without any inherited `GIT_*` variable but `GIT_CEILING_DIRECTORIES`, which only narrows repository discovery, so a directory below a ceiling is never resolved to the repository above it; only the config reads of `deleteMerged` and of the upstreams run twice, both with the system config: once with the caller's `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_PARAMETERS` and `GIT_CONFIG_COUNT` with its `GIT_CONFIG_KEY_<n>` and `GIT_CONFIG_VALUE_<n>`, once without any of them, without `XDG_CONFIG_HOME` and with `HOME` set to the passwd home, and a branch either read keeps stays, so the environment can add keeps but never remove one. A `--merged-into` REF must name exactly one branch or remote-tracking ref, as `git rev-parse --symbolic-full-name` resolves it, in every scanned repository git can read; `X~0`, `X^0`, `X@{0}`, a sha, a range or an unknown ref stops the run. The default comes from `origin`, or from the only remote when there is no `origin`: the ref `refs/remotes/<remote>/HEAD`, else `main`, else `master` resolves to, every symref step inside `refs/remotes/<remote>/`, so never a local branch or `HEAD`; without one, for example with several remotes and no `origin`, the repository is refused, also under `--merged-into`; so is one whose `refs`, `packed-refs`, `reftable`, `logs` or `logs/refs` is a symlink (git-new-workdir), one with a symlink anywhere below `refs/`, `reftable/` or `logs/refs/` (for example `refs/heads/team` linked to another clone's heads), one whose git dir is neither its git common dir nor directly under `<common>/worktrees/` (a registration moved elsewhere), or one whose git output is not UTF-8. The repository is the one the current directory belongs to, also in a submodule or with a separate git dir; one whose main worktree belongs to another repository (`core.worktree`), whose git dir is neither its git common dir nor directly under `<common>/worktrees/`, or whose path is not UTF-8 is refused with exit 2. Skips a symbolic branch, every branch a symbolic ref anywhere under `refs/` (also a tag or remote-tracking one) or under the main worktree's or any registration's `refs/worktree/` points to, a branch that is itself a `--merged-into` target, a branch a worktree holds or that the HEAD of the main repository or of any `worktrees/<id>` registration names (also one `git worktree list` omits or whose id is no valid ref name, read through `git --git-dir=<dir> symbolic-ref HEAD`, so also under reftable), one a rebase or bisect in any worktree works on, one merged only by patch or PR, and, as `git branch --delete-merged` keeps them, one whose `branch.<name>.deleteMerged` is false in the config of any worktree (also its `config.worktree` or an `includeIf "onbranch:..."` file) or in the system config file, and the local upstream, as git's `%(upstream)` resolves it in any worktree, of any branch that stays, also of one that `--branch` or `--exclude` leaves out, each shown as kept with its reason; these holds are read through the git common dir, whichever worktree is scanned, and a registration, symbolic ref, HEAD or state file they cannot read refuses the repository; when a repository vanishes, moves or stops being readable, or its default or a `--merged-into` target stops resolving mid-run, its later items are skipped with that reason and the plan is still printed. A repository git or the filesystem fails on while planning (for example a dangling `.git` file under `--all`) is refused with that reason and the run goes on. The plan, refused repositories included, is printed (as JSON with `--json`), and the run exits 1 when an item failed, else 2 when a repository was refused, else 0. It stops with a message on stderr, no plan and exit 2 in exactly these cases: without `--all`, the current directory is not inside a git repository, its git dir is neither its git common dir nor directly under `<common>/worktrees/`, its main worktree belongs to another repository (`core.worktree`), or its path or git output is not UTF-8; `--apply` outside the host PID namespace; a `--merged-into` REF refused as above; a `--branch` that matches no item (also one that exists only on a remote). Meant for working clones and their worktrees, not for a bare server repository. Not mirrored from `git branch --delete-merged`: git also keeps a branch whose push would update its own upstream; `--local` does not. A branch is deleted before its planned local upstream; right before each delete its holds and then itLine truncated
|
||||
| `pkgmgr branch tree [--format json\|yaml] [--output FILE]` | Writes every managed repository's branches and worktrees with their cleanup state, without fetching |
|
||||
| `pkgmgr gc [--all] [--apply]` | Both cleanups in one pass, for the current repository or every managed one |
|
||||
| `pkgmgr gc --report [--all] [--root DIR] [--threshold-mb MB] [--docker] [--json]` | Read-only disk inventory: worktree sizes, changes a cleanup would keep, `--root` children, core dumps, docker usage, free space per filesystem |
|
||||
| `pkgmgr worktree orphans --stale-days N --top N` | Lists merged and abandoned branches and worktrees with a proposal each |
|
||||
|
||||
A hook runs only when the `worktree_hooks` config pins its command under the
|
||||
`<provider>/<account>/<repository>` of a repository managed in the pkgmgr
|
||||
config, and only for that repository's directory; origin's URL, which the
|
||||
repository's own config sets, never selects a pin. `{path}` and `{slot}` are
|
||||
replaced; a
|
||||
`worktree-init` or `worktree-fini` target in the repository's Makefile is
|
||||
reported, never run, because an agent may have written it. The pinned program
|
||||
must be an absolute path or a root-owned command on a `PATH` entry that root
|
||||
owns and no group or other user can write, up to `/`, so a binary planted in a
|
||||
user-writable directory such as a virtualenv never runs. The Nix store never
|
||||
counts: it is group-writable, and any user can have the daemon build
|
||||
root-owned content there, so pin an absolute path on Nix. A bare name runs as
|
||||
the resolved file that was checked. Inside a user namespace other than the
|
||||
initial one, root means the overflow uid, under which the real root's files
|
||||
show there, as do those of every other unmapped owner. Outside such a
|
||||
namespace a directory on a nosuid mount, where udisks2 and FUSE put user
|
||||
mounts, never counts as root's. The hook runs with
|
||||
stdin closed, only those `PATH` entries and a 30 minute timeout. Removal walks to
|
||||
the worktree without following a symbolic link and skips a worktree path that
|
||||
is not its own realpath. A pinned command that reads repository files, such as `make` or a
|
||||
script in the repository, trusts the worktree's content, tracked or ignored.
|
||||
|
||||
Every cleanup is a dry run until `--apply`, and `--json` prints the plan for
|
||||
other tools. The [agent skills](https://github.com/kevinveenbirkenbach/skills)
|
||||
wrap these commands; see [AGENTS.md](AGENTS.md) for the split.
|
||||
|
||||
#### Merge flow
|
||||
|
||||
Every worktree can carry a merge flow that scripts and skills read: `pull`
|
||||
lists the refs merged into the branch, in order, before a gate, deploy or
|
||||
merge; `push` lists the branches the branch is merged into, in order, when it
|
||||
is finished, each then pushed by the operator. It lives in
|
||||
`pkgmgr/flow.yml` inside the worktree's own git directory (`.git` of the main
|
||||
worktree, `<common>/worktrees/<id>` of a linked one), so it is never committed
|
||||
and goes with the worktree:
|
||||
|
||||
```yaml
|
||||
version: 1
|
||||
branch: feature/x
|
||||
pull:
|
||||
- origin/main
|
||||
- store-i18n
|
||||
push:
|
||||
- feature/iam-profile-rbac
|
||||
- production
|
||||
```
|
||||
|
||||
`branch` is the branch the flow was set on; another current branch shows as a
|
||||
warning. `worktree up` records `--pull` and `--push`; without them pull is
|
||||
the base the worktree came from and push that base's local branch
|
||||
(`origin/main` gives `main`). `flow set` needs each list or
|
||||
its `--no-pull`/`--no-push`, and writes atomically into a `pkgmgr/` of mode
|
||||
0700. Every entry must pass `git check-ref-format --branch` and must not start
|
||||
with `-`; a remote-tracking name such as `origin/main` passes. An invalid name
|
||||
exits 2 and writes nothing. A flow file that is a symbolic link, no regular
|
||||
file, larger than 64 KiB or malformed reads as `invalid`, with empty lists and
|
||||
a warning, and is never followed.
|
||||
|
||||
`flow --json` prints `worktree` and `git_dir` (absolute paths), `branch` (the
|
||||
current branch, `null` when detached), `flow_branch` (the file's `branch`),
|
||||
`pull`, `push`, `source` (`file`, `none` or `invalid`) and `warnings`; it
|
||||
exits 0 also without a flow, 2 when `PATH` is not a git worktree. In
|
||||
`pkgmgr branch tree` every item carries `flow`: `{"pull", "push", "source"}`,
|
||||
or `null` without a worktree or a flow; flow warnings join the repository's
|
||||
`warnings`.
|
||||
|
||||
---
|
||||
|
||||
## Architecture & Setup Map 🗺️
|
||||
|
||||
The following diagram gives a full overview of:
|
||||
@@ -181,16 +265,50 @@ is a manifest list covering `linux/amd64` and `linux/arm64`.
|
||||
|
||||
All images live under `ghcr.io/kevinveenbirkenbach/`:
|
||||
|
||||
| Tag | Contains |
|
||||
| --------------------------- | ---------------------------------- |
|
||||
| `pkgmgr-<distro>:latest` | newest build for that distribution |
|
||||
| `pkgmgr-<distro>:<version>` | one release |
|
||||
| `pkgmgr-<distro>:stable` | newest release marked stable |
|
||||
| Tag | Contains |
|
||||
| ------------------------------------- | --------------------------------------------------------- |
|
||||
| `pkgmgr-<distro>:latest` | newest build of the newest release on `main` |
|
||||
| `pkgmgr-<distro>:stable` | newest build of the release the git tag `stable` marks |
|
||||
| `pkgmgr-<distro>:<major>` | newest build of the newest release of that major |
|
||||
| `pkgmgr-<distro>:<major>.<minor>` | newest build of the newest release of that minor |
|
||||
| `pkgmgr-<distro>:<version>` | newest build of that release |
|
||||
| `pkgmgr-<distro>:<version>.<unix-ts>` | one build, never moves |
|
||||
|
||||
`<distro>` is one of `arch`, `debian`, `ubuntu`, `fedora`, `centos`. The Arch
|
||||
image is published without the suffix as well, so `pkgmgr:stable` and
|
||||
`pkgmgr-arch:stable` are the same image.
|
||||
|
||||
`<version>` is the PKGMGR release and `<unix-ts>` the build time, so
|
||||
`2.3.0.1767225600` is a full version an updater can order and pin. Every tag of
|
||||
one build points at the same image.
|
||||
|
||||
`stable` moves only once "Mark stable commit" has moved the git tag `stable`,
|
||||
which it does after every test of that release passed. Every day at 03:00 UTC,
|
||||
after the daily 00:00 UTC build of base-images, and on demand through the
|
||||
workflow's manual trigger, two releases are rebuilt on the newest base image:
|
||||
|
||||
- the newest `vX.Y.Z` release on `main`, moving `latest`, its prefixes and
|
||||
`<version>`, and adding `<version>.<unix-ts>`;
|
||||
- the release the git tag `stable` marks, when that is an older one, moving
|
||||
`stable` and `<version>`, adding its own `<version>.<unix-ts>`, and moving a
|
||||
prefix only while it is still the newest release of that prefix.
|
||||
|
||||
With newest `2.4.0` and stable `2.3.0`, `2.4.0` takes `latest`, `2` and `2.4`,
|
||||
and `2.3.0` takes `stable` and `2.3`. A security update in base-images thereby
|
||||
reaches whoever pinned a major, a minor, a release or follows `stable`.
|
||||
|
||||
Each release is compared with its own published `<version>`. A rebuild whose
|
||||
installed packages equal it pushes nothing, since a new timestamp tag would make
|
||||
every pin bump for no change; a tag of that release that does not show the
|
||||
published build yet, such as `stable` right after "Mark stable commit", is moved
|
||||
without a new timestamp.
|
||||
|
||||
A rebuild runs the build scripts of the release it rebuilds, not those of
|
||||
`main`, so the skip and the tag rules above only hold for releases tagged after
|
||||
this scheme landed. The scripts of an earlier release know no aliases: its merge
|
||||
step fails and leaves its tags where they are, until a newer release replaces
|
||||
it as the newest and the stable one.
|
||||
|
||||
For a clean environment that carries the system dependencies but no PKGMGR,
|
||||
pull `base-<distro>` from
|
||||
[base-images](https://github.com/kevinveenbirkenbach/base-images) directly.
|
||||
|
||||
Generated
+3
-3
@@ -2,11 +2,11 @@
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1771714954,
|
||||
"narHash": "sha256-nhZJPnBavtu40/L2aqpljrfUNb2rxmWTmSjK2c9UKds=",
|
||||
"lastModified": 1782847189,
|
||||
"narHash": "sha256-twXPFqFsrrY5r28Zh7Homgcp2gUMBgQ6WDS98Q/3xFI=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "afbbf774e2087c3d734266c22f96fca2e78d3620",
|
||||
"rev": "b6018f87da91d19d0ab4cf979885689b469cdd41",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
rec {
|
||||
pkgmgr = pyPkgs.buildPythonApplication {
|
||||
pname = "package-manager";
|
||||
version = "2.0.1";
|
||||
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.0.1
|
||||
pkgver=2.6.0
|
||||
pkgrel=1
|
||||
pkgdesc="Local-flake wrapper for Kevin's package-manager (Nix-based)."
|
||||
arch=('any')
|
||||
|
||||
@@ -1,3 +1,226 @@
|
||||
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:
|
||||
|
||||
- Branch: *cleanup --local* deletes merged branches only where git would
|
||||
- Review: expand and collapse are icon buttons with labels
|
||||
|
||||
Fixed:
|
||||
|
||||
- GC: merged local-only branches are removed without a forge token
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Fri, 13 Nov 2026 22:53:12 +0000
|
||||
|
||||
package-manager (2.4.0-1) unstable; urgency=medium
|
||||
|
||||
Added:
|
||||
|
||||
- Worktree: *worktree up* and *down* give each branch its own slot
|
||||
- Worktree: *worktree flow* keeps pull sources and push targets per worktree
|
||||
- Worktree: *up --pull* and *--push* record the flow; default is the base
|
||||
- Branch: *branch tree* writes a hardened meta-tree of all repositories
|
||||
- Branch: the tree carries each worktree's merge flow
|
||||
- GC: *gc --report* prints a read-only disk inventory
|
||||
- Review: a branch review renders as a local HTML page
|
||||
- Publish: releases rebuild nightly; stable follows the tested build
|
||||
|
||||
Changed:
|
||||
|
||||
- Push: signs only an unsigned HEAD instead of re-signing the whole range
|
||||
|
||||
Fixed:
|
||||
|
||||
- Push, release, gc: refuse a repository config that would run a program
|
||||
- Git: hooks named in the config no longer run in hardened git calls
|
||||
- Tests: the trusted PATH fixture comes from os.defpath, not the host
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Push: move repo-local sshCommand, credential helpers, hooks to global config
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Sat, 07 Nov 2026 15:45:28 +0000
|
||||
|
||||
package-manager (2.3.0-1) unstable; urgency=medium
|
||||
|
||||
Added:
|
||||
|
||||
- Branch: *gc --merged-into REF* treats items merged into REF as merged
|
||||
- Branch: *--merged-into* is repeatable, protects REF and works for *purge*
|
||||
- Branch: *--sizes* adds each worktree's disk usage to the plan
|
||||
- Branch: *--min-age HOURS* skips items with a commit or index that recent
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Sun, 01 Nov 2026 15:14:53 +0100
|
||||
|
||||
package-manager (2.2.0-1) unstable; urgency=medium
|
||||
|
||||
Added:
|
||||
|
||||
- Push: *--no-sign* pushes unsigned commits as they are; leases still apply
|
||||
- Push: *--rewrite* replaces commits a remote already has (amend, squash)
|
||||
|
||||
Changed:
|
||||
|
||||
- Push: *pkgmgr push* signs every unpushed unsigned commit before pushing
|
||||
- Push: each pushurl gets its own lease; mirrors no longer fail as stale
|
||||
- Push: a commit that exists only on a mirror stops the push, nothing lost
|
||||
- Push: without a selection it pushes the current checkout or worktree
|
||||
- Release: signs before tagging and pushes branch and tag like *pkgmgr push*
|
||||
|
||||
Fixed:
|
||||
|
||||
- Container: images build on native amd64 and arm64 runners, not QEMU
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Push: needs a working signing key; pass *--no-sign* to push unsigned
|
||||
- Container: no 2.1.0 or 2.1.1 image reached GHCR; notes below carry over
|
||||
- Release: a version file ahead of the newest tag now raises the next version
|
||||
- Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Sun, 01 Nov 2026 01:55:29 +0100
|
||||
|
||||
package-manager (2.1.1-1) unstable; urgency=medium
|
||||
|
||||
Fixed:
|
||||
|
||||
- Release: tool-only or dynamic-version pyproject.toml is skipped, no crash
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Container: no 2.1.0 image reached GHCR; the two notes below carry over
|
||||
- Release: a version file ahead of the newest tag now raises the next version
|
||||
- Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Sat, 31 Oct 2026 18:47:35 +0100
|
||||
|
||||
package-manager (2.1.0-1) unstable; urgency=medium
|
||||
|
||||
Added:
|
||||
|
||||
- Branch: *pkgmgr branch gc* removes merged clean branches, worktrees, stacks
|
||||
- Branch: *gc* only prints its plan; *--apply* acts, *--json* for scripts
|
||||
- Branch: *pkgmgr branch purge* deletes unmerged or dirty items after y/N
|
||||
- Release: Cargo.toml version and its Cargo.lock entry follow the release
|
||||
|
||||
Changed:
|
||||
|
||||
- Release: starts from the highest version in the tag and all version files
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Release: a version file ahead of the newest tag now raises the next version
|
||||
- Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Sat, 31 Oct 2026 14:38:54 +0100
|
||||
|
||||
package-manager (2.0.5-1) unstable; urgency=medium
|
||||
|
||||
Fixed:
|
||||
|
||||
- Config: *pkgmgr config edit* opens nano instead of aborting without a TTY
|
||||
- Config: *pkgmgr config edit* exits with the editor's code when it fails
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Thu, 29 Oct 2026 13:57:31 +0100
|
||||
|
||||
package-manager (2.0.4-1) unstable; urgency=medium
|
||||
|
||||
Fixed:
|
||||
|
||||
- CI: Python lint passes again on ruff 0.17 and still on 0.16
|
||||
- CI: actions bumped: *actions/checkout* v7, *hadolint-action* 3.5.0
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- 2.0.3 was never marked *stable* nor published to GHCR: its CI failed
|
||||
- Release: write list items with dash bullets when markdownlint-cli2 is absent
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Mon, 19 Oct 2026 10:06:02 +0200
|
||||
|
||||
package-manager (2.0.3-1) unstable; urgency=medium
|
||||
|
||||
Fixed:
|
||||
|
||||
- Release: the entry is linted inside the CHANGELOG.md it lands in
|
||||
- Release: a list marker that breaks the file's consistency is caught (MD004)
|
||||
- Release: findings the file already has are not blamed on the entry
|
||||
- Release: *--no-globs* keeps the target repo's other files out of the lint
|
||||
- Release: without markdownlint-cli2, list items must use dash bullets
|
||||
|
||||
Upgrade notes:
|
||||
|
||||
- Release: write list items with dash bullets when markdownlint-cli2 is absent
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Sun, 18 Oct 2026 23:33:52 +0200
|
||||
|
||||
package-manager (2.0.2-1) unstable; urgency=medium
|
||||
|
||||
Fixes a release flow that could reject every entry written for it.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A heading in a changelog message became bold, which markdown-lint reads
|
||||
back as a heading and refuses with MD036
|
||||
- Since the editor reopens on failure, no structured entry could ever pass
|
||||
- Headings now move below the release heading they are filed under
|
||||
- The lint findings reached nobody: the editor took over the terminal in the
|
||||
same breath they were printed
|
||||
- They are held until Enter and repeated inside the editor, above the text
|
||||
- The Makefile installer accepted install-* as proof of an install target but
|
||||
always ran plain make install
|
||||
- A repository with install-python and no install died on "No rule to make
|
||||
target" instead of being skipped
|
||||
|
||||
### Tests
|
||||
|
||||
- transform and lint were covered separately, so a transform producing lint
|
||||
errors went unseen; one test now runs the first through the second
|
||||
- Three tests were checking behaviour the code had already left behind
|
||||
|
||||
### Dependencies
|
||||
|
||||
- docker/login-action 3.7.0 to 4.6.0, setup-buildx-action 3.12.0 to 4.4.0
|
||||
- actions/setup-python 5 to 7
|
||||
- DeterminateSystems nix-installer-action 16 to 23, update-flake-lock 24 to 29
|
||||
|
||||
### Upgrading
|
||||
|
||||
- Nothing to do; a changelog entry written with headings now keeps them
|
||||
|
||||
-- Kevin Veen-Birkenbach <kevin@veen.world> Thu, 01 Oct 2026 17:47:12 +0200
|
||||
|
||||
package-manager (2.0.1-1) unstable; urgency=medium
|
||||
|
||||
* A release no longer ends *CHANGELOG.md* on a blank line, which is MD012.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Name: package-manager
|
||||
Version: 2.0.1
|
||||
Version: 2.6.0
|
||||
Release: 1%{?dist}
|
||||
Summary: Wrapper that runs Kevin's package-manager via Nix flake
|
||||
|
||||
@@ -74,6 +74,196 @@ 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:
|
||||
|
||||
- - Branch: *cleanup --local* deletes merged branches only where git would
|
||||
- - Review: expand and collapse are icon buttons with labels
|
||||
|
||||
- Fixed:
|
||||
|
||||
- - GC: merged local-only branches are removed without a forge token
|
||||
|
||||
* Sat Nov 07 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.4.0-1
|
||||
- Added:
|
||||
|
||||
- - Worktree: *worktree up* and *down* give each branch its own slot
|
||||
- - Worktree: *worktree flow* keeps pull sources and push targets per worktree
|
||||
- - Worktree: *up --pull* and *--push* record the flow; default is the base
|
||||
- - Branch: *branch tree* writes a hardened meta-tree of all repositories
|
||||
- - Branch: the tree carries each worktree's merge flow
|
||||
- - GC: *gc --report* prints a read-only disk inventory
|
||||
- - Review: a branch review renders as a local HTML page
|
||||
- - Publish: releases rebuild nightly; stable follows the tested build
|
||||
|
||||
- Changed:
|
||||
|
||||
- - Push: signs only an unsigned HEAD instead of re-signing the whole range
|
||||
|
||||
- Fixed:
|
||||
|
||||
- - Push, release, gc: refuse a repository config that would run a program
|
||||
- - Git: hooks named in the config no longer run in hardened git calls
|
||||
- - Tests: the trusted PATH fixture comes from os.defpath, not the host
|
||||
|
||||
- Upgrade notes:
|
||||
|
||||
- - Push: move repo-local sshCommand, credential helpers, hooks to global config
|
||||
|
||||
* Sun Nov 01 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.3.0-1
|
||||
- Added:
|
||||
|
||||
- - Branch: *gc --merged-into REF* treats items merged into REF as merged
|
||||
- - Branch: *--merged-into* is repeatable, protects REF and works for *purge*
|
||||
- - Branch: *--sizes* adds each worktree's disk usage to the plan
|
||||
- - Branch: *--min-age HOURS* skips items with a commit or index that recent
|
||||
|
||||
* Sun Nov 01 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.2.0-1
|
||||
- Added:
|
||||
|
||||
- - Push: *--no-sign* pushes unsigned commits as they are; leases still apply
|
||||
- - Push: *--rewrite* replaces commits a remote already has (amend, squash)
|
||||
|
||||
- Changed:
|
||||
|
||||
- - Push: *pkgmgr push* signs every unpushed unsigned commit before pushing
|
||||
- - Push: each pushurl gets its own lease; mirrors no longer fail as stale
|
||||
- - Push: a commit that exists only on a mirror stops the push, nothing lost
|
||||
- - Push: without a selection it pushes the current checkout or worktree
|
||||
- - Release: signs before tagging and pushes branch and tag like *pkgmgr push*
|
||||
|
||||
- Fixed:
|
||||
|
||||
- - Container: images build on native amd64 and arm64 runners, not QEMU
|
||||
|
||||
- Upgrade notes:
|
||||
|
||||
- - Push: needs a working signing key; pass *--no-sign* to push unsigned
|
||||
- - Container: no 2.1.0 or 2.1.1 image reached GHCR; notes below carry over
|
||||
- - Release: a version file ahead of the newest tag now raises the next version
|
||||
- - Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
* Sat Oct 31 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.1.1-1
|
||||
- Fixed:
|
||||
|
||||
- - Release: tool-only or dynamic-version pyproject.toml is skipped, no crash
|
||||
|
||||
- Upgrade notes:
|
||||
|
||||
- - Container: no 2.1.0 image reached GHCR; the two notes below carry over
|
||||
- - Release: a version file ahead of the newest tag now raises the next version
|
||||
- - Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
* Sat Oct 31 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.1.0-1
|
||||
- Added:
|
||||
|
||||
- - Branch: *pkgmgr branch gc* removes merged clean branches, worktrees, stacks
|
||||
- - Branch: *gc* only prints its plan; *--apply* acts, *--json* for scripts
|
||||
- - Branch: *pkgmgr branch purge* deletes unmerged or dirty items after y/N
|
||||
- - Release: Cargo.toml version and its Cargo.lock entry follow the release
|
||||
|
||||
- Changed:
|
||||
|
||||
- - Release: starts from the highest version in the tag and all version files
|
||||
|
||||
- Upgrade notes:
|
||||
|
||||
- - Release: a version file ahead of the newest tag now raises the next version
|
||||
- - Branch: *gc --apply* and *purge* refuse to run inside a PID sandbox
|
||||
|
||||
* Thu Oct 29 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.0.5-1
|
||||
- Fixed:
|
||||
|
||||
- - Config: *pkgmgr config edit* opens nano instead of aborting without a TTY
|
||||
- - Config: *pkgmgr config edit* exits with the editor's code when it fails
|
||||
|
||||
* Mon Oct 19 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.0.4-1
|
||||
- Fixed:
|
||||
|
||||
- - CI: Python lint passes again on ruff 0.17 and still on 0.16
|
||||
- - CI: actions bumped: *actions/checkout* v7, *hadolint-action* 3.5.0
|
||||
|
||||
- Upgrade notes:
|
||||
|
||||
- - 2.0.3 was never marked *stable* nor published to GHCR: its CI failed
|
||||
- - Release: write list items with dash bullets when markdownlint-cli2 is absent
|
||||
|
||||
* Sun Oct 18 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.0.3-1
|
||||
- Fixed:
|
||||
|
||||
- - Release: the entry is linted inside the CHANGELOG.md it lands in
|
||||
- - Release: a list marker that breaks the file's consistency is caught (MD004)
|
||||
- - Release: findings the file already has are not blamed on the entry
|
||||
- - Release: *--no-globs* keeps the target repo's other files out of the lint
|
||||
- - Release: without markdownlint-cli2, list items must use dash bullets
|
||||
|
||||
- Upgrade notes:
|
||||
|
||||
- - Release: write list items with dash bullets when markdownlint-cli2 is absent
|
||||
|
||||
* Thu Oct 01 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.0.2-1
|
||||
- Fixes a release flow that could reject every entry written for it.
|
||||
|
||||
- ### Fixed
|
||||
|
||||
- - A heading in a changelog message became bold, which markdown-lint reads
|
||||
- back as a heading and refuses with MD036
|
||||
- - Since the editor reopens on failure, no structured entry could ever pass
|
||||
- - Headings now move below the release heading they are filed under
|
||||
- - The lint findings reached nobody: the editor took over the terminal in the
|
||||
- same breath they were printed
|
||||
- - They are held until Enter and repeated inside the editor, above the text
|
||||
- - The Makefile installer accepted install-* as proof of an install target but
|
||||
- always ran plain make install
|
||||
- - A repository with install-python and no install died on "No rule to make
|
||||
- target" instead of being skipped
|
||||
|
||||
- ### Tests
|
||||
|
||||
- - transform and lint were covered separately, so a transform producing lint
|
||||
- errors went unseen; one test now runs the first through the second
|
||||
- - Three tests were checking behaviour the code had already left behind
|
||||
|
||||
- ### Dependencies
|
||||
|
||||
- - docker/login-action 3.7.0 to 4.6.0, setup-buildx-action 3.12.0 to 4.4.0
|
||||
- - actions/setup-python 5 to 7
|
||||
- - DeterminateSystems nix-installer-action 16 to 23, update-flake-lock 24 to 29
|
||||
|
||||
- ### Upgrading
|
||||
|
||||
- - Nothing to do; a changelog entry written with headings now keeps them
|
||||
|
||||
* Fri Sep 18 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.0.1-1
|
||||
- * A release no longer ends *CHANGELOG.md* on a blank line, which is MD012.
|
||||
- * The entry's separator only belongs there when another entry follows it.
|
||||
|
||||
+3
-2
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "kpmx"
|
||||
version = "2.0.1"
|
||||
version = "2.6.0"
|
||||
description = "Kevin's package-manager tool (pkgmgr)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
@@ -21,7 +21,7 @@ authors = [
|
||||
dependencies = [
|
||||
"PyYAML>=6.0",
|
||||
"tomli; python_version < \"3.11\"",
|
||||
"jinja2>=3.1"
|
||||
"jinja2>=3.1.6"
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
@@ -52,3 +52,4 @@ include = ["pkgmgr*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"pkgmgr.config" = ["*.yml", "*.yaml"]
|
||||
"pkgmgr.actions.review" = ["*.j2", "*.LICENSE"]
|
||||
@@ -30,3 +30,24 @@ resolve_platforms() {
|
||||
*) echo "ERROR: Unknown distro '$PKGMGR_DISTRO'" >&2; exit 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
package_set_cmd() {
|
||||
local PKGMGR_DISTRO="$1"
|
||||
case "$PKGMGR_DISTRO" in
|
||||
arch|manjaro) echo 'pacman -Q' ;;
|
||||
debian|ubuntu) echo 'dpkg-query -W' ;;
|
||||
fedora|centos) echo 'rpm -qa | sort' ;;
|
||||
*) echo "ERROR: Unknown distro '$PKGMGR_DISTRO'" >&2; exit 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
version_prefixes() {
|
||||
local -a parts
|
||||
IFS=. read -ra parts <<< "$1"
|
||||
local acc="${parts[0]}" i
|
||||
echo "${acc}"
|
||||
for ((i = 1; i < ${#parts[@]}; i++)); do
|
||||
acc+=".${parts[i]}"
|
||||
echo "${acc}"
|
||||
done
|
||||
}
|
||||
+136
-32
@@ -12,12 +12,15 @@ NO_CACHE=0
|
||||
MISSING_ONLY=0
|
||||
IMAGE_TAG="" # local image name or base tag (without registry)
|
||||
PUSH=0 # if 1 -> use buildx and push (requires docker buildx)
|
||||
PUBLISH=0 # if 1 -> push with semantic tags (latest/version/stable + arch aliases)
|
||||
PUBLISH=0 # if 1 -> push <version>, <version>.<unix-ts> and the --aliases, plus arch aliases
|
||||
REGISTRY="" # e.g. ghcr.io
|
||||
OWNER="" # e.g. github org/user
|
||||
REPO_PREFIX="pkgmgr" # image base name (pkgmgr)
|
||||
VERSION="" # X.Y.Z (required for --publish)
|
||||
IS_STABLE="false" # "true" -> publish stable tags
|
||||
ALIASES="" # moving tags besides <version>, e.g. "latest 2 2.4 stable"
|
||||
ALIASES_SET=0 # 1 once --aliases was given, also when empty
|
||||
PLATFORM="" # e.g. linux/arm64 -> build and push only this platform
|
||||
MERGE=0 # if 1 -> join the per-platform tags of --version under the publish tags
|
||||
DEFAULT_DISTRO="arch"
|
||||
|
||||
usage() {
|
||||
@@ -33,15 +36,24 @@ Build options:
|
||||
|
||||
Publish options:
|
||||
--push Push the built image (uses docker buildx build --push)
|
||||
--publish Publish semantic tags (latest, <version>, optional stable) + arch aliases
|
||||
--publish Publish <version>, <version>.<unix-ts> and every --aliases tag, plus arch
|
||||
aliases
|
||||
--registry <reg> Registry (e.g. ghcr.io)
|
||||
--owner <owner> Registry namespace (e.g. \${GITHUB_REPOSITORY_OWNER})
|
||||
--repo-prefix <name> Image base name (default: pkgmgr)
|
||||
--version <X.Y.Z> Version for --publish
|
||||
--stable <true|false> Whether to publish :stable tags (default: false)
|
||||
--aliases "<tags>" Moving tags besides <version>, space separated, may be empty
|
||||
(e.g. "latest 2 2.4 stable")
|
||||
--platform <os/arch> Build and push only this platform; with --publish as <version>-<arch>,
|
||||
skipped when its package set equals the published <version>
|
||||
--merge Join the <version>-<arch> tags of all platforms under the publish tags;
|
||||
when <version> already joins exactly these images, only the aliases
|
||||
that do not are moved and no <version>.<unix-ts> is added
|
||||
|
||||
Notes:
|
||||
- --publish implies --push and requires --registry, --owner, and --version.
|
||||
- --publish without --platform requires --aliases.
|
||||
- --platform requires --push; --merge requires --publish and builds nothing.
|
||||
- Local build (no --push) uses "docker build" and creates a local image like "pkgmgr-arch".
|
||||
EOF
|
||||
}
|
||||
@@ -77,11 +89,18 @@ while [[ $# -gt 0 ]]; do
|
||||
[[ -n "${VERSION}" ]] || { echo "ERROR: --version requires a value"; exit 2; }
|
||||
shift 2
|
||||
;;
|
||||
--stable)
|
||||
IS_STABLE="${2:-}"
|
||||
[[ -n "${IS_STABLE}" ]] || { echo "ERROR: --stable requires a value (true|false)"; exit 2; }
|
||||
--aliases)
|
||||
[[ $# -ge 2 ]] || { echo "ERROR: --aliases requires a value, empty for none"; exit 2; }
|
||||
ALIASES="$2"
|
||||
ALIASES_SET=1
|
||||
shift 2
|
||||
;;
|
||||
--platform)
|
||||
PLATFORM="${2:-}"
|
||||
[[ -n "${PLATFORM}" ]] || { echo "ERROR: --platform requires a value"; exit 2; }
|
||||
shift 2
|
||||
;;
|
||||
--merge) MERGE=1; shift ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*)
|
||||
echo "ERROR: Unknown argument: $1" >&2
|
||||
@@ -115,8 +134,24 @@ if [[ "${PUBLISH}" == "1" ]]; then
|
||||
[[ -n "${REGISTRY}" ]] || { echo "ERROR: --publish requires --registry"; exit 2; }
|
||||
[[ -n "${OWNER}" ]] || { echo "ERROR: --publish requires --owner"; exit 2; }
|
||||
[[ -n "${VERSION}" ]] || { echo "ERROR: --publish requires --version"; exit 2; }
|
||||
[[ -n "${PLATFORM}" || "${ALIASES_SET}" == "1" ]] \
|
||||
|| { echo "ERROR: --publish without --platform requires --aliases"; exit 2; }
|
||||
fi
|
||||
|
||||
if [[ -n "${PLATFORM}" ]]; then
|
||||
[[ "${PUSH}" == "1" ]] || { echo "ERROR: --platform requires --push or --publish"; exit 2; }
|
||||
[[ ",$(resolve_platforms "$PKGMGR_DISTRO")," == *",${PLATFORM},"* ]] \
|
||||
|| { echo "ERROR: ${PKGMGR_DISTRO} offers no platform ${PLATFORM}"; exit 2; }
|
||||
fi
|
||||
|
||||
if [[ "${MERGE}" == "1" ]]; then
|
||||
[[ "${PUBLISH}" == "1" ]] || { echo "ERROR: --merge requires --publish"; exit 2; }
|
||||
[[ -z "${PLATFORM}" ]] || { echo "ERROR: --merge and --platform exclude each other"; exit 2; }
|
||||
fi
|
||||
|
||||
DISTRO_TAG_BASE="${REGISTRY}/${OWNER}/${REPO_PREFIX}-${PKGMGR_DISTRO}"
|
||||
STAMP="$(date -u +%s)"
|
||||
|
||||
# Guard: --push without --publish requires fully-qualified --tag
|
||||
if [[ "${PUSH}" == "1" && "${PUBLISH}" != "1" ]]; then
|
||||
if [[ "${IMAGE_TAG}" != */* ]]; then
|
||||
@@ -130,7 +165,7 @@ echo "------------------------------------------------------------"
|
||||
echo "[build] Building image"
|
||||
echo "distro = ${PKGMGR_DISTRO}"
|
||||
echo "BASE_IMAGE = ${BASE_IMAGE}"
|
||||
echo "platforms = $(resolve_platforms "$PKGMGR_DISTRO")"
|
||||
echo "platforms = ${PLATFORM:-$(resolve_platforms "$PKGMGR_DISTRO")}"
|
||||
if [[ "${NO_CACHE}" == "1" ]]; then echo "cache = disabled"; fi
|
||||
if [[ "${PUSH}" == "1" ]]; then echo "push = enabled"; fi
|
||||
if [[ "${PUBLISH}" == "1" ]]; then
|
||||
@@ -138,7 +173,8 @@ if [[ "${PUBLISH}" == "1" ]]; then
|
||||
echo "registry = ${REGISTRY}"
|
||||
echo "owner = ${OWNER}"
|
||||
echo "version = ${VERSION}"
|
||||
echo "stable = ${IS_STABLE}"
|
||||
echo "stamp = ${STAMP}"
|
||||
echo "aliases = ${ALIASES}"
|
||||
fi
|
||||
echo "------------------------------------------------------------"
|
||||
|
||||
@@ -149,45 +185,113 @@ if [[ "${NO_CACHE}" == "1" ]]; then
|
||||
build_args+=(--no-cache)
|
||||
fi
|
||||
|
||||
compute_publish_tags() {
|
||||
local distro_tag_base="${REGISTRY}/${OWNER}/${REPO_PREFIX}-${PKGMGR_DISTRO}"
|
||||
local alias_tag_base=""
|
||||
|
||||
publish_bases() {
|
||||
echo "${DISTRO_TAG_BASE}"
|
||||
if [[ "${PKGMGR_DISTRO}" == "${DEFAULT_DISTRO}" ]]; then
|
||||
alias_tag_base="${REGISTRY}/${OWNER}/${REPO_PREFIX}"
|
||||
echo "${REGISTRY}/${OWNER}/${REPO_PREFIX}"
|
||||
fi
|
||||
}
|
||||
|
||||
moving_tags() {
|
||||
local base alias
|
||||
local -a aliases
|
||||
read -ra aliases <<< "${ALIASES}"
|
||||
while read -r base; do
|
||||
echo "${base}:${VERSION}"
|
||||
for alias in "${aliases[@]}"; do
|
||||
echo "${base}:${alias}"
|
||||
done
|
||||
done < <(publish_bases)
|
||||
}
|
||||
|
||||
stamp_tags() {
|
||||
local base
|
||||
while read -r base; do
|
||||
echo "${base}:${VERSION}.${STAMP}"
|
||||
done < <(publish_bases)
|
||||
}
|
||||
|
||||
raw_index() {
|
||||
docker buildx imagetools inspect --raw "$1" 2>/dev/null || true
|
||||
}
|
||||
|
||||
digest_of() {
|
||||
docker buildx imagetools inspect --format '{{json .Manifest.Digest}}' "$1"
|
||||
}
|
||||
|
||||
if [[ "${MERGE}" == "1" ]]; then
|
||||
sources=()
|
||||
IFS=',' read -ra platforms <<< "$(resolve_platforms "$PKGMGR_DISTRO")"
|
||||
for p in "${platforms[@]}"; do
|
||||
sources+=("${DISTRO_TAG_BASE}:${VERSION}-${p#*/}")
|
||||
done
|
||||
|
||||
mapfile -t moving < <(moving_tags)
|
||||
planned="$(docker buildx imagetools create --dry-run -t "${DISTRO_TAG_BASE}:${VERSION}" "${sources[@]}")"
|
||||
tags=()
|
||||
if [[ "$(raw_index "${DISTRO_TAG_BASE}:${VERSION}")" == "${planned}" ]]; then
|
||||
for t in "${moving[@]}"; do
|
||||
if [[ "$(raw_index "${t}")" != "${planned}" ]]; then
|
||||
tags+=("${t}")
|
||||
fi
|
||||
done
|
||||
else
|
||||
mapfile -t stamps < <(stamp_tags)
|
||||
tags=("${moving[@]}" "${stamps[@]}")
|
||||
fi
|
||||
|
||||
local tags=()
|
||||
tags+=("${distro_tag_base}:latest")
|
||||
tags+=("${distro_tag_base}:${VERSION}")
|
||||
|
||||
if [[ "${IS_STABLE}" == "true" ]]; then
|
||||
tags+=("${distro_tag_base}:stable")
|
||||
if ((${#tags[@]} == 0)); then
|
||||
echo "[build] ${PKGMGR_DISTRO} ${VERSION}: every tag already joins these platform images, nothing to push."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ -n "${alias_tag_base}" ]]; then
|
||||
tags+=("${alias_tag_base}:latest")
|
||||
tags+=("${alias_tag_base}:${VERSION}")
|
||||
if [[ "${IS_STABLE}" == "true" ]]; then
|
||||
tags+=("${alias_tag_base}:stable")
|
||||
create_args=()
|
||||
for t in "${tags[@]}"; do
|
||||
create_args+=(-t "$t")
|
||||
done
|
||||
|
||||
echo "[build] Running: docker buildx imagetools create ${create_args[*]} ${sources[*]}"
|
||||
docker buildx imagetools create "${create_args[@]}" "${sources[@]}"
|
||||
|
||||
version_digest="$(digest_of "${DISTRO_TAG_BASE}:${VERSION}")"
|
||||
for t in "${moving[@]}"; do
|
||||
if [[ "$(digest_of "${t}")" != "${version_digest}" ]]; then
|
||||
echo "[build] ❌ ${PKGMGR_DISTRO}: :${VERSION} and ${t} point at different images." >&2
|
||||
echo "[build] Whoever pinned ${t##*:} stopped receiving what ${VERSION} gets." >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
echo "[build] ✅ ${PKGMGR_DISTRO}: every tag of ${VERSION} == ${version_digest}"
|
||||
elif [[ "${PUSH}" == "1" ]]; then
|
||||
if [[ "${PUBLISH}" == "1" && -n "${PLATFORM}" ]]; then
|
||||
probe="${REPO_PREFIX}-${PKGMGR_DISTRO}:probe"
|
||||
docker buildx build --load --platform "${PLATFORM}" -t "${probe}" "${build_args[@]}" .
|
||||
|
||||
package_set="$(package_set_cmd "${PKGMGR_DISTRO}")"
|
||||
built_set="$(docker run --rm --platform "${PLATFORM}" --entrypoint bash "${probe}" -lc "${package_set}" | sha256sum)"
|
||||
published_set="$(docker run --rm --pull always --platform "${PLATFORM}" --entrypoint bash "${DISTRO_TAG_BASE}:${VERSION}" -lc "${package_set}" 2>/dev/null | sha256sum || true)"
|
||||
if [[ "${built_set}" == "${published_set}" ]]; then
|
||||
echo "[build] ${PKGMGR_DISTRO} ${PLATFORM} unchanged since the published ${VERSION}, nothing to push."
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
printf '%s\n' "${tags[@]}"
|
||||
}
|
||||
|
||||
if [[ "${PUSH}" == "1" ]]; then
|
||||
bx_args=(docker buildx build --push)
|
||||
|
||||
if [[ "${PUBLISH}" == "1" ]]; then
|
||||
if [[ "${PUBLISH}" == "1" && -n "${PLATFORM}" ]]; then
|
||||
bx_args+=(-t "${DISTRO_TAG_BASE}:${VERSION}-${PLATFORM#*/}")
|
||||
elif [[ "${PUBLISH}" == "1" ]]; then
|
||||
while IFS= read -r t; do
|
||||
bx_args+=(-t "$t")
|
||||
done < <(compute_publish_tags)
|
||||
done < <(moving_tags)
|
||||
while IFS= read -r t; do
|
||||
bx_args+=(-t "$t")
|
||||
done < <(stamp_tags)
|
||||
else
|
||||
bx_args+=(-t "${IMAGE_TAG}")
|
||||
fi
|
||||
|
||||
bx_args+=(--platform "$(resolve_platforms "$PKGMGR_DISTRO")")
|
||||
bx_args+=(--platform "${PLATFORM:-$(resolve_platforms "$PKGMGR_DISTRO")}")
|
||||
bx_args+=("${build_args[@]}")
|
||||
bx_args+=(.)
|
||||
|
||||
|
||||
@@ -6,25 +6,28 @@ set -euo pipefail
|
||||
# Required env:
|
||||
# OWNER (e.g. GITHUB_REPOSITORY_OWNER)
|
||||
# VERSION (e.g. 1.2.3)
|
||||
# ALIASES moving tags besides VERSION, space separated, may be empty (e.g. "latest 1 1.2 stable")
|
||||
#
|
||||
# Optional env:
|
||||
# REGISTRY (default: ghcr.io)
|
||||
# IS_STABLE (default: false)
|
||||
# DISTROS (default: "arch debian ubuntu fedora centos")
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
# shellcheck source=./scripts/build/base.sh
|
||||
source "${SCRIPT_DIR}/base.sh"
|
||||
|
||||
REGISTRY="${REGISTRY:-ghcr.io}"
|
||||
IS_STABLE="${IS_STABLE:-false}"
|
||||
DISTROS="${DISTROS:-arch debian ubuntu fedora centos}"
|
||||
|
||||
: "${OWNER:?Environment variable OWNER must be set (e.g. github.repository_owner)}"
|
||||
: "${VERSION:?Environment variable VERSION must be set (e.g. 1.2.3)}"
|
||||
: "${ALIASES?Environment variable ALIASES must be set, empty for none (e.g. \"latest 1 1.2 stable\")}"
|
||||
|
||||
echo "[publish] REGISTRY=${REGISTRY}"
|
||||
echo "[publish] OWNER=${OWNER}"
|
||||
echo "[publish] VERSION=${VERSION}"
|
||||
echo "[publish] IS_STABLE=${IS_STABLE}"
|
||||
echo "[publish] ALIASES=${ALIASES}"
|
||||
echo "[publish] DISTROS=${DISTROS}"
|
||||
|
||||
for d in ${DISTROS}; do
|
||||
@@ -33,12 +36,23 @@ for d in ${DISTROS}; do
|
||||
echo "[publish] PKGMGR_DISTRO=${d}"
|
||||
echo "============================================================"
|
||||
|
||||
IFS=',' read -ra platforms <<< "$(resolve_platforms "${d}")"
|
||||
for p in "${platforms[@]}"; do
|
||||
PKGMGR_DISTRO="${d}" bash "${SCRIPT_DIR}/image.sh" \
|
||||
--publish \
|
||||
--registry "${REGISTRY}" \
|
||||
--owner "${OWNER}" \
|
||||
--version "${VERSION}" \
|
||||
--platform "${p}"
|
||||
done
|
||||
|
||||
PKGMGR_DISTRO="${d}" bash "${SCRIPT_DIR}/image.sh" \
|
||||
--publish \
|
||||
--registry "${REGISTRY}" \
|
||||
--owner "${OWNER}" \
|
||||
--version "${VERSION}" \
|
||||
--stable "${IS_STABLE}"
|
||||
--aliases "${ALIASES}" \
|
||||
--merge
|
||||
done
|
||||
|
||||
echo
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
WORKFLOW_RUN_SHA="${WORKFLOW_RUN_SHA:?WORKFLOW_RUN_SHA must be set}"
|
||||
|
||||
git checkout -f "${WORKFLOW_RUN_SHA}"
|
||||
git fetch --tags --force
|
||||
git tag --list 'stable' 'v*' --sort=version:refname | tail -n 20
|
||||
@@ -1,23 +1,91 @@
|
||||
#!/usr/bin/env bash
|
||||
# Param: WORKFLOW_RUN_SHA commit the "Mark stable commit" run tagged; empty on a scheduled or
|
||||
# manual rebuild, which publishes the newest vX.Y.Z release on origin/main
|
||||
# and the release the git tag stable marks
|
||||
# Output: releases=<JSON list of {"sha", "version", "aliases"}> in GITHUB_OUTPUT; aliases are the
|
||||
# moving tags a release takes besides <version> and <version>.<unix-ts>
|
||||
set -euo pipefail
|
||||
|
||||
SHA="$(git rev-parse HEAD)"
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
V_TAG="$(git tag --points-at "${SHA}" --list 'v*' | sort -V | tail -n1)"
|
||||
if [[ -z "${V_TAG}" ]]; then
|
||||
echo "No version tag found for ${SHA}. Skipping publish."
|
||||
echo "should_publish=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
# shellcheck source=scripts/build/base.sh
|
||||
source "${SCRIPT_DIR}/../../build/base.sh"
|
||||
|
||||
: "${WORKFLOW_RUN_SHA?WORKFLOW_RUN_SHA must be set, empty for a rebuild}"
|
||||
: "${GITHUB_OUTPUT:?GITHUB_OUTPUT must be set}"
|
||||
|
||||
RELEASE_TAG='^v[0-9]+\.[0-9]+\.[0-9]+$'
|
||||
|
||||
release_at() {
|
||||
local listed tag
|
||||
listed="$(git tag --points-at "$1" --sort=-v:refname)"
|
||||
tag="$(grep -m1 -E "${RELEASE_TAG}" <<< "${listed}" || true)"
|
||||
echo "${tag#v}"
|
||||
}
|
||||
|
||||
newest_of() {
|
||||
local prefix="$1" version
|
||||
for version in "${RELEASES[@]}"; do
|
||||
if [[ "${version}." == "${prefix}."* ]]; then
|
||||
echo "${version}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
aliases_of() {
|
||||
local version="$1" prefix
|
||||
local -a aliases=()
|
||||
if [[ "${version}" == "${RELEASES[0]}" ]]; then
|
||||
aliases+=(latest)
|
||||
fi
|
||||
while read -r prefix; do
|
||||
if [[ "${prefix}" != "${version}" && "$(newest_of "${prefix}")" == "${version}" ]]; then
|
||||
aliases+=("${prefix}")
|
||||
fi
|
||||
done < <(version_prefixes "${version}")
|
||||
if [[ "${version}" == "${STABLE}" ]]; then
|
||||
aliases+=(stable)
|
||||
fi
|
||||
echo "${aliases[*]}"
|
||||
}
|
||||
|
||||
listed="$(git tag --merged origin/main --sort=-v:refname)"
|
||||
mapfile -t tags < <(grep -E "${RELEASE_TAG}" <<< "${listed}")
|
||||
RELEASES=("${tags[@]#v}")
|
||||
|
||||
STABLE=""
|
||||
stable_sha="$(git rev-parse -q --verify 'refs/tags/stable^{commit}' || true)"
|
||||
if [[ -n "${stable_sha}" ]]; then
|
||||
STABLE="$(release_at "${stable_sha}")"
|
||||
fi
|
||||
|
||||
VERSION="${V_TAG#v}"
|
||||
targets=()
|
||||
if [[ -n "${WORKFLOW_RUN_SHA}" ]]; then
|
||||
version="$(release_at "${WORKFLOW_RUN_SHA}")"
|
||||
if ! git merge-base --is-ancestor "${WORKFLOW_RUN_SHA}" origin/main; then
|
||||
echo "${WORKFLOW_RUN_SHA} is not on origin/main. Skipping publish."
|
||||
elif [[ -z "${version}" ]]; then
|
||||
echo "No vX.Y.Z tag found for ${WORKFLOW_RUN_SHA}. Skipping publish."
|
||||
else
|
||||
targets+=("${version}")
|
||||
fi
|
||||
else
|
||||
((${#RELEASES[@]} > 0)) || { echo "No vX.Y.Z tag is reachable from origin/main." >&2; exit 1; }
|
||||
targets+=("${RELEASES[0]}")
|
||||
if [[ -z "${STABLE}" ]]; then
|
||||
echo "The git tag stable marks no vX.Y.Z release; the stable image stays where it is."
|
||||
elif [[ "${STABLE}" != "${RELEASES[0]}" ]]; then
|
||||
targets+=("${STABLE}")
|
||||
fi
|
||||
fi
|
||||
|
||||
STABLE_SHA="$(git rev-parse -q --verify 'refs/tags/stable^{commit}' 2>/dev/null || true)"
|
||||
IS_STABLE=false
|
||||
[[ -n "${STABLE_SHA}" && "${STABLE_SHA}" == "${SHA}" ]] && IS_STABLE=true
|
||||
json=""
|
||||
for version in "${targets[@]}"; do
|
||||
sha="$(git rev-parse "v${version}^{commit}")"
|
||||
moving="$(aliases_of "${version}")"
|
||||
echo "Publishing ${version} at ${sha}, moving: ${moving}"
|
||||
json+="${json:+,}{\"sha\":\"${sha}\",\"version\":\"${version}\",\"aliases\":\"${moving}\"}"
|
||||
done
|
||||
|
||||
{
|
||||
echo "should_publish=true"
|
||||
echo "version=${VERSION}"
|
||||
echo "is_stable=${IS_STABLE}"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
echo "releases=[${json}]" >> "${GITHUB_OUTPUT}"
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
: "${OWNER:?OWNER must be set}"
|
||||
: "${VERSION:?VERSION must be set}"
|
||||
: "${ALIASES?ALIASES must be set, empty for none}"
|
||||
: "${PKGMGR_DISTRO:?PKGMGR_DISTRO must be set}"
|
||||
|
||||
bash scripts/build/image.sh \
|
||||
--publish \
|
||||
--registry ghcr.io \
|
||||
--owner "${OWNER}" \
|
||||
--version "${VERSION}" \
|
||||
--aliases "${ALIASES}" \
|
||||
--merge
|
||||
@@ -3,6 +3,12 @@ set -euo pipefail
|
||||
|
||||
: "${OWNER:?OWNER must be set}"
|
||||
: "${VERSION:?VERSION must be set}"
|
||||
: "${IS_STABLE:?IS_STABLE must be set}"
|
||||
: "${PKGMGR_DISTRO:?PKGMGR_DISTRO must be set}"
|
||||
: "${PLATFORM:?PLATFORM must be set}"
|
||||
|
||||
bash scripts/build/publish.sh
|
||||
bash scripts/build/image.sh \
|
||||
--publish \
|
||||
--registry ghcr.io \
|
||||
--owner "${OWNER}" \
|
||||
--version "${VERSION}" \
|
||||
--platform "${PLATFORM}"
|
||||
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
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd /opt/src/pkgmgr
|
||||
make setup-venv
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
||||
|
||||
pkgmgr version pkgmgr
|
||||
|
||||
export NIX_REMOTE=local
|
||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
git config --global --add safe.directory /opt/src/pkgmgr
|
||||
|
||||
make install
|
||||
make setup
|
||||
|
||||
# shellcheck source=/dev/null
|
||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
||||
|
||||
pkgmgr update pkgmgr --clone-mode shallow --no-verification
|
||||
pkgmgr version pkgmgr
|
||||
|
||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
mode="$1"
|
||||
distro="$2"
|
||||
|
||||
case "$mode" in
|
||||
root) volumes=(-v pkgmgr_repos:/root/Repositories -v pkgmgr_pip_cache:/root/.cache/pip) ;;
|
||||
user) volumes=() ;;
|
||||
*)
|
||||
echo "usage: $0 root|user <distro>" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
docker run --rm \
|
||||
-v "$PWD":/opt/src/pkgmgr \
|
||||
"${volumes[@]}" \
|
||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||
-w /opt/src/pkgmgr \
|
||||
"ghcr.io/kevinveenbirkenbach/base-${distro}:latest" \
|
||||
bash -l "scripts/test/virgin/${mode}.sh"
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
make install
|
||||
|
||||
useradd -m dev
|
||||
echo "dev ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dev
|
||||
chmod 0440 /etc/sudoers.d/dev
|
||||
chown -R dev:dev /opt/src/pkgmgr
|
||||
|
||||
mkdir -p /nix/store /nix/var/nix /nix/var/log/nix /nix/var/nix/profiles
|
||||
chown -R dev:dev /nix
|
||||
chmod 0755 /nix
|
||||
chmod 1777 /nix/store
|
||||
|
||||
sudo -H -u dev env \
|
||||
HOME=/home/dev \
|
||||
NIX_CONFIG="$NIX_CONFIG" \
|
||||
PKGMGR_DISABLE_NIX_FLAKE_INSTALLER=1 \
|
||||
bash -l /opt/src/pkgmgr/scripts/test/virgin/dev.sh
|
||||
@@ -4,10 +4,16 @@ Public API for branch actions.
|
||||
|
||||
from .close_branch import close_branch
|
||||
from .drop_branch import drop_branch
|
||||
from .gc import branch_purge, cleanup
|
||||
from .open_branch import open_branch
|
||||
from .tree import branch_tree, refresh_tree_entry
|
||||
|
||||
__all__ = [
|
||||
"branch_purge",
|
||||
"branch_tree",
|
||||
"cleanup",
|
||||
"close_branch",
|
||||
"drop_branch",
|
||||
"open_branch",
|
||||
"refresh_tree_entry",
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,127 @@
|
||||
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
|
||||
from pkgmgr.core.credentials.resolver import ResolutionOptions, TokenResolver
|
||||
from pkgmgr.core.credentials.types import CredentialError
|
||||
from pkgmgr.core.remote_provisioning.http.client import HttpClient
|
||||
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
|
||||
class ForgeFacts:
|
||||
"""
|
||||
Pull-request and protection facts of every GitHub remote of one repository.
|
||||
|
||||
Attributes:
|
||||
merged_heads: head SHA of a merged PR -> PR number.
|
||||
open_heads: head branch name of an open PR -> PR number.
|
||||
protected: branch names protected on any of the remotes.
|
||||
unavailable: why the facts could not be fetched, or None.
|
||||
"""
|
||||
|
||||
merged_heads: dict[str, int] = field(default_factory=dict)
|
||||
open_heads: dict[str, int] = field(default_factory=dict)
|
||||
protected: set[str] = field(default_factory=set)
|
||||
unavailable: str | None = None
|
||||
|
||||
|
||||
def github_slugs(remote_urls: dict[str, str]) -> list[tuple[str, str]]:
|
||||
slugs: list[tuple[str, str]] = []
|
||||
for url in remote_urls.values():
|
||||
host, owner, name = parse_repo_from_git_url(url)
|
||||
if (
|
||||
host.lower() == GITHUB_HOST
|
||||
and owner
|
||||
and name
|
||||
and (owner, name) not in slugs
|
||||
):
|
||||
slugs.append((owner, name))
|
||||
return slugs
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
batch = json.loads(resp.text or "[]")
|
||||
items.extend(batch)
|
||||
if len(batch) < PAGE_SIZE:
|
||||
return items
|
||||
page += 1
|
||||
|
||||
|
||||
def fetch_forge_facts(remote_urls: dict[str, str]) -> ForgeFacts:
|
||||
facts = ForgeFacts()
|
||||
slugs = github_slugs(remote_urls)
|
||||
if not slugs:
|
||||
return facts
|
||||
|
||||
try:
|
||||
token = (
|
||||
TokenResolver()
|
||||
.get_token(
|
||||
"github",
|
||||
GITHUB_HOST,
|
||||
options=ResolutionOptions(interactive=False, allow_prompt=False),
|
||||
)
|
||||
.token
|
||||
)
|
||||
except CredentialError as exc:
|
||||
facts.unavailable = f"no GitHub token ({exc})"
|
||||
return facts
|
||||
return facts_with_token(slugs, token)
|
||||
|
||||
|
||||
def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
|
||||
"""
|
||||
Fetch the pull-request and protection facts of GitHub repositories.
|
||||
|
||||
Args:
|
||||
slugs: (owner, name) of each repository.
|
||||
token: the GitHub token sent as bearer.
|
||||
|
||||
Returns:
|
||||
The facts, or facts whose unavailable names the failing repository.
|
||||
"""
|
||||
facts = ForgeFacts()
|
||||
http = HttpClient(timeout_s=TIMEOUT_S)
|
||||
deadline = time.monotonic() + BUDGET_S
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
"User-Agent": "pkgmgr",
|
||||
}
|
||||
for owner, name in slugs:
|
||||
base = f"{GITHUB_API}/repos/{owner}/{name}"
|
||||
try:
|
||||
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", deadline
|
||||
):
|
||||
facts.protected.add(branch["name"])
|
||||
except (HttpError, ValueError, KeyError, TypeError) as exc:
|
||||
return ForgeFacts(
|
||||
unavailable=f"GitHub API failed for {owner}/{name}: {exc}"
|
||||
)
|
||||
return facts
|
||||
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from pkgmgr.core.git import GitRunError, run
|
||||
|
||||
HELD_FILES = (
|
||||
("rebase-merge/head-name", "rebase in progress"),
|
||||
("rebase-merge/update-refs", "rebase in progress"),
|
||||
("rebase-apply/head-name", "rebase in progress"),
|
||||
("BISECT_START", "bisect in progress"),
|
||||
)
|
||||
|
||||
|
||||
def _git(args: list[str], cwd: str) -> str:
|
||||
return run(args, cwd=cwd, scan=True)
|
||||
|
||||
|
||||
def _common_dir(cwd: str) -> str:
|
||||
return _git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd)
|
||||
|
||||
|
||||
def _symbolic(repo_root: str, prefix: str, git_dir: str = "") -> dict[str, str]:
|
||||
args = ["for-each-ref", "--format=%(refname)%00%(symref)", prefix]
|
||||
out = _git([f"--git-dir={git_dir}", *args] if git_dir else args, repo_root)
|
||||
return dict(line.split("\x00", 1) for line in out.splitlines())
|
||||
|
||||
|
||||
def _worktree_heads(repo_root: str, git_dirs: list[str]) -> dict[str, str]:
|
||||
heads: dict[str, str] = {}
|
||||
for git_dir in git_dirs:
|
||||
try:
|
||||
target = _git(
|
||||
[f"--git-dir={git_dir}", "symbolic-ref", "--quiet", "HEAD"], repo_root
|
||||
)
|
||||
except GitRunError as exc:
|
||||
if exc.returncode == 1:
|
||||
continue
|
||||
raise
|
||||
if target.startswith("refs/heads/"):
|
||||
heads.setdefault(
|
||||
target.removeprefix("refs/heads/"), f"checked out in {git_dir}"
|
||||
)
|
||||
return heads
|
||||
|
||||
|
||||
def _git_dirs(repo_root: str) -> list[str]:
|
||||
common = _common_dir(repo_root)
|
||||
base = os.path.join(common, "worktrees")
|
||||
entries = sorted(os.listdir(base)) if os.path.isdir(base) else []
|
||||
return [common, *(os.path.join(base, entry) for entry in entries)]
|
||||
|
||||
|
||||
def _held_branches(repo_root: str) -> dict[str, str]:
|
||||
git_dirs = _git_dirs(repo_root)
|
||||
held: dict[str, str] = {}
|
||||
_symref_holds(repo_root, git_dirs, held)
|
||||
for branch, reason in _worktree_heads(repo_root, git_dirs).items():
|
||||
held.setdefault(branch, reason)
|
||||
for git_dir in git_dirs:
|
||||
_state_file_holds(git_dir, held)
|
||||
return held
|
||||
|
||||
|
||||
def _symref_holds(repo_root: str, git_dirs: list[str], held: dict[str, str]) -> None:
|
||||
symrefs = _symbolic(repo_root, "refs", git_dirs[0])
|
||||
for git_dir in git_dirs[1:]:
|
||||
for ref, target in _symbolic(repo_root, "refs/worktree", git_dir).items():
|
||||
symrefs[f"worktrees/{os.path.basename(git_dir)}/{ref}"] = target
|
||||
for ref, target in symrefs.items():
|
||||
if target and ref.startswith("refs/heads/"):
|
||||
held.setdefault(
|
||||
ref.removeprefix("refs/heads/"), f"symbolic ref to {target}"
|
||||
)
|
||||
if target.startswith("refs/heads/"):
|
||||
held.setdefault(
|
||||
target.removeprefix("refs/heads/"), f"target of symbolic ref {ref}"
|
||||
)
|
||||
|
||||
|
||||
def _state_file_holds(git_dir: str, held: dict[str, str]) -> None:
|
||||
for name, operation in HELD_FILES:
|
||||
try:
|
||||
with open(os.path.join(git_dir, name), encoding="utf-8") as fh:
|
||||
lines = fh.read().splitlines()
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
for line in lines:
|
||||
ref = line.strip().removeprefix("ref: ")
|
||||
if ref.startswith("refs/heads/") or name == "BISECT_START":
|
||||
held.setdefault(
|
||||
ref.removeprefix("refs/heads/"), f"{operation} in {git_dir}"
|
||||
)
|
||||
@@ -0,0 +1,44 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
|
||||
DIR_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
|
||||
|
||||
def canonical(path: str) -> bool:
|
||||
"""
|
||||
Args:
|
||||
path: a path as git or a plan names it.
|
||||
|
||||
Returns:
|
||||
True when path is absolute and already its own realpath: no symbolic
|
||||
link and no `..` component that the kernel could resolve elsewhere.
|
||||
"""
|
||||
return os.path.isabs(path) and os.path.realpath(path) == path
|
||||
|
||||
|
||||
def remove_tree(path: str) -> None:
|
||||
"""
|
||||
Delete a directory tree without following a symbolic link anywhere on
|
||||
the way to it, even one swapped in after the caller checked the path.
|
||||
|
||||
Args:
|
||||
path: absolute, canonical directory to delete.
|
||||
|
||||
Raises:
|
||||
OSError: a component of path is a symbolic link or missing, or the
|
||||
deletion failed.
|
||||
"""
|
||||
parent, name = os.path.split(path)
|
||||
fd = os.open(os.sep, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
for component in [c for c in parent.split(os.sep) if c]:
|
||||
child = os.open(component, DIR_FLAGS, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
# Trip-wire: rmtree(dir_fd=) needs Python 3.11; the fd link pins the
|
||||
# opened parent on every version, and rmtree refuses a symlinked name.
|
||||
shutil.rmtree(f"/proc/self/fd/{fd}/{name}")
|
||||
finally:
|
||||
os.close(fd)
|
||||
@@ -0,0 +1,377 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import yaml
|
||||
|
||||
from pkgmgr.actions.worktree import flow
|
||||
from pkgmgr.core.credentials.store_keys import build_keyring_key
|
||||
from pkgmgr.core.git.errors import GitBaseError
|
||||
|
||||
from . import gc
|
||||
from .gc_forge import GITHUB_HOST, ForgeFacts, facts_with_token, github_slugs
|
||||
|
||||
WORKTREES_ROOT = os.path.join(
|
||||
os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"),
|
||||
"worktrees",
|
||||
)
|
||||
WORKTREE_DEPTH = 6
|
||||
CACHE_TTL = 600
|
||||
SLUG = re.compile(r"^(?!\.\.?$)[\w.-]+$")
|
||||
|
||||
|
||||
def now() -> float:
|
||||
return time.time()
|
||||
|
||||
|
||||
def _iso(stamp: float) -> str:
|
||||
return datetime.fromtimestamp(stamp, timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def tree_file() -> str:
|
||||
state = os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state")
|
||||
return os.environ.get("PKGMGR_TREE_FILE") or os.path.join(
|
||||
state, "pkgmgr", "tree", "branch-tree.json"
|
||||
)
|
||||
|
||||
|
||||
def _cache_path(owner: str, name: str) -> str:
|
||||
base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
|
||||
return os.path.join(base, "pkgmgr", "forge", owner, f"{name}.json")
|
||||
|
||||
|
||||
class SecretServiceUnavailable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _secret_service_token() -> str:
|
||||
try:
|
||||
import secretstorage
|
||||
except ImportError as exc:
|
||||
raise SecretServiceUnavailable("secretstorage not installed") from exc
|
||||
key = build_keyring_key("github", GITHUB_HOST, None)
|
||||
try:
|
||||
connection = secretstorage.dbus_init()
|
||||
try:
|
||||
items = list(
|
||||
secretstorage.search_items(
|
||||
connection, {"service": key.service, "username": key.username}
|
||||
)
|
||||
)
|
||||
unlocked = [item for item in items if not item.is_locked()]
|
||||
if not items:
|
||||
raise SecretServiceUnavailable("no GitHub token in the Secret Service")
|
||||
if not unlocked:
|
||||
raise SecretServiceUnavailable("Secret Service locked")
|
||||
return unlocked[0].get_secret().decode()
|
||||
finally:
|
||||
connection.close()
|
||||
except (secretstorage.exceptions.SecretStorageException, OSError) as 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
|
||||
def _locked(path: str) -> Iterator[None]:
|
||||
folder, name = os.path.split(os.path.abspath(path))
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
with open(os.path.join(folder, f".{name}.lock"), "w", encoding="utf-8") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def _replace(path: str, text: str) -> None:
|
||||
folder, name = os.path.split(os.path.abspath(path))
|
||||
fd, tmp = tempfile.mkstemp(dir=folder, prefix=f".{name}.")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
fh.write(text)
|
||||
fh.flush()
|
||||
os.fsync(fh.fileno())
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
|
||||
|
||||
def _write(path: str, text: str) -> None:
|
||||
with _locked(path):
|
||||
_replace(path, text)
|
||||
|
||||
|
||||
def _cached(path: str) -> ForgeFacts | None:
|
||||
try:
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
if now() - data["fetched_at"] >= CACHE_TTL:
|
||||
return None
|
||||
return ForgeFacts(
|
||||
merged_heads=data["merged_heads"],
|
||||
open_heads=data["open_heads"],
|
||||
protected=set(data["protected"]),
|
||||
)
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _store(path: str, facts: ForgeFacts) -> None:
|
||||
data = {
|
||||
"fetched_at": now(),
|
||||
"merged_heads": facts.merged_heads,
|
||||
"open_heads": facts.open_heads,
|
||||
"protected": sorted(facts.protected),
|
||||
}
|
||||
_write(path, json.dumps(data))
|
||||
|
||||
|
||||
def _unavailable(reason: str | None) -> tuple[ForgeFacts, str]:
|
||||
return ForgeFacts(unavailable=reason), f"unavailable: {reason}"
|
||||
|
||||
|
||||
def forge_facts(
|
||||
urls: dict[str, str], token: str | None, reason: str | None
|
||||
) -> tuple[ForgeFacts, str]:
|
||||
"""
|
||||
Forge facts of one repository from the cache, or live once the cache is stale.
|
||||
|
||||
Args:
|
||||
urls: remote name -> URL.
|
||||
token: GitHub token from the Secret Service, or None.
|
||||
reason: why the token is None.
|
||||
|
||||
Returns:
|
||||
The facts and their source: none, cached, live or unavailable: <why>.
|
||||
"""
|
||||
slugs = github_slugs(urls)
|
||||
if not slugs:
|
||||
return ForgeFacts(), "none"
|
||||
invalid = [f"{o}/{n}" for o, n in slugs if not (SLUG.match(o) and SLUG.match(n))]
|
||||
if invalid:
|
||||
return _unavailable(f"invalid GitHub slug {invalid[0]}")
|
||||
merged, label = ForgeFacts(), "cached"
|
||||
for owner, name in slugs:
|
||||
path = _cache_path(owner, name)
|
||||
facts = _cached(path)
|
||||
if facts is None:
|
||||
if token is None:
|
||||
return _unavailable(reason)
|
||||
facts = facts_with_token([(owner, name)], token)
|
||||
if facts.unavailable:
|
||||
return _unavailable(facts.unavailable)
|
||||
try:
|
||||
_store(path, facts)
|
||||
label = "live" if label == "cached" else label
|
||||
except OSError as exc:
|
||||
label = f"live: cache not written ({exc})"
|
||||
merged.merged_heads.update(facts.merged_heads)
|
||||
merged.open_heads.update(facts.open_heads)
|
||||
merged.protected |= facts.protected
|
||||
return merged, label
|
||||
|
||||
|
||||
def _missing(root: str, known: bool, scanned_at: str) -> dict:
|
||||
return {
|
||||
"path": root,
|
||||
"remote": None,
|
||||
"default": None,
|
||||
"missing": True,
|
||||
"known": known,
|
||||
"forge": None,
|
||||
"scanned_at": scanned_at,
|
||||
"warnings": [],
|
||||
"items": [],
|
||||
}
|
||||
|
||||
|
||||
def _git_dir(
|
||||
root: str, registrations: gc.Registrations, worktree: str | None
|
||||
) -> str | None:
|
||||
if worktree is None:
|
||||
return None
|
||||
if worktree == root:
|
||||
return os.path.dirname(registrations[0])
|
||||
return gc._linked_meta(registrations, worktree)
|
||||
|
||||
|
||||
def _flow(git_dir: str | None, item: dict, warnings: list[str]) -> dict | None:
|
||||
found = flow.read_flow(git_dir) if git_dir else None
|
||||
if found is None or found.source == "none":
|
||||
return None
|
||||
warnings += [
|
||||
f"flow of {item['worktree']}: {warning}"
|
||||
for warning in found.warnings + flow.mismatch(found, item["branch"])
|
||||
]
|
||||
return {"pull": found.pull, "push": found.push, "source": found.source}
|
||||
|
||||
|
||||
def _scan(
|
||||
root: str,
|
||||
known: bool,
|
||||
token: str | None,
|
||||
reason: str | None,
|
||||
containers: list[gc.Container] | None,
|
||||
host_ns: bool,
|
||||
) -> dict:
|
||||
scanned_at = _iso(now())
|
||||
entry = _missing(root, known, scanned_at)
|
||||
if not os.path.exists(os.path.join(root, ".git")):
|
||||
return entry
|
||||
sources: list[str] = []
|
||||
|
||||
def source(urls: dict[str, str]) -> ForgeFacts:
|
||||
facts, label = forge_facts(urls, token, reason)
|
||||
sources.append(label)
|
||||
return facts
|
||||
|
||||
entry["missing"] = False
|
||||
try:
|
||||
repo = gc.plan_repo(
|
||||
root,
|
||||
containers,
|
||||
host_ns,
|
||||
merged_into=[],
|
||||
sizes=False,
|
||||
min_age=None,
|
||||
scope="all",
|
||||
activity=True,
|
||||
hooks={},
|
||||
fetch=False,
|
||||
forge_source=source,
|
||||
)
|
||||
registrations = gc._registrations(root)
|
||||
except GitBaseError as exc:
|
||||
entry["warnings"] = [f"scan failed: {str(exc).strip().splitlines()[0]}"]
|
||||
return entry
|
||||
owner = next((r for r in repo.remotes if repo.default.startswith(f"{r}/")), None)
|
||||
items = [asdict(item) for item in repo.items]
|
||||
for item in items:
|
||||
git_dir = _git_dir(root, registrations, item["worktree"])
|
||||
item["flow"] = _flow(git_dir, item, repo.warnings)
|
||||
entry.update(
|
||||
remote=repo.urls[repo.remotes[0]] if repo.remotes else None,
|
||||
default=repo.default.removeprefix(f"{owner}/") if owner else repo.default,
|
||||
forge=sources[0],
|
||||
warnings=repo.warnings,
|
||||
items=items,
|
||||
)
|
||||
return entry
|
||||
|
||||
|
||||
def _owner_root(checkout: str) -> str | None:
|
||||
try:
|
||||
with open(os.path.join(checkout, ".git"), encoding="utf-8") as fh:
|
||||
gitdir = fh.read().strip().removeprefix("gitdir: ")
|
||||
except OSError:
|
||||
return None
|
||||
parent = os.path.dirname(os.path.realpath(os.path.join(checkout, gitdir)))
|
||||
if os.path.basename(parent) != "worktrees":
|
||||
return None
|
||||
common = os.path.dirname(parent)
|
||||
return os.path.dirname(common) if os.path.basename(common) == ".git" else common
|
||||
|
||||
|
||||
def _shared_owners(worktrees_root: str) -> list[str]:
|
||||
owners: set[str] = set()
|
||||
base = worktrees_root.rstrip("/").count("/")
|
||||
for path, dirs, files in os.walk(worktrees_root):
|
||||
dirs.sort()
|
||||
owner = _owner_root(path) if ".git" in files else None
|
||||
if owner:
|
||||
owners.add(owner)
|
||||
if (
|
||||
".git" in files
|
||||
or ".git" in dirs
|
||||
or path.count("/") - base >= WORKTREE_DEPTH
|
||||
):
|
||||
dirs.clear()
|
||||
return sorted(owners)
|
||||
|
||||
|
||||
def branch_tree(
|
||||
repo_dirs: list[str], *, fmt: str, output: str | None, worktrees_root: str
|
||||
) -> int:
|
||||
"""
|
||||
Print or write the branch and worktree state of every repository, without fetching.
|
||||
|
||||
Args:
|
||||
repo_dirs: directories of the repositories pkgmgr knows.
|
||||
fmt: json or yaml.
|
||||
output: file to write atomically; None prints to stdout.
|
||||
worktrees_root: shared worktree root whose unknown owners are added.
|
||||
|
||||
Returns:
|
||||
0 on success, 1 when the output could not be written.
|
||||
"""
|
||||
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 = _forge_access()
|
||||
host_ns = gc.host_pid_namespace()
|
||||
containers = gc.list_compose_containers()
|
||||
data = {
|
||||
"generated_at": _iso(now()),
|
||||
"host_pid_namespace": host_ns,
|
||||
"delete_ready": token is not None,
|
||||
"delete_reason": reason,
|
||||
"repos": [
|
||||
_scan(root, root in known, token, reason, containers, host_ns)
|
||||
for root in known + orphans
|
||||
],
|
||||
}
|
||||
text = (
|
||||
yaml.safe_dump(data, sort_keys=False)
|
||||
if fmt == "yaml"
|
||||
else json.dumps(data, indent=2) + "\n"
|
||||
)
|
||||
if output is None:
|
||||
sys.stdout.write(text)
|
||||
return 0
|
||||
try:
|
||||
_write(output, text)
|
||||
except OSError as exc:
|
||||
print(f"Cannot write {output}: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
def refresh_tree_entry(repo_root: str) -> None:
|
||||
"""
|
||||
Rescan one repository into the tree file, if the file exists and holds it.
|
||||
|
||||
Args:
|
||||
repo_root: main worktree root of the repository.
|
||||
|
||||
Skipped outside the host PID namespace and when the file's entry is newer.
|
||||
"""
|
||||
path = tree_file()
|
||||
if not os.path.isfile(path) or not gc.host_pid_namespace():
|
||||
return
|
||||
root = os.path.realpath(repo_root)
|
||||
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:
|
||||
data = json.load(fh)
|
||||
index = next(
|
||||
(i for i, entry in enumerate(data["repos"]) if entry["path"] == root), None
|
||||
)
|
||||
if index is None or data["repos"][index]["scanned_at"] > fresh["scanned_at"]:
|
||||
return
|
||||
fresh["known"] = data["repos"][index]["known"]
|
||||
data["repos"][index] = fresh
|
||||
_replace(path, json.dumps(data, indent=2) + "\n")
|
||||
Whitespace-only changes.
@@ -0,0 +1,4 @@
|
||||
from .render import render_text
|
||||
from .report import disk_report
|
||||
|
||||
__all__ = ["disk_report", "render_text"]
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from pkgmgr.actions.branch.gc import _inside
|
||||
|
||||
|
||||
def _mount(path: str) -> str:
|
||||
path = os.path.realpath(path)
|
||||
while not os.path.ismount(path):
|
||||
path = os.path.dirname(path)
|
||||
return path
|
||||
|
||||
|
||||
def balance(paths: list[str], items: list[tuple[str, int]]) -> list[dict]:
|
||||
"""
|
||||
Set what the report attributes against each filesystem's capacity.
|
||||
|
||||
Args:
|
||||
paths: the roots and repository roots; each one's filesystem gets a row.
|
||||
items: (path, allocated bytes) of every listed entry; an entry inside
|
||||
another listed entry is counted only through the outer one.
|
||||
|
||||
Returns:
|
||||
Per filesystem (grouped by st_dev): its mount point, total and free
|
||||
bytes (as available to unprivileged users) and the attributed bytes.
|
||||
"""
|
||||
filesystems: dict[int, dict] = {}
|
||||
for path in paths:
|
||||
try:
|
||||
dev = os.stat(path).st_dev
|
||||
if dev in filesystems:
|
||||
continue
|
||||
vfs = os.statvfs(path)
|
||||
except OSError:
|
||||
continue
|
||||
filesystems[dev] = {
|
||||
"filesystem": _mount(path),
|
||||
"total_bytes": vfs.f_blocks * vfs.f_frsize,
|
||||
"free_bytes": vfs.f_bavail * vfs.f_frsize,
|
||||
"attributed_bytes": 0,
|
||||
}
|
||||
kept: list[str] = []
|
||||
for path, size in sorted((os.path.realpath(p), s) for p, s in items):
|
||||
if any(_inside(path, outer) for outer in kept):
|
||||
continue
|
||||
kept.append(path)
|
||||
try:
|
||||
dev = os.lstat(path).st_dev
|
||||
except OSError:
|
||||
continue
|
||||
if dev in filesystems:
|
||||
filesystems[dev]["attributed_bytes"] += size
|
||||
return sorted(filesystems.values(), key=lambda fs: fs["filesystem"])
|
||||
@@ -0,0 +1,58 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from .walk import BLOCK
|
||||
|
||||
ELF_MAGIC = b"\x7fELF"
|
||||
ELF_HEADER = 18
|
||||
ET_CORE = 4
|
||||
BYTE_ORDER = {1: "little", 2: "big"}
|
||||
|
||||
|
||||
def is_core_dump(path: str) -> bool:
|
||||
try:
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
||||
except OSError:
|
||||
return False
|
||||
try:
|
||||
head = os.read(fd, ELF_HEADER)
|
||||
except OSError:
|
||||
return False
|
||||
finally:
|
||||
os.close(fd)
|
||||
order = BYTE_ORDER.get(head[5]) if len(head) == ELF_HEADER else None
|
||||
return (
|
||||
head[:4] == ELF_MAGIC
|
||||
and order is not None
|
||||
and int.from_bytes(head[16:18], order) == ET_CORE
|
||||
)
|
||||
|
||||
|
||||
def core_dumps(candidates: list[str]) -> list[dict]:
|
||||
"""
|
||||
Keep the candidates whose ELF header says ET_CORE.
|
||||
|
||||
Args:
|
||||
candidates: paths of regular files named like core dumps.
|
||||
|
||||
Returns:
|
||||
One entry per dump with its allocated and apparent size and mtime,
|
||||
biggest first.
|
||||
"""
|
||||
dumps: dict[str, dict] = {}
|
||||
for path in candidates:
|
||||
real = os.path.realpath(path)
|
||||
if real in dumps or not is_core_dump(path):
|
||||
continue
|
||||
try:
|
||||
st = os.lstat(path)
|
||||
except OSError:
|
||||
continue
|
||||
dumps[real] = {
|
||||
"path": path,
|
||||
"size_bytes": st.st_blocks * BLOCK,
|
||||
"apparent_bytes": st.st_size,
|
||||
"mtime": st.st_mtime,
|
||||
}
|
||||
return sorted(dumps.values(), key=lambda d: (-d["size_bytes"], d["path"]))
|
||||
@@ -0,0 +1,50 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from pkgmgr.actions.branch.gc import _describe, _docker
|
||||
|
||||
DF_ARGS = ["system", "df", "--format", "{{json .}}"]
|
||||
|
||||
|
||||
def _count(value: object) -> int | None:
|
||||
text = str(value)
|
||||
return int(text) if text.isdigit() else None
|
||||
|
||||
|
||||
def docker_usage() -> tuple[list[dict] | None, str | None]:
|
||||
"""
|
||||
Read `docker system df` per type.
|
||||
|
||||
Returns:
|
||||
The rows (type, total and active counts, size and reclaimable as docker
|
||||
prints them) and None, or None and a warning when docker is missing,
|
||||
fails or prints something else than JSON lines.
|
||||
"""
|
||||
try:
|
||||
out = _docker(DF_ARGS)
|
||||
except FileNotFoundError:
|
||||
return None, "docker unavailable: not installed"
|
||||
except subprocess.CalledProcessError as exc:
|
||||
return None, f"docker unavailable: {_describe(exc)}"
|
||||
rows: list[dict] = []
|
||||
for line in out.splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
data = json.loads(line)
|
||||
except ValueError:
|
||||
data = None
|
||||
if not isinstance(data, dict):
|
||||
return None, "docker system df: output is not JSON lines"
|
||||
rows.append(
|
||||
{
|
||||
"type": data.get("Type"),
|
||||
"total": _count(data.get("TotalCount")),
|
||||
"active": _count(data.get("Active")),
|
||||
"size": data.get("Size"),
|
||||
"reclaimable": data.get("Reclaimable"),
|
||||
}
|
||||
)
|
||||
return rows, None
|
||||
@@ -0,0 +1,186 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import stat
|
||||
|
||||
from pkgmgr.actions.branch.gc import _describe, _git, _has_submodules
|
||||
from pkgmgr.core.git.errors import GitBaseError
|
||||
from pkgmgr.core.git.queries import FILTER_CONFIG, local_config
|
||||
from pkgmgr.core.git.run import run
|
||||
|
||||
REF_NAMESPACES = ("refs/heads", "refs/remotes", "refs/tags")
|
||||
PEELED = "%(if)%(*objectname)%(then)%(*objectname)%(else)%(objectname)%(end)"
|
||||
UNMERGED = "unmerged"
|
||||
DELETED = "deleted"
|
||||
DIRECTORY = "directory"
|
||||
SPECIAL = "special"
|
||||
UNHASHABLE = {
|
||||
DIRECTORY: "untracked directory or gitlink",
|
||||
SPECIAL: "not a regular file",
|
||||
}
|
||||
MAX_REASONS = 5
|
||||
|
||||
|
||||
def _tips(repo: str) -> list[str]:
|
||||
out = _git(["for-each-ref", f"--format={PEELED}", *REF_NAMESPACES], repo)
|
||||
return sorted(set(out.split()))
|
||||
|
||||
|
||||
def _status_entries(tree: str) -> list[tuple[str, str | None]]:
|
||||
raw = _git(
|
||||
[
|
||||
"status",
|
||||
"--porcelain=v2",
|
||||
"-z",
|
||||
"--untracked-files=all",
|
||||
"--no-renames",
|
||||
],
|
||||
tree,
|
||||
)
|
||||
entries: list[tuple[str, str | None]] = []
|
||||
for record in raw.split("\0"):
|
||||
kind = record[:1]
|
||||
if kind == "1":
|
||||
parts = record.split(" ", 8)
|
||||
entries.append((parts[8], parts[7]))
|
||||
elif kind == "u":
|
||||
entries.append((record.split(" ", 10)[10], UNMERGED))
|
||||
elif kind == "?":
|
||||
entries.append((record[2:], None))
|
||||
return entries
|
||||
|
||||
|
||||
def _hashes(tree: str, paths: list[str]) -> dict[str, str]:
|
||||
hashes: dict[str, str] = {}
|
||||
files: list[str] = []
|
||||
for path in paths:
|
||||
full = os.path.join(tree, path)
|
||||
try:
|
||||
mode = os.lstat(full).st_mode
|
||||
except FileNotFoundError:
|
||||
hashes[path] = DELETED
|
||||
continue
|
||||
if stat.S_ISREG(mode):
|
||||
files.append(path)
|
||||
elif stat.S_ISLNK(mode):
|
||||
hashes[path] = run(
|
||||
["hash-object", "-t", "blob", "--no-filters", "--stdin"],
|
||||
cwd=tree,
|
||||
scan=True,
|
||||
input_text=os.readlink(full),
|
||||
)
|
||||
else:
|
||||
hashes[path] = DIRECTORY if stat.S_ISDIR(mode) else SPECIAL
|
||||
if files:
|
||||
out = run(
|
||||
["hash-object", "--no-filters", "--stdin-paths"],
|
||||
cwd=tree,
|
||||
scan=True,
|
||||
input_text="".join(f"{path}\n" for path in files),
|
||||
)
|
||||
hashes.update(zip(files, out.split("\n")))
|
||||
return hashes
|
||||
|
||||
|
||||
def _absent(
|
||||
repo: str, tips: list[str], wanted: list[tuple[str, set[str]]]
|
||||
) -> list[str]:
|
||||
query = "".join(f"{tip}:{path}\n" for path, _ in wanted for tip in tips)
|
||||
if not query:
|
||||
return [path for path, _ in wanted]
|
||||
found = run(
|
||||
["cat-file", "--batch-check=%(objectname)"],
|
||||
cwd=repo,
|
||||
scan=True,
|
||||
input_text=query,
|
||||
).split("\n")
|
||||
width = len(tips)
|
||||
return [
|
||||
path
|
||||
for index, (path, blobs) in enumerate(wanted)
|
||||
if blobs - set(found[index * width : (index + 1) * width])
|
||||
]
|
||||
|
||||
|
||||
def _reachable(repo: str, head: str | None) -> bool:
|
||||
if not head:
|
||||
return False
|
||||
return bool(
|
||||
_git(["for-each-ref", "--count=1", f"--contains={head}", *REF_NAMESPACES], repo)
|
||||
)
|
||||
|
||||
|
||||
def _unpreserved(
|
||||
repo: str, record: dict, tips: list[str]
|
||||
) -> tuple[int | None, list[str]]:
|
||||
tree = record["path"]
|
||||
if _has_submodules(tree):
|
||||
return None, ["submodules, whose config the scan cannot vet"]
|
||||
unsafe = local_config(tree, FILTER_CONFIG)
|
||||
if unsafe:
|
||||
return None, [f"{', '.join(unsafe)} in the repository config"]
|
||||
entries = _status_entries(tree)
|
||||
reasons: list[str] = []
|
||||
if entries and record["branch"] is None and not _reachable(repo, record["head"]):
|
||||
reasons.append("detached HEAD reachable from no ref")
|
||||
hashable: list[tuple[str, str | None]] = []
|
||||
for path, index_blob in entries:
|
||||
if "\n" in path:
|
||||
reasons.append(f"{path!r}: path with a newline")
|
||||
elif index_blob == UNMERGED:
|
||||
reasons.append(f"{path}: unmerged")
|
||||
else:
|
||||
hashable.append((path, index_blob))
|
||||
hashes = _hashes(tree, [path for path, _ in hashable])
|
||||
wanted: list[tuple[str, set[str]]] = []
|
||||
for path, index_blob in hashable:
|
||||
current = hashes[path]
|
||||
if current in UNHASHABLE:
|
||||
reasons.append(f"{path}: {UNHASHABLE[current]}")
|
||||
continue
|
||||
blobs = {current} - {DELETED}
|
||||
if index_blob and set(index_blob) != {"0"}:
|
||||
blobs.add(index_blob)
|
||||
if blobs:
|
||||
wanted.append((path, blobs))
|
||||
reasons += [f"{path}: content in no ref" for path in _absent(repo, tips, wanted)]
|
||||
return len(entries), reasons
|
||||
|
||||
|
||||
def preserved(repo: str, records: list[dict]) -> list[dict]:
|
||||
"""
|
||||
Decide for each dirty worktree whether all its work survives its deletion.
|
||||
|
||||
Args:
|
||||
repo: main worktree root of the repository.
|
||||
records: its worktree records from list_worktrees.
|
||||
|
||||
Returns:
|
||||
One entry per dirty or unreadable worktree; `preserved` is true only
|
||||
when every changed, staged and untracked file's content is a blob at
|
||||
the same path of some branch, remote or tag tip, and a detached HEAD is
|
||||
reachable from a ref. `reasons` lists what is not, capped.
|
||||
"""
|
||||
live = [r for r in records if not r["orphaned"] and not r["missing"]]
|
||||
tips = _tips(repo) if live else []
|
||||
results: list[dict] = []
|
||||
for record in live:
|
||||
try:
|
||||
paths, reasons = _unpreserved(repo, record, tips)
|
||||
except (GitBaseError, OSError, UnicodeError) as exc:
|
||||
paths, reasons = None, [f"status failed: {_describe(exc)}"]
|
||||
if paths == 0:
|
||||
continue
|
||||
extra = len(reasons) - MAX_REASONS
|
||||
results.append(
|
||||
{
|
||||
"repo": repo,
|
||||
"path": record["path"],
|
||||
"branch": record["branch"],
|
||||
"paths": paths,
|
||||
"preserved": not reasons,
|
||||
"reasons": reasons[:MAX_REASONS]
|
||||
+ ([f"... {extra} more"] if extra > 0 else []),
|
||||
}
|
||||
)
|
||||
return results
|
||||
@@ -0,0 +1,132 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pkgmgr.actions.branch.gc import human_size
|
||||
|
||||
UNITS = (("d", 86400), ("h", 3600), ("m", 60))
|
||||
DOCKER_COLUMNS = ("type", "total", "active", "size", "reclaimable")
|
||||
|
||||
|
||||
def _size(value: int | None) -> str:
|
||||
return "-" if value is None else human_size(value)
|
||||
|
||||
|
||||
def _age(now: float, stamp: float | None) -> str:
|
||||
if not stamp:
|
||||
return "-"
|
||||
seconds = max(0.0, now - stamp)
|
||||
for unit, length in UNITS:
|
||||
if seconds >= length:
|
||||
return f"{seconds / length:.1f}{unit}"
|
||||
return f"{seconds:.0f}s"
|
||||
|
||||
|
||||
def _section(title: str, headers: list[str], rows: list[list[str]]) -> list[str]:
|
||||
if not rows:
|
||||
return [f"== {title}", "(none)"]
|
||||
widths = [max(len(cell) for cell in column) for column in zip(headers, *rows)]
|
||||
return [f"== {title}"] + [
|
||||
" ".join(cell.ljust(width) for cell, width in zip(row, widths)).rstrip()
|
||||
for row in (headers, *rows)
|
||||
]
|
||||
|
||||
|
||||
def _branch(tree: dict) -> str:
|
||||
if tree["orphaned"]:
|
||||
return "-"
|
||||
return tree["branch"] or "(detached)"
|
||||
|
||||
|
||||
def _state(tree: dict) -> str:
|
||||
if tree["orphaned"]:
|
||||
return "orphaned"
|
||||
return "missing" if tree["missing"] else "linked"
|
||||
|
||||
|
||||
def render_text(report: dict) -> str:
|
||||
"""
|
||||
Render a disk_report result as aligned text tables.
|
||||
|
||||
Args:
|
||||
report: the dict disk_report returned.
|
||||
|
||||
Returns:
|
||||
The tables, one section per report key, newline-joined.
|
||||
"""
|
||||
now = report["generated_at"]
|
||||
lines = _section(
|
||||
"worktrees",
|
||||
["SIZE", "ACTIVE", "FOREIGN", "STATE", "BRANCH", "PATH"],
|
||||
[
|
||||
[
|
||||
_size(t["size_bytes"]),
|
||||
_age(now, t["last_activity"]),
|
||||
str(t["foreign_entries"]),
|
||||
_state(t),
|
||||
_branch(t),
|
||||
t["path"],
|
||||
]
|
||||
for t in report["worktrees"]
|
||||
],
|
||||
)
|
||||
lines += _section(
|
||||
"preserved (dirty worktrees)",
|
||||
["PRESERVED", "PATHS", "BRANCH", "PATH", "REASONS"],
|
||||
[
|
||||
[
|
||||
"yes" if p["preserved"] else "no",
|
||||
"-" if p["paths"] is None else str(p["paths"]),
|
||||
p["branch"] or "(detached)",
|
||||
p["path"],
|
||||
"; ".join(p["reasons"]),
|
||||
]
|
||||
for p in report["preserved"]
|
||||
],
|
||||
)
|
||||
for root in report["roots"]:
|
||||
lines += _section(
|
||||
f"root {root['root']} (over {human_size(report['threshold_bytes'])})",
|
||||
["SIZE", "AGE", "KIND", "PATH"],
|
||||
[
|
||||
[
|
||||
_size(c["size_bytes"]),
|
||||
_age(now, c["newest_mtime"]),
|
||||
c["kind"],
|
||||
c["path"],
|
||||
]
|
||||
for c in root["children"]
|
||||
],
|
||||
)
|
||||
lines += _section(
|
||||
"core dumps",
|
||||
["SIZE", "APPARENT", "AGE", "PATH"],
|
||||
[
|
||||
[
|
||||
_size(d["size_bytes"]),
|
||||
_size(d["apparent_bytes"]),
|
||||
_age(now, d["mtime"]),
|
||||
d["path"],
|
||||
]
|
||||
for d in report["core_dumps"]
|
||||
],
|
||||
)
|
||||
if report["docker"] is not None:
|
||||
lines += _section(
|
||||
"docker",
|
||||
["TYPE", "TOTAL", "ACTIVE", "SIZE", "RECLAIMABLE"],
|
||||
[[str(row[key]) for key in DOCKER_COLUMNS] for row in report["docker"]],
|
||||
)
|
||||
lines += _section(
|
||||
"balance",
|
||||
["FILESYSTEM", "TOTAL", "FREE", "ATTRIBUTED"],
|
||||
[
|
||||
[
|
||||
fs["filesystem"],
|
||||
_size(fs["total_bytes"]),
|
||||
_size(fs["free_bytes"]),
|
||||
_size(fs["attributed_bytes"]),
|
||||
]
|
||||
for fs in report["balance"]
|
||||
],
|
||||
)
|
||||
lines += [f"WARN {warning}" for warning in report["warnings"]]
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,97 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from pkgmgr.actions.branch.gc import _describe
|
||||
from pkgmgr.core.git.errors import GitBaseError
|
||||
|
||||
from .balance import balance
|
||||
from .core_dumps import core_dumps
|
||||
from .docker_usage import docker_usage
|
||||
from .preserved import preserved
|
||||
from .roots import scan_root
|
||||
from .worktrees import list_worktrees
|
||||
|
||||
|
||||
def disk_report(
|
||||
roots: list[str], repo_roots: list[str], threshold_bytes: int, docker: bool
|
||||
) -> dict:
|
||||
"""
|
||||
Inventory disk usage read-only: it deletes and writes nothing.
|
||||
|
||||
Args:
|
||||
roots: directories whose direct children are measured.
|
||||
repo_roots: main worktree roots of the repositories whose linked
|
||||
worktrees are listed (pkgmgr passes every managed repository).
|
||||
threshold_bytes: list only root children larger than this.
|
||||
docker: also read `docker system df`.
|
||||
|
||||
Returns:
|
||||
A JSON-serialisable dict. Sizes are allocated bytes (st_blocks * 512,
|
||||
sparse files and hard links counted as stored), measured without
|
||||
following symlinks or leaving the filesystem a walk starts on; times
|
||||
are epoch seconds.
|
||||
generated_at: when the scan started.
|
||||
threshold_bytes: as given.
|
||||
worktrees: per linked worktree and orphaned `.claude/worktrees/agent-*`
|
||||
dir: repo, path, branch, head, orphaned, missing, size_bytes,
|
||||
last_activity (newest mtime inside or of its index/HEAD),
|
||||
foreign_entries (not owned by the current uid, pruned at the first
|
||||
per subtree), unreadable (directories that could not be listed).
|
||||
preserved: per dirty worktree: repo, path, branch, paths (changed,
|
||||
staged and untracked; None when status was not read), preserved,
|
||||
reasons.
|
||||
roots: per root: root, children over the threshold with path, kind
|
||||
(worktree, git-repo, venv, node_modules, cache, core-dump, dir,
|
||||
file), size_bytes, newest_mtime, unreadable; biggest first.
|
||||
core_dumps: files named `core` or `core.<digits>` under the roots and
|
||||
worktrees whose ELF e_type is ET_CORE: path, size_bytes,
|
||||
apparent_bytes (st_size), mtime; biggest first.
|
||||
docker: rows of type, total, active, size, reclaimable; None when not
|
||||
asked for or unavailable.
|
||||
balance: per filesystem of the roots and repository roots: filesystem
|
||||
(mount point), total_bytes, free_bytes, attributed_bytes.
|
||||
warnings: what could not be read.
|
||||
"""
|
||||
started = time.time()
|
||||
warnings: list[str] = []
|
||||
cores: list[str] = []
|
||||
trees: list[dict] = []
|
||||
kept: list[dict] = []
|
||||
for repo in repo_roots:
|
||||
try:
|
||||
records = list_worktrees(repo, cores)
|
||||
except (GitBaseError, OSError) as exc:
|
||||
warnings.append(f"{repo}: worktrees not listed: {_describe(exc)}")
|
||||
continue
|
||||
trees += records
|
||||
try:
|
||||
kept += preserved(repo, records)
|
||||
except (GitBaseError, OSError) as exc:
|
||||
warnings.append(f"{repo}: preservation not checked: {_describe(exc)}")
|
||||
scanned: list[dict] = []
|
||||
for root in roots:
|
||||
try:
|
||||
scanned.append(scan_root(root, threshold_bytes, cores))
|
||||
except OSError as exc:
|
||||
warnings.append(f"{root}: not scanned: {_describe(exc)}")
|
||||
dumps = core_dumps(cores)
|
||||
usage = None
|
||||
if docker:
|
||||
usage, warning = docker_usage()
|
||||
if warning:
|
||||
warnings.append(warning)
|
||||
items = [(t["path"], t["size_bytes"]) for t in trees if t["size_bytes"]]
|
||||
items += [(c["path"], c["size_bytes"]) for s in scanned for c in s["children"]]
|
||||
items += [(d["path"], d["size_bytes"]) for d in dumps]
|
||||
return {
|
||||
"generated_at": started,
|
||||
"threshold_bytes": threshold_bytes,
|
||||
"worktrees": trees,
|
||||
"preserved": kept,
|
||||
"roots": scanned,
|
||||
"core_dumps": dumps,
|
||||
"docker": usage,
|
||||
"balance": balance([*roots, *repo_roots], items),
|
||||
"warnings": warnings,
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import stat
|
||||
|
||||
from .core_dumps import is_core_dump
|
||||
from .walk import walk
|
||||
|
||||
CACHE_TAG = "CACHEDIR.TAG"
|
||||
NODE_MODULES = "node_modules"
|
||||
|
||||
|
||||
def _has(path: str, name: str, check=os.path.isfile) -> bool:
|
||||
return check(os.path.join(path, name))
|
||||
|
||||
|
||||
def _kind(path: str, st: os.stat_result) -> str:
|
||||
name = os.path.basename(path)
|
||||
if not stat.S_ISDIR(st.st_mode):
|
||||
regular = stat.S_ISREG(st.st_mode)
|
||||
return "core-dump" if regular and is_core_dump(path) else "file"
|
||||
if name == NODE_MODULES:
|
||||
return "node_modules"
|
||||
if _has(path, ".git"):
|
||||
return "worktree"
|
||||
if _has(path, ".git", os.path.isdir) or (
|
||||
_has(path, "HEAD") and _has(path, "objects", os.path.isdir)
|
||||
):
|
||||
return "git-repo"
|
||||
if _has(path, "pyvenv.cfg"):
|
||||
return "venv"
|
||||
if _has(path, CACHE_TAG) or name.lower().endswith("cache"):
|
||||
return "cache"
|
||||
return "dir"
|
||||
|
||||
|
||||
def scan_root(root: str, threshold_bytes: int, cores: list[str]) -> dict:
|
||||
"""
|
||||
Measure the direct children of one root on the root's own filesystem.
|
||||
|
||||
Args:
|
||||
root: the directory to inventory.
|
||||
threshold_bytes: keep only children whose allocated size is above it.
|
||||
cores: receives the core dump candidates found while measuring.
|
||||
|
||||
Returns:
|
||||
The root with its children over the threshold: path, kind, allocated
|
||||
size, newest mtime inside and unlistable directories, biggest first.
|
||||
|
||||
Raises:
|
||||
OSError: when the root itself cannot be listed.
|
||||
"""
|
||||
dev = os.stat(root).st_dev
|
||||
children: list[dict] = []
|
||||
with os.scandir(root) as entries:
|
||||
listing = sorted(entries, key=lambda entry: entry.name)
|
||||
for entry in listing:
|
||||
try:
|
||||
st = entry.stat(follow_symlinks=False)
|
||||
except OSError:
|
||||
continue
|
||||
if st.st_dev != dev:
|
||||
continue
|
||||
stats = walk(entry.path, dev)
|
||||
cores.extend(stats.cores)
|
||||
if stats.size_bytes > threshold_bytes:
|
||||
children.append(
|
||||
{
|
||||
"path": entry.path,
|
||||
"kind": _kind(entry.path, st),
|
||||
"size_bytes": stats.size_bytes,
|
||||
"newest_mtime": stats.newest_mtime,
|
||||
"unreadable": stats.unreadable,
|
||||
}
|
||||
)
|
||||
children.sort(key=lambda child: (-child["size_bytes"], child["path"]))
|
||||
return {"root": root, "children": children}
|
||||
@@ -0,0 +1,86 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
BLOCK = 512
|
||||
CORE_NAME = re.compile(r"core(\.\d+)?")
|
||||
|
||||
|
||||
@dataclass
|
||||
class TreeStats:
|
||||
size_bytes: int = 0
|
||||
newest_mtime: float = 0.0
|
||||
foreign_entries: int = 0
|
||||
unreadable: int = 0
|
||||
cores: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def is_foreign(path: str, st: os.stat_result) -> bool:
|
||||
return st.st_uid != os.getuid()
|
||||
|
||||
|
||||
def _account(
|
||||
stats: TreeStats, path: str, st: os.stat_result, seen: set[tuple[int, int]]
|
||||
) -> None:
|
||||
if st.st_nlink > 1 and not stat.S_ISDIR(st.st_mode):
|
||||
if (st.st_dev, st.st_ino) in seen:
|
||||
return
|
||||
seen.add((st.st_dev, st.st_ino))
|
||||
stats.size_bytes += st.st_blocks * BLOCK
|
||||
stats.newest_mtime = max(stats.newest_mtime, st.st_mtime)
|
||||
if stat.S_ISREG(st.st_mode) and CORE_NAME.fullmatch(os.path.basename(path)):
|
||||
stats.cores.append(path)
|
||||
|
||||
|
||||
def _children(path: str, stats: TreeStats) -> list[os.DirEntry]:
|
||||
try:
|
||||
with os.scandir(path) as entries:
|
||||
return list(entries)
|
||||
except OSError:
|
||||
stats.unreadable += 1
|
||||
return []
|
||||
|
||||
|
||||
def walk(path: str, dev: int | None = None) -> TreeStats:
|
||||
"""
|
||||
Measure a tree like `du -x`: allocated blocks, symlinks never followed.
|
||||
|
||||
Args:
|
||||
path: the tree root, measured itself as well.
|
||||
dev: the filesystem (st_dev) to stay on; that of path when None.
|
||||
|
||||
Returns:
|
||||
Allocated bytes (st_blocks * 512, each hard-linked inode once), the
|
||||
newest mtime, entries not owned by the current uid (none counted below a
|
||||
foreign one), directories that could not be listed, and the regular
|
||||
files named `core` or `core.<digits>`.
|
||||
"""
|
||||
stats = TreeStats()
|
||||
try:
|
||||
top = os.lstat(path)
|
||||
except OSError:
|
||||
stats.unreadable += 1
|
||||
return stats
|
||||
dev = top.st_dev if dev is None else dev
|
||||
if top.st_dev != dev:
|
||||
return stats
|
||||
seen: set[tuple[int, int]] = set()
|
||||
stack: list[tuple[str, os.stat_result, bool]] = [(path, top, False)]
|
||||
while stack:
|
||||
current, st, pruned = stack.pop()
|
||||
_account(stats, current, st, seen)
|
||||
foreign = not pruned and is_foreign(current, st)
|
||||
stats.foreign_entries += foreign
|
||||
if not stat.S_ISDIR(st.st_mode):
|
||||
continue
|
||||
for entry in _children(current, stats):
|
||||
try:
|
||||
child = entry.stat(follow_symlinks=False)
|
||||
except OSError:
|
||||
continue
|
||||
if child.st_dev == dev:
|
||||
stack.append((entry.path, child, pruned or foreign))
|
||||
return stats
|
||||
@@ -0,0 +1,96 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from pkgmgr.actions.branch.gc import _worktrees
|
||||
|
||||
from .walk import TreeStats, walk
|
||||
|
||||
AGENT_DIR = os.path.join(".claude", "worktrees")
|
||||
AGENT_PREFIX = "agent-"
|
||||
METADATA_FILES = ("index", "HEAD")
|
||||
|
||||
|
||||
def _metadata_mtime(path: str) -> float:
|
||||
try:
|
||||
with open(os.path.join(path, ".git"), encoding="utf-8") as fh:
|
||||
gitdir = fh.read().strip().removeprefix("gitdir: ")
|
||||
except OSError:
|
||||
return 0.0
|
||||
meta = os.path.normpath(os.path.join(path, gitdir))
|
||||
stamps = [0.0]
|
||||
for name in METADATA_FILES:
|
||||
try:
|
||||
stamps.append(os.stat(os.path.join(meta, name)).st_mtime)
|
||||
except OSError:
|
||||
continue
|
||||
return max(stamps)
|
||||
|
||||
|
||||
def _record(
|
||||
repo: str,
|
||||
path: str,
|
||||
branch: str | None,
|
||||
head: str | None,
|
||||
orphaned: bool,
|
||||
cores: list[str],
|
||||
) -> dict:
|
||||
present = os.path.isdir(path)
|
||||
stats = walk(path) if present else TreeStats()
|
||||
cores.extend(stats.cores)
|
||||
activity = max(stats.newest_mtime, _metadata_mtime(path)) if present else 0.0
|
||||
return {
|
||||
"repo": repo,
|
||||
"path": path,
|
||||
"branch": branch,
|
||||
"head": head,
|
||||
"orphaned": orphaned,
|
||||
"missing": not present,
|
||||
"size_bytes": stats.size_bytes if present else None,
|
||||
"last_activity": activity or None,
|
||||
"foreign_entries": stats.foreign_entries,
|
||||
"unreadable": stats.unreadable,
|
||||
}
|
||||
|
||||
|
||||
def _agent_dirs(repo: str) -> list[str]:
|
||||
base = os.path.join(repo, AGENT_DIR)
|
||||
try:
|
||||
names = sorted(os.listdir(base))
|
||||
except OSError:
|
||||
return []
|
||||
return [
|
||||
os.path.join(base, name)
|
||||
for name in names
|
||||
if name.startswith(AGENT_PREFIX)
|
||||
and os.path.isdir(os.path.join(base, name))
|
||||
and not os.path.islink(os.path.join(base, name))
|
||||
]
|
||||
|
||||
|
||||
def list_worktrees(repo: str, cores: list[str]) -> list[dict]:
|
||||
"""
|
||||
Inventory the linked worktrees of one repository, orphaned agent dirs included.
|
||||
|
||||
Args:
|
||||
repo: main worktree root of the repository.
|
||||
cores: receives the core dump candidates found while measuring.
|
||||
|
||||
Returns:
|
||||
One record per linked worktree git lists and per `.claude/worktrees/agent-*`
|
||||
directory it does not list (orphaned), sorted by path.
|
||||
|
||||
Raises:
|
||||
GitBaseError: when `git worktree list` fails.
|
||||
"""
|
||||
trees = [tree for tree in _worktrees(repo) if not tree.main]
|
||||
listed = {os.path.realpath(tree.path) for tree in trees}
|
||||
records = [
|
||||
_record(repo, tree.path, tree.branch, tree.head, False, cores) for tree in trees
|
||||
]
|
||||
records += [
|
||||
_record(repo, path, None, None, True, cores)
|
||||
for path in _agent_dirs(repo)
|
||||
if os.path.realpath(path) not in listed
|
||||
]
|
||||
return sorted(records, key=lambda record: record["path"])
|
||||
@@ -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"
|
||||
@@ -31,9 +31,7 @@ class MakefileInstaller(BaseInstaller):
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
if re.search(r"^install\s*:", content, flags=re.MULTILINE):
|
||||
return True
|
||||
return bool(re.search(r"^install-[a-zA-Z0-9_-]*\s*:", content, flags=re.MULTILINE))
|
||||
return bool(re.search(r"^install\s*:", content, flags=re.MULTILINE))
|
||||
|
||||
def run(self, ctx: RepoContext) -> None:
|
||||
makefile_path = os.path.join(ctx.repo_dir, self.MAKEFILE_NAME)
|
||||
|
||||
@@ -161,7 +161,6 @@ class InstallationPipeline:
|
||||
else:
|
||||
repo.pop("command", None)
|
||||
|
||||
state = new_state
|
||||
return
|
||||
|
||||
if attempted:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from pkgmgr.actions.mirror.io import read_mirrors_file
|
||||
from pkgmgr.actions.mirror.types import Repository
|
||||
@@ -12,20 +12,62 @@ from pkgmgr.core.version.semver import SemVer
|
||||
|
||||
from .git_tags import head_semver_tags
|
||||
from .pypi_url import parse_pypi_project_url
|
||||
from .types import PyPITarget
|
||||
|
||||
UPLOAD_URLS = {
|
||||
"pypi.org": "https://upload.pypi.org/legacy/",
|
||||
"test.pypi.org": "https://test.pypi.org/legacy/",
|
||||
}
|
||||
|
||||
|
||||
def _require_tool(module: str) -> None:
|
||||
def _child_env(repo_dir: str) -> dict[str, str]:
|
||||
"""
|
||||
Args:
|
||||
repo_dir: absolute path of the repository being published.
|
||||
|
||||
Returns:
|
||||
The environment for build and twine without pkgmgr's own variables,
|
||||
so no PKGMGR_* token reaches a build backend or an upload, and
|
||||
without PYTHONPATH entries inside repo_dir, so no repository file
|
||||
shadows build or twine.
|
||||
"""
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("PKGMGR_")}
|
||||
if "PYTHONPATH" in env:
|
||||
root = os.path.realpath(repo_dir)
|
||||
kept = [
|
||||
entry
|
||||
for entry in env["PYTHONPATH"].split(os.pathsep)
|
||||
if entry and os.path.commonpath([root, os.path.realpath(entry)]) != root
|
||||
]
|
||||
if kept:
|
||||
env["PYTHONPATH"] = os.pathsep.join(kept)
|
||||
else:
|
||||
del env["PYTHONPATH"]
|
||||
return env
|
||||
|
||||
|
||||
def _require_tool(module: str, cwd: str, env: dict[str, str]) -> None:
|
||||
"""
|
||||
Args:
|
||||
module: the Python module run with -m.
|
||||
cwd: an empty private directory, so no file of the repository
|
||||
shadows the module on sys.path.
|
||||
env: the child environment from _child_env.
|
||||
"""
|
||||
try:
|
||||
subprocess.run(
|
||||
["python", "-m", module, "--help"],
|
||||
[sys.executable, "-m", module, "--help"],
|
||||
cwd=cwd,
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"Required Python module '{module}' is not available. "
|
||||
f"Install it via: pip install {module}"
|
||||
f"Required Python module '{module}' is not available to "
|
||||
f"{sys.executable}. Install it via: "
|
||||
f"{sys.executable} -m pip install {module}"
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -66,22 +108,38 @@ def publish(
|
||||
print("[PREVIEW] Would build and upload to PyPI.")
|
||||
return
|
||||
|
||||
_require_tool("build")
|
||||
_require_tool("twine")
|
||||
with tempfile.TemporaryDirectory() as out:
|
||||
_upload(target, os.path.abspath(repo_dir), out, interactive, allow_prompt)
|
||||
|
||||
dist_dir = os.path.join(repo_dir, "dist")
|
||||
if os.path.isdir(dist_dir):
|
||||
shutil.rmtree(dist_dir, ignore_errors=True)
|
||||
print("[INFO] Publish completed.")
|
||||
|
||||
|
||||
def _upload(
|
||||
target: PyPITarget, repo_dir: str, out: str, interactive: bool, allow_prompt: bool
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
target: the PyPI target parsed from the mirror URL.
|
||||
repo_dir: absolute path of the repository to build.
|
||||
out: an empty private directory that receives the artifacts and is
|
||||
the working directory of every child process.
|
||||
interactive: allow interactive token resolution.
|
||||
allow_prompt: allow prompting for the token.
|
||||
"""
|
||||
env = _child_env(repo_dir)
|
||||
_require_tool("build", out, env)
|
||||
_require_tool("twine", out, env)
|
||||
|
||||
subprocess.run(
|
||||
["python", "-m", "build"],
|
||||
cwd=repo_dir,
|
||||
[sys.executable, "-m", "build", "--outdir", out, repo_dir],
|
||||
cwd=out,
|
||||
env=env,
|
||||
check=True,
|
||||
)
|
||||
|
||||
artifacts = sorted(glob.glob(os.path.join(dist_dir, "*")))
|
||||
artifacts = sorted(os.path.join(out, name) for name in os.listdir(out))
|
||||
if not artifacts:
|
||||
raise RuntimeError("No build artifacts found in dist/.")
|
||||
raise RuntimeError("No build artifacts found.")
|
||||
|
||||
resolver = TokenResolver()
|
||||
|
||||
@@ -98,15 +156,18 @@ def publish(
|
||||
),
|
||||
).token
|
||||
|
||||
env = dict(os.environ)
|
||||
env["TWINE_USERNAME"] = "__token__"
|
||||
env["TWINE_PASSWORD"] = token
|
||||
|
||||
subprocess.run(
|
||||
["python", "-m", "twine", "upload", *artifacts],
|
||||
cwd=repo_dir,
|
||||
env=env,
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"twine",
|
||||
"upload",
|
||||
"--non-interactive",
|
||||
"--repository-url",
|
||||
UPLOAD_URLS[target.host],
|
||||
*artifacts,
|
||||
],
|
||||
cwd=out,
|
||||
env={**env, "TWINE_USERNAME": "__token__", "TWINE_PASSWORD": token},
|
||||
check=True,
|
||||
)
|
||||
|
||||
print("[INFO] Publish completed.")
|
||||
@@ -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"]
|
||||
@@ -10,6 +10,7 @@ Keep this package stable so existing imports continue to work, e.g.:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .cargo import update_cargo_version
|
||||
from .changelog_md import update_changelog
|
||||
from .debian import _get_debian_author, update_debian_changelog
|
||||
from .editor import _open_editor_for_changelog
|
||||
@@ -22,6 +23,7 @@ from .rpm_spec import update_spec_version
|
||||
__all__ = [
|
||||
"_get_debian_author",
|
||||
"_open_editor_for_changelog",
|
||||
"update_cargo_version",
|
||||
"update_changelog",
|
||||
"update_debian_changelog",
|
||||
"update_flake_version",
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
|
||||
def _read(path: str) -> str:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def _write(path: str, content: str) -> None:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
|
||||
|
||||
def update_cargo_version(
|
||||
repo_root: str, new_version: str, preview: bool = False
|
||||
) -> list[str]:
|
||||
"""
|
||||
Set the root crate's version in Cargo.toml and its entry in Cargo.lock.
|
||||
|
||||
Args:
|
||||
repo_root: repository root that may hold Cargo.toml and Cargo.lock.
|
||||
new_version: release version without the leading "v".
|
||||
preview: only print what would change.
|
||||
|
||||
Returns:
|
||||
The paths that were (or in preview would be) changed.
|
||||
"""
|
||||
toml_path = os.path.join(repo_root, "Cargo.toml")
|
||||
if not os.path.exists(toml_path):
|
||||
print("[INFO] No Cargo.toml found. Skipping Cargo version update.")
|
||||
return []
|
||||
|
||||
toml = _read(toml_path)
|
||||
block = re.search(r"(?ms)^\[package\]\s*$.*?(?=^\s*\[|\Z)", toml)
|
||||
if not block:
|
||||
print("[INFO] Cargo.toml has no [package] section. Skipping.")
|
||||
return []
|
||||
|
||||
name = re.search(r'(?m)^\s*name\s*=\s*"([^"]+)"', block.group(0))
|
||||
if not name:
|
||||
raise RuntimeError("Missing name key in [package] section of Cargo.toml")
|
||||
new_block, count = re.subn(
|
||||
r'(?m)^(\s*version\s*=\s*")[^"]+(")',
|
||||
lambda m: f"{m.group(1)}{new_version}{m.group(2)}",
|
||||
block.group(0),
|
||||
count=1,
|
||||
)
|
||||
if count == 0:
|
||||
raise RuntimeError("Missing version key in [package] section of Cargo.toml")
|
||||
changes = {toml_path: toml[: block.start()] + new_block + toml[block.end() :]}
|
||||
|
||||
lock_path = os.path.join(repo_root, "Cargo.lock")
|
||||
if os.path.exists(lock_path):
|
||||
lock, count = re.subn(
|
||||
rf'(?m)^(\[\[package\]\]\nname = "{re.escape(name.group(1))}"\n'
|
||||
r'version = ")[^"]+("\n)(?!source = )',
|
||||
lambda m: f"{m.group(1)}{new_version}{m.group(2)}",
|
||||
_read(lock_path),
|
||||
)
|
||||
if count != 1:
|
||||
raise RuntimeError(
|
||||
f"Expected one local {name.group(1)!r} package in Cargo.lock, "
|
||||
f"found {count}"
|
||||
)
|
||||
changes[lock_path] = lock
|
||||
|
||||
for path, content in changes.items():
|
||||
if preview:
|
||||
print(f"[PREVIEW] Would update {path} version to {new_version}")
|
||||
else:
|
||||
_write(path, content)
|
||||
print(f"Updated {path} version to {new_version}")
|
||||
return list(changes)
|
||||
@@ -6,11 +6,15 @@ import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from collections import Counter
|
||||
|
||||
_HEADING = re.compile(r"^\s*#{1,6}\s+(.*?)\s*#*\s*$")
|
||||
_HEADING = re.compile(r"^\s*(#{1,6})\s+(.*?)\s*#*\s*$")
|
||||
_INLINE_CODE = re.compile(r"`([^`\n]+)`")
|
||||
_FINDING = re.compile(r"\bMD\d{3}\b")
|
||||
_LOCATION = re.compile(r"^.*?:\d+(?::\d+)?\s+")
|
||||
_NON_DASH_ITEM = re.compile(r"^\s*[*+]\s")
|
||||
_MULTI_BLANK = re.compile(r"\n{3,}")
|
||||
_ENTRY_LEVEL = 3
|
||||
|
||||
|
||||
class ChangelogLintError(RuntimeError):
|
||||
@@ -20,10 +24,10 @@ class ChangelogLintError(RuntimeError):
|
||||
def transform_changelog_message(text: str) -> str:
|
||||
"""Normalise a free-form release message into the changelog house style.
|
||||
|
||||
A leading ``#`` heading becomes a bold line of its own (markdown
|
||||
headings inside an entry body would collide with the ``## [version]``
|
||||
structure), and inline ``code`` spans become ``*italic*`` so the entry
|
||||
stays free of backticks.
|
||||
Headings are pushed below the ``## [version]`` line the entry is filed
|
||||
under, so they nest instead of competing with it. Bolding them instead
|
||||
would read as a heading to markdown-lint and fail MD036. Inline ``code``
|
||||
spans become ``*italic*`` so the entry stays free of backticks.
|
||||
"""
|
||||
text = _INLINE_CODE.sub(r"*\1*", text)
|
||||
|
||||
@@ -31,9 +35,10 @@ def transform_changelog_message(text: str) -> str:
|
||||
for line in text.split("\n"):
|
||||
heading = _HEADING.match(line)
|
||||
if heading:
|
||||
level = max(len(heading.group(1)), _ENTRY_LEVEL)
|
||||
if out and out[-1].strip():
|
||||
out.append("")
|
||||
out.append(f"**{heading.group(1).strip()}**")
|
||||
out.append(f"{'#' * level} {heading.group(2).strip()}")
|
||||
out.append("")
|
||||
else:
|
||||
out.append(line)
|
||||
@@ -57,6 +62,35 @@ def lint_changelog_entry(reference_path: str, entry: str) -> list[str]:
|
||||
return _builtin_lint(document)
|
||||
|
||||
|
||||
def lint_changelog_context(reference_path: str, existing: str, merged: str) -> list[str]:
|
||||
"""Return the findings *merged* has beyond those *existing* already has.
|
||||
|
||||
Args:
|
||||
reference_path: path of the target CHANGELOG.md; its directory supplies
|
||||
the markdownlint config.
|
||||
existing: the target file before the entry is inserted.
|
||||
merged: the target file with the entry inserted.
|
||||
|
||||
Returns:
|
||||
Findings of *merged* that *existing* does not produce. Empty when
|
||||
``markdownlint-cli2`` is unavailable.
|
||||
"""
|
||||
if not shutil.which("markdownlint-cli2"):
|
||||
return []
|
||||
known = Counter(
|
||||
_LOCATION.sub("", finding)
|
||||
for finding in (_markdownlint(reference_path, existing) if existing.strip() else [])
|
||||
)
|
||||
new: list[str] = []
|
||||
for finding in _markdownlint(reference_path, merged):
|
||||
key = _LOCATION.sub("", finding)
|
||||
if known[key]:
|
||||
known[key] -= 1
|
||||
else:
|
||||
new.append(finding)
|
||||
return new
|
||||
|
||||
|
||||
def _markdownlint(reference_path: str, document: str) -> list[str]:
|
||||
directory = os.path.dirname(os.path.abspath(reference_path)) or "."
|
||||
fd, tmp_path = tempfile.mkstemp(
|
||||
@@ -67,7 +101,7 @@ def _markdownlint(reference_path: str, document: str) -> list[str]:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||
handle.write(document)
|
||||
proc = subprocess.run(
|
||||
["markdownlint-cli2", name],
|
||||
["markdownlint-cli2", "--no-globs", name],
|
||||
cwd=directory,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
@@ -94,6 +128,8 @@ def _builtin_lint(document: str) -> list[str]:
|
||||
errors.append(f"line {number}: trailing whitespace (MD009)")
|
||||
if "`" in line:
|
||||
errors.append(f"line {number}: backtick is not allowed (use *italic*)")
|
||||
if _NON_DASH_ITEM.match(line):
|
||||
errors.append(f"line {number}: list items use '-' (MD004)")
|
||||
if "\n\n\n" in document:
|
||||
errors.append("multiple consecutive blank lines (MD012)")
|
||||
return errors
|
||||
@@ -3,10 +3,11 @@ from __future__ import annotations
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import date
|
||||
from datetime import datetime
|
||||
|
||||
from .changelog_lint import (
|
||||
ChangelogLintError,
|
||||
lint_changelog_context,
|
||||
lint_changelog_entry,
|
||||
transform_changelog_message,
|
||||
)
|
||||
@@ -68,7 +69,7 @@ def update_changelog(
|
||||
missing) and above any existing release entries, so the result stays
|
||||
markdown-lint-clean (MD041 first-line-h1, MD012 no-multiple-blanks).
|
||||
"""
|
||||
today = date.today().isoformat() # noqa: DTZ011 - changelog dates are local calendar dates
|
||||
today = datetime.now().astimezone().date().isoformat()
|
||||
|
||||
def _entry_for(raw: str) -> tuple[str, str]:
|
||||
body = transform_changelog_message(raw).strip() or f"Release {new_version}"
|
||||
@@ -80,30 +81,10 @@ def update_changelog(
|
||||
print(f" - {finding}")
|
||||
print()
|
||||
|
||||
if message is not None:
|
||||
body, entry = _entry_for(message)
|
||||
findings = lint_changelog_entry(changelog_path, entry)
|
||||
if findings:
|
||||
_print_findings(findings)
|
||||
raise ChangelogLintError(
|
||||
"Provided changelog message is not markdown-lint clean."
|
||||
)
|
||||
elif preview or not sys.stdin.isatty():
|
||||
body, entry = _entry_for(message or f"Release {new_version}")
|
||||
else:
|
||||
attempt: str | None = None
|
||||
while True:
|
||||
print(
|
||||
"\n[INFO] Provide the changelog entry — a leading '#' becomes "
|
||||
"bold, `code` becomes italic.\n"
|
||||
)
|
||||
raw = _open_editor_for_changelog(attempt)
|
||||
body, entry = _entry_for(raw or f"Release {new_version}")
|
||||
findings = lint_changelog_entry(changelog_path, entry)
|
||||
if not findings:
|
||||
break
|
||||
_print_findings(findings)
|
||||
attempt = body
|
||||
def _wait_for_reader() -> None:
|
||||
try:
|
||||
input("[INFO] Press Enter to re-open the editor and fix the entry...")
|
||||
except EOFError:
|
||||
print("[INFO] Re-opening the editor so you can fix the entry...")
|
||||
|
||||
changelog = ""
|
||||
@@ -114,6 +95,39 @@ def update_changelog(
|
||||
except (OSError, UnicodeDecodeError) as exc:
|
||||
print(f"[WARN] Could not read existing CHANGELOG.md: {exc}")
|
||||
|
||||
def _findings_for(entry: str) -> list[str]:
|
||||
return lint_changelog_entry(changelog_path, entry) or lint_changelog_context(
|
||||
changelog_path, changelog, _insert_after_h1(changelog, entry)
|
||||
)
|
||||
|
||||
if message is not None:
|
||||
body, entry = _entry_for(message)
|
||||
findings = _findings_for(entry)
|
||||
if findings:
|
||||
_print_findings(findings)
|
||||
raise ChangelogLintError(
|
||||
"Provided changelog message is not markdown-lint clean."
|
||||
)
|
||||
elif preview or not sys.stdin.isatty():
|
||||
body, entry = _entry_for(message or f"Release {new_version}")
|
||||
else:
|
||||
attempt: str | None = None
|
||||
rejected: list[str] | None = None
|
||||
while True:
|
||||
print(
|
||||
"\n[INFO] Provide the changelog entry - a leading '#' becomes "
|
||||
"a sub-heading, `code` becomes italic.\n"
|
||||
)
|
||||
raw = _open_editor_for_changelog(attempt, rejected)
|
||||
body, entry = _entry_for(raw or f"Release {new_version}")
|
||||
findings = _findings_for(entry)
|
||||
if not findings:
|
||||
break
|
||||
_print_findings(findings)
|
||||
attempt = body
|
||||
rejected = findings
|
||||
_wait_for_reader()
|
||||
|
||||
new_changelog = _insert_after_h1(changelog, entry)
|
||||
|
||||
print("\n================ CHANGELOG ENTRY ================")
|
||||
|
||||
@@ -6,7 +6,14 @@ import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def _open_editor_for_changelog(initial_message: str | None = None) -> str:
|
||||
def _open_editor_for_changelog(
|
||||
initial_message: str | None = None,
|
||||
findings: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Args:
|
||||
initial_message: the previous attempt, pre-loaded for editing.
|
||||
findings: why that attempt was rejected, shown above it.
|
||||
"""
|
||||
editor = os.environ.get("EDITOR", "nano")
|
||||
|
||||
with tempfile.NamedTemporaryFile(
|
||||
@@ -18,9 +25,15 @@ def _open_editor_for_changelog(initial_message: str | None = None) -> str:
|
||||
tmp.write(
|
||||
"; Write the changelog entry for this release.\n"
|
||||
"; Lines starting with ';' are ignored.\n"
|
||||
"; A leading '#' becomes bold; `code` becomes italic.\n"
|
||||
"; Empty result will fall back to a generic message.\n\n"
|
||||
"; A leading '#' becomes a sub-heading; `code` becomes italic.\n"
|
||||
"; Empty result will fall back to a generic message.\n"
|
||||
)
|
||||
if findings:
|
||||
tmp.write(";\n; markdown-lint rejected the previous entry:\n")
|
||||
for finding in findings:
|
||||
for line in str(finding).splitlines() or [""]:
|
||||
tmp.write(f"; {line}\n")
|
||||
tmp.write("\n")
|
||||
if initial_message:
|
||||
tmp.write(initial_message.strip() + "\n")
|
||||
tmp.flush()
|
||||
|
||||
@@ -3,6 +3,41 @@ from __future__ import annotations
|
||||
import os
|
||||
import re
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
except ImportError:
|
||||
import tomli as tomllib # type: ignore
|
||||
|
||||
from pkgmgr.core.version.source import dynamic_version_source, version_literal
|
||||
|
||||
|
||||
def update_module_version(
|
||||
path: str, name: str, new_version: str, preview: bool
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
path: the module file that holds the version literal.
|
||||
name: the attribute assigned the version, e.g. __version__.
|
||||
new_version: the version to write.
|
||||
preview: print the change instead of writing it.
|
||||
|
||||
Raises:
|
||||
RuntimeError: the file holds no `name = "..."` literal.
|
||||
"""
|
||||
with open(path, encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
new_content, count = version_literal(name).subn(
|
||||
lambda mm: f"{mm.group(1)}{new_version}{mm.group(3)}", content, count=1
|
||||
)
|
||||
if count == 0:
|
||||
raise RuntimeError(f"Missing {name} literal in {path}")
|
||||
if preview:
|
||||
print(f"[PREVIEW] Would update {name} in {path} to {new_version}")
|
||||
return
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(new_content)
|
||||
print(f"Updated {name} in {path} to {new_version}")
|
||||
|
||||
|
||||
def update_pyproject_version(
|
||||
pyproject_path: str, new_version: str, preview: bool = False
|
||||
@@ -18,6 +53,16 @@ def update_pyproject_version(
|
||||
print(f"[WARN] Could not read pyproject.toml: {exc}")
|
||||
return
|
||||
|
||||
data = tomllib.loads(content)
|
||||
project = data.get("project")
|
||||
source = dynamic_version_source(pyproject_path, data)
|
||||
if source is not None:
|
||||
update_module_version(*source, new_version, preview)
|
||||
return
|
||||
if project is None or "version" in project.get("dynamic", []):
|
||||
print("[INFO] pyproject.toml declares no static version, skipping.")
|
||||
return
|
||||
|
||||
m = re.search(r"(?ms)^\s*\[project\]\s*$.*?(?=^\s*\[|\Z)", content)
|
||||
if not m:
|
||||
raise RuntimeError("Missing [project] section in pyproject.toml")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pkgmgr.core.git import run
|
||||
from pkgmgr.core.git.commands import (
|
||||
fetch,
|
||||
pull_ff_only,
|
||||
@@ -14,7 +15,18 @@ def ensure_clean_and_synced(*, preview: bool = False) -> None:
|
||||
Always run a pull BEFORE modifying anything.
|
||||
Uses --ff-only to avoid creating merge commits automatically.
|
||||
If no upstream is configured, we skip.
|
||||
|
||||
Raises:
|
||||
RuntimeError: a tracked file is modified; the release commit uses
|
||||
``commit -a`` and would ship it.
|
||||
"""
|
||||
dirty = run(["status", "--porcelain", "--untracked-files=no"])
|
||||
if dirty:
|
||||
raise RuntimeError(
|
||||
"Tracked changes in the release checkout; commit or park them "
|
||||
f"first, the release commit would include them:\n{dirty}"
|
||||
)
|
||||
|
||||
upstream = get_upstream_ref()
|
||||
if not upstream:
|
||||
print("[INFO] No upstream configured for current branch. Skipping pull.")
|
||||
@@ -29,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
|
||||
@@ -10,7 +10,7 @@ the side effects downstream are incomplete.
|
||||
`retry_release` re-runs the idempotent tail of that flow so a botched
|
||||
release can be re-pushed without touching code or recreating tags:
|
||||
|
||||
* `git push origin <branch> <tag>` for the existing HEAD tag
|
||||
* push the branch and the existing HEAD tag through `pkgmgr push`'s leases
|
||||
* re-align the floating `latest` tag if HEAD tag is the highest
|
||||
|
||||
Publishing (PyPI etc.) stays the caller's responsibility — the publish
|
||||
@@ -23,7 +23,8 @@ from __future__ import annotations
|
||||
import os
|
||||
|
||||
from pkgmgr.actions.publish.git_tags import head_semver_tags
|
||||
from pkgmgr.core.git import GitRunError, run
|
||||
from pkgmgr.actions.repository.push import push_branch
|
||||
from pkgmgr.core.git import GitRunError
|
||||
from pkgmgr.core.git.queries import get_current_branch
|
||||
from pkgmgr.core.version.semver import SemVer
|
||||
|
||||
@@ -50,7 +51,7 @@ def retry_release(
|
||||
tag = max(tags, key=SemVer.parse)
|
||||
print(f"Re-pushing existing tag: {tag}")
|
||||
|
||||
run(["push", "origin", branch, tag], preview=preview)
|
||||
push_branch(".", [], sign=True, refs=(tag,), preview=preview)
|
||||
|
||||
try:
|
||||
if is_highest_version_tag(tag):
|
||||
|
||||
@@ -4,6 +4,8 @@ Version discovery and bumping helpers for the release workflow.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from pkgmgr.core.git.queries import get_tags
|
||||
from pkgmgr.core.version.semver import (
|
||||
SemVer,
|
||||
@@ -12,26 +14,60 @@ from pkgmgr.core.version.semver import (
|
||||
bump_patch,
|
||||
find_latest_version,
|
||||
)
|
||||
from pkgmgr.core.version.source import (
|
||||
read_cargo_version,
|
||||
read_changelog_version,
|
||||
read_debian_changelog_version,
|
||||
read_flake_version,
|
||||
read_pkgbuild_version,
|
||||
read_pyproject_version,
|
||||
read_spec_version,
|
||||
)
|
||||
|
||||
FILE_SOURCES = {
|
||||
"pyproject.toml": read_pyproject_version,
|
||||
"CHANGELOG.md": read_changelog_version,
|
||||
"flake.nix": read_flake_version,
|
||||
"PKGBUILD": read_pkgbuild_version,
|
||||
"RPM spec": read_spec_version,
|
||||
"debian/changelog": read_debian_changelog_version,
|
||||
"Cargo.toml": read_cargo_version,
|
||||
}
|
||||
_CORE_VERSION = re.compile(r"^v?(\d+\.\d+\.\d+)")
|
||||
|
||||
|
||||
def determine_current_version() -> SemVer:
|
||||
def _file_versions(repo_dir: str) -> dict[str, SemVer]:
|
||||
versions: dict[str, SemVer] = {}
|
||||
for source, read in FILE_SOURCES.items():
|
||||
match = _CORE_VERSION.match(read(repo_dir) or "")
|
||||
if match:
|
||||
versions[source] = SemVer.parse(match.group(1))
|
||||
return versions
|
||||
|
||||
|
||||
def determine_current_version(repo_dir: str) -> SemVer:
|
||||
"""
|
||||
Determine the current semantic version from Git tags.
|
||||
Determine the highest version across the latest SemVer tag and every
|
||||
version file the release writes.
|
||||
|
||||
Behaviour:
|
||||
- If there are no tags or no SemVer-compatible tags, return 0.0.0.
|
||||
- Otherwise, use the latest SemVer tag as current version.
|
||||
Args:
|
||||
repo_dir: repository root holding the version files.
|
||||
|
||||
Returns:
|
||||
The highest version found, or 0.0.0 when no source has one.
|
||||
"""
|
||||
tags = get_tags()
|
||||
if not tags:
|
||||
versions = _file_versions(repo_dir)
|
||||
latest = find_latest_version(get_tags() or [])
|
||||
if latest is not None:
|
||||
versions["tag"] = latest[1]
|
||||
if not versions:
|
||||
return SemVer(0, 0, 0)
|
||||
|
||||
latest = find_latest_version(tags)
|
||||
if latest is None:
|
||||
return SemVer(0, 0, 0)
|
||||
|
||||
_tag, ver = latest
|
||||
return ver
|
||||
highest = max(versions.values())
|
||||
if len(set(versions.values())) > 1:
|
||||
found = ", ".join(f"{source} {ver}" for source, ver in versions.items())
|
||||
print(f"[INFO] Version sources disagree ({found}); starting from {highest}.")
|
||||
return highest
|
||||
|
||||
|
||||
def bump_semver(current: SemVer, release_type: str) -> SemVer:
|
||||
|
||||
@@ -2,14 +2,21 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
from pkgmgr.actions.branch import close_branch
|
||||
from pkgmgr.core.git import GitRunError, run
|
||||
from pkgmgr.actions.repository.push import (
|
||||
push_branch,
|
||||
refuse_unsafe_config,
|
||||
sign_unpushed,
|
||||
)
|
||||
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,
|
||||
update_changelog,
|
||||
update_debian_changelog,
|
||||
update_flake_version,
|
||||
@@ -20,84 +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"
|
||||
|
||||
# Pull BEFORE making any modifications
|
||||
ensure_clean_and_synced(preview=preview)
|
||||
|
||||
current_ver = determine_current_version()
|
||||
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})")
|
||||
|
||||
repo_root = os.path.dirname(os.path.abspath(pyproject_path))
|
||||
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)
|
||||
|
||||
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:
|
||||
@@ -107,150 +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,
|
||||
]
|
||||
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)
|
||||
tag_annotated(new_tag, tag_msg, preview=True)
|
||||
run(["push", "origin", branch, 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)
|
||||
tag_annotated(new_tag, tag_msg, preview=False)
|
||||
|
||||
# Push branch and ONLY the newly created version tag in one command (no --tags)
|
||||
run(["push", "origin", branch, 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,39 +1,434 @@
|
||||
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 (
|
||||
RepoRef,
|
||||
resolve_repos,
|
||||
run_on_repos,
|
||||
)
|
||||
from pkgmgr.core.git.commands import GitPushArgsError, push_args
|
||||
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
|
||||
|
||||
Repository = dict[str, Any]
|
||||
|
||||
# Re-signing opens pinentry; parallel pushes must not ask for the passphrase at once.
|
||||
_SIGN_LOCK = threading.Lock()
|
||||
|
||||
def _push_one(repo_dir: str, extra_args: list[str], preview: bool) -> tuple[bool, str]:
|
||||
_AUTHOR = re.compile(rb"(.*?) <([^>]*)> (\d+) ([+-]\d{4})")
|
||||
|
||||
|
||||
@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:
|
||||
"""
|
||||
Args:
|
||||
repo_dir: checkout about to be signed or pushed.
|
||||
|
||||
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.
|
||||
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:
|
||||
raise PushRefusedError(
|
||||
f"{repo_dir}: the repository config sets {', '.join(unsafe)}, which can "
|
||||
"run a program or reroute the push; unset it or move it to the global config"
|
||||
)
|
||||
|
||||
|
||||
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 _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:
|
||||
push_args(extra_args, cwd=repo_dir, preview=preview)
|
||||
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: read and check as usual, but print the signing instead of doing it.
|
||||
|
||||
"""
|
||||
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 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 tgit(target.tdir, "cherry", tip, sha).splitlines()
|
||||
if line.startswith("+")
|
||||
}
|
||||
lost = plus if lost is None else lost & plus
|
||||
if lost:
|
||||
raise PushRefusedError(
|
||||
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"
|
||||
)
|
||||
|
||||
|
||||
def push_branch(
|
||||
repo_dir: str,
|
||||
extra_args: list[str],
|
||||
*,
|
||||
sign: bool,
|
||||
refs: tuple[str, ...] = (),
|
||||
rewrite: bool = False,
|
||||
preview: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
repo_dir: checkout whose current branch is pushed.
|
||||
extra_args: flags appended to every `git push`.
|
||||
sign: refuse an unpushed, unsigned HEAD; False pushes it as it is.
|
||||
refs: extra refs (e.g. a release tag) pushed to every URL.
|
||||
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.
|
||||
|
||||
"""
|
||||
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))}"
|
||||
)
|
||||
|
||||
|
||||
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(
|
||||
repo_dir: str, extra_args: list[str], sign: bool, rewrite: bool, preview: bool
|
||||
) -> tuple[bool, str]:
|
||||
try:
|
||||
if sign:
|
||||
sign_unpushed(repo_dir, preview=preview)
|
||||
push_branch(repo_dir, extra_args, sign=sign, rewrite=rewrite, preview=preview)
|
||||
return (True, "")
|
||||
except GitPushArgsError as exc:
|
||||
except (GitRunError, PushRefusedError) as exc:
|
||||
return (False, str(exc))
|
||||
|
||||
|
||||
def push_repo_dirs(
|
||||
repos: list[RepoRef],
|
||||
extra_args: list[str],
|
||||
preview: bool,
|
||||
sign: bool,
|
||||
jobs: int = 1,
|
||||
rewrite: bool = False,
|
||||
) -> None:
|
||||
run_on_repos(
|
||||
repos,
|
||||
lambda rd: _push_one(rd, extra_args, sign, rewrite, preview),
|
||||
jobs=jobs,
|
||||
op_name="push",
|
||||
)
|
||||
|
||||
|
||||
def push_in_parallel(
|
||||
selected_repos: list[Repository],
|
||||
repositories_base_dir: str,
|
||||
all_repos: list[Repository],
|
||||
extra_args: list[str],
|
||||
preview: bool,
|
||||
sign: bool,
|
||||
jobs: int = 1,
|
||||
rewrite: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
Execute `git push` for each repository, optionally in parallel.
|
||||
"""
|
||||
repos = resolve_repos(selected_repos, repositories_base_dir, all_repos)
|
||||
run_on_repos(
|
||||
repos,
|
||||
lambda rd: _push_one(rd, extra_args, preview),
|
||||
push_repo_dirs(
|
||||
resolve_repos(selected_repos, repositories_base_dir, all_repos),
|
||||
extra_args,
|
||||
preview,
|
||||
sign,
|
||||
jobs=jobs,
|
||||
op_name="push",
|
||||
rewrite=rewrite,
|
||||
)
|
||||
@@ -0,0 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from .collect import collect_review
|
||||
from .model import ReviewError
|
||||
from .render import render_review, write_review
|
||||
|
||||
__all__ = ["ReviewError", "collect_review", "render_review", "write_review"]
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2019-2024 The Bootstrap Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,113 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from pkgmgr.actions.branch.gc import GITLINK
|
||||
from pkgmgr.core.git.errors import GitBaseError, GitRunError
|
||||
from pkgmgr.core.git.queries import FILTER_CONFIG, local_config
|
||||
from pkgmgr.core.git.run import run
|
||||
|
||||
from .model import FileView, ReviewError
|
||||
from .repo import git_text
|
||||
|
||||
ATTRIBUTE_BINARY = (
|
||||
"{} is shown as binary because {}, not because of its content: "
|
||||
"run git diff --text to see it."
|
||||
)
|
||||
UNSET = "a gitattributes entry unsets its diff attribute"
|
||||
DRIVER = "its gitattributes diff driver {0} sets diff.{0}.binary"
|
||||
RUNS = "a command git would run on this host"
|
||||
|
||||
|
||||
def hidden_entries(top: str) -> list[str]:
|
||||
listing = git_text(["ls-files", "-v", "-z"], top)
|
||||
return [
|
||||
f"Index entry {entry[2:]} is marked "
|
||||
f"{'skip-worktree' if entry[0] == 'S' else 'assume-unchanged'}: "
|
||||
"its worktree changes are not shown."
|
||||
for entry in listing.split("\0")
|
||||
if entry[:1] == "S" or entry[:1].islower()
|
||||
]
|
||||
|
||||
|
||||
def _binary_drivers(top: str) -> set[str]:
|
||||
try:
|
||||
out = run(
|
||||
["config", "-z", "--type=bool", "--get-regexp", r"^diff\..*\.binary$"],
|
||||
cwd=top,
|
||||
scan=True,
|
||||
)
|
||||
except GitRunError as exc:
|
||||
if exc.returncode == 1:
|
||||
return set()
|
||||
raise ReviewError("git config failed reading diff.<driver>.binary") from None
|
||||
last: dict[str, str] = {}
|
||||
for record in filter(None, out.split("\0")):
|
||||
key, _, value = record.partition("\n")
|
||||
last[key.removeprefix("diff.").removesuffix(".binary")] = value
|
||||
return {driver for driver, value in last.items() if value == "true"}
|
||||
|
||||
|
||||
def attribute_binary(files: list[FileView], top: str) -> list[str]:
|
||||
paths = list(dict.fromkeys(view.diff.path for view in files if view.diff.binary))
|
||||
if not paths:
|
||||
return []
|
||||
fields = git_text(["check-attr", "-z", "diff", "--", *paths], top).split("\0")
|
||||
reasons = {
|
||||
**{driver: DRIVER.format(driver) for driver in _binary_drivers(top)},
|
||||
"unset": UNSET,
|
||||
}
|
||||
return [
|
||||
ATTRIBUTE_BINARY.format(path, reasons[value])
|
||||
for path, value in zip(fields[0::3], fields[2::3])
|
||||
if value in reasons
|
||||
]
|
||||
|
||||
|
||||
def _submodule_configs(top: str, prefix: str) -> list[str]:
|
||||
"""
|
||||
Args:
|
||||
top: Real path of the top-level working tree.
|
||||
prefix: Submodule path below ``top`` whose gitlinks are walked, or ""
|
||||
for the top level itself.
|
||||
|
||||
Returns:
|
||||
One reason per populated submodule, nested ones included, whose
|
||||
config defines a filter or cannot be read. A gitlink behind a symbolic
|
||||
link or without a ``.git`` is skipped: git runs nothing there either.
|
||||
"""
|
||||
listing = git_text(["ls-files", "--stage", "-z"], os.path.join(top, prefix))
|
||||
gitlinks = dict.fromkeys(
|
||||
path
|
||||
for meta, _, path in (entry.partition("\t") for entry in listing.split("\0"))
|
||||
if meta.startswith(f"{GITLINK} ")
|
||||
)
|
||||
reasons: list[str] = []
|
||||
for path in gitlinks:
|
||||
relative = os.path.join(prefix, path)
|
||||
full = os.path.join(top, relative)
|
||||
if os.path.realpath(full) != full or not os.path.lexists(
|
||||
os.path.join(full, ".git")
|
||||
):
|
||||
continue
|
||||
try:
|
||||
keys = local_config(full, FILTER_CONFIG)
|
||||
nested = _submodule_configs(top, relative)
|
||||
except (GitBaseError, ReviewError):
|
||||
reasons.append(
|
||||
f"the config of submodule {relative} cannot be read, so its "
|
||||
"filters cannot be ruled out"
|
||||
)
|
||||
continue
|
||||
if keys:
|
||||
reasons.append(
|
||||
f"the config of submodule {relative} defines {', '.join(keys)}, {RUNS}"
|
||||
)
|
||||
reasons.extend(nested)
|
||||
return reasons
|
||||
|
||||
|
||||
def unsafe_configs(top: str) -> list[str]:
|
||||
keys = local_config(top, FILTER_CONFIG)
|
||||
own = [f"the repository config defines {', '.join(keys)}, {RUNS}"] if keys else []
|
||||
return own + _submodule_configs(os.path.realpath(top), "")
|
||||
@@ -0,0 +1,153 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from pkgmgr.core.git.run import END_OF_OPTIONS
|
||||
|
||||
from .checks import attribute_binary, hidden_entries, unsafe_configs
|
||||
from .diff import parse_patch
|
||||
from .files import read_note, untracked_views
|
||||
from .model import Commit, Review, Section
|
||||
from .repo import base_ref, git_optional, git_text, top_level
|
||||
from .views import file_views
|
||||
|
||||
DIFF_FLAGS = [
|
||||
"--no-color",
|
||||
"--no-ext-diff",
|
||||
"--no-textconv",
|
||||
"-M",
|
||||
"--submodule=short",
|
||||
"--ignore-submodules=none",
|
||||
"--src-prefix=a/",
|
||||
"--dst-prefix=b/",
|
||||
]
|
||||
|
||||
|
||||
def _commit(sha: str, anchor: str, top: str, limit: int) -> Commit:
|
||||
meta = git_text(
|
||||
[
|
||||
"show",
|
||||
"-s",
|
||||
"--no-color",
|
||||
"--no-show-signature",
|
||||
"--format=%h%x00%an <%ae>%x00%s%x00%b",
|
||||
END_OF_OPTIONS,
|
||||
sha,
|
||||
],
|
||||
top,
|
||||
)
|
||||
short, author, subject, body = meta.split("\0", 3)
|
||||
patch = git_text(
|
||||
[
|
||||
"show",
|
||||
"--format=",
|
||||
"--no-show-signature",
|
||||
"--diff-merges=first-parent",
|
||||
*DIFF_FLAGS,
|
||||
END_OF_OPTIONS,
|
||||
sha,
|
||||
],
|
||||
top,
|
||||
)
|
||||
return Commit(
|
||||
anchor=anchor,
|
||||
short=short,
|
||||
author=author,
|
||||
subject=subject,
|
||||
body=body.rstrip("\n"),
|
||||
files=file_views(parse_patch(patch), anchor, top, limit),
|
||||
)
|
||||
|
||||
|
||||
def collect_review(
|
||||
cwd: str, max_file_lines: int, base: str | None, notes: list[str]
|
||||
) -> Review:
|
||||
"""
|
||||
Args:
|
||||
cwd: Directory inside the git working copy to review.
|
||||
max_file_lines: Diff lines shown per file before the rest is summarised.
|
||||
base: Branch, under refs/heads/ or refs/remotes/, whose ``REF..HEAD``
|
||||
commits are listed, or None for no Commits section.
|
||||
notes: Regular text files shown verbatim at the top, relative to
|
||||
``cwd``; a symbolic link anywhere in the path is refused.
|
||||
|
||||
Returns:
|
||||
The collected Review model.
|
||||
"""
|
||||
top = top_level(cwd)
|
||||
base_name, base_sha = (None, None) if base is None else base_ref(base, top)
|
||||
note_items = tuple(read_note(path, cwd) for path in notes)
|
||||
unsafe = unsafe_configs(top)
|
||||
skipped = (
|
||||
f"Unstaged changes and index tree not computed: {'; '.join(unsafe)}."
|
||||
if unsafe
|
||||
else None
|
||||
)
|
||||
staged = Section(
|
||||
key="staged",
|
||||
title="Staged",
|
||||
files=file_views(
|
||||
parse_patch(git_text(["diff", "--cached", *DIFF_FLAGS], top)),
|
||||
"staged",
|
||||
top,
|
||||
max_file_lines,
|
||||
),
|
||||
skipped=None,
|
||||
)
|
||||
unstaged = Section(
|
||||
key="unstaged",
|
||||
title="Unstaged",
|
||||
files=()
|
||||
if skipped
|
||||
else file_views(
|
||||
parse_patch(git_text(["diff", *DIFF_FLAGS], top)),
|
||||
"unstaged",
|
||||
top,
|
||||
max_file_lines,
|
||||
),
|
||||
skipped=skipped,
|
||||
)
|
||||
untracked = Section(
|
||||
key="untracked",
|
||||
title="Untracked",
|
||||
files=untracked_views(top, max_file_lines),
|
||||
skipped=None,
|
||||
)
|
||||
commits: tuple[Commit, ...] = ()
|
||||
if base_sha is not None:
|
||||
shas = git_text(["rev-list", END_OF_OPTIONS, f"{base_sha}..HEAD"], top)
|
||||
commits = tuple(
|
||||
_commit(sha, f"commit-{index}", top, max_file_lines)
|
||||
for index, sha in enumerate(shas.split(), 1)
|
||||
)
|
||||
tracked = [
|
||||
*staged.files,
|
||||
*unstaged.files,
|
||||
*(view for commit in commits for view in commit.files),
|
||||
]
|
||||
return Review(
|
||||
top_level=top,
|
||||
name=os.path.basename(top),
|
||||
branch=git_optional(
|
||||
["symbolic-ref", "--short", "-q", END_OF_OPTIONS, "HEAD"], top
|
||||
),
|
||||
head=git_optional(
|
||||
["rev-parse", "--verify", "--quiet", "--short", END_OF_OPTIONS, "HEAD"],
|
||||
top,
|
||||
),
|
||||
index_tree="(not computed, see the warnings)"
|
||||
if skipped
|
||||
else git_optional(["write-tree"], top) or "(index has unmerged entries)",
|
||||
base=base_name,
|
||||
base_short=None
|
||||
if base_sha is None
|
||||
else git_text(["rev-parse", "--short", END_OF_OPTIONS, base_sha], top).strip(),
|
||||
warnings=tuple(
|
||||
([skipped] if skipped else [])
|
||||
+ hidden_entries(top)
|
||||
+ attribute_binary(tracked, top)
|
||||
),
|
||||
notes=note_items,
|
||||
sections=(staged, unstaged, untracked),
|
||||
commits=commits,
|
||||
)
|
||||
@@ -0,0 +1,154 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .model import FileDiff, Hunk, Line
|
||||
|
||||
HUNK_HEADER = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
|
||||
GIT_HEADER = "diff --git "
|
||||
ESCAPES = {
|
||||
"a": 7,
|
||||
"b": 8,
|
||||
"t": 9,
|
||||
"n": 10,
|
||||
"v": 11,
|
||||
"f": 12,
|
||||
"r": 13,
|
||||
'"': 34,
|
||||
"\\": 92,
|
||||
}
|
||||
HEADER_FIELDS = (
|
||||
"rename from ",
|
||||
"rename to ",
|
||||
"copy from ",
|
||||
"copy to ",
|
||||
"new file mode ",
|
||||
"deleted file mode ",
|
||||
"old mode ",
|
||||
"new mode ",
|
||||
"--- ",
|
||||
"+++ ",
|
||||
)
|
||||
|
||||
|
||||
def unquote(text: str) -> str:
|
||||
if len(text) < 2 or not (text.startswith('"') and text.endswith('"')):
|
||||
return text
|
||||
body = text[1:-1]
|
||||
raw = bytearray()
|
||||
index = 0
|
||||
while index < len(body):
|
||||
char = body[index]
|
||||
escaped = body[index + 1 : index + 2]
|
||||
octal = body[index + 1 : index + 4]
|
||||
if char == "\\" and escaped in ESCAPES:
|
||||
raw.append(ESCAPES[escaped])
|
||||
index += 2
|
||||
elif char == "\\" and len(octal) == 3 and set(octal) <= set("01234567"):
|
||||
raw.append(int(octal, 8) & 0xFF)
|
||||
index += 4
|
||||
else:
|
||||
raw.extend(char.encode("utf-8"))
|
||||
index += 1
|
||||
return raw.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def _side(value: str, prefix: str) -> str | None:
|
||||
value = value.removesuffix("\t")
|
||||
if value == "/dev/null":
|
||||
return None
|
||||
return unquote(value).removeprefix(prefix)
|
||||
|
||||
|
||||
def _file(
|
||||
git_line: str, headers: list[str], pending: list[tuple[str, int, list[Line]]]
|
||||
) -> FileDiff:
|
||||
fields: dict[str, str] = {}
|
||||
for header in headers:
|
||||
for key in HEADER_FIELDS:
|
||||
if header.startswith(key):
|
||||
fields[key.strip()] = header[len(key) :]
|
||||
break
|
||||
half = (len(git_line) - 1) // 2
|
||||
old_path = _side(git_line[:half], "a/")
|
||||
new_path = _side(git_line[half + 1 :], "b/")
|
||||
if "---" in fields:
|
||||
old_path = _side(fields["---"], "a/")
|
||||
if "+++" in fields:
|
||||
new_path = _side(fields["+++"], "b/")
|
||||
status = "modified"
|
||||
for kind, moved in (("rename", "renamed"), ("copy", "copied")):
|
||||
if f"{kind} from" in fields and f"{kind} to" in fields:
|
||||
old_path = unquote(fields[f"{kind} from"])
|
||||
new_path = unquote(fields[f"{kind} to"])
|
||||
status = moved
|
||||
if "new file mode" in fields:
|
||||
old_path, status = None, "added"
|
||||
if "deleted file mode" in fields:
|
||||
new_path, status = None, "deleted"
|
||||
mode_change = None
|
||||
if "old mode" in fields and "new mode" in fields:
|
||||
mode_change = f"{fields['old mode']} → {fields['new mode']}"
|
||||
return FileDiff(
|
||||
old_path=old_path,
|
||||
new_path=new_path,
|
||||
status=status,
|
||||
binary=any(header.startswith("Binary files ") for header in headers),
|
||||
mode_change=mode_change,
|
||||
hunks=tuple(
|
||||
Hunk(header, start, tuple(lines)) for header, start, lines in pending
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def parse_patch(text: str) -> list[FileDiff]:
|
||||
"""
|
||||
Args:
|
||||
text: Output of ``git diff`` or ``git show`` produced with ``a/`` and
|
||||
``b/`` prefixes and decoded without newline translation.
|
||||
|
||||
Returns:
|
||||
One FileDiff per ``diff --git`` block, in git's order.
|
||||
"""
|
||||
files: list[FileDiff] = []
|
||||
git_line: str | None = None
|
||||
headers: list[str] = []
|
||||
pending: list[tuple[str, int, list[Line]]] = []
|
||||
old_no = new_no = old_left = new_left = 0
|
||||
for raw in text.split("\n"):
|
||||
if pending and (old_left > 0 or new_left > 0):
|
||||
lines = pending[-1][2]
|
||||
sign, body = raw[:1], raw[1:]
|
||||
if sign == "+":
|
||||
lines.append(Line("add", None, new_no, body))
|
||||
new_no, new_left = new_no + 1, new_left - 1
|
||||
elif sign == "-":
|
||||
lines.append(Line("del", old_no, None, body))
|
||||
old_no, old_left = old_no + 1, old_left - 1
|
||||
elif sign == "\\":
|
||||
lines.append(Line("meta", None, None, raw))
|
||||
else:
|
||||
lines.append(Line("ctx", old_no, new_no, body))
|
||||
old_no, new_no = old_no + 1, new_no + 1
|
||||
old_left, new_left = old_left - 1, new_left - 1
|
||||
continue
|
||||
if raw.startswith(GIT_HEADER):
|
||||
if git_line is not None:
|
||||
files.append(_file(git_line, headers, pending))
|
||||
git_line, headers, pending = raw[len(GIT_HEADER) :], [], []
|
||||
continue
|
||||
if git_line is None:
|
||||
continue
|
||||
match = HUNK_HEADER.match(raw)
|
||||
if match:
|
||||
old_no, new_no = int(match[1]), int(match[3])
|
||||
old_left = 1 if match[2] is None else int(match[2])
|
||||
new_left = 1 if match[4] is None else int(match[4])
|
||||
pending.append((raw, new_no, []))
|
||||
elif pending and raw.startswith("\\"):
|
||||
pending[-1][2].append(Line("meta", None, None, raw))
|
||||
elif not pending:
|
||||
headers.append(raw)
|
||||
if git_line is not None:
|
||||
files.append(_file(git_line, headers, pending))
|
||||
return files
|
||||
@@ -0,0 +1,115 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import os
|
||||
import stat
|
||||
|
||||
from .model import FileDiff, FileView, Hunk, Line, Note, ReviewError
|
||||
from .repo import git_text
|
||||
from .views import BINARY_DETAIL, file_view
|
||||
|
||||
READ_MAX_BYTES = 1024 * 1024
|
||||
BINARY_SNIFF_BYTES = 8000
|
||||
|
||||
|
||||
def _listed(path: str, binary: bool) -> FileDiff:
|
||||
return FileDiff(
|
||||
old_path=None,
|
||||
new_path=path,
|
||||
status="untracked",
|
||||
binary=binary,
|
||||
mode_change=None,
|
||||
hunks=(),
|
||||
)
|
||||
|
||||
|
||||
def _read_regular(path: str, limit: int) -> tuple[bytes, int] | None:
|
||||
"""
|
||||
Args:
|
||||
path: Absolute path, opened one component at a time without following
|
||||
a symbolic link anywhere along it.
|
||||
limit: Most bytes to read.
|
||||
|
||||
Returns:
|
||||
The bytes read and the file size, or None when a component is a
|
||||
symbolic link or the target is not a regular file.
|
||||
"""
|
||||
names = [name for name in path.split(os.sep) if name not in ("", ".")]
|
||||
fd = os.open(os.sep, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
for index, name in enumerate(names, 1):
|
||||
kind = os.O_NONBLOCK if index == len(names) else os.O_DIRECTORY
|
||||
child = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | kind, dir_fd=fd)
|
||||
os.close(fd)
|
||||
fd = child
|
||||
info = os.fstat(fd)
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
return None
|
||||
with os.fdopen(os.dup(fd), "rb") as handle:
|
||||
return handle.read(limit), info.st_size
|
||||
except OSError as exc:
|
||||
if exc.errno in (errno.ELOOP, errno.ENOTDIR):
|
||||
return None
|
||||
raise
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def _untracked_file(path: str, top: str) -> tuple[FileDiff, str | None]:
|
||||
try:
|
||||
read = _read_regular(os.path.join(top, path), READ_MAX_BYTES + 1)
|
||||
except OSError as exc:
|
||||
return _listed(path, False), f"Unreadable: {exc.strerror}."
|
||||
if read is None:
|
||||
return _listed(path, False), "Not a regular file, contents not shown."
|
||||
data, size = read
|
||||
if len(data) > READ_MAX_BYTES:
|
||||
return _listed(path, False), f"Large file ({size} bytes), contents not shown."
|
||||
if b"\0" in data[:BINARY_SNIFF_BYTES]:
|
||||
return _listed(path, True), BINARY_DETAIL
|
||||
lines = data.decode("utf-8", "replace").split("\n")
|
||||
if lines[-1] == "":
|
||||
lines.pop()
|
||||
added = tuple(
|
||||
Line("add", None, number, text) for number, text in enumerate(lines, 1)
|
||||
)
|
||||
hunks = (Hunk(f"@@ -0,0 +1,{len(added)} @@", 1, added),) if added else ()
|
||||
return (
|
||||
FileDiff(
|
||||
old_path=None,
|
||||
new_path=path,
|
||||
status="untracked",
|
||||
binary=False,
|
||||
mode_change=None,
|
||||
hunks=hunks,
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def untracked_views(top: str, limit: int) -> tuple[FileView, ...]:
|
||||
listing = git_text(["ls-files", "--others", "--exclude-standard", "-z"], top)
|
||||
views = []
|
||||
for index, path in enumerate(sorted(p for p in listing.split("\0") if p), 1):
|
||||
diff, detail = _untracked_file(path, top)
|
||||
views.append(file_view(diff, f"untracked-{index}", top, limit, detail))
|
||||
return tuple(views)
|
||||
|
||||
|
||||
def read_note(path: str, cwd: str) -> Note:
|
||||
try:
|
||||
read = _read_regular(
|
||||
os.path.abspath(os.path.join(cwd, path)), READ_MAX_BYTES + 1
|
||||
)
|
||||
except OSError as exc:
|
||||
raise ReviewError(f"cannot read note {path!r}: {exc.strerror}") from None
|
||||
if read is None:
|
||||
raise ReviewError(
|
||||
f"cannot read note {path!r}: a symbolic link or not a regular file"
|
||||
)
|
||||
data, size = read
|
||||
if len(data) > READ_MAX_BYTES:
|
||||
raise ReviewError(
|
||||
f"cannot read note {path!r}: {size} bytes, more than {READ_MAX_BYTES}"
|
||||
)
|
||||
return Note(title=os.path.basename(path), text=data.decode("utf-8", "replace"))
|
||||
@@ -0,0 +1,136 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
class ReviewError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Line:
|
||||
kind: str
|
||||
old: int | None
|
||||
new: int | None
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Hunk:
|
||||
header: str
|
||||
new_start: int
|
||||
lines: tuple[Line, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileDiff:
|
||||
old_path: str | None
|
||||
new_path: str | None
|
||||
status: str
|
||||
binary: bool
|
||||
mode_change: str | None
|
||||
hunks: tuple[Hunk, ...]
|
||||
|
||||
@property
|
||||
def path(self) -> str:
|
||||
return self.new_path if self.new_path is not None else str(self.old_path)
|
||||
|
||||
@property
|
||||
def moved(self) -> bool:
|
||||
return self.status in ("renamed", "copied")
|
||||
|
||||
@property
|
||||
def added(self) -> int:
|
||||
return sum(
|
||||
1 for hunk in self.hunks for line in hunk.lines if line.kind == "add"
|
||||
)
|
||||
|
||||
@property
|
||||
def removed(self) -> int:
|
||||
return sum(
|
||||
1 for hunk in self.hunks for line in hunk.lines if line.kind == "del"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileView:
|
||||
anchor: str
|
||||
diff: FileDiff
|
||||
detail: str | None
|
||||
link_base: str | None
|
||||
link: str | None
|
||||
hunks: tuple[Hunk, ...]
|
||||
hidden: int
|
||||
|
||||
@property
|
||||
def search(self) -> str:
|
||||
if self.diff.moved:
|
||||
return f"{self.diff.old_path} {self.diff.new_path}"
|
||||
return self.diff.path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Section:
|
||||
key: str
|
||||
title: str
|
||||
files: tuple[FileView, ...]
|
||||
skipped: str | None
|
||||
|
||||
@property
|
||||
def added(self) -> int:
|
||||
return sum(view.diff.added for view in self.files)
|
||||
|
||||
@property
|
||||
def removed(self) -> int:
|
||||
return sum(view.diff.removed for view in self.files)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Commit:
|
||||
anchor: str
|
||||
short: str
|
||||
author: str
|
||||
subject: str
|
||||
body: str
|
||||
files: tuple[FileView, ...]
|
||||
|
||||
@property
|
||||
def added(self) -> int:
|
||||
return sum(view.diff.added for view in self.files)
|
||||
|
||||
@property
|
||||
def removed(self) -> int:
|
||||
return sum(view.diff.removed for view in self.files)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Note:
|
||||
title: str
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Review:
|
||||
top_level: str
|
||||
name: str
|
||||
branch: str | None
|
||||
head: str | None
|
||||
index_tree: str
|
||||
base: str | None
|
||||
base_short: str | None
|
||||
warnings: tuple[str, ...]
|
||||
notes: tuple[Note, ...]
|
||||
sections: tuple[Section, ...]
|
||||
commits: tuple[Commit, ...]
|
||||
|
||||
@property
|
||||
def commit_files(self) -> int:
|
||||
return sum(len(commit.files) for commit in self.commits)
|
||||
|
||||
@property
|
||||
def commit_added(self) -> int:
|
||||
return sum(commit.added for commit in self.commits)
|
||||
|
||||
@property
|
||||
def commit_removed(self) -> int:
|
||||
return sum(commit.removed for commit in self.commits)
|
||||
@@ -0,0 +1,86 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from jinja2 import Environment, FileSystemLoader, StrictUndefined
|
||||
|
||||
from .collect import collect_review
|
||||
from .model import Review, ReviewError
|
||||
|
||||
TEMPLATE = "review.html.j2"
|
||||
INVISIBLE = {
|
||||
code: f"<U+{code:04X}>"
|
||||
for code in (
|
||||
*range(0x200B, 0x2010),
|
||||
*range(0x202A, 0x202F),
|
||||
*range(0x2066, 0x206A),
|
||||
0x061C,
|
||||
0xFEFF,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def _csp_hash(text: str) -> str:
|
||||
digest = hashlib.sha256(str(text).encode("utf-8")).digest()
|
||||
return "sha256-" + base64.b64encode(digest).decode("ascii")
|
||||
|
||||
|
||||
def _visible(value: object) -> object:
|
||||
# not isinstance: Markup.translate() would splice the marks in unescaped,
|
||||
# and macro output is Markup whose text was already marked when built
|
||||
return value.translate(INVISIBLE) if type(value) is str else value
|
||||
|
||||
|
||||
def render_review(review: Review) -> str:
|
||||
environment = Environment(
|
||||
loader=FileSystemLoader(os.path.dirname(os.path.abspath(__file__))),
|
||||
autoescape=True,
|
||||
undefined=StrictUndefined,
|
||||
trim_blocks=True,
|
||||
lstrip_blocks=True,
|
||||
keep_trailing_newline=True,
|
||||
finalize=_visible,
|
||||
)
|
||||
environment.filters["csp_hash"] = _csp_hash
|
||||
return environment.get_template(TEMPLATE).render(review=review)
|
||||
|
||||
|
||||
def write_review(
|
||||
cwd: str, out: str, max_file_lines: int, base: str | None, notes: list[str]
|
||||
) -> str:
|
||||
"""
|
||||
Args:
|
||||
cwd: Directory inside the git working copy to review.
|
||||
out: Output HTML path, relative to ``cwd`` unless absolute; written as
|
||||
a new mode 0600 file renamed onto it, so a symbolic link there is
|
||||
replaced, never followed.
|
||||
max_file_lines: Diff lines shown per file before the rest is summarised.
|
||||
base: Branch whose ``REF..HEAD`` commits are listed, or None.
|
||||
notes: Text files shown verbatim at the top of the page.
|
||||
|
||||
Returns:
|
||||
The absolute path of the written page.
|
||||
"""
|
||||
html = render_review(
|
||||
collect_review(cwd=cwd, max_file_lines=max_file_lines, base=base, notes=notes)
|
||||
)
|
||||
path = os.path.abspath(os.path.join(cwd, out))
|
||||
directory = os.path.dirname(path)
|
||||
try:
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
fd, temp = tempfile.mkstemp(prefix=".review-", suffix=".tmp", dir=directory)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(html)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp, path)
|
||||
except OSError:
|
||||
os.unlink(temp)
|
||||
raise
|
||||
except OSError as exc:
|
||||
raise ReviewError(f"cannot write {path!r}: {exc.strerror}") from None
|
||||
return path
|
||||
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user