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: "/"
|
directory: "/"
|
||||||
schedule:
|
schedule:
|
||||||
interval: "weekly"
|
interval: "weekly"
|
||||||
day: "monday"
|
open-pull-requests-limit: 0
|
||||||
time: "00:00"
|
groups:
|
||||||
rebase-strategy: "auto"
|
pip-security:
|
||||||
|
applies-to: security-updates
|
||||||
|
patterns: ["*"]
|
||||||
labels:
|
labels:
|
||||||
- "dependencies"
|
- "dependencies"
|
||||||
- "python"
|
|
||||||
|
|
||||||
- package-ecosystem: "github-actions"
|
- package-ecosystem: "github-actions"
|
||||||
directory: "/"
|
directory: "/"
|
||||||
schedule:
|
schedule:
|
||||||
interval: "weekly"
|
interval: "weekly"
|
||||||
day: "monday"
|
groups:
|
||||||
time: "00:00"
|
github-actions:
|
||||||
|
applies-to: version-updates
|
||||||
|
patterns: ["*"]
|
||||||
labels:
|
labels:
|
||||||
- "dependencies"
|
- "dependencies"
|
||||||
- "ci"
|
|
||||||
@@ -46,15 +46,10 @@ jobs:
|
|||||||
contents: read
|
contents: read
|
||||||
uses: ./.github/workflows/test-e2e.yml
|
uses: ./.github/workflows/test-e2e.yml
|
||||||
|
|
||||||
test-virgin-user:
|
test-virgin:
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
uses: ./.github/workflows/test-virgin-user.yml
|
uses: ./.github/workflows/test-virgin.yml
|
||||||
|
|
||||||
test-virgin-root:
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
uses: ./.github/workflows/test-virgin-root.yml
|
|
||||||
|
|
||||||
lint-shell:
|
lint-shell:
|
||||||
permissions:
|
permissions:
|
||||||
@@ -71,3 +66,9 @@ jobs:
|
|||||||
contents: read
|
contents: read
|
||||||
security-events: write
|
security-events: write
|
||||||
uses: ./.github/workflows/lint-docker.yml
|
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,7 +15,7 @@ jobs:
|
|||||||
security-events: write
|
security-events: write
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Run hadolint (produce SARIF)
|
- name: Run hadolint (produce SARIF)
|
||||||
id: hadolint
|
id: hadolint
|
||||||
@@ -29,7 +29,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload analysis results to GitHub
|
- name: Upload analysis results to GitHub
|
||||||
if: always()
|
if: always()
|
||||||
uses: github/codeql-action/upload-sarif@v4
|
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||||
with:
|
with:
|
||||||
sarif_file: hadolint-results.sarif
|
sarif_file: hadolint-results.sarif
|
||||||
wait-for-processing: true
|
wait-for-processing: true
|
||||||
|
|||||||
@@ -8,19 +8,7 @@ permissions:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint-python:
|
lint-python:
|
||||||
runs-on: ubuntu-latest
|
uses: infinito-nexus/quality/.github/workflows/tool.yml@2eaac6f644eb4c47102bd8cc353635c71af5dab9 # v1.2.0
|
||||||
|
with:
|
||||||
steps:
|
tool: ruff
|
||||||
- uses: actions/checkout@v7
|
args: check src tests
|
||||||
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v7
|
|
||||||
with:
|
|
||||||
python-version: "3.12"
|
|
||||||
|
|
||||||
- name: Install ruff
|
|
||||||
run: pip install ruff
|
|
||||||
|
|
||||||
- name: Run ruff
|
|
||||||
run: |
|
|
||||||
ruff check src tests
|
|
||||||
@@ -10,7 +10,7 @@ jobs:
|
|||||||
lint-shell:
|
lint-shell:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
- name: Install ShellCheck
|
- name: Install ShellCheck
|
||||||
run: sudo apt-get update && sudo apt-get install -y shellcheck
|
run: sudo apt-get update && sudo apt-get install -y shellcheck
|
||||||
- name: Run ShellCheck
|
- name: Run ShellCheck
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ on:
|
|||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- 'v*'
|
- 'v*'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
mark-stable:
|
mark-stable:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -19,7 +23,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
fetch-tags: true # We need tags and main history for version comparison
|
fetch-tags: true # We need tags and main history for version comparison
|
||||||
|
|||||||
@@ -4,56 +4,121 @@ on:
|
|||||||
workflow_run:
|
workflow_run:
|
||||||
workflows: ["Mark stable commit"]
|
workflows: ["Mark stable commit"]
|
||||||
types: [completed]
|
types: [completed]
|
||||||
|
schedule:
|
||||||
|
- cron: "0 3 * * *"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
prepare:
|
||||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event_name != 'workflow_run' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository) }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
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
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: write
|
packages: write
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
distro: *distros
|
||||||
|
release: ${{ fromJSON(needs.prepare.outputs.releases) }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository (with tags)
|
- name: Checkout ${{ matrix.release.version }}
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
ref: ${{ matrix.release.sha }}
|
||||||
|
|
||||||
- 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
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
if: ${{ steps.info.outputs.should_publish == 'true' }}
|
|
||||||
uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003
|
uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003
|
||||||
with:
|
with:
|
||||||
use: true
|
use: true
|
||||||
|
|
||||||
- name: Login to GHCR
|
- name: Login to GHCR
|
||||||
if: ${{ steps.info.outputs.should_publish == 'true' }}
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
|
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
- name: Publish all images
|
- name: Join both platforms of ${{ matrix.distro }} ${{ matrix.release.version }} under its tags
|
||||||
if: ${{ steps.info.outputs.should_publish == 'true' }}
|
|
||||||
env:
|
env:
|
||||||
OWNER: ${{ github.repository_owner }}
|
OWNER: ${{ github.repository_owner }}
|
||||||
VERSION: ${{ steps.info.outputs.version }}
|
VERSION: ${{ matrix.release.version }}
|
||||||
IS_STABLE: ${{ steps.info.outputs.is_stable }}
|
ALIASES: ${{ matrix.release.aliases }}
|
||||||
run: bash scripts/github/publish-containers/publish-container-images.sh
|
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:
|
on:
|
||||||
workflow_call:
|
workflow_call:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
analyze:
|
analyze:
|
||||||
name: Check security
|
name: Check security
|
||||||
@@ -23,10 +26,10 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Initialize CodeQL
|
- name: Initialize CodeQL
|
||||||
uses: github/codeql-action/init@v4
|
uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
build-mode: ${{ matrix.build-mode }}
|
build-mode: ${{ matrix.build-mode }}
|
||||||
@@ -42,6 +45,6 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
- name: Perform CodeQL Analysis
|
||||||
uses: github/codeql-action/analyze@v4
|
uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||||
with:
|
with:
|
||||||
category: "/language:${{ matrix.language }}"
|
category: "/language:${{ matrix.language }}"
|
||||||
@@ -19,7 +19,7 @@ jobs:
|
|||||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Show Docker version
|
- name: Show Docker version
|
||||||
run: docker version
|
run: docker version
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ jobs:
|
|||||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Show Docker version
|
- name: Show Docker version
|
||||||
run: docker version
|
run: docker version
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ jobs:
|
|||||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Show commit SHA
|
- name: Show commit SHA
|
||||||
run: git rev-parse HEAD
|
run: git rev-parse HEAD
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ jobs:
|
|||||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Show Docker version
|
- name: Show Docker version
|
||||||
run: docker version
|
run: docker version
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ jobs:
|
|||||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Show Docker version
|
- name: Show Docker version
|
||||||
run: 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@v7
|
|
||||||
|
|
||||||
- name: Show Docker version
|
|
||||||
run: docker version
|
|
||||||
|
|
||||||
- name: Pull base image (${{ matrix.distro }})
|
|
||||||
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest"
|
|
||||||
|
|
||||||
- name: Virgin ${{ matrix.distro }} pkgmgr test (root)
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
docker run --rm \
|
|
||||||
-v "$PWD":/opt/src/pkgmgr \
|
|
||||||
-v pkgmgr_repos:/root/Repositories \
|
|
||||||
-v pkgmgr_pip_cache:/root/.cache/pip \
|
|
||||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
|
||||||
-w /opt/src/pkgmgr \
|
|
||||||
"ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest" \
|
|
||||||
bash -lc '
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
git config --global --add safe.directory /opt/src/pkgmgr
|
|
||||||
|
|
||||||
make install
|
|
||||||
make setup
|
|
||||||
|
|
||||||
. "$HOME/.venvs/pkgmgr/bin/activate"
|
|
||||||
|
|
||||||
pkgmgr update pkgmgr --clone-mode shallow --no-verification
|
|
||||||
pkgmgr version pkgmgr
|
|
||||||
|
|
||||||
echo ">>> Running Nix-based: nix run .#pkgmgr -- version pkgmgr"
|
|
||||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
|
||||||
'
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
name: Test Virgin User
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
test-virgin-user:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
timeout-minutes: 45
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
distro: [arch, debian, ubuntu, fedora, centos]
|
|
||||||
env:
|
|
||||||
NIX_CONFIG: |
|
|
||||||
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- name: Show Docker version
|
|
||||||
run: docker version
|
|
||||||
|
|
||||||
- name: Pull base image (${{ matrix.distro }})
|
|
||||||
run: docker pull "ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest"
|
|
||||||
|
|
||||||
- name: Virgin ${{ matrix.distro }} pkgmgr test (user)
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
docker run --rm \
|
|
||||||
-v "$PWD":/opt/src/pkgmgr \
|
|
||||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
|
||||||
-w /opt/src/pkgmgr \
|
|
||||||
"ghcr.io/kevinveenbirkenbach/base-${{ matrix.distro }}:latest" \
|
|
||||||
bash -lc '
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
make install
|
|
||||||
|
|
||||||
useradd -m dev
|
|
||||||
echo "dev ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/dev
|
|
||||||
chmod 0440 /etc/sudoers.d/dev
|
|
||||||
chown -R dev:dev /opt/src/pkgmgr
|
|
||||||
|
|
||||||
mkdir -p /nix/store /nix/var/nix /nix/var/log/nix /nix/var/nix/profiles
|
|
||||||
chown -R dev:dev /nix
|
|
||||||
chmod 0755 /nix
|
|
||||||
chmod 1777 /nix/store
|
|
||||||
sudo -H -u dev env \
|
|
||||||
HOME=/home/dev \
|
|
||||||
NIX_CONFIG="$NIX_CONFIG" \
|
|
||||||
PKGMGR_DISABLE_NIX_FLAKE_INSTALLER=1 \
|
|
||||||
bash -lc "
|
|
||||||
set -euo pipefail
|
|
||||||
cd /opt/src/pkgmgr
|
|
||||||
make setup-venv
|
|
||||||
. \"\$HOME/.venvs/pkgmgr/bin/activate\"
|
|
||||||
|
|
||||||
pkgmgr version pkgmgr
|
|
||||||
|
|
||||||
export NIX_REMOTE=local
|
|
||||||
nix run /opt/src/pkgmgr#pkgmgr -- version pkgmgr
|
|
||||||
"
|
|
||||||
'
|
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
name: Test Virgin
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test-virgin:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 45
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
mode: [user, root]
|
||||||
|
distro: [arch, debian, ubuntu, fedora, centos]
|
||||||
|
env:
|
||||||
|
NIX_CONFIG: |
|
||||||
|
access-tokens = github.com=${{ secrets.GITHUB_TOKEN }}
|
||||||
|
MODE: ${{ matrix.mode }}
|
||||||
|
DISTRO: ${{ matrix.distro }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@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:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
|
||||||
- name: Install Nix
|
- name: Install Nix
|
||||||
uses: DeterminateSystems/nix-installer-action@v23
|
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
|
||||||
|
|
||||||
- name: Update flake.lock and open a pull request
|
- name: Update flake.lock and open a pull request
|
||||||
uses: DeterminateSystems/update-flake-lock@v29
|
uses: DeterminateSystems/update-flake-lock@da03c0f078bc4b2c37ee4f7e072d34bf8f188bb3 # v29
|
||||||
with:
|
with:
|
||||||
pr-title: "chore(deps): update flake.lock"
|
pr-title: "chore(deps): update flake.lock"
|
||||||
pr-labels: |
|
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.
|
||||||
+116
@@ -1,5 +1,121 @@
|
|||||||
# Changelog
|
# 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
|
## [2.1.0] - 2026-10-31
|
||||||
|
|
||||||
Added:
|
Added:
|
||||||
|
|||||||
@@ -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 🗺️
|
## Architecture & Setup Map 🗺️
|
||||||
|
|
||||||
The following diagram gives a full overview of:
|
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/`:
|
All images live under `ghcr.io/kevinveenbirkenbach/`:
|
||||||
|
|
||||||
| Tag | Contains |
|
| Tag | Contains |
|
||||||
| --------------------------- | ---------------------------------- |
|
| ------------------------------------- | --------------------------------------------------------- |
|
||||||
| `pkgmgr-<distro>:latest` | newest build for that distribution |
|
| `pkgmgr-<distro>:latest` | newest build of the newest release on `main` |
|
||||||
| `pkgmgr-<distro>:<version>` | one release |
|
| `pkgmgr-<distro>:stable` | newest build of the release the git tag `stable` marks |
|
||||||
| `pkgmgr-<distro>:stable` | newest release marked stable |
|
| `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
|
`<distro>` is one of `arch`, `debian`, `ubuntu`, `fedora`, `centos`. The Arch
|
||||||
image is published without the suffix as well, so `pkgmgr:stable` and
|
image is published without the suffix as well, so `pkgmgr:stable` and
|
||||||
`pkgmgr-arch:stable` are the same image.
|
`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,
|
For a clean environment that carries the system dependencies but no PKGMGR,
|
||||||
pull `base-<distro>` from
|
pull `base-<distro>` from
|
||||||
[base-images](https://github.com/kevinveenbirkenbach/base-images) directly.
|
[base-images](https://github.com/kevinveenbirkenbach/base-images) directly.
|
||||||
|
|||||||
Generated
+3
-3
@@ -2,11 +2,11 @@
|
|||||||
"nodes": {
|
"nodes": {
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1771714954,
|
"lastModified": 1782847189,
|
||||||
"narHash": "sha256-nhZJPnBavtu40/L2aqpljrfUNb2rxmWTmSjK2c9UKds=",
|
"narHash": "sha256-twXPFqFsrrY5r28Zh7Homgcp2gUMBgQ6WDS98Q/3xFI=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "afbbf774e2087c3d734266c22f96fca2e78d3620",
|
"rev": "b6018f87da91d19d0ab4cf979885689b469cdd41",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|||||||
@@ -32,7 +32,7 @@
|
|||||||
rec {
|
rec {
|
||||||
pkgmgr = pyPkgs.buildPythonApplication {
|
pkgmgr = pyPkgs.buildPythonApplication {
|
||||||
pname = "package-manager";
|
pname = "package-manager";
|
||||||
version = "2.1.0";
|
version = "2.6.0";
|
||||||
|
|
||||||
# Use the git repo as source
|
# Use the git repo as source
|
||||||
src = ./.;
|
src = ./.;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Maintainer: Kevin Veen-Birkenbach <info@veen.world>
|
# Maintainer: Kevin Veen-Birkenbach <info@veen.world>
|
||||||
|
|
||||||
pkgname=package-manager
|
pkgname=package-manager
|
||||||
pkgver=2.1.0
|
pkgver=2.6.0
|
||||||
pkgrel=1
|
pkgrel=1
|
||||||
pkgdesc="Local-flake wrapper for Kevin's package-manager (Nix-based)."
|
pkgdesc="Local-flake wrapper for Kevin's package-manager (Nix-based)."
|
||||||
arch=('any')
|
arch=('any')
|
||||||
|
|||||||
@@ -1,3 +1,131 @@
|
|||||||
|
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
|
package-manager (2.1.0-1) unstable; urgency=medium
|
||||||
|
|
||||||
Added:
|
Added:
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
Name: package-manager
|
Name: package-manager
|
||||||
Version: 2.1.0
|
Version: 2.6.0
|
||||||
Release: 1%{?dist}
|
Release: 1%{?dist}
|
||||||
Summary: Wrapper that runs Kevin's package-manager via Nix flake
|
Summary: Wrapper that runs Kevin's package-manager via Nix flake
|
||||||
|
|
||||||
@@ -74,6 +74,116 @@ echo ">>> package-manager removed. Nix itself was not removed."
|
|||||||
/usr/lib/package-manager/
|
/usr/lib/package-manager/
|
||||||
|
|
||||||
%changelog
|
%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
|
* Sat Oct 31 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.1.0-1
|
||||||
- Added:
|
- Added:
|
||||||
|
|
||||||
|
|||||||
+3
-2
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "kpmx"
|
name = "kpmx"
|
||||||
version = "2.1.0"
|
version = "2.6.0"
|
||||||
description = "Kevin's package-manager tool (pkgmgr)"
|
description = "Kevin's package-manager tool (pkgmgr)"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.9"
|
requires-python = ">=3.9"
|
||||||
@@ -21,7 +21,7 @@ authors = [
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"PyYAML>=6.0",
|
"PyYAML>=6.0",
|
||||||
"tomli; python_version < \"3.11\"",
|
"tomli; python_version < \"3.11\"",
|
||||||
"jinja2>=3.1"
|
"jinja2>=3.1.6"
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
@@ -52,3 +52,4 @@ include = ["pkgmgr*"]
|
|||||||
|
|
||||||
[tool.setuptools.package-data]
|
[tool.setuptools.package-data]
|
||||||
"pkgmgr.config" = ["*.yml", "*.yaml"]
|
"pkgmgr.config" = ["*.yml", "*.yaml"]
|
||||||
|
"pkgmgr.actions.review" = ["*.j2", "*.LICENSE"]
|
||||||
@@ -30,3 +30,24 @@ resolve_platforms() {
|
|||||||
*) echo "ERROR: Unknown distro '$PKGMGR_DISTRO'" >&2; exit 1 ;;
|
*) echo "ERROR: Unknown distro '$PKGMGR_DISTRO'" >&2; exit 1 ;;
|
||||||
esac
|
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
|
MISSING_ONLY=0
|
||||||
IMAGE_TAG="" # local image name or base tag (without registry)
|
IMAGE_TAG="" # local image name or base tag (without registry)
|
||||||
PUSH=0 # if 1 -> use buildx and push (requires docker buildx)
|
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
|
REGISTRY="" # e.g. ghcr.io
|
||||||
OWNER="" # e.g. github org/user
|
OWNER="" # e.g. github org/user
|
||||||
REPO_PREFIX="pkgmgr" # image base name (pkgmgr)
|
REPO_PREFIX="pkgmgr" # image base name (pkgmgr)
|
||||||
VERSION="" # X.Y.Z (required for --publish)
|
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"
|
DEFAULT_DISTRO="arch"
|
||||||
|
|
||||||
usage() {
|
usage() {
|
||||||
@@ -33,15 +36,24 @@ Build options:
|
|||||||
|
|
||||||
Publish options:
|
Publish options:
|
||||||
--push Push the built image (uses docker buildx build --push)
|
--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)
|
--registry <reg> Registry (e.g. ghcr.io)
|
||||||
--owner <owner> Registry namespace (e.g. \${GITHUB_REPOSITORY_OWNER})
|
--owner <owner> Registry namespace (e.g. \${GITHUB_REPOSITORY_OWNER})
|
||||||
--repo-prefix <name> Image base name (default: pkgmgr)
|
--repo-prefix <name> Image base name (default: pkgmgr)
|
||||||
--version <X.Y.Z> Version for --publish
|
--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:
|
Notes:
|
||||||
- --publish implies --push and requires --registry, --owner, and --version.
|
- --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".
|
- Local build (no --push) uses "docker build" and creates a local image like "pkgmgr-arch".
|
||||||
EOF
|
EOF
|
||||||
}
|
}
|
||||||
@@ -77,11 +89,18 @@ while [[ $# -gt 0 ]]; do
|
|||||||
[[ -n "${VERSION}" ]] || { echo "ERROR: --version requires a value"; exit 2; }
|
[[ -n "${VERSION}" ]] || { echo "ERROR: --version requires a value"; exit 2; }
|
||||||
shift 2
|
shift 2
|
||||||
;;
|
;;
|
||||||
--stable)
|
--aliases)
|
||||||
IS_STABLE="${2:-}"
|
[[ $# -ge 2 ]] || { echo "ERROR: --aliases requires a value, empty for none"; exit 2; }
|
||||||
[[ -n "${IS_STABLE}" ]] || { echo "ERROR: --stable requires a value (true|false)"; exit 2; }
|
ALIASES="$2"
|
||||||
|
ALIASES_SET=1
|
||||||
shift 2
|
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 ;;
|
-h|--help) usage; exit 0 ;;
|
||||||
*)
|
*)
|
||||||
echo "ERROR: Unknown argument: $1" >&2
|
echo "ERROR: Unknown argument: $1" >&2
|
||||||
@@ -115,8 +134,24 @@ if [[ "${PUBLISH}" == "1" ]]; then
|
|||||||
[[ -n "${REGISTRY}" ]] || { echo "ERROR: --publish requires --registry"; exit 2; }
|
[[ -n "${REGISTRY}" ]] || { echo "ERROR: --publish requires --registry"; exit 2; }
|
||||||
[[ -n "${OWNER}" ]] || { echo "ERROR: --publish requires --owner"; exit 2; }
|
[[ -n "${OWNER}" ]] || { echo "ERROR: --publish requires --owner"; exit 2; }
|
||||||
[[ -n "${VERSION}" ]] || { echo "ERROR: --publish requires --version"; 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
|
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
|
# Guard: --push without --publish requires fully-qualified --tag
|
||||||
if [[ "${PUSH}" == "1" && "${PUBLISH}" != "1" ]]; then
|
if [[ "${PUSH}" == "1" && "${PUBLISH}" != "1" ]]; then
|
||||||
if [[ "${IMAGE_TAG}" != */* ]]; then
|
if [[ "${IMAGE_TAG}" != */* ]]; then
|
||||||
@@ -130,7 +165,7 @@ echo "------------------------------------------------------------"
|
|||||||
echo "[build] Building image"
|
echo "[build] Building image"
|
||||||
echo "distro = ${PKGMGR_DISTRO}"
|
echo "distro = ${PKGMGR_DISTRO}"
|
||||||
echo "BASE_IMAGE = ${BASE_IMAGE}"
|
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 [[ "${NO_CACHE}" == "1" ]]; then echo "cache = disabled"; fi
|
||||||
if [[ "${PUSH}" == "1" ]]; then echo "push = enabled"; fi
|
if [[ "${PUSH}" == "1" ]]; then echo "push = enabled"; fi
|
||||||
if [[ "${PUBLISH}" == "1" ]]; then
|
if [[ "${PUBLISH}" == "1" ]]; then
|
||||||
@@ -138,7 +173,8 @@ if [[ "${PUBLISH}" == "1" ]]; then
|
|||||||
echo "registry = ${REGISTRY}"
|
echo "registry = ${REGISTRY}"
|
||||||
echo "owner = ${OWNER}"
|
echo "owner = ${OWNER}"
|
||||||
echo "version = ${VERSION}"
|
echo "version = ${VERSION}"
|
||||||
echo "stable = ${IS_STABLE}"
|
echo "stamp = ${STAMP}"
|
||||||
|
echo "aliases = ${ALIASES}"
|
||||||
fi
|
fi
|
||||||
echo "------------------------------------------------------------"
|
echo "------------------------------------------------------------"
|
||||||
|
|
||||||
@@ -149,45 +185,113 @@ if [[ "${NO_CACHE}" == "1" ]]; then
|
|||||||
build_args+=(--no-cache)
|
build_args+=(--no-cache)
|
||||||
fi
|
fi
|
||||||
|
|
||||||
compute_publish_tags() {
|
publish_bases() {
|
||||||
local distro_tag_base="${REGISTRY}/${OWNER}/${REPO_PREFIX}-${PKGMGR_DISTRO}"
|
echo "${DISTRO_TAG_BASE}"
|
||||||
local alias_tag_base=""
|
|
||||||
|
|
||||||
if [[ "${PKGMGR_DISTRO}" == "${DEFAULT_DISTRO}" ]]; then
|
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
|
fi
|
||||||
|
|
||||||
local tags=()
|
if ((${#tags[@]} == 0)); then
|
||||||
tags+=("${distro_tag_base}:latest")
|
echo "[build] ${PKGMGR_DISTRO} ${VERSION}: every tag already joins these platform images, nothing to push."
|
||||||
tags+=("${distro_tag_base}:${VERSION}")
|
exit 0
|
||||||
|
|
||||||
if [[ "${IS_STABLE}" == "true" ]]; then
|
|
||||||
tags+=("${distro_tag_base}:stable")
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ -n "${alias_tag_base}" ]]; then
|
create_args=()
|
||||||
tags+=("${alias_tag_base}:latest")
|
for t in "${tags[@]}"; do
|
||||||
tags+=("${alias_tag_base}:${VERSION}")
|
create_args+=(-t "$t")
|
||||||
if [[ "${IS_STABLE}" == "true" ]]; then
|
done
|
||||||
tags+=("${alias_tag_base}:stable")
|
|
||||||
|
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
|
||||||
fi
|
fi
|
||||||
|
|
||||||
printf '%s\n' "${tags[@]}"
|
|
||||||
}
|
|
||||||
|
|
||||||
if [[ "${PUSH}" == "1" ]]; then
|
|
||||||
bx_args=(docker buildx build --push)
|
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
|
while IFS= read -r t; do
|
||||||
bx_args+=(-t "$t")
|
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
|
else
|
||||||
bx_args+=(-t "${IMAGE_TAG}")
|
bx_args+=(-t "${IMAGE_TAG}")
|
||||||
fi
|
fi
|
||||||
|
|
||||||
bx_args+=(--platform "$(resolve_platforms "$PKGMGR_DISTRO")")
|
bx_args+=(--platform "${PLATFORM:-$(resolve_platforms "$PKGMGR_DISTRO")}")
|
||||||
bx_args+=("${build_args[@]}")
|
bx_args+=("${build_args[@]}")
|
||||||
bx_args+=(.)
|
bx_args+=(.)
|
||||||
|
|
||||||
|
|||||||
@@ -6,25 +6,28 @@ set -euo pipefail
|
|||||||
# Required env:
|
# Required env:
|
||||||
# OWNER (e.g. GITHUB_REPOSITORY_OWNER)
|
# OWNER (e.g. GITHUB_REPOSITORY_OWNER)
|
||||||
# VERSION (e.g. 1.2.3)
|
# 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:
|
# Optional env:
|
||||||
# REGISTRY (default: ghcr.io)
|
# REGISTRY (default: ghcr.io)
|
||||||
# IS_STABLE (default: false)
|
|
||||||
# DISTROS (default: "arch debian ubuntu fedora centos")
|
# DISTROS (default: "arch debian ubuntu fedora centos")
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
|
||||||
|
# shellcheck source=./scripts/build/base.sh
|
||||||
|
source "${SCRIPT_DIR}/base.sh"
|
||||||
|
|
||||||
REGISTRY="${REGISTRY:-ghcr.io}"
|
REGISTRY="${REGISTRY:-ghcr.io}"
|
||||||
IS_STABLE="${IS_STABLE:-false}"
|
|
||||||
DISTROS="${DISTROS:-arch debian ubuntu fedora centos}"
|
DISTROS="${DISTROS:-arch debian ubuntu fedora centos}"
|
||||||
|
|
||||||
: "${OWNER:?Environment variable OWNER must be set (e.g. github.repository_owner)}"
|
: "${OWNER:?Environment variable OWNER must be set (e.g. github.repository_owner)}"
|
||||||
: "${VERSION:?Environment variable VERSION must be set (e.g. 1.2.3)}"
|
: "${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] REGISTRY=${REGISTRY}"
|
||||||
echo "[publish] OWNER=${OWNER}"
|
echo "[publish] OWNER=${OWNER}"
|
||||||
echo "[publish] VERSION=${VERSION}"
|
echo "[publish] VERSION=${VERSION}"
|
||||||
echo "[publish] IS_STABLE=${IS_STABLE}"
|
echo "[publish] ALIASES=${ALIASES}"
|
||||||
echo "[publish] DISTROS=${DISTROS}"
|
echo "[publish] DISTROS=${DISTROS}"
|
||||||
|
|
||||||
for d in ${DISTROS}; do
|
for d in ${DISTROS}; do
|
||||||
@@ -33,12 +36,23 @@ for d in ${DISTROS}; do
|
|||||||
echo "[publish] PKGMGR_DISTRO=${d}"
|
echo "[publish] PKGMGR_DISTRO=${d}"
|
||||||
echo "============================================================"
|
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" \
|
PKGMGR_DISTRO="${d}" bash "${SCRIPT_DIR}/image.sh" \
|
||||||
--publish \
|
--publish \
|
||||||
--registry "${REGISTRY}" \
|
--registry "${REGISTRY}" \
|
||||||
--owner "${OWNER}" \
|
--owner "${OWNER}" \
|
||||||
--version "${VERSION}" \
|
--version "${VERSION}" \
|
||||||
--stable "${IS_STABLE}"
|
--aliases "${ALIASES}" \
|
||||||
|
--merge
|
||||||
done
|
done
|
||||||
|
|
||||||
echo
|
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
|
#!/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
|
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)"
|
# shellcheck source=scripts/build/base.sh
|
||||||
if [[ -z "${V_TAG}" ]]; then
|
source "${SCRIPT_DIR}/../../build/base.sh"
|
||||||
echo "No version tag found for ${SHA}. Skipping publish."
|
|
||||||
echo "should_publish=false" >> "$GITHUB_OUTPUT"
|
: "${WORKFLOW_RUN_SHA?WORKFLOW_RUN_SHA must be set, empty for a rebuild}"
|
||||||
exit 0
|
: "${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
|
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)"
|
json=""
|
||||||
IS_STABLE=false
|
for version in "${targets[@]}"; do
|
||||||
[[ -n "${STABLE_SHA}" && "${STABLE_SHA}" == "${SHA}" ]] && IS_STABLE=true
|
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 "releases=[${json}]" >> "${GITHUB_OUTPUT}"
|
||||||
echo "should_publish=true"
|
|
||||||
echo "version=${VERSION}"
|
|
||||||
echo "is_stable=${IS_STABLE}"
|
|
||||||
} >> "$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}"
|
: "${OWNER:?OWNER must be set}"
|
||||||
: "${VERSION:?VERSION 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}" \
|
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||||
--workdir /opt/src/pkgmgr \
|
--workdir /opt/src/pkgmgr \
|
||||||
"pkgmgr-${PKGMGR_DISTRO}" \
|
"pkgmgr-${PKGMGR_DISTRO}" \
|
||||||
bash -lc '
|
bash -l scripts/test/container/e2e.sh
|
||||||
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"
|
|
||||||
'
|
|
||||||
@@ -16,48 +16,4 @@ docker run --rm \
|
|||||||
-e REINSTALL_PKGMGR=1 \
|
-e REINSTALL_PKGMGR=1 \
|
||||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||||
"${IMAGE}" \
|
"${IMAGE}" \
|
||||||
bash -lc '
|
bash -l scripts/test/container/env/nix.sh "${IMAGE}" "${PKGMGR_DISTRO}"
|
||||||
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."
|
|
||||||
'
|
|
||||||
@@ -12,31 +12,13 @@ echo "[test-env-virtual] Inspect image metadata:"
|
|||||||
docker image inspect "${IMAGE}" | sed -n '1,40p'
|
docker image inspect "${IMAGE}" | sed -n '1,40p'
|
||||||
echo
|
echo
|
||||||
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
# Run VENV-based pkgmgr test inside container
|
|
||||||
# ------------------------------------------------------------
|
|
||||||
if OUTPUT=$(docker run --rm \
|
if OUTPUT=$(docker run --rm \
|
||||||
-e REINSTALL_PKGMGR=1 \
|
-e REINSTALL_PKGMGR=1 \
|
||||||
-v "$(pwd):/opt/src/pkgmgr" \
|
-v "$(pwd):/opt/src/pkgmgr" \
|
||||||
-w /opt/src/pkgmgr \
|
-w /opt/src/pkgmgr \
|
||||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||||
"${IMAGE}" \
|
"${IMAGE}" \
|
||||||
bash -lc '
|
bash -l scripts/test/container/env/virtual.sh 2>&1); then
|
||||||
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
|
|
||||||
|
|
||||||
echo "$OUTPUT"
|
echo "$OUTPUT"
|
||||||
echo
|
echo
|
||||||
|
|||||||
@@ -14,12 +14,4 @@ docker run --rm \
|
|||||||
-e TEST_PATTERN="${TEST_PATTERN}" \
|
-e TEST_PATTERN="${TEST_PATTERN}" \
|
||||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||||
"pkgmgr-${PKGMGR_DISTRO}" \
|
"pkgmgr-${PKGMGR_DISTRO}" \
|
||||||
bash -lc '
|
bash -l scripts/test/container/unittest.sh tests/integration
|
||||||
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";
|
|
||||||
'
|
|
||||||
@@ -14,12 +14,4 @@ docker run --rm \
|
|||||||
-e TEST_PATTERN="${TEST_PATTERN}" \
|
-e TEST_PATTERN="${TEST_PATTERN}" \
|
||||||
-e NIX_CONFIG="${NIX_CONFIG}" \
|
-e NIX_CONFIG="${NIX_CONFIG}" \
|
||||||
"pkgmgr-${PKGMGR_DISTRO}" \
|
"pkgmgr-${PKGMGR_DISTRO}" \
|
||||||
bash -lc '
|
bash -l scripts/test/container/unittest.sh tests/unit
|
||||||
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";
|
|
||||||
'
|
|
||||||
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,13 +4,16 @@ Public API for branch actions.
|
|||||||
|
|
||||||
from .close_branch import close_branch
|
from .close_branch import close_branch
|
||||||
from .drop_branch import drop_branch
|
from .drop_branch import drop_branch
|
||||||
from .gc import branch_gc, branch_purge
|
from .gc import branch_purge, cleanup
|
||||||
from .open_branch import open_branch
|
from .open_branch import open_branch
|
||||||
|
from .tree import branch_tree, refresh_tree_entry
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"branch_gc",
|
|
||||||
"branch_purge",
|
"branch_purge",
|
||||||
|
"branch_tree",
|
||||||
|
"cleanup",
|
||||||
"close_branch",
|
"close_branch",
|
||||||
"drop_branch",
|
"drop_branch",
|
||||||
"open_branch",
|
"open_branch",
|
||||||
|
"refresh_tree_entry",
|
||||||
]
|
]
|
||||||
+1417
-126
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import time
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
from pkgmgr.actions.mirror.url_utils import parse_repo_from_git_url
|
from pkgmgr.actions.mirror.url_utils import parse_repo_from_git_url
|
||||||
@@ -12,6 +13,8 @@ from pkgmgr.core.remote_provisioning.http.errors import HttpError
|
|||||||
GITHUB_HOST = "github.com"
|
GITHUB_HOST = "github.com"
|
||||||
GITHUB_API = "https://api.github.com"
|
GITHUB_API = "https://api.github.com"
|
||||||
PAGE_SIZE = 100
|
PAGE_SIZE = 100
|
||||||
|
TIMEOUT_S = 10
|
||||||
|
BUDGET_S = 60
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -46,10 +49,14 @@ def github_slugs(remote_urls: dict[str, str]) -> list[tuple[str, str]]:
|
|||||||
return slugs
|
return slugs
|
||||||
|
|
||||||
|
|
||||||
def _pages(http: HttpClient, headers: dict[str, str], url: str) -> list[dict]:
|
def _pages(
|
||||||
|
http: HttpClient, headers: dict[str, str], url: str, deadline: float
|
||||||
|
) -> list[dict]:
|
||||||
items: list[dict] = []
|
items: list[dict] = []
|
||||||
page = 1
|
page = 1
|
||||||
while True:
|
while True:
|
||||||
|
if time.monotonic() > deadline:
|
||||||
|
raise HttpError(status=0, message=f"budget of {BUDGET_S}s exceeded")
|
||||||
resp = http.request_json(
|
resp = http.request_json(
|
||||||
"GET", f"{url}&per_page={PAGE_SIZE}&page={page}", headers=headers
|
"GET", f"{url}&per_page={PAGE_SIZE}&page={page}", headers=headers
|
||||||
)
|
)
|
||||||
@@ -79,8 +86,23 @@ def fetch_forge_facts(remote_urls: dict[str, str]) -> ForgeFacts:
|
|||||||
except CredentialError as exc:
|
except CredentialError as exc:
|
||||||
facts.unavailable = f"no GitHub token ({exc})"
|
facts.unavailable = f"no GitHub token ({exc})"
|
||||||
return facts
|
return facts
|
||||||
|
return facts_with_token(slugs, token)
|
||||||
|
|
||||||
http = HttpClient(timeout_s=30)
|
|
||||||
|
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 = {
|
headers = {
|
||||||
"Authorization": f"Bearer {token}",
|
"Authorization": f"Bearer {token}",
|
||||||
"Accept": "application/vnd.github+json",
|
"Accept": "application/vnd.github+json",
|
||||||
@@ -89,14 +111,17 @@ def fetch_forge_facts(remote_urls: dict[str, str]) -> ForgeFacts:
|
|||||||
for owner, name in slugs:
|
for owner, name in slugs:
|
||||||
base = f"{GITHUB_API}/repos/{owner}/{name}"
|
base = f"{GITHUB_API}/repos/{owner}/{name}"
|
||||||
try:
|
try:
|
||||||
for pr in _pages(http, headers, f"{base}/pulls?state=all"):
|
for pr in _pages(http, headers, f"{base}/pulls?state=all", deadline):
|
||||||
if pr["merged_at"]:
|
if pr["merged_at"]:
|
||||||
facts.merged_heads[pr["head"]["sha"]] = pr["number"]
|
facts.merged_heads[pr["head"]["sha"]] = pr["number"]
|
||||||
elif pr["state"] == "open":
|
elif pr["state"] == "open":
|
||||||
facts.open_heads[pr["head"]["ref"]] = pr["number"]
|
facts.open_heads[pr["head"]["ref"]] = pr["number"]
|
||||||
for branch in _pages(http, headers, f"{base}/branches?protected=true"):
|
for branch in _pages(
|
||||||
|
http, headers, f"{base}/branches?protected=true", deadline
|
||||||
|
):
|
||||||
facts.protected.add(branch["name"])
|
facts.protected.add(branch["name"])
|
||||||
except (HttpError, ValueError, KeyError, TypeError) as exc:
|
except (HttpError, ValueError, KeyError, TypeError) as exc:
|
||||||
facts.unavailable = f"GitHub API failed for {owner}/{name}: {exc}"
|
return ForgeFacts(
|
||||||
return facts
|
unavailable=f"GitHub API failed for {owner}/{name}: {exc}"
|
||||||
|
)
|
||||||
return facts
|
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"
|
||||||
@@ -161,7 +161,6 @@ class InstallationPipeline:
|
|||||||
else:
|
else:
|
||||||
repo.pop("command", None)
|
repo.pop("command", None)
|
||||||
|
|
||||||
state = new_state
|
|
||||||
return
|
return
|
||||||
|
|
||||||
if attempted:
|
if attempted:
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import glob
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
from pkgmgr.actions.mirror.io import read_mirrors_file
|
from pkgmgr.actions.mirror.io import read_mirrors_file
|
||||||
from pkgmgr.actions.mirror.types import Repository
|
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 .git_tags import head_semver_tags
|
||||||
from .pypi_url import parse_pypi_project_url
|
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:
|
try:
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["python", "-m", module, "--help"],
|
[sys.executable, "-m", module, "--help"],
|
||||||
|
cwd=cwd,
|
||||||
|
env=env,
|
||||||
stdout=subprocess.DEVNULL,
|
stdout=subprocess.DEVNULL,
|
||||||
stderr=subprocess.DEVNULL,
|
stderr=subprocess.DEVNULL,
|
||||||
check=True,
|
check=True,
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f"Required Python module '{module}' is not available. "
|
f"Required Python module '{module}' is not available to "
|
||||||
f"Install it via: pip install {module}"
|
f"{sys.executable}. Install it via: "
|
||||||
|
f"{sys.executable} -m pip install {module}"
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
@@ -66,22 +108,38 @@ def publish(
|
|||||||
print("[PREVIEW] Would build and upload to PyPI.")
|
print("[PREVIEW] Would build and upload to PyPI.")
|
||||||
return
|
return
|
||||||
|
|
||||||
_require_tool("build")
|
with tempfile.TemporaryDirectory() as out:
|
||||||
_require_tool("twine")
|
_upload(target, os.path.abspath(repo_dir), out, interactive, allow_prompt)
|
||||||
|
|
||||||
dist_dir = os.path.join(repo_dir, "dist")
|
print("[INFO] Publish completed.")
|
||||||
if os.path.isdir(dist_dir):
|
|
||||||
shutil.rmtree(dist_dir, ignore_errors=True)
|
|
||||||
|
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(
|
subprocess.run(
|
||||||
["python", "-m", "build"],
|
[sys.executable, "-m", "build", "--outdir", out, repo_dir],
|
||||||
cwd=repo_dir,
|
cwd=out,
|
||||||
|
env=env,
|
||||||
check=True,
|
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:
|
if not artifacts:
|
||||||
raise RuntimeError("No build artifacts found in dist/.")
|
raise RuntimeError("No build artifacts found.")
|
||||||
|
|
||||||
resolver = TokenResolver()
|
resolver = TokenResolver()
|
||||||
|
|
||||||
@@ -98,15 +156,18 @@ def publish(
|
|||||||
),
|
),
|
||||||
).token
|
).token
|
||||||
|
|
||||||
env = dict(os.environ)
|
|
||||||
env["TWINE_USERNAME"] = "__token__"
|
|
||||||
env["TWINE_PASSWORD"] = token
|
|
||||||
|
|
||||||
subprocess.run(
|
subprocess.run(
|
||||||
["python", "-m", "twine", "upload", *artifacts],
|
[
|
||||||
cwd=repo_dir,
|
sys.executable,
|
||||||
env=env,
|
"-m",
|
||||||
|
"twine",
|
||||||
|
"upload",
|
||||||
|
"--non-interactive",
|
||||||
|
"--repository-url",
|
||||||
|
UPLOAD_URLS[target.host],
|
||||||
|
*artifacts,
|
||||||
|
],
|
||||||
|
cwd=out,
|
||||||
|
env={**env, "TWINE_USERNAME": "__token__", "TWINE_PASSWORD": token},
|
||||||
check=True,
|
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)
|
## Execution Flow (ASCII Diagram)
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .options import ReleaseOptions
|
||||||
from .workflow import release
|
from .workflow import release
|
||||||
|
|
||||||
__all__ = ["release"]
|
__all__ = ["ReleaseOptions", "release"]
|
||||||
@@ -3,6 +3,41 @@ from __future__ import annotations
|
|||||||
import os
|
import os
|
||||||
import re
|
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(
|
def update_pyproject_version(
|
||||||
pyproject_path: str, new_version: str, preview: bool = False
|
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}")
|
print(f"[WARN] Could not read pyproject.toml: {exc}")
|
||||||
return
|
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)
|
m = re.search(r"(?ms)^\s*\[project\]\s*$.*?(?=^\s*\[|\Z)", content)
|
||||||
if not m:
|
if not m:
|
||||||
raise RuntimeError("Missing [project] section in pyproject.toml")
|
raise RuntimeError("Missing [project] section in pyproject.toml")
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pkgmgr.core.git import run
|
||||||
from pkgmgr.core.git.commands import (
|
from pkgmgr.core.git.commands import (
|
||||||
fetch,
|
fetch,
|
||||||
pull_ff_only,
|
pull_ff_only,
|
||||||
@@ -14,7 +15,18 @@ def ensure_clean_and_synced(*, preview: bool = False) -> None:
|
|||||||
Always run a pull BEFORE modifying anything.
|
Always run a pull BEFORE modifying anything.
|
||||||
Uses --ff-only to avoid creating merge commits automatically.
|
Uses --ff-only to avoid creating merge commits automatically.
|
||||||
If no upstream is configured, we skip.
|
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()
|
upstream = get_upstream_ref()
|
||||||
if not upstream:
|
if not upstream:
|
||||||
print("[INFO] No upstream configured for current branch. Skipping pull.")
|
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)
|
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:
|
def _parse_v_tag(tag: str) -> tuple[int, ...] | None:
|
||||||
"""
|
"""
|
||||||
Parse tags like 'v1.2.3' into (1, 2, 3).
|
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
|
`retry_release` re-runs the idempotent tail of that flow so a botched
|
||||||
release can be re-pushed without touching code or recreating tags:
|
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
|
* re-align the floating `latest` tag if HEAD tag is the highest
|
||||||
|
|
||||||
Publishing (PyPI etc.) stays the caller's responsibility — the publish
|
Publishing (PyPI etc.) stays the caller's responsibility — the publish
|
||||||
@@ -23,7 +23,8 @@ from __future__ import annotations
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
from pkgmgr.actions.publish.git_tags import head_semver_tags
|
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.git.queries import get_current_branch
|
||||||
from pkgmgr.core.version.semver import SemVer
|
from pkgmgr.core.version.semver import SemVer
|
||||||
|
|
||||||
@@ -50,7 +51,7 @@ def retry_release(
|
|||||||
tag = max(tags, key=SemVer.parse)
|
tag = max(tags, key=SemVer.parse)
|
||||||
print(f"Re-pushing existing tag: {tag}")
|
print(f"Re-pushing existing tag: {tag}")
|
||||||
|
|
||||||
run(["push", "origin", branch, tag], preview=preview)
|
push_branch(".", [], sign=True, refs=(tag,), preview=preview)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if is_highest_version_tag(tag):
|
if is_highest_version_tag(tag):
|
||||||
|
|||||||
@@ -2,12 +2,18 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
from dataclasses import dataclass, replace
|
||||||
|
|
||||||
from pkgmgr.actions.branch import close_branch
|
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.commands import add, commit, tag_annotated
|
||||||
from pkgmgr.core.git.queries import get_current_branch
|
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 (
|
from .files import (
|
||||||
update_cargo_version,
|
update_cargo_version,
|
||||||
@@ -21,86 +27,91 @@ from .files import (
|
|||||||
)
|
)
|
||||||
from .git_ops import (
|
from .git_ops import (
|
||||||
ensure_clean_and_synced,
|
ensure_clean_and_synced,
|
||||||
|
ensure_head_tree,
|
||||||
|
ensure_inputs_tracked,
|
||||||
is_highest_version_tag,
|
is_highest_version_tag,
|
||||||
update_latest_tag,
|
update_latest_tag,
|
||||||
)
|
)
|
||||||
|
from .options import ReleaseOptions
|
||||||
from .package_name import resolve_package_name
|
from .package_name import resolve_package_name
|
||||||
from .prompts import confirm_proceed_release, should_delete_branch
|
from .prompts import confirm_proceed_release, should_delete_branch
|
||||||
from .retry import retry_release
|
from .retry import retry_release
|
||||||
from .versioning import bump_semver, determine_current_version
|
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",
|
@dataclass(frozen=True)
|
||||||
changelog_path: str = "CHANGELOG.md",
|
class _Prepared:
|
||||||
release_type: str = "patch",
|
branch: str
|
||||||
message: str | None = None,
|
version: str
|
||||||
preview: bool = False,
|
tag: str
|
||||||
close: bool = False,
|
tag_message: str
|
||||||
force: bool = False,
|
files: list[str]
|
||||||
) -> None:
|
|
||||||
# Determine current branch early
|
|
||||||
|
def _current_branch() -> str:
|
||||||
try:
|
try:
|
||||||
branch = get_current_branch() or "main"
|
return get_current_branch() or "main"
|
||||||
except GitRunError:
|
except GitRunError:
|
||||||
branch = "main"
|
return "main"
|
||||||
print(f"Releasing on branch: {branch}")
|
|
||||||
|
|
||||||
# Pull BEFORE making any modifications
|
|
||||||
ensure_clean_and_synced(preview=preview)
|
|
||||||
|
|
||||||
repo_root = os.path.dirname(os.path.abspath(pyproject_path))
|
def _existing(files: list[str | None]) -> list[str]:
|
||||||
current_ver = determine_current_version(repo_root)
|
return [p for p in files if isinstance(p, str) and p and os.path.exists(p)]
|
||||||
new_ver = bump_semver(current_ver, release_type)
|
|
||||||
new_ver_str = str(new_ver)
|
|
||||||
new_tag = new_ver.to_tag(with_prefix=True)
|
|
||||||
|
|
||||||
mode = "PREVIEW" if preview else "REAL"
|
|
||||||
print(f"Release mode: {mode}")
|
|
||||||
print(f"Current version: {current_ver}")
|
|
||||||
print(f"New version: {new_ver_str} ({release_type})")
|
|
||||||
|
|
||||||
paths = resolve_repo_paths(repo_root)
|
def _release_files(
|
||||||
|
options: ReleaseOptions, paths: RepoPaths, extra: list[str]
|
||||||
# --- Update versioned files ------------------------------------------------
|
) -> list[str]:
|
||||||
|
return _existing(
|
||||||
update_pyproject_version(pyproject_path, new_ver_str, preview=preview)
|
[
|
||||||
|
options.pyproject_path,
|
||||||
changelog_message = update_changelog(
|
options.changelog_path,
|
||||||
changelog_path,
|
paths.flake_nix,
|
||||||
new_ver_str,
|
paths.arch_pkgbuild,
|
||||||
message=message,
|
paths.rpm_spec,
|
||||||
preview=preview,
|
paths.debian_changelog,
|
||||||
|
*extra,
|
||||||
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
update_flake_version(paths.flake_nix, new_ver_str, preview=preview)
|
|
||||||
|
|
||||||
cargo_files = update_cargo_version(repo_root, new_ver_str, preview=preview)
|
def _next_version(options: ReleaseOptions, repo_root: str):
|
||||||
|
current_ver = determine_current_version(repo_root)
|
||||||
|
new_ver = bump_semver(current_ver, options.release_type)
|
||||||
|
print(f"Release mode: {'PREVIEW' if options.preview else 'REAL'}")
|
||||||
|
print(f"Current version: {current_ver}")
|
||||||
|
print(f"New version: {new_ver} ({options.release_type})")
|
||||||
|
return new_ver
|
||||||
|
|
||||||
|
|
||||||
|
def _update_packaging_versions(paths: RepoPaths, version: str, preview: bool) -> None:
|
||||||
if paths.arch_pkgbuild:
|
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:
|
else:
|
||||||
print(
|
print(
|
||||||
"[INFO] No PKGBUILD found (packaging/arch/PKGBUILD or PKGBUILD). Skipping."
|
"[INFO] No PKGBUILD found (packaging/arch/PKGBUILD or PKGBUILD). Skipping."
|
||||||
)
|
)
|
||||||
|
|
||||||
if paths.rpm_spec:
|
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:
|
else:
|
||||||
print("[INFO] No RPM spec file found. Skipping spec version update.")
|
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)
|
package_name = resolve_package_name(paths)
|
||||||
|
|
||||||
if paths.debian_changelog:
|
if paths.debian_changelog:
|
||||||
update_debian_changelog(
|
update_debian_changelog(
|
||||||
paths.debian_changelog,
|
paths.debian_changelog,
|
||||||
package_name=package_name,
|
package_name=package_name,
|
||||||
new_version=new_ver_str,
|
new_version=version,
|
||||||
message=effective_message,
|
message=message,
|
||||||
preview=preview,
|
preview=preview,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -110,151 +121,150 @@ def _release_impl(
|
|||||||
update_spec_changelog(
|
update_spec_changelog(
|
||||||
spec_path=paths.rpm_spec,
|
spec_path=paths.rpm_spec,
|
||||||
package_name=package_name,
|
package_name=package_name,
|
||||||
new_version=new_ver_str,
|
new_version=version,
|
||||||
message=effective_message,
|
message=message,
|
||||||
preview=preview,
|
preview=preview,
|
||||||
)
|
)
|
||||||
|
|
||||||
# --- Git commit / tag / push ----------------------------------------------
|
|
||||||
|
|
||||||
commit_msg = f"Release version {new_ver_str}"
|
def _update_files(
|
||||||
tag_msg = effective_message or commit_msg
|
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 = [
|
message = options.message
|
||||||
pyproject_path,
|
if isinstance(changelog_message, str) and changelog_message.strip():
|
||||||
changelog_path,
|
message = changelog_message.strip()
|
||||||
paths.flake_nix,
|
|
||||||
paths.arch_pkgbuild,
|
|
||||||
paths.rpm_spec,
|
|
||||||
paths.debian_changelog,
|
|
||||||
*cargo_files,
|
|
||||||
]
|
|
||||||
existing_files = [
|
|
||||||
p for p in files_to_add if isinstance(p, str) and p and os.path.exists(p)
|
|
||||||
]
|
|
||||||
|
|
||||||
if preview:
|
_update_packaging_changelogs(paths, version, message, preview)
|
||||||
add(existing_files, preview=True)
|
return message, cargo_files
|
||||||
commit(commit_msg, all=True, preview=True)
|
|
||||||
tag_annotated(new_tag, tag_msg, preview=True)
|
|
||||||
run(["push", "origin", branch, new_tag], preview=True)
|
|
||||||
|
|
||||||
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:
|
else:
|
||||||
print(
|
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)
|
def _move_latest(tag: str) -> None:
|
||||||
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
|
|
||||||
try:
|
try:
|
||||||
if is_highest_version_tag(new_tag):
|
if is_highest_version_tag(tag):
|
||||||
update_latest_tag(new_tag, preview=False)
|
update_latest_tag(tag, preview=False)
|
||||||
else:
|
else:
|
||||||
print(
|
print(f"[INFO] Skipping 'latest' update (tag {tag} is not the highest).")
|
||||||
f"[INFO] Skipping 'latest' update (tag {new_tag} is not the highest)."
|
|
||||||
)
|
|
||||||
except GitRunError as exc:
|
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("'latest' tag was not updated.")
|
||||||
|
|
||||||
print(f"Release {new_ver_str} completed.")
|
|
||||||
|
|
||||||
if close:
|
def _close_released_branch(branch: str, force: bool) -> None:
|
||||||
if branch in ("main", "master"):
|
if branch in MAIN_BRANCHES:
|
||||||
print(
|
print(
|
||||||
f"[INFO] close=True but current branch is {branch}; skipping branch deletion."
|
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,
|
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# If force or non-interactive: no preview+confirmation step
|
if not should_delete_branch(force=force):
|
||||||
if force or (not sys.stdin.isatty()):
|
print(f"[INFO] Branch deletion declined. Keeping branch {branch}.")
|
||||||
_release_impl(
|
return
|
||||||
pyproject_path=pyproject_path,
|
|
||||||
changelog_path=changelog_path,
|
print(f"[INFO] Deleting branch {branch} after successful release...")
|
||||||
release_type=release_type,
|
try:
|
||||||
message=message,
|
close_branch(name=branch, base_branch="main", cwd=".")
|
||||||
preview=False,
|
except (RuntimeError, GitRunError) as exc:
|
||||||
close=close,
|
print(f"[WARN] Failed to close branch {branch} automatically: {exc}")
|
||||||
force=force,
|
|
||||||
)
|
|
||||||
|
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
|
return
|
||||||
|
|
||||||
print("[INFO] Running preview before actual release...\n")
|
print("[INFO] Running preview before actual release...\n")
|
||||||
_release_impl(
|
_release_impl(replace(options, preview=True))
|
||||||
pyproject_path=pyproject_path,
|
|
||||||
changelog_path=changelog_path,
|
|
||||||
release_type=release_type,
|
|
||||||
message=message,
|
|
||||||
preview=True,
|
|
||||||
close=close,
|
|
||||||
force=force,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not confirm_proceed_release():
|
if not confirm_proceed_release():
|
||||||
print()
|
print()
|
||||||
return
|
return
|
||||||
|
|
||||||
print("\n[INFO] Running REAL release...\n")
|
print("\n[INFO] Running REAL release...\n")
|
||||||
_release_impl(
|
_release_impl(options)
|
||||||
pyproject_path=pyproject_path,
|
|
||||||
changelog_path=changelog_path,
|
|
||||||
release_type=release_type,
|
|
||||||
message=message,
|
|
||||||
preview=False,
|
|
||||||
close=close,
|
|
||||||
force=force,
|
|
||||||
)
|
|
||||||
@@ -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
|
from pkgmgr.core.git.queries import get_repo_root
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from jinja2 import Environment, FileSystemLoader, StrictUndefined
|
from jinja2 import (
|
||||||
except ImportError as exc: # pragma: no cover
|
Environment,
|
||||||
|
FileSystemLoader,
|
||||||
|
StrictUndefined,
|
||||||
|
select_autoescape,
|
||||||
|
)
|
||||||
|
except ImportError as exc: # pragma: no cover
|
||||||
Environment = None # type: ignore
|
Environment = None # type: ignore
|
||||||
FileSystemLoader = None # type: ignore
|
FileSystemLoader = None # type: ignore
|
||||||
StrictUndefined = None # type: ignore
|
StrictUndefined = None # type: ignore
|
||||||
@@ -41,7 +46,18 @@ class TemplateRenderer:
|
|||||||
env = Environment(
|
env = Environment(
|
||||||
loader=FileSystemLoader(self.templates_dir),
|
loader=FileSystemLoader(self.templates_dir),
|
||||||
undefined=StrictUndefined,
|
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,
|
keep_trailing_newline=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,39 +1,434 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import threading
|
||||||
|
from dataclasses import dataclass
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from pkgmgr.actions.repository._parallel import (
|
from pkgmgr.actions.repository._parallel import (
|
||||||
|
RepoRef,
|
||||||
resolve_repos,
|
resolve_repos,
|
||||||
run_on_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]
|
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:
|
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, "")
|
return (True, "")
|
||||||
except GitPushArgsError as exc:
|
except (GitRunError, PushRefusedError) as exc:
|
||||||
return (False, str(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(
|
def push_in_parallel(
|
||||||
selected_repos: list[Repository],
|
selected_repos: list[Repository],
|
||||||
repositories_base_dir: str,
|
repositories_base_dir: str,
|
||||||
all_repos: list[Repository],
|
all_repos: list[Repository],
|
||||||
extra_args: list[str],
|
extra_args: list[str],
|
||||||
preview: bool,
|
preview: bool,
|
||||||
|
sign: bool,
|
||||||
jobs: int = 1,
|
jobs: int = 1,
|
||||||
|
rewrite: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
push_repo_dirs(
|
||||||
Execute `git push` for each repository, optionally in parallel.
|
resolve_repos(selected_repos, repositories_base_dir, all_repos),
|
||||||
"""
|
extra_args,
|
||||||
repos = resolve_repos(selected_repos, repositories_base_dir, all_repos)
|
preview,
|
||||||
run_on_repos(
|
sign,
|
||||||
repos,
|
|
||||||
lambda rd: _push_one(rd, extra_args, preview),
|
|
||||||
jobs=jobs,
|
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
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
from pkgmgr.core.git.errors import GitBaseError
|
||||||
|
from pkgmgr.core.git.run import END_OF_OPTIONS, SCAN_FLAGS, SCAN_TIMEOUT, _scan_env, run
|
||||||
|
|
||||||
|
from .model import ReviewError
|
||||||
|
|
||||||
|
BRANCH_NAMESPACES = ("refs/heads/", "refs/remotes/")
|
||||||
|
|
||||||
|
|
||||||
|
def git_text(args: list[str], cwd: str) -> str:
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", *SCAN_FLAGS, "-c", "core.quotepath=false", *args],
|
||||||
|
cwd=cwd,
|
||||||
|
env=_scan_env(),
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
capture_output=True,
|
||||||
|
timeout=SCAN_TIMEOUT,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
raise ReviewError(f"git {args[0]} timed out") from None
|
||||||
|
if result.returncode != 0:
|
||||||
|
stderr = result.stderr.decode("utf-8", "replace").strip().splitlines()
|
||||||
|
reason = stderr[0] if stderr else f"exit code {result.returncode}"
|
||||||
|
raise ReviewError(f"git {args[0]} failed: {reason}")
|
||||||
|
return result.stdout.decode("utf-8", "replace")
|
||||||
|
|
||||||
|
|
||||||
|
def git_optional(args: list[str], cwd: str) -> str | None:
|
||||||
|
try:
|
||||||
|
return run(args, cwd=cwd, scan=True) or None
|
||||||
|
except GitBaseError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def top_level(cwd: str) -> str:
|
||||||
|
top = git_optional(["rev-parse", "--show-toplevel"], cwd)
|
||||||
|
if top is None:
|
||||||
|
raise ReviewError(f"not inside a git working copy: {cwd!r}")
|
||||||
|
return top
|
||||||
|
|
||||||
|
|
||||||
|
def base_ref(base: str, top: str) -> tuple[str, str]:
|
||||||
|
names = (
|
||||||
|
[base]
|
||||||
|
if base.startswith(BRANCH_NAMESPACES)
|
||||||
|
else [namespace + base for namespace in BRANCH_NAMESPACES]
|
||||||
|
)
|
||||||
|
refs: dict[str, str] = {}
|
||||||
|
for name in names:
|
||||||
|
sha = git_optional(
|
||||||
|
["show-ref", "--verify", "--hash", END_OF_OPTIONS, name], top
|
||||||
|
)
|
||||||
|
if sha is not None:
|
||||||
|
refs[name] = sha
|
||||||
|
if len(refs) > 1:
|
||||||
|
raise ReviewError(f"ambiguous base ref: {base!r} names {' and '.join(refs)}")
|
||||||
|
if not refs:
|
||||||
|
raise ReviewError(
|
||||||
|
f"unknown base ref: {base!r}, expected a branch under "
|
||||||
|
f"{' or '.join(BRANCH_NAMESPACES)}"
|
||||||
|
)
|
||||||
|
[(name, sha)] = refs.items()
|
||||||
|
commit = git_optional(
|
||||||
|
["rev-parse", "--verify", "--quiet", END_OF_OPTIONS, f"{sha}^{{commit}}"], top
|
||||||
|
)
|
||||||
|
if commit is None:
|
||||||
|
raise ReviewError(f"base ref {name!r} does not point to a commit")
|
||||||
|
return name, commit
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
{% set status_letters = {"added": "A", "deleted": "D", "modified": "M", "renamed": "R", "copied": "C", "untracked": "U"} %}
|
||||||
|
{% set signs = {"add": "+", "del": "-", "ctx": "", "meta": ""} %}
|
||||||
|
{% set icon_paths = {
|
||||||
|
"arrows-expand": "M1 8a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 8M7.646.146a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 1.707V5.5a.5.5 0 0 1-1 0V1.707L6.354 2.854a.5.5 0 1 1-.708-.708zM8 10a.5.5 0 0 1 .5.5v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 0 1 .708-.708L7.5 14.293V10.5A.5.5 0 0 1 8 10",
|
||||||
|
"arrows-collapse": "M1 8a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13A.5.5 0 0 1 1 8m7-8a.5.5 0 0 1 .5.5v3.793l1.146-1.147a.5.5 0 0 1 .708.708l-2 2a.5.5 0 0 1-.708 0l-2-2a.5.5 0 1 1 .708-.708L7.5 4.293V.5A.5.5 0 0 1 8 0m-.5 11.707-1.146 1.147a.5.5 0 0 1-.708-.708l2-2a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1-.708.708L8.5 11.707V15.5a.5.5 0 0 1-1 0z",
|
||||||
|
} %}
|
||||||
|
{% set style %}
|
||||||
|
:root {
|
||||||
|
color-scheme: light dark;
|
||||||
|
--bg: #f6f8fa;
|
||||||
|
--panel: #ffffff;
|
||||||
|
--subtle: #f6f8fa;
|
||||||
|
--border: #d1d9e0;
|
||||||
|
--border-muted: #e1e6eb;
|
||||||
|
--text: #1f2328;
|
||||||
|
--muted: #59636e;
|
||||||
|
--accent: #0969da;
|
||||||
|
--accent-bg: #ddf4ff;
|
||||||
|
--add-fg: #1a7f37;
|
||||||
|
--add-bg: #dafbe1;
|
||||||
|
--add-line: #e6ffec;
|
||||||
|
--add-num: #ccffd8;
|
||||||
|
--del-fg: #cf222e;
|
||||||
|
--del-bg: #ffebe9;
|
||||||
|
--del-line: #ffebe9;
|
||||||
|
--del-num: #ffd7d5;
|
||||||
|
--hunk-bg: #ddf4ff;
|
||||||
|
--hunk-fg: #59636e;
|
||||||
|
--warn-fg: #9a6700;
|
||||||
|
--warn-bg: #fff8c5;
|
||||||
|
--shadow: 0 1px 2px rgba(31, 35, 40, 0.06);
|
||||||
|
--mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
|
||||||
|
--sans: system-ui, -apple-system, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
--bg: #0d1117;
|
||||||
|
--panel: #151b23;
|
||||||
|
--subtle: #1b222c;
|
||||||
|
--border: #3d444d;
|
||||||
|
--border-muted: #2a313c;
|
||||||
|
--text: #e6edf3;
|
||||||
|
--muted: #9198a1;
|
||||||
|
--accent: #4493f8;
|
||||||
|
--accent-bg: rgba(56, 139, 253, 0.15);
|
||||||
|
--add-fg: #3fb950;
|
||||||
|
--add-bg: rgba(46, 160, 67, 0.2);
|
||||||
|
--add-line: rgba(46, 160, 67, 0.15);
|
||||||
|
--add-num: rgba(63, 185, 80, 0.3);
|
||||||
|
--del-fg: #f85149;
|
||||||
|
--del-bg: rgba(248, 81, 73, 0.2);
|
||||||
|
--del-line: rgba(248, 81, 73, 0.1);
|
||||||
|
--del-num: rgba(248, 81, 73, 0.3);
|
||||||
|
--hunk-bg: rgba(56, 139, 253, 0.1);
|
||||||
|
--hunk-fg: #9198a1;
|
||||||
|
--warn-fg: #d29922;
|
||||||
|
--warn-bg: rgba(187, 128, 9, 0.15);
|
||||||
|
--shadow: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*, *::before, *::after { box-sizing: border-box; }
|
||||||
|
[hidden] { display: none !important; }
|
||||||
|
html { scroll-padding-top: 64px; }
|
||||||
|
body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.5 var(--sans); }
|
||||||
|
a { color: var(--accent); text-decoration: none; }
|
||||||
|
a:hover { text-decoration: underline; }
|
||||||
|
pre, code { font-family: var(--mono); }
|
||||||
|
.muted { color: var(--muted); font-weight: 400; }
|
||||||
|
.masthead { background: var(--panel); border-bottom: 1px solid var(--border); }
|
||||||
|
.masthead-inner, .toolbar-inner, main { max-width: 1280px; margin: 0 auto; padding-left: 32px; padding-right: 32px; }
|
||||||
|
.masthead-inner { padding-top: 24px; padding-bottom: 20px; }
|
||||||
|
.eyebrow { margin: 0 0 4px; color: var(--muted); font-size: 12px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; }
|
||||||
|
h1 { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 0; font-size: 22px; font-weight: 600; }
|
||||||
|
.pill { padding: 2px 10px; border-radius: 999px; background: var(--accent-bg); color: var(--accent); font: 500 12px/20px var(--mono); }
|
||||||
|
.facts { display: grid; grid-template-columns: max-content 1fr; gap: 4px 20px; margin: 16px 0 0; font-size: 13px; }
|
||||||
|
.facts dt { color: var(--muted); }
|
||||||
|
.facts dd { margin: 0; font-family: var(--mono); overflow-wrap: anywhere; }
|
||||||
|
.warnings, .skipped { border: 1px solid var(--warn-fg); border-radius: 8px; background: var(--warn-bg); color: var(--warn-fg); font-size: 13px; overflow-wrap: anywhere; }
|
||||||
|
.warnings { margin: 16px 0 0; padding: 10px 14px 10px 34px; }
|
||||||
|
.skipped { margin: 0; padding: 14px 16px; border-style: dashed; }
|
||||||
|
.totals { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; }
|
||||||
|
.total { display: flex; flex-direction: column; gap: 2px; min-width: 160px; padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; background: var(--subtle); color: var(--text); }
|
||||||
|
.total:hover { border-color: var(--accent); text-decoration: none; }
|
||||||
|
.total .label { color: var(--muted); font-size: 12px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; }
|
||||||
|
.total .files { font-size: 15px; font-weight: 600; }
|
||||||
|
.stat { display: inline-flex; gap: 6px; font: 600 12px var(--mono); white-space: nowrap; }
|
||||||
|
.stat .add { color: var(--add-fg); }
|
||||||
|
.stat .del { color: var(--del-fg); }
|
||||||
|
.toolbar { position: sticky; top: 0; z-index: 10; border-bottom: 1px solid var(--border); background: var(--panel); background: color-mix(in srgb, var(--panel) 86%, transparent); backdrop-filter: saturate(180%) blur(10px); box-shadow: var(--shadow); }
|
||||||
|
.toolbar-inner { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 8px; padding-bottom: 8px; }
|
||||||
|
.jumps { display: flex; flex-wrap: wrap; gap: 2px; }
|
||||||
|
.jumps a { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 6px; color: var(--text); font-weight: 500; }
|
||||||
|
.jumps a:hover { background: var(--accent-bg); text-decoration: none; }
|
||||||
|
.count { min-width: 20px; padding: 0 6px; border: 1px solid var(--border-muted); border-radius: 999px; background: var(--subtle); color: var(--muted); font-size: 12px; line-height: 18px; text-align: center; }
|
||||||
|
.spacer { flex: 1; }
|
||||||
|
input[type="search"] { width: 260px; max-width: 100%; padding: 5px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); font: 13px var(--mono); }
|
||||||
|
input[type="search"]:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
|
||||||
|
button { padding: 5px 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--subtle); color: var(--text); font: 500 13px var(--sans); cursor: pointer; }
|
||||||
|
button:hover { border-color: var(--muted); }
|
||||||
|
button.icon { display: inline-flex; align-items: center; justify-content: center; padding: 6px 8px; }
|
||||||
|
main { padding-top: 24px; padding-bottom: 80px; }
|
||||||
|
.group { margin-bottom: 36px; }
|
||||||
|
h2 { display: flex; flex-wrap: wrap; align-items: baseline; gap: 12px; margin: 0 0 12px; font-size: 17px; font-weight: 600; }
|
||||||
|
.note { margin: 0 0 14px; border: 1px solid var(--border); border-radius: 8px; background: var(--panel); overflow: hidden; }
|
||||||
|
.note figcaption { padding: 8px 14px; border-bottom: 1px solid var(--border); background: var(--subtle); font: 600 13px var(--mono); }
|
||||||
|
.note pre, .commit-body { margin: 0; padding: 12px 14px; font-size: 13px; line-height: 1.55; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
|
details.file, details.commit { margin-bottom: 12px; border: 1px solid var(--border); border-radius: 8px; background: var(--panel); box-shadow: var(--shadow); overflow: hidden; }
|
||||||
|
summary { display: flex; align-items: center; gap: 10px; padding: 8px 12px; cursor: pointer; list-style: none; }
|
||||||
|
summary::-webkit-details-marker { display: none; }
|
||||||
|
summary::before { content: ""; flex: none; width: 6px; height: 6px; margin: 0 4px 0 2px; border-right: 2px solid var(--muted); border-bottom: 2px solid var(--muted); transform: rotate(-45deg); transition: transform 0.12s ease; }
|
||||||
|
details[open] > summary::before { transform: rotate(45deg); }
|
||||||
|
details.file > summary { background: var(--subtle); font: 13px var(--mono); }
|
||||||
|
details.file[open] > summary, details.commit[open] > summary { border-bottom: 1px solid var(--border); }
|
||||||
|
summary:hover { background: var(--accent-bg); }
|
||||||
|
.badge { flex: none; width: 20px; height: 20px; border-radius: 5px; font: 700 11px/20px var(--sans); text-align: center; }
|
||||||
|
.badge.added, .badge.untracked { background: var(--add-bg); color: var(--add-fg); }
|
||||||
|
.badge.deleted { background: var(--del-bg); color: var(--del-fg); }
|
||||||
|
.badge.modified { background: var(--accent-bg); color: var(--accent); }
|
||||||
|
.badge.renamed, .badge.copied { background: var(--warn-bg); color: var(--warn-fg); }
|
||||||
|
.path { flex: 1; min-width: 0; font-weight: 600; overflow-wrap: anywhere; }
|
||||||
|
.path .old, .path .arrow { color: var(--muted); font-weight: 400; }
|
||||||
|
.tag { flex: none; padding: 0 8px; border: 1px solid var(--border); border-radius: 999px; color: var(--muted); font: 500 11px/18px var(--sans); }
|
||||||
|
.open { flex: none; font: 500 12px var(--sans); }
|
||||||
|
.placeholder, .empty { margin: 0; padding: 14px 16px; color: var(--muted); font-style: italic; }
|
||||||
|
.empty { border: 1px dashed var(--border); border-radius: 8px; }
|
||||||
|
table.diff { width: 100%; border-collapse: collapse; font: 12.5px/20px var(--mono); tab-size: 4; }
|
||||||
|
.diff td { height: 20px; padding: 0; vertical-align: top; }
|
||||||
|
td.num { width: 1%; min-width: 50px; padding: 0 10px; color: var(--muted); text-align: right; white-space: nowrap; user-select: none; }
|
||||||
|
td.num a { color: inherit; }
|
||||||
|
td.num a:hover { color: var(--accent); }
|
||||||
|
td.sign { width: 20px; padding-left: 10px; color: var(--muted); user-select: none; }
|
||||||
|
td.code { padding-right: 16px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
|
tr.add td { background: var(--add-line); }
|
||||||
|
tr.add td.num { background: var(--add-num); }
|
||||||
|
tr.add td.sign { color: var(--add-fg); }
|
||||||
|
tr.del td { background: var(--del-line); }
|
||||||
|
tr.del td.num { background: var(--del-num); }
|
||||||
|
tr.del td.sign { color: var(--del-fg); }
|
||||||
|
tr.hunk td { padding-top: 4px; padding-bottom: 4px; background: var(--hunk-bg); color: var(--hunk-fg); }
|
||||||
|
tr.meta td.code { color: var(--muted); font-style: italic; }
|
||||||
|
tr.more td { padding: 8px 16px; border-top: 1px dashed var(--border); background: var(--subtle); color: var(--muted); font: italic 12px var(--sans); text-align: center; }
|
||||||
|
details.commit > summary { padding: 10px 14px; }
|
||||||
|
.sha { flex: none; padding: 1px 8px; border: 1px solid var(--border-muted); border-radius: 6px; background: var(--subtle); font-size: 12px; }
|
||||||
|
.subject { flex: 1; min-width: 0; font-weight: 600; overflow-wrap: anywhere; }
|
||||||
|
.commit-meta { padding: 10px 14px 0; color: var(--muted); font-size: 13px; }
|
||||||
|
.commit-files { padding: 12px 14px 2px; }
|
||||||
|
@media (max-width: 720px) {
|
||||||
|
.masthead-inner, .toolbar-inner, main { padding-left: 14px; padding-right: 14px; }
|
||||||
|
input[type="search"] { width: 100%; }
|
||||||
|
.spacer { display: none; }
|
||||||
|
}
|
||||||
|
{% endset %}
|
||||||
|
{% set script %}
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
var files = Array.prototype.slice.call(document.querySelectorAll("details.file"));
|
||||||
|
var filter = document.getElementById("filter");
|
||||||
|
var counter = document.getElementById("filter-count");
|
||||||
|
function setOpen(open) {
|
||||||
|
document.querySelectorAll("details").forEach(function (item) {
|
||||||
|
item.open = open;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function applyFilter() {
|
||||||
|
var query = filter.value.trim().toLowerCase();
|
||||||
|
var shown = 0;
|
||||||
|
files.forEach(function (item) {
|
||||||
|
var match = query === "" || item.dataset.path.toLowerCase().indexOf(query) !== -1;
|
||||||
|
item.hidden = !match;
|
||||||
|
shown += match ? 1 : 0;
|
||||||
|
});
|
||||||
|
counter.textContent = query === "" ? "" : shown + " of " + files.length + " files";
|
||||||
|
}
|
||||||
|
document.getElementById("expand-all").addEventListener("click", function () {
|
||||||
|
setOpen(true);
|
||||||
|
});
|
||||||
|
document.getElementById("collapse-all").addEventListener("click", function () {
|
||||||
|
setOpen(false);
|
||||||
|
});
|
||||||
|
filter.addEventListener("input", applyFilter);
|
||||||
|
document.addEventListener("keydown", function (event) {
|
||||||
|
if (event.key === "/" && document.activeElement !== filter) {
|
||||||
|
event.preventDefault();
|
||||||
|
filter.focus();
|
||||||
|
} else if (event.key === "Escape" && document.activeElement === filter) {
|
||||||
|
filter.value = "";
|
||||||
|
applyFilter();
|
||||||
|
filter.blur();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
applyFilter();
|
||||||
|
})();
|
||||||
|
{% endset %}
|
||||||
|
{% macro stat(added, removed) %}<span class="stat"><span class="add">+{{ added }}</span><span class="del">−{{ removed }}</span></span>{% endmacro %}
|
||||||
|
{% macro icon(name) %}<svg class="bi bi-{{ name }}" width="16" height="16" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true" focusable="false"><path fill-rule="evenodd" d="{{ icon_paths[name] }}"/></svg>{% endmacro %}
|
||||||
|
{% macro plural(count, word) %}{{ count }} {{ word }}{{ "" if count == 1 else "s" }}{% endmacro %}
|
||||||
|
{% macro file_block(file, open) %}
|
||||||
|
<details class="file" id="{{ file.anchor }}" data-path="{{ file.search }}"{% if open %} open{% endif %}>
|
||||||
|
<summary>
|
||||||
|
<span class="badge {{ file.diff.status }}" title="{{ file.diff.status }}">{{ status_letters[file.diff.status] }}</span>
|
||||||
|
<span class="path">{% if file.diff.moved %}<span class="old">{{ file.diff.old_path }}</span><span class="arrow"> → </span>{% endif %}{{ file.diff.path }}</span>
|
||||||
|
{% if file.diff.mode_change %}
|
||||||
|
<span class="tag">mode {{ file.diff.mode_change }}</span>
|
||||||
|
{% endif %}
|
||||||
|
{% if file.diff.binary %}
|
||||||
|
<span class="tag">binary</span>
|
||||||
|
{% endif %}
|
||||||
|
{{ stat(file.diff.added, file.diff.removed) }}
|
||||||
|
{% if file.link %}
|
||||||
|
<a class="open" href="{{ file.link }}" title="Open in VS Code">Open ↗</a>
|
||||||
|
{% endif %}
|
||||||
|
</summary>
|
||||||
|
{% if file.detail %}
|
||||||
|
<p class="placeholder">{{ file.detail }}</p>
|
||||||
|
{% elif not file.hunks %}
|
||||||
|
<p class="placeholder">No content changes.</p>
|
||||||
|
{% else %}
|
||||||
|
<table class="diff">
|
||||||
|
{% for hunk in file.hunks %}
|
||||||
|
<tbody>
|
||||||
|
<tr class="hunk"><td class="num" colspan="2"></td><td class="code" colspan="2">{{ hunk.header }}</td></tr>
|
||||||
|
{% for line in hunk.lines %}
|
||||||
|
<tr class="{{ line.kind }}"><td class="num">{{ "" if line.old is none else line.old }}</td><td class="num">{% if line.new is not none and file.link_base %}<a href="{{ file.link_base }}:{{ line.new }}">{{ line.new }}</a>{% elif line.new is not none %}{{ line.new }}{% endif %}</td><td class="sign">{{ signs[line.kind] }}</td><td class="code">{{ line.text }}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
{% endfor %}
|
||||||
|
{% if file.hidden %}
|
||||||
|
<tbody><tr class="more"><td colspan="4">… {{ plural(file.hidden, "more line") }} not shown</td></tr></tbody>
|
||||||
|
{% endif %}
|
||||||
|
</table>
|
||||||
|
{% endif %}
|
||||||
|
</details>
|
||||||
|
{% endmacro %}
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src '{{ style|csp_hash }}'; script-src '{{ script|csp_hash }}'; base-uri 'none'; form-action 'none'">
|
||||||
|
<meta name="referrer" content="no-referrer">
|
||||||
|
<title>Review: {{ review.name }}{% if review.branch %} ({{ review.branch }}){% endif %}</title>
|
||||||
|
<style>{{ style }}</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="masthead">
|
||||||
|
<div class="masthead-inner">
|
||||||
|
<p class="eyebrow">Working copy review</p>
|
||||||
|
<h1>{{ review.name }} <span class="pill">{{ review.branch or "detached HEAD" }}</span></h1>
|
||||||
|
<dl class="facts">
|
||||||
|
<dt>Top level</dt><dd>{{ review.top_level }}</dd>
|
||||||
|
<dt>Branch</dt><dd>{{ review.branch or "(detached HEAD)" }}</dd>
|
||||||
|
<dt>HEAD</dt><dd>{{ review.head or "(no commits yet)" }}</dd>
|
||||||
|
<dt>Index tree</dt><dd>{{ review.index_tree }}</dd>
|
||||||
|
{% if review.base is not none %}
|
||||||
|
<dt>Base</dt><dd>{{ review.base }} @ {{ review.base_short }}</dd>
|
||||||
|
{% endif %}
|
||||||
|
</dl>
|
||||||
|
{% if review.warnings %}
|
||||||
|
<ul class="warnings">
|
||||||
|
{% for warning in review.warnings %}
|
||||||
|
<li>{{ warning }}</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
{% endif %}
|
||||||
|
<div class="totals">
|
||||||
|
{% for section in review.sections %}
|
||||||
|
<a class="total" href="#{{ section.key }}"><span class="label">{{ section.title }}</span><span class="files">{{ plural(section.files|length, "file") }}</span>{{ stat(section.added, section.removed) }}</a>
|
||||||
|
{% endfor %}
|
||||||
|
{% if review.base is not none %}
|
||||||
|
<a class="total" href="#commits"><span class="label">Commits</span><span class="files">{{ plural(review.commits|length, "commit") }} · {{ plural(review.commit_files, "file") }}</span>{{ stat(review.commit_added, review.commit_removed) }}</a>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<nav class="toolbar">
|
||||||
|
<div class="toolbar-inner">
|
||||||
|
<div class="jumps">
|
||||||
|
{% if review.notes %}
|
||||||
|
<a href="#notes">Notes <span class="count">{{ review.notes|length }}</span></a>
|
||||||
|
{% endif %}
|
||||||
|
{% for section in review.sections %}
|
||||||
|
<a href="#{{ section.key }}">{{ section.title }} <span class="count">{{ section.files|length }}</span></a>
|
||||||
|
{% endfor %}
|
||||||
|
{% if review.base is not none %}
|
||||||
|
<a href="#commits">Commits <span class="count">{{ review.commits|length }}</span></a>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
<div class="spacer"></div>
|
||||||
|
<input id="filter" type="search" placeholder="Filter files by path ( / )" autocomplete="off" spellcheck="false" aria-label="Filter files by path">
|
||||||
|
<span id="filter-count" class="muted"></span>
|
||||||
|
<button type="button" id="expand-all" class="icon" title="Expand all" aria-label="Expand all">{{ icon("arrows-expand") }}</button>
|
||||||
|
<button type="button" id="collapse-all" class="icon" title="Collapse all" aria-label="Collapse all">{{ icon("arrows-collapse") }}</button>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<main>
|
||||||
|
{% if review.notes %}
|
||||||
|
<section class="group" id="notes">
|
||||||
|
<h2>Notes</h2>
|
||||||
|
{% for note in review.notes %}
|
||||||
|
<figure class="note">
|
||||||
|
<figcaption>{{ note.title }}</figcaption>
|
||||||
|
<pre>
|
||||||
|
{{ note.text }}</pre>
|
||||||
|
</figure>
|
||||||
|
{% endfor %}
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
{% for section in review.sections %}
|
||||||
|
<section class="group" id="{{ section.key }}" data-files="{{ section.files|length }}" data-added="{{ section.added }}" data-removed="{{ section.removed }}">
|
||||||
|
<h2>{{ section.title }} <span class="muted">{{ plural(section.files|length, "file") }}</span>{{ stat(section.added, section.removed) }}</h2>
|
||||||
|
{% if section.skipped %}
|
||||||
|
<p class="skipped">{{ section.skipped }}</p>
|
||||||
|
{% else %}
|
||||||
|
{% for file in section.files %}
|
||||||
|
{{ file_block(file, true) }}
|
||||||
|
{% else %}
|
||||||
|
<p class="empty">No changes.</p>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endfor %}
|
||||||
|
{% if review.base is not none %}
|
||||||
|
<section class="group" id="commits" data-commits="{{ review.commits|length }}" data-files="{{ review.commit_files }}" data-added="{{ review.commit_added }}" data-removed="{{ review.commit_removed }}">
|
||||||
|
<h2>Commits <span class="muted">{{ review.base }}..HEAD · {{ plural(review.commits|length, "commit") }}</span>{{ stat(review.commit_added, review.commit_removed) }}</h2>
|
||||||
|
{% for commit in review.commits %}
|
||||||
|
<details class="commit" id="{{ commit.anchor }}" open>
|
||||||
|
<summary>
|
||||||
|
<code class="sha">{{ commit.short }}</code>
|
||||||
|
<span class="subject">{{ commit.subject }}</span>
|
||||||
|
{{ stat(commit.added, commit.removed) }}
|
||||||
|
</summary>
|
||||||
|
<div class="commit-meta">{{ commit.author }}</div>
|
||||||
|
{% if commit.body %}
|
||||||
|
<pre class="commit-body">
|
||||||
|
{{ commit.body }}</pre>
|
||||||
|
{% endif %}
|
||||||
|
<div class="commit-files">
|
||||||
|
{% for file in commit.files %}
|
||||||
|
{{ file_block(file, false) }}
|
||||||
|
{% else %}
|
||||||
|
<p class="placeholder">No file changes.</p>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
{% else %}
|
||||||
|
<p class="empty">No commits between {{ review.base }} and HEAD.</p>
|
||||||
|
{% endfor %}
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
</main>
|
||||||
|
<script>{{ script }}</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from .model import FileDiff, FileView, Hunk
|
||||||
|
|
||||||
|
BINARY_DETAIL = "Binary file, contents not shown."
|
||||||
|
|
||||||
|
|
||||||
|
def _first_changed_line(hunks: tuple[Hunk, ...]) -> int:
|
||||||
|
for hunk in hunks:
|
||||||
|
position = hunk.new_start
|
||||||
|
for line in hunk.lines:
|
||||||
|
if line.kind in ("add", "del"):
|
||||||
|
return max(position, 1)
|
||||||
|
if line.new is not None:
|
||||||
|
position = line.new + 1
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
def _truncate(hunks: tuple[Hunk, ...], limit: int) -> tuple[tuple[Hunk, ...], int]:
|
||||||
|
shown: list[Hunk] = []
|
||||||
|
budget = limit
|
||||||
|
for hunk in hunks:
|
||||||
|
if budget <= 0:
|
||||||
|
break
|
||||||
|
lines = hunk.lines[:budget]
|
||||||
|
shown.append(Hunk(hunk.header, hunk.new_start, lines))
|
||||||
|
budget -= len(lines)
|
||||||
|
total = sum(len(hunk.lines) for hunk in hunks)
|
||||||
|
return tuple(shown), total - (limit - budget)
|
||||||
|
|
||||||
|
|
||||||
|
def file_view(
|
||||||
|
diff: FileDiff, anchor: str, top: str, limit: int, detail: str | None
|
||||||
|
) -> FileView:
|
||||||
|
link_base = None
|
||||||
|
if diff.new_path is not None:
|
||||||
|
link_base = "vscode://file" + quote(os.path.join(top, diff.new_path))
|
||||||
|
hunks, hidden = _truncate(diff.hunks, limit)
|
||||||
|
return FileView(
|
||||||
|
anchor=anchor,
|
||||||
|
diff=diff,
|
||||||
|
detail=detail,
|
||||||
|
link_base=link_base,
|
||||||
|
link=None
|
||||||
|
if link_base is None
|
||||||
|
else f"{link_base}:{_first_changed_line(diff.hunks)}",
|
||||||
|
hunks=hunks,
|
||||||
|
hidden=hidden,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def file_views(
|
||||||
|
diffs: list[FileDiff], prefix: str, top: str, limit: int
|
||||||
|
) -> tuple[FileView, ...]:
|
||||||
|
return tuple(
|
||||||
|
file_view(
|
||||||
|
diff,
|
||||||
|
f"{prefix}-{index}",
|
||||||
|
top,
|
||||||
|
limit,
|
||||||
|
BINARY_DETAIL if diff.binary else None,
|
||||||
|
)
|
||||||
|
for index, diff in enumerate(diffs, 1)
|
||||||
|
)
|
||||||
Whitespace-only changes.
@@ -0,0 +1,237 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import stat
|
||||||
|
from contextlib import suppress
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.nofollow import DIR_FLAGS
|
||||||
|
from pkgmgr.core.git.errors import GitBaseError
|
||||||
|
from pkgmgr.core.git.run import run
|
||||||
|
|
||||||
|
FLOW_DIR = "pkgmgr"
|
||||||
|
FLOW_FILE = "flow.yml"
|
||||||
|
RELATIVE = f"{FLOW_DIR}/{FLOW_FILE}"
|
||||||
|
VERSION = 1
|
||||||
|
MAX_BYTES = 64 * 1024
|
||||||
|
FOLDER_MODE = 0o700
|
||||||
|
FILE_MODE = 0o600
|
||||||
|
KEYS = ("version", "branch", "pull", "push")
|
||||||
|
REQUIRED = ("version", "pull", "push")
|
||||||
|
# O_NONBLOCK: opening a planted FIFO for reading would block until a writer comes
|
||||||
|
READ_FLAGS = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
|
||||||
|
WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW
|
||||||
|
DETACHED = "a detached HEAD"
|
||||||
|
NONE_LISTED = "(none)"
|
||||||
|
|
||||||
|
|
||||||
|
class FlowError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Flow:
|
||||||
|
pull: list[str] = field(default_factory=list)
|
||||||
|
push: list[str] = field(default_factory=list)
|
||||||
|
branch: str | None = None
|
||||||
|
source: str = "none"
|
||||||
|
warnings: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def describe(exc: BaseException) -> str:
|
||||||
|
return (str(exc).strip().splitlines() or [type(exc).__name__])[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _ref_format(name: str) -> bool:
|
||||||
|
# check-ref-format needs no repository, so / keeps any repository config
|
||||||
|
# out; --branch would expand @{-N} into another name inside one
|
||||||
|
try:
|
||||||
|
return (
|
||||||
|
run(["check-ref-format", "--branch", name], cwd=os.sep, scan=True) == name
|
||||||
|
)
|
||||||
|
except (GitBaseError, OSError, ValueError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def check_name(kind: str, name: object) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
kind: pull, push or branch, for the message.
|
||||||
|
name: an entry from the file or the command line.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
name, once it is a string git accepts as a branch name that does not
|
||||||
|
start with `-`; a remote-tracking name such as origin/main passes.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FlowError: name is anything else.
|
||||||
|
"""
|
||||||
|
if not isinstance(name, str) or name.startswith("-") or not _ref_format(name):
|
||||||
|
raise FlowError(f"{kind} {name!r} is not a valid branch name")
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def check_names(kind: str, names: object) -> list[str]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
kind: pull or push, for the message.
|
||||||
|
names: the list from the file or the command line.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The names in order, each passed through check_name.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FlowError: names is not a list or an entry is invalid.
|
||||||
|
"""
|
||||||
|
if not isinstance(names, list):
|
||||||
|
raise FlowError(f"{kind} must be a list of branch names")
|
||||||
|
return [check_name(kind, name) for name in names]
|
||||||
|
|
||||||
|
|
||||||
|
def _folder(git_dir: str, create: bool) -> int:
|
||||||
|
parent = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY)
|
||||||
|
try:
|
||||||
|
if create:
|
||||||
|
with suppress(FileExistsError):
|
||||||
|
os.mkdir(FLOW_DIR, FOLDER_MODE, dir_fd=parent)
|
||||||
|
return os.open(FLOW_DIR, DIR_FLAGS, dir_fd=parent)
|
||||||
|
finally:
|
||||||
|
os.close(parent)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_text(git_dir: str) -> str | None:
|
||||||
|
try:
|
||||||
|
folder = _folder(git_dir, create=False)
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
fd = os.open(FLOW_FILE, READ_FLAGS, dir_fd=folder)
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
os.close(folder)
|
||||||
|
# os.fdopen refuses a directory but leaves its fd open, so check first
|
||||||
|
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
||||||
|
os.close(fd)
|
||||||
|
raise FlowError("not a regular file")
|
||||||
|
with os.fdopen(fd, "rb") as fh:
|
||||||
|
data = fh.read(MAX_BYTES + 1)
|
||||||
|
if len(data) > MAX_BYTES:
|
||||||
|
raise FlowError(f"larger than {MAX_BYTES} bytes")
|
||||||
|
return data.decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(text: str) -> tuple[str | None, list[str], list[str]]:
|
||||||
|
data = yaml.safe_load(text)
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise FlowError("not a mapping")
|
||||||
|
unknown = [repr(key) for key in data if key not in KEYS]
|
||||||
|
if unknown:
|
||||||
|
raise FlowError(f"unknown keys {', '.join(unknown)}")
|
||||||
|
missing = [key for key in REQUIRED if key not in data]
|
||||||
|
if missing:
|
||||||
|
raise FlowError(f"missing keys {', '.join(missing)}")
|
||||||
|
# bool is an int, and True == 1
|
||||||
|
if type(data["version"]) is not int or data["version"] != VERSION:
|
||||||
|
raise FlowError(f"version must be {VERSION}")
|
||||||
|
branch = data.get("branch")
|
||||||
|
if branch is not None:
|
||||||
|
check_name("branch", branch)
|
||||||
|
return branch, check_names("pull", data["pull"]), check_names("push", data["push"])
|
||||||
|
|
||||||
|
|
||||||
|
def read_flow(git_dir: str) -> Flow:
|
||||||
|
"""
|
||||||
|
Read `<git_dir>/pkgmgr/flow.yml`, which an agent may have written.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
git_dir: the worktree's own git directory.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The flow with source file; source none when there is no file; source
|
||||||
|
invalid, empty lists and a warning when the file is a symbolic link,
|
||||||
|
no regular file, larger than MAX_BYTES or malformed. Never raises.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
text = _read_text(git_dir)
|
||||||
|
if text is None:
|
||||||
|
return Flow()
|
||||||
|
branch, pull, push = _parse(text)
|
||||||
|
# RecursionError: safe_load recurses once per nesting level
|
||||||
|
except (OSError, ValueError, yaml.YAMLError, RecursionError) as exc:
|
||||||
|
return Flow(source="invalid", warnings=[f"{RELATIVE} ignored: {describe(exc)}"])
|
||||||
|
return Flow(pull=pull, push=push, branch=branch, source="file")
|
||||||
|
|
||||||
|
|
||||||
|
def write_flow(
|
||||||
|
git_dir: str, branch: str | None, pull: list[str], push: list[str]
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Replace the flow atomically, never writing through a symbolic link.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
git_dir: the worktree's own git directory.
|
||||||
|
branch: the worktree's branch now; None when detached.
|
||||||
|
pull: refs merged into the branch, in order, already through check_names.
|
||||||
|
push: branches the branch is merged into, in order, likewise checked.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
OSError: `pkgmgr` is a symbolic link or no directory, or a write failed.
|
||||||
|
"""
|
||||||
|
data = {"version": VERSION, "branch": branch, "pull": pull, "push": push}
|
||||||
|
text = yaml.safe_dump(data, sort_keys=False, default_flow_style=False)
|
||||||
|
folder = _folder(git_dir, create=True)
|
||||||
|
tmp = f".{FLOW_FILE}.{secrets.token_hex(8)}"
|
||||||
|
try:
|
||||||
|
fd = os.open(tmp, WRITE_FLAGS, FILE_MODE, dir_fd=folder)
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(text)
|
||||||
|
fh.flush()
|
||||||
|
os.fsync(fh.fileno())
|
||||||
|
os.replace(tmp, FLOW_FILE, src_dir_fd=folder, dst_dir_fd=folder)
|
||||||
|
finally:
|
||||||
|
with suppress(FileNotFoundError):
|
||||||
|
os.unlink(tmp, dir_fd=folder)
|
||||||
|
os.close(folder)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_flow(git_dir: str) -> None:
|
||||||
|
"""
|
||||||
|
Remove the flow file; a symbolic link in its place goes, never its target.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
git_dir: the worktree's own git directory.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
OSError: `pkgmgr` is a symbolic link or no directory, or the unlink failed.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
folder = _folder(git_dir, create=False)
|
||||||
|
except FileNotFoundError:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
with suppress(FileNotFoundError):
|
||||||
|
os.unlink(FLOW_FILE, dir_fd=folder)
|
||||||
|
finally:
|
||||||
|
os.close(folder)
|
||||||
|
|
||||||
|
|
||||||
|
def mismatch(flow: Flow, branch: str | None) -> list[str]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
flow: a flow from read_flow.
|
||||||
|
branch: the worktree's current branch; None when detached.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
One warning when the file was written on another branch, else none.
|
||||||
|
"""
|
||||||
|
if flow.source != "file" or flow.branch == branch:
|
||||||
|
return []
|
||||||
|
warning = (
|
||||||
|
f"flow was set on {flow.branch or DETACHED}, "
|
||||||
|
f"the worktree is on {branch or DETACHED}"
|
||||||
|
)
|
||||||
|
return [warning]
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from pkgmgr.core.git.errors import GitBaseError
|
||||||
|
from pkgmgr.core.git.run import run
|
||||||
|
|
||||||
|
from .flow import (
|
||||||
|
NONE_LISTED,
|
||||||
|
Flow,
|
||||||
|
FlowError,
|
||||||
|
check_names,
|
||||||
|
clear_flow,
|
||||||
|
describe,
|
||||||
|
mismatch,
|
||||||
|
read_flow,
|
||||||
|
write_flow,
|
||||||
|
)
|
||||||
|
|
||||||
|
Located = tuple[str, str, str | None]
|
||||||
|
|
||||||
|
|
||||||
|
def locate(path: str) -> Located:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
path: any directory inside the worktree.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The worktree root, its own git directory (`.git` of the main
|
||||||
|
worktree, `<common>/worktrees/<id>` of a linked one) and its branch,
|
||||||
|
None when detached.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
GitBaseError: path is not inside a worktree, e.g. a bare repository.
|
||||||
|
OSError: path is no directory.
|
||||||
|
ValueError: a path git printed spans lines.
|
||||||
|
"""
|
||||||
|
out = run(
|
||||||
|
["rev-parse", "--absolute-git-dir", "--show-toplevel"], cwd=path, scan=True
|
||||||
|
)
|
||||||
|
git_dir, top = out.split("\n")
|
||||||
|
try:
|
||||||
|
ref = run(["symbolic-ref", "--quiet", "HEAD"], cwd=top, scan=True)
|
||||||
|
except GitBaseError:
|
||||||
|
ref = ""
|
||||||
|
branch = ref.removeprefix("refs/heads/") if ref.startswith("refs/heads/") else None
|
||||||
|
return top, git_dir, branch
|
||||||
|
|
||||||
|
|
||||||
|
def _located(path: str) -> Located | None:
|
||||||
|
try:
|
||||||
|
return locate(path)
|
||||||
|
except (GitBaseError, OSError, ValueError) as exc:
|
||||||
|
print(
|
||||||
|
f"Refusing: {path} is not a git worktree: {describe(exc)}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _report(located: Located, flow: Flow, as_json: bool) -> None:
|
||||||
|
top, git_dir, branch = located
|
||||||
|
result = {
|
||||||
|
"worktree": top,
|
||||||
|
"git_dir": git_dir,
|
||||||
|
"branch": branch,
|
||||||
|
"flow_branch": flow.branch,
|
||||||
|
"pull": flow.pull,
|
||||||
|
"push": flow.push,
|
||||||
|
"source": flow.source,
|
||||||
|
"warnings": flow.warnings + mismatch(flow, branch),
|
||||||
|
}
|
||||||
|
if as_json:
|
||||||
|
print(json.dumps(result, indent=2))
|
||||||
|
return
|
||||||
|
for warning in result["warnings"]:
|
||||||
|
print(f"WARN {warning}")
|
||||||
|
for key in ("pull", "push"):
|
||||||
|
print(f"{key}: {', '.join(result[key]) or NONE_LISTED}")
|
||||||
|
|
||||||
|
|
||||||
|
def worktree_flow_show(path: str, *, as_json: bool) -> int:
|
||||||
|
"""
|
||||||
|
Print the flow of the worktree at path.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: any directory inside the worktree.
|
||||||
|
as_json: print the result as JSON instead of text.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
0, also without a flow or with an invalid file; 2 when path is not a
|
||||||
|
git worktree.
|
||||||
|
"""
|
||||||
|
located = _located(path)
|
||||||
|
if located is None:
|
||||||
|
return 2
|
||||||
|
_report(located, read_flow(located[1]), as_json)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def worktree_flow_set(
|
||||||
|
path: str, *, pull: list[str], push: list[str], as_json: bool
|
||||||
|
) -> int:
|
||||||
|
"""
|
||||||
|
Replace both lists of the worktree's flow and print the result.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: any directory inside the worktree.
|
||||||
|
pull: refs merged into the branch before a gate, deploy or merge, in
|
||||||
|
order; may be empty.
|
||||||
|
push: branches the branch is merged into when finished, in order;
|
||||||
|
may be empty.
|
||||||
|
as_json: print the result as JSON instead of text.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
0 when written, 1 when the write failed, 2 on an invalid name or when
|
||||||
|
path is not a git worktree; nothing is written unless 0.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
pull, push = check_names("pull", pull), check_names("push", push)
|
||||||
|
except FlowError as exc:
|
||||||
|
print(f"Refusing: {exc}", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
located = _located(path)
|
||||||
|
if located is None:
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
write_flow(located[1], located[2], pull, push)
|
||||||
|
except OSError as exc:
|
||||||
|
print(f"Cannot write the flow of {located[0]}: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
_report(located, read_flow(located[1]), as_json)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def worktree_flow_clear(path: str, *, as_json: bool) -> int:
|
||||||
|
"""
|
||||||
|
Remove the worktree's flow and print the empty result.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: any directory inside the worktree.
|
||||||
|
as_json: print the result as JSON instead of text.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
0 when no flow is left, 1 when the removal failed, 2 when path is not
|
||||||
|
a git worktree.
|
||||||
|
"""
|
||||||
|
located = _located(path)
|
||||||
|
if located is None:
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
clear_flow(located[1])
|
||||||
|
except OSError as exc:
|
||||||
|
print(f"Cannot clear the flow of {located[0]}: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
_report(located, read_flow(located[1]), as_json)
|
||||||
|
return 0
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
|
||||||
|
from .trust import root_resolved, trusted_path
|
||||||
|
|
||||||
|
INIT_HOOK = "worktree-init"
|
||||||
|
FINI_HOOK = "worktree-fini"
|
||||||
|
MAKEFILES = ("GNUmakefile", "makefile", "Makefile")
|
||||||
|
MAKEFILE_LIMIT = 1 << 20
|
||||||
|
HOOK_TIMEOUT = 1800
|
||||||
|
HOOK_GRACE = 5
|
||||||
|
PLACEHOLDER = re.compile(r"\{(path|slot)\}")
|
||||||
|
|
||||||
|
|
||||||
|
def defined_in(path: str, target: str) -> str | None:
|
||||||
|
"""
|
||||||
|
Name the makefile in path that defines target, read as text and never run:
|
||||||
|
make expands $(shell) and include lines even under -n.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: directory that may hold a makefile.
|
||||||
|
target: make target name.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The first makefile, in make's lookup order, with a `<target>:` rule;
|
||||||
|
None when none has one.
|
||||||
|
"""
|
||||||
|
rule = re.compile(rf"^{re.escape(target)}\s*:", re.MULTILINE)
|
||||||
|
for name in MAKEFILES:
|
||||||
|
file = os.path.join(path, name)
|
||||||
|
if os.path.islink(file) or not os.path.isfile(file):
|
||||||
|
continue
|
||||||
|
with open(file, encoding="utf-8", errors="replace") as fh:
|
||||||
|
if rule.search(fh.read(MAKEFILE_LIMIT)):
|
||||||
|
return name
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def hook_command(name: str, argv: list[str], path: str, slot: int | None) -> list[str]:
|
||||||
|
"""
|
||||||
|
Fill a pinned hook command in one pass and resolve its program.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name: the hook, for error messages.
|
||||||
|
argv: the command pinned in the `worktree_hooks` config.
|
||||||
|
path: the worktree, replacing `{path}`.
|
||||||
|
slot: the worktree's slot, replacing `{slot}`; None leaves it as is.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The argv to run; its program is an absolute path, for a bare name the
|
||||||
|
resolved file that was checked, so a multi-call binary sees that
|
||||||
|
file's name; pin the link's absolute path to keep the link's name.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: the program is neither absolute nor a bare name found,
|
||||||
|
as a root-controlled file, on a root-owned PATH entry no group or
|
||||||
|
other user can write; anything relative resolves in the worktree.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def fill(match: re.Match[str]) -> str:
|
||||||
|
if match.group(1) == "path":
|
||||||
|
return path
|
||||||
|
return match.group(0) if slot is None else str(slot)
|
||||||
|
|
||||||
|
filled = [PLACEHOLDER.sub(fill, arg) for arg in argv]
|
||||||
|
program = filled[0] if filled else ""
|
||||||
|
if not os.path.isabs(program):
|
||||||
|
found = (
|
||||||
|
shutil.which(program, path=trusted_path())
|
||||||
|
if program and "/" not in program
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
resolved = root_resolved(found) if found else None
|
||||||
|
if resolved is None:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{name} pin {program!r} is neither an absolute path nor a "
|
||||||
|
"root-owned command on a root-owned PATH entry"
|
||||||
|
)
|
||||||
|
program = resolved
|
||||||
|
return [program, *filled[1:]]
|
||||||
|
|
||||||
|
|
||||||
|
def run_hook(
|
||||||
|
name: str, command: list[str], path: str, *, check: bool, **kwargs
|
||||||
|
) -> subprocess.CompletedProcess:
|
||||||
|
"""
|
||||||
|
Run a resolved hook command in the worktree.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name: the hook, for error messages.
|
||||||
|
command: the argv from hook_command.
|
||||||
|
path: the worktree to run in.
|
||||||
|
check: raise CalledProcessError on a non-zero exit.
|
||||||
|
kwargs: further subprocess.Popen arguments, such as output handling.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The completed process; stdin was closed, PATH held only its
|
||||||
|
root-controlled entries and HOOK_TIMEOUT applied to its whole process
|
||||||
|
group.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: the hook ran longer than HOOK_TIMEOUT, or no PATH entry
|
||||||
|
is root-controlled.
|
||||||
|
"""
|
||||||
|
with subprocess.Popen(
|
||||||
|
command,
|
||||||
|
cwd=path,
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
env={**os.environ, "PATH": trusted_path()},
|
||||||
|
start_new_session=True,
|
||||||
|
**kwargs,
|
||||||
|
) as process:
|
||||||
|
try:
|
||||||
|
stdout, stderr = process.communicate(timeout=HOOK_TIMEOUT)
|
||||||
|
except subprocess.TimeoutExpired as exc:
|
||||||
|
_stop_group(process)
|
||||||
|
raise RuntimeError(f"{name} timed out after {HOOK_TIMEOUT} s") from exc
|
||||||
|
if check and process.returncode:
|
||||||
|
raise subprocess.CalledProcessError(
|
||||||
|
process.returncode, command, output=stdout, stderr=stderr
|
||||||
|
)
|
||||||
|
return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
|
||||||
|
|
||||||
|
|
||||||
|
def _stop_group(process: subprocess.Popen) -> None:
|
||||||
|
for sig in (signal.SIGTERM, signal.SIGKILL):
|
||||||
|
try:
|
||||||
|
os.killpg(process.pid, sig)
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
deadline = time.monotonic() + HOOK_GRACE
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
process.poll()
|
||||||
|
try:
|
||||||
|
os.killpg(process.pid, 0)
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
time.sleep(0.05)
|
||||||
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user