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
|
||||||
|
|||||||
@@ -8,9 +8,12 @@ on:
|
|||||||
- cron: "0 3 * * *"
|
- cron: "0 3 * * *"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
prepare:
|
prepare:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
if: ${{ github.event_name != 'workflow_run' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository) }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
@@ -21,7 +24,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository (with tags)
|
- name: Checkout repository (with tags)
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
@@ -54,7 +57,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout ${{ matrix.release.version }}
|
- name: Checkout ${{ matrix.release.version }}
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
with:
|
with:
|
||||||
ref: ${{ matrix.release.sha }}
|
ref: ${{ matrix.release.sha }}
|
||||||
|
|
||||||
@@ -64,7 +67,7 @@ jobs:
|
|||||||
use: true
|
use: true
|
||||||
|
|
||||||
- name: Login to GHCR
|
- name: Login to GHCR
|
||||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
@@ -96,7 +99,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout ${{ matrix.release.version }}
|
- name: Checkout ${{ matrix.release.version }}
|
||||||
uses: actions/checkout@v7
|
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
with:
|
with:
|
||||||
ref: ${{ matrix.release.sha }}
|
ref: ${{ matrix.release.sha }}
|
||||||
|
|
||||||
@@ -106,7 +109,7 @@ jobs:
|
|||||||
use: true
|
use: true
|
||||||
|
|
||||||
- name: Login to GHCR
|
- name: Login to GHCR
|
||||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
name: Scorecard supply-chain security
|
||||||
|
|
||||||
|
on:
|
||||||
|
branch_protection_rule:
|
||||||
|
schedule:
|
||||||
|
- cron: '00 00 * * *'
|
||||||
|
push:
|
||||||
|
branches: [ "main" ]
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: scorecard-${{ github.repository }}-${{ github.ref_name }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
permissions: read-all
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analysis:
|
||||||
|
name: Scorecard analysis
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event.repository.default_branch == github.ref_name
|
||||||
|
permissions:
|
||||||
|
security-events: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@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: |
|
||||||
|
|||||||
@@ -1,5 +1,47 @@
|
|||||||
# 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
|
## [2.4.0] - 2026-11-07
|
||||||
|
|
||||||
Added:
|
Added:
|
||||||
|
|||||||
@@ -80,6 +80,7 @@ versioning features it can drive **end-to-end workflows**:
|
|||||||
| `pkgmgr worktree flow clear [PATH] [--json]` | Removes the merge flow |
|
| `pkgmgr worktree 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 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 [--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 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 [--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 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 |
|
||||||
|
|||||||
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.4.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.4.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,49 @@
|
|||||||
|
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
|
package-manager (2.4.0-1) unstable; urgency=medium
|
||||||
|
|
||||||
Added:
|
Added:
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
Name: package-manager
|
Name: package-manager
|
||||||
Version: 2.4.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,46 @@ 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
|
* Sat Nov 07 2026 Kevin Veen-Birkenbach <kevin@veen.world> - 2.4.0-1
|
||||||
- Added:
|
- Added:
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "kpmx"
|
name = "kpmx"
|
||||||
version = "2.4.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"
|
||||||
@@ -52,4 +52,4 @@ include = ["pkgmgr*"]
|
|||||||
|
|
||||||
[tool.setuptools.package-data]
|
[tool.setuptools.package-data]
|
||||||
"pkgmgr.config" = ["*.yml", "*.yaml"]
|
"pkgmgr.config" = ["*.yml", "*.yaml"]
|
||||||
"pkgmgr.actions.review" = ["*.j2"]
|
"pkgmgr.actions.review" = ["*.j2", "*.LICENSE"]
|
||||||
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
|
||||||
+774
-40
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
|
||||||
)
|
)
|
||||||
@@ -94,7 +101,8 @@ def facts_with_token(slugs: list[tuple[str, str]], token: str) -> ForgeFacts:
|
|||||||
The facts, or facts whose unavailable names the failing repository.
|
The facts, or facts whose unavailable names the failing repository.
|
||||||
"""
|
"""
|
||||||
facts = ForgeFacts()
|
facts = ForgeFacts()
|
||||||
http = HttpClient(timeout_s=30)
|
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",
|
||||||
@@ -103,14 +111,17 @@ def facts_with_token(slugs: list[tuple[str, str]], token: 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}"
|
||||||
|
)
|
||||||
@@ -50,17 +50,15 @@ def _cache_path(owner: str, name: str) -> str:
|
|||||||
return os.path.join(base, "pkgmgr", "forge", owner, f"{name}.json")
|
return os.path.join(base, "pkgmgr", "forge", owner, f"{name}.json")
|
||||||
|
|
||||||
|
|
||||||
def secret_service_token() -> tuple[str | None, str | None]:
|
class SecretServiceUnavailable(Exception):
|
||||||
"""
|
pass
|
||||||
Read the GitHub token from the Secret Service without unlocking it.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
(token, None), or (None, why no token is available).
|
def _secret_service_token() -> str:
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
import secretstorage
|
import secretstorage
|
||||||
except ImportError:
|
except ImportError as exc:
|
||||||
return None, "secretstorage not installed"
|
raise SecretServiceUnavailable("secretstorage not installed") from exc
|
||||||
key = build_keyring_key("github", GITHUB_HOST, None)
|
key = build_keyring_key("github", GITHUB_HOST, None)
|
||||||
try:
|
try:
|
||||||
connection = secretstorage.dbus_init()
|
connection = secretstorage.dbus_init()
|
||||||
@@ -72,14 +70,21 @@ def secret_service_token() -> tuple[str | None, str | None]:
|
|||||||
)
|
)
|
||||||
unlocked = [item for item in items if not item.is_locked()]
|
unlocked = [item for item in items if not item.is_locked()]
|
||||||
if not items:
|
if not items:
|
||||||
return None, "no GitHub token in the Secret Service"
|
raise SecretServiceUnavailable("no GitHub token in the Secret Service")
|
||||||
if not unlocked:
|
if not unlocked:
|
||||||
return None, "Secret Service locked"
|
raise SecretServiceUnavailable("Secret Service locked")
|
||||||
return unlocked[0].get_secret().decode(), None
|
return unlocked[0].get_secret().decode()
|
||||||
finally:
|
finally:
|
||||||
connection.close()
|
connection.close()
|
||||||
except (secretstorage.exceptions.SecretStorageException, OSError) as exc:
|
except (secretstorage.exceptions.SecretStorageException, OSError) as exc:
|
||||||
return None, f"Secret Service unavailable: {exc}"
|
raise SecretServiceUnavailable(f"Secret Service unavailable: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _forge_access() -> tuple[str | None, str | None]:
|
||||||
|
try:
|
||||||
|
return _secret_service_token(), None
|
||||||
|
except SecretServiceUnavailable as exc:
|
||||||
|
return None, str(exc)
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
@@ -315,7 +320,7 @@ def branch_tree(
|
|||||||
"""
|
"""
|
||||||
known = list(dict.fromkeys(os.path.realpath(d) for d in repo_dirs))
|
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]
|
orphans = [d for d in _shared_owners(worktrees_root) if d not in known]
|
||||||
token, reason = secret_service_token()
|
token, reason = _forge_access()
|
||||||
host_ns = gc.host_pid_namespace()
|
host_ns = gc.host_pid_namespace()
|
||||||
containers = gc.list_compose_containers()
|
containers = gc.list_compose_containers()
|
||||||
data = {
|
data = {
|
||||||
@@ -357,7 +362,7 @@ def refresh_tree_entry(repo_root: str) -> None:
|
|||||||
if not os.path.isfile(path) or not gc.host_pid_namespace():
|
if not os.path.isfile(path) or not gc.host_pid_namespace():
|
||||||
return
|
return
|
||||||
root = os.path.realpath(repo_root)
|
root = os.path.realpath(repo_root)
|
||||||
token, reason = secret_service_token()
|
token, reason = _forge_access()
|
||||||
fresh = _scan(root, True, token, reason, gc.list_compose_containers(), True)
|
fresh = _scan(root, True, token, reason, gc.list_compose_containers(), True)
|
||||||
with _locked(path):
|
with _locked(path):
|
||||||
with open(path, encoding="utf-8") as fh:
|
with open(path, encoding="utf-8") as fh:
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
from .levels import LEVELS
|
||||||
|
from .plan import RiskRequest, risk_cleanup
|
||||||
|
|
||||||
|
__all__ = ["LEVELS", "RiskRequest", "risk_cleanup"]
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc import COMPOSE_PROJECT, _describe, _docker
|
||||||
|
|
||||||
|
from .levels import DAY_S, HIGH, IDLE_DAYS, LOW, MEDIUM, item
|
||||||
|
|
||||||
|
DF_VERBOSE = ["system", "df", "--verbose", "--format", "{{json .}}"]
|
||||||
|
DANGLING = ["image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true"]
|
||||||
|
STOPPED = ("exited", "dead")
|
||||||
|
UNITS = {"": 1, "k": 10**3, "m": 10**6, "g": 10**9, "t": 10**12, "p": 10**15}
|
||||||
|
SIZE = re.compile(r"([0-9.]+)\s*([kKmMgGtTpP]?)B")
|
||||||
|
STAMP = re.compile(r"(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)(?:\.(\d+))? ([+-]\d{4})")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_size(text: object) -> int | None:
|
||||||
|
match = SIZE.fullmatch(str(text or "").strip())
|
||||||
|
if not match:
|
||||||
|
return None
|
||||||
|
return int(float(match.group(1)) * UNITS[match.group(2).lower()])
|
||||||
|
|
||||||
|
|
||||||
|
def parse_time(text: object) -> float | None:
|
||||||
|
match = STAMP.match(str(text or "").strip())
|
||||||
|
if not match:
|
||||||
|
return None
|
||||||
|
clock, fraction, zone = match.groups()
|
||||||
|
micro = (fraction or "")[:6].ljust(6, "0")
|
||||||
|
return datetime.strptime(
|
||||||
|
f"{clock}.{micro} {zone}", "%Y-%m-%d %H:%M:%S.%f %z"
|
||||||
|
).timestamp()
|
||||||
|
|
||||||
|
|
||||||
|
def _project(labels: object) -> str | None:
|
||||||
|
for pair in str(labels or "").split(","):
|
||||||
|
key, _, value = pair.partition("=")
|
||||||
|
if key == COMPOSE_PROJECT:
|
||||||
|
return value
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _volumes(rows: list[dict]) -> list[dict]:
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
links = int(row["Links"]) if str(row.get("Links")).isdigit() else None
|
||||||
|
unused = links == 0
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"volume",
|
||||||
|
str(row["Name"]),
|
||||||
|
MEDIUM if unused else HIGH,
|
||||||
|
"unused volume: its data is lost"
|
||||||
|
if unused
|
||||||
|
else "volume in use by a container",
|
||||||
|
size_bytes=parse_size(row.get("Size")),
|
||||||
|
compose_project=_project(row.get("Labels")),
|
||||||
|
links=links,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _images(rows: list[dict], dangling: set[str]) -> list[dict]:
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
if str(row.get("Containers")) != "0":
|
||||||
|
continue
|
||||||
|
loose = row["ID"] in dangling
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"image",
|
||||||
|
str(row["ID"]),
|
||||||
|
LOW if loose else MEDIUM,
|
||||||
|
"dangling image without containers" if loose else "unused tagged image",
|
||||||
|
size_bytes=parse_size(row.get("UniqueSize")),
|
||||||
|
repository=row.get("Repository"),
|
||||||
|
tag=row.get("Tag"),
|
||||||
|
created_at=row.get("CreatedAt"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _cache(rows: list[dict], now: float) -> list[dict]:
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
if str(row.get("InUse")).lower() != "false":
|
||||||
|
continue
|
||||||
|
used = parse_time(row.get("LastUsedAt")) or parse_time(row.get("CreatedAt"))
|
||||||
|
idle = used is not None and now - used > IDLE_DAYS * DAY_S
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"build-cache",
|
||||||
|
str(row["ID"]),
|
||||||
|
LOW if idle else MEDIUM,
|
||||||
|
f"build cache idle > {IDLE_DAYS} days"
|
||||||
|
if idle
|
||||||
|
else f"build cache used within {IDLE_DAYS} days",
|
||||||
|
size_bytes=parse_size(row.get("Size")),
|
||||||
|
last_used_since=row.get("LastUsedSince"),
|
||||||
|
last_used_at=used,
|
||||||
|
shared=str(row.get("Shared")).lower() == "true",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _containers(rows: list[dict]) -> list[dict]:
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
if row.get("State") not in STOPPED:
|
||||||
|
continue
|
||||||
|
volumes = str(row.get("LocalVolumes"))
|
||||||
|
bare = volumes == "0"
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"container",
|
||||||
|
str(row["ID"]),
|
||||||
|
LOW if bare else MEDIUM,
|
||||||
|
"stopped container without volumes"
|
||||||
|
if bare
|
||||||
|
else f"stopped container with {volumes} local volumes",
|
||||||
|
names=row.get("Names"),
|
||||||
|
image=row.get("Image"),
|
||||||
|
compose_project=_project(row.get("Labels")),
|
||||||
|
status=row.get("Status"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def docker_items(now: float) -> tuple[list[dict], list[str]]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
now: epoch seconds the build cache idle time is measured against.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Every volume, unused image, idle build cache record and stopped
|
||||||
|
container with its risk, read without changing anything, and
|
||||||
|
warnings when docker is missing, fails or prints no JSON.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
data = json.loads(_docker(DF_VERBOSE))
|
||||||
|
dangling = set(_docker(DANGLING).split())
|
||||||
|
except FileNotFoundError:
|
||||||
|
return [], ["docker unavailable: not installed"]
|
||||||
|
except subprocess.CalledProcessError as exc:
|
||||||
|
return [], [f"docker unavailable: {_describe(exc)}"]
|
||||||
|
except ValueError:
|
||||||
|
return [], ["docker system df --verbose: output is not JSON"]
|
||||||
|
return [
|
||||||
|
*_volumes(data.get("Volumes") or []),
|
||||||
|
*_images(data.get("Images") or [], dangling),
|
||||||
|
*_cache(data.get("BuildCache") or [], now),
|
||||||
|
*_containers(data.get("Containers") or []),
|
||||||
|
], []
|
||||||
|
|
||||||
|
|
||||||
|
def delete_docker(entry: dict, now: float) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
entry: a low image, build-cache or container item of the plan.
|
||||||
|
now: as docker_items takes it.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
done, or skipped with the reason: an item that docker no longer
|
||||||
|
lists as low right before its delete, or a kind that is never low.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
subprocess.CalledProcessError: when docker refuses the delete.
|
||||||
|
RuntimeError: when docker cannot be read again before the delete.
|
||||||
|
"""
|
||||||
|
name = entry["name"]
|
||||||
|
fresh, warnings = docker_items(now)
|
||||||
|
if warnings:
|
||||||
|
raise RuntimeError(f"revalidation failed: {'; '.join(warnings)}")
|
||||||
|
if not any(
|
||||||
|
i["kind"] == entry["kind"] and i["name"] == name and i["risk"] == LOW
|
||||||
|
for i in fresh
|
||||||
|
):
|
||||||
|
return "skipped: changed since plan"
|
||||||
|
if entry["kind"] == "image":
|
||||||
|
_docker(["image", "rm", name])
|
||||||
|
elif entry["kind"] == "build-cache":
|
||||||
|
_docker(
|
||||||
|
[
|
||||||
|
"builder",
|
||||||
|
"prune",
|
||||||
|
"--force",
|
||||||
|
"--filter",
|
||||||
|
f"id={name}",
|
||||||
|
"--filter",
|
||||||
|
f"until={IDLE_DAYS * 24}h",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
elif entry["kind"] == "container":
|
||||||
|
_docker(["container", "rm", name])
|
||||||
|
else:
|
||||||
|
return f"skipped: {entry['kind']} is never deleted as low"
|
||||||
|
return "done"
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc import (
|
||||||
|
FORGE_UNAVAILABLE,
|
||||||
|
Item,
|
||||||
|
Repo,
|
||||||
|
_git,
|
||||||
|
_rebuild,
|
||||||
|
execute,
|
||||||
|
prepare,
|
||||||
|
)
|
||||||
|
from pkgmgr.actions.worktree.hooks import FINI_HOOK
|
||||||
|
|
||||||
|
from .levels import HIGH, LOW, MEDIUM, item
|
||||||
|
|
||||||
|
LOCAL_PROOF = ("ancestor", "patch")
|
||||||
|
TREE_STEPS = (f"hook:{FINI_HOOK}", "worktree")
|
||||||
|
|
||||||
|
|
||||||
|
def _pushed(repo: Repo, head: str | None) -> bool:
|
||||||
|
if not head:
|
||||||
|
return False
|
||||||
|
count = _git(["rev-list", "--count", head, "--not", "--remotes"], repo.repo)
|
||||||
|
return count == "0"
|
||||||
|
|
||||||
|
|
||||||
|
def pr_state(repo: Repo, it: Item) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo: the planned repository with its forge facts.
|
||||||
|
it: one of its items.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
unknown when the forge was not read, else open #N, merged #N or none.
|
||||||
|
"""
|
||||||
|
if repo.forge.unavailable:
|
||||||
|
return "unknown"
|
||||||
|
number = repo.forge.open_heads.get(it.branch) if it.branch else None
|
||||||
|
if number:
|
||||||
|
return f"open #{number}"
|
||||||
|
shas = [it.local_sha, it.head, *it.remotes.values()]
|
||||||
|
merged = [repo.forge.merged_heads[s] for s in shas if s in repo.forge.merged_heads]
|
||||||
|
return f"merged #{merged[0]}" if merged else "none"
|
||||||
|
|
||||||
|
|
||||||
|
def classify(repo: Repo, it: Item) -> tuple[str, str]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo: the planned repository.
|
||||||
|
it: one of its items, planned with scope `all` or `worktree`.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The risk and why. Low only for a linked worktree merged into the
|
||||||
|
default branch by ancestry or patch id, without staged, unstaged or
|
||||||
|
untracked change, whose head is on a remote, without compose stack
|
||||||
|
and with nothing but the forge's absence holding it.
|
||||||
|
"""
|
||||||
|
return _state_verdict(it) or _tree_verdict(repo, it)
|
||||||
|
|
||||||
|
|
||||||
|
def _state_verdict(it: Item) -> tuple[str, str] | None:
|
||||||
|
if it.state == "protected":
|
||||||
|
return HIGH, it.reason
|
||||||
|
if it.state == "stale":
|
||||||
|
return MEDIUM, "stale worktree metadata"
|
||||||
|
if it.state == "dirty":
|
||||||
|
return HIGH, it.reason
|
||||||
|
if it.worktree is None:
|
||||||
|
if it.state == "merged-clean":
|
||||||
|
return MEDIUM, f"merged branch ({it.reason}): branches are never low"
|
||||||
|
return HIGH, it.reason
|
||||||
|
if it.state != "merged-clean":
|
||||||
|
if it.unpushed:
|
||||||
|
return HIGH, f"{it.reason}; {it.unpushed} commits on no remote"
|
||||||
|
return MEDIUM, it.reason
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _tree_verdict(repo: Repo, it: Item) -> tuple[str, str]:
|
||||||
|
if it.merged_by not in LOCAL_PROOF or it.merged_into != repo.default:
|
||||||
|
return MEDIUM, f"merged by {it.merged_by}, not locally into {repo.default}"
|
||||||
|
if it.worktree_state != "clean" or any((it.staged, it.unstaged, it.untracked)):
|
||||||
|
return HIGH, "worktree has changes"
|
||||||
|
if it.compose_projects:
|
||||||
|
return MEDIUM, f"compose stack {', '.join(it.compose_projects)}"
|
||||||
|
if it.skip not in (None, FORGE_UNAVAILABLE):
|
||||||
|
return MEDIUM, it.skip
|
||||||
|
if "worktree" not in it.actions:
|
||||||
|
return MEDIUM, "no worktree removal planned"
|
||||||
|
if not _pushed(repo, it.head):
|
||||||
|
return MEDIUM, "head is on no remote"
|
||||||
|
return LOW, f"merged into {repo.default} by {it.merged_by}, clean, pushed"
|
||||||
|
|
||||||
|
|
||||||
|
def _entry(repo: Repo, it: Item) -> dict:
|
||||||
|
risk, reason = classify(repo, it)
|
||||||
|
linked = it.worktree is not None and it.worktree != repo.repo
|
||||||
|
kind = "stale" if it.state == "stale" else "worktree" if linked else "branch"
|
||||||
|
return item(
|
||||||
|
kind,
|
||||||
|
it.worktree if linked or not it.branch else it.branch,
|
||||||
|
risk,
|
||||||
|
reason,
|
||||||
|
size_bytes=it.size_bytes,
|
||||||
|
repo=repo.repo,
|
||||||
|
branch=it.branch,
|
||||||
|
head=it.head,
|
||||||
|
state=it.state,
|
||||||
|
merged_by=it.merged_by,
|
||||||
|
merged_into=it.merged_into,
|
||||||
|
staged=it.staged,
|
||||||
|
unstaged=it.unstaged,
|
||||||
|
untracked=it.untracked,
|
||||||
|
compose_projects=it.compose_projects,
|
||||||
|
pr=pr_state(repo, it),
|
||||||
|
skip=it.skip,
|
||||||
|
steps=[a for a in it.actions if a in TREE_STEPS] if risk == LOW else [],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def git_items(
|
||||||
|
repo_roots: list[str], include: list[str], exclude: list[str], options: dict
|
||||||
|
) -> tuple[list[tuple[Repo, Item, dict]], list[str], bool] | None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo_roots: main worktree roots of the repositories to scan, each
|
||||||
|
planned with scope `all`.
|
||||||
|
include: only items whose branch or worktree path matches one of these.
|
||||||
|
exclude: drop items whose branch or worktree path matches one of these.
|
||||||
|
options: the plan_repo keyword options but scope.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(repository, item, plan entry) per chosen item, the warnings and
|
||||||
|
whether this runs in the host PID namespace; None for an unknown
|
||||||
|
include.
|
||||||
|
"""
|
||||||
|
prepared = prepare(repo_roots, include, exclude, {**options, "scope": "all"})
|
||||||
|
if prepared is None:
|
||||||
|
return None
|
||||||
|
repos, host_ns, chosen = prepared
|
||||||
|
warnings = [f"{repo.repo}: {w}" for repo in repos for w in repo.warnings]
|
||||||
|
entries = [
|
||||||
|
(repo, it, _entry(repo, it))
|
||||||
|
for repo in repos
|
||||||
|
for it in repo.items
|
||||||
|
if chosen(it)
|
||||||
|
]
|
||||||
|
return entries, warnings, host_ns
|
||||||
|
|
||||||
|
|
||||||
|
def delete_worktree(repo: Repo, it: Item) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo: the planned repository.
|
||||||
|
it: the low worktree item as planned; planned again with scope
|
||||||
|
`worktree`, so its branch stays, and removed only while low.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The result execute settles, or skipped when it changed since the plan.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: when execute settles no result.
|
||||||
|
"""
|
||||||
|
tree_repo = replace(repo, scope="worktree")
|
||||||
|
fresh = _rebuild(tree_repo, it)
|
||||||
|
risk, reason = classify(tree_repo, fresh)
|
||||||
|
if risk != LOW or fresh.head != it.head or fresh.worktree != it.worktree:
|
||||||
|
return f"skipped: changed since plan ({reason})"
|
||||||
|
execute(tree_repo, fresh)
|
||||||
|
if fresh.result is None:
|
||||||
|
raise RuntimeError(f"execute settled no result for {it.worktree}")
|
||||||
|
return fresh.result
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
LOW = "low"
|
||||||
|
MEDIUM = "medium"
|
||||||
|
HIGH = "high"
|
||||||
|
LEVELS = (LOW, MEDIUM, HIGH)
|
||||||
|
DAY_S = 86400
|
||||||
|
IDLE_DAYS = 7
|
||||||
|
TMP_AGE_S = DAY_S
|
||||||
|
|
||||||
|
|
||||||
|
def rank(level: str) -> int:
|
||||||
|
return LEVELS.index(level)
|
||||||
|
|
||||||
|
|
||||||
|
def item(kind: str, name: str, risk: str, reason: str, **facts: object) -> dict:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
kind: worktree, branch, stale, image, build-cache, container, volume or tmp.
|
||||||
|
name: what the item deletes: a path, branch, docker id or volume name.
|
||||||
|
risk: one of LEVELS.
|
||||||
|
reason: why the item has that risk.
|
||||||
|
facts: kind-specific fields; size_bytes is read by the totals.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
One plan item; result stays None until an apply sets it.
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"kind": kind,
|
||||||
|
"name": name,
|
||||||
|
"risk": risk,
|
||||||
|
"reason": reason,
|
||||||
|
"size_bytes": None,
|
||||||
|
**facts,
|
||||||
|
"result": None,
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc import (
|
||||||
|
REFUSAL,
|
||||||
|
_describe,
|
||||||
|
_process_cwds,
|
||||||
|
host_pid_namespace,
|
||||||
|
human_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
from .docker_items import delete_docker, docker_items
|
||||||
|
from .git_items import delete_worktree, git_items
|
||||||
|
from .levels import LEVELS, LOW, rank
|
||||||
|
from .tmp_items import delete_tmp, read_owners, tmp_items
|
||||||
|
|
||||||
|
DOCKER_KINDS = ("image", "build-cache", "container")
|
||||||
|
NO_HOST_NS = "process and lock checks unavailable: not in the host PID namespace"
|
||||||
|
INCLUDE_ONLY_GIT = (
|
||||||
|
"--branch selects git items only; docker and scratch items stay out of the plan"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RiskRequest:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
level: print the git, docker and scratch items up to this risk;
|
||||||
|
apply needs `low`.
|
||||||
|
apply: delete exactly the low items of the same plan, each
|
||||||
|
re-checked right before.
|
||||||
|
as_json: print the plan as JSON instead of text lines.
|
||||||
|
owners_file: optional JSON object of scratch path -> task status.
|
||||||
|
include: only git items whose branch or worktree path matches; when
|
||||||
|
set, docker and scratch items are neither planned nor deleted.
|
||||||
|
exclude: drop git items whose branch or worktree path matches.
|
||||||
|
merged_into: integration lines (refs) that also count as merged.
|
||||||
|
sizes: measure each worktree's disk usage into the plan.
|
||||||
|
min_age: skip git items younger than this many hours.
|
||||||
|
hooks: pinned hooks by managed repository root realpath.
|
||||||
|
tmp_root: the scratch directory whose direct children are listed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
level: str
|
||||||
|
apply: bool
|
||||||
|
as_json: bool
|
||||||
|
owners_file: str | None
|
||||||
|
include: list[str]
|
||||||
|
exclude: list[str]
|
||||||
|
merged_into: list[str]
|
||||||
|
sizes: bool
|
||||||
|
min_age: float | None
|
||||||
|
hooks: dict[str, dict[str, list[str]]]
|
||||||
|
tmp_root: str
|
||||||
|
|
||||||
|
|
||||||
|
def _totals(entries: list[dict]) -> dict:
|
||||||
|
return {
|
||||||
|
level: {
|
||||||
|
"count": sum(e["risk"] == level for e in entries),
|
||||||
|
"size_bytes": sum(
|
||||||
|
e["size_bytes"]
|
||||||
|
for e in entries
|
||||||
|
if e["risk"] == level and e["size_bytes"] is not None
|
||||||
|
),
|
||||||
|
}
|
||||||
|
for level in LEVELS
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _render(plan: dict) -> str:
|
||||||
|
lines = [f"== gc plan (risk up to {plan['risk']})"]
|
||||||
|
for entry in plan["items"]:
|
||||||
|
size = "-" if entry["size_bytes"] is None else human_size(entry["size_bytes"])
|
||||||
|
line = (
|
||||||
|
f"{entry['risk'].upper():<6} {entry['kind']:<11} {size:>8} "
|
||||||
|
f"{entry['name']} {entry['reason']}"
|
||||||
|
)
|
||||||
|
lines.append(f"{line} -> {entry['result']}" if entry["result"] else line)
|
||||||
|
lines += [
|
||||||
|
f"TOTAL {level}: {t['count']} items, {human_size(t['size_bytes'])}"
|
||||||
|
for level, t in plan["totals"].items()
|
||||||
|
]
|
||||||
|
lines += [f"WARN {warning}" for warning in plan["warnings"]]
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def _delete(
|
||||||
|
entry: dict,
|
||||||
|
git_by_name: dict,
|
||||||
|
owners_file: str | None,
|
||||||
|
now: float,
|
||||||
|
) -> str:
|
||||||
|
try:
|
||||||
|
if entry["kind"] in DOCKER_KINDS:
|
||||||
|
return delete_docker(entry, now)
|
||||||
|
if entry["kind"] == "tmp":
|
||||||
|
return delete_tmp(
|
||||||
|
entry, read_owners(owners_file), now, _process_cwds()
|
||||||
|
)
|
||||||
|
if entry["kind"] == "worktree":
|
||||||
|
repo, it = git_by_name[(entry["repo"], entry["name"])]
|
||||||
|
return delete_worktree(repo, it)
|
||||||
|
except (subprocess.CalledProcessError, OSError, RuntimeError, ValueError) as exc:
|
||||||
|
return f"failed: {_describe(exc)}"
|
||||||
|
return f"skipped: {entry['kind']} is never deleted as low"
|
||||||
|
|
||||||
|
|
||||||
|
def _refusal(request: RiskRequest, host_ns: bool) -> str | None:
|
||||||
|
if request.apply and request.level != LOW:
|
||||||
|
return "Refusing: --apply removes only low items; use --risk low"
|
||||||
|
if request.apply and not host_ns:
|
||||||
|
return REFUSAL
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _git_options(request: RiskRequest) -> dict:
|
||||||
|
return {
|
||||||
|
"merged_into": request.merged_into,
|
||||||
|
"sizes": request.sizes,
|
||||||
|
"min_age": request.min_age,
|
||||||
|
"activity": False,
|
||||||
|
"hooks": request.hooks,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _host_items(
|
||||||
|
request: RiskRequest, owners: dict[str, str], now: float, host_ns: bool
|
||||||
|
) -> tuple[list[dict], list[str]]:
|
||||||
|
notes = [] if host_ns else [NO_HOST_NS]
|
||||||
|
if request.include:
|
||||||
|
return [], [*notes, INCLUDE_ONLY_GIT]
|
||||||
|
docker, docker_warnings = docker_items(now)
|
||||||
|
cwds = _process_cwds() if host_ns else {}
|
||||||
|
scratch = tmp_items(request.tmp_root, owners, now, cwds)
|
||||||
|
return [*docker, *scratch], [*notes, *docker_warnings]
|
||||||
|
|
||||||
|
|
||||||
|
def _apply(
|
||||||
|
entries: list[dict], git: list, owners_file: str | None, now: float
|
||||||
|
) -> None:
|
||||||
|
git_by_name = {(e["repo"], e["name"]): (repo, it) for repo, it, e in git}
|
||||||
|
for entry in entries:
|
||||||
|
if entry["risk"] == LOW:
|
||||||
|
entry["result"] = _delete(entry, git_by_name, owners_file, now)
|
||||||
|
print(
|
||||||
|
f"[gc] {entry['kind']} {entry['name']}: {entry['result']}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _report(
|
||||||
|
request: RiskRequest,
|
||||||
|
host_ns: bool,
|
||||||
|
now: float,
|
||||||
|
entries: list[dict],
|
||||||
|
warnings: list[str],
|
||||||
|
) -> int:
|
||||||
|
plan = {
|
||||||
|
"host_pid_namespace": host_ns,
|
||||||
|
"risk": request.level,
|
||||||
|
"generated_at": now,
|
||||||
|
"totals": _totals(entries),
|
||||||
|
"items": [e for e in entries if rank(e["risk"]) <= rank(request.level)],
|
||||||
|
"warnings": warnings,
|
||||||
|
}
|
||||||
|
print(json.dumps(plan, indent=2) if request.as_json else _render(plan))
|
||||||
|
failed = any((e["result"] or "").startswith("failed") for e in entries)
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
def risk_cleanup(repo_roots: list[str], request: RiskRequest) -> int:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
repo_roots: main worktree roots of the repositories to scan.
|
||||||
|
request: what to plan, print and apply.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
2 when refused, 1 when an applied item failed, else 0.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: for a level outside LEVELS.
|
||||||
|
"""
|
||||||
|
if request.level not in LEVELS:
|
||||||
|
raise ValueError(f"unknown risk {request.level!r}")
|
||||||
|
host_ns = host_pid_namespace()
|
||||||
|
refusal = _refusal(request, host_ns)
|
||||||
|
if refusal:
|
||||||
|
print(refusal, file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
try:
|
||||||
|
owners = read_owners(request.owners_file)
|
||||||
|
except (OSError, ValueError) as exc:
|
||||||
|
print(f"Refusing: owner file: {_describe(exc)}", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
now = time.time()
|
||||||
|
planned = git_items(
|
||||||
|
repo_roots, request.include, request.exclude, _git_options(request)
|
||||||
|
)
|
||||||
|
if planned is None:
|
||||||
|
return 2
|
||||||
|
git, git_warnings, _ = planned
|
||||||
|
host, host_warnings = _host_items(request, owners, now, host_ns)
|
||||||
|
entries = [*(entry for _, _, entry in git), *host]
|
||||||
|
if request.apply:
|
||||||
|
_apply(entries, git, request.owners_file, now)
|
||||||
|
return _report(request, host_ns, now, entries, [*git_warnings, *host_warnings])
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import stat
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch.gc import _busy
|
||||||
|
from pkgmgr.actions.branch.nofollow import canonical, remove_tree
|
||||||
|
from pkgmgr.actions.gc.report.walk import TreeStats, walk
|
||||||
|
|
||||||
|
from .levels import HIGH, LOW, MEDIUM, TMP_AGE_S, item
|
||||||
|
|
||||||
|
ENDED = ("done", "stopped")
|
||||||
|
MOUNTINFO = "/proc/self/mountinfo"
|
||||||
|
OCTAL = re.compile(r"\\([0-7]{3})")
|
||||||
|
|
||||||
|
|
||||||
|
def read_owners(path: str | None) -> dict[str, str]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
path: a JSON object of absolute path -> task status, or None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Normalised absolute path -> lower-case status; empty without a file.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
OSError: when the file cannot be read.
|
||||||
|
ValueError: when it is not such a JSON object.
|
||||||
|
"""
|
||||||
|
if not path:
|
||||||
|
return {}
|
||||||
|
with open(path, encoding="utf-8") as fh:
|
||||||
|
data = json.load(fh)
|
||||||
|
if not isinstance(data, dict) or not all(
|
||||||
|
isinstance(k, str) and isinstance(v, str) for k, v in data.items()
|
||||||
|
):
|
||||||
|
raise ValueError(f"{path}: expected a JSON object of path -> status")
|
||||||
|
return {os.path.abspath(k): v.lower() for k, v in data.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def _measure(path: str, st: os.stat_result) -> tuple[TreeStats | None, int, float]:
|
||||||
|
if not stat.S_ISDIR(st.st_mode):
|
||||||
|
return None, st.st_blocks * 512, st.st_mtime
|
||||||
|
stats = walk(path)
|
||||||
|
return stats, stats.size_bytes, max(stats.newest_mtime, st.st_mtime)
|
||||||
|
|
||||||
|
|
||||||
|
def _mount_hold(path: str) -> tuple[str, str] | None:
|
||||||
|
try:
|
||||||
|
with open(MOUNTINFO, encoding="utf-8", errors="surrogateescape") as fh:
|
||||||
|
points = [OCTAL.sub(_char, line.split()[4]) for line in fh]
|
||||||
|
except (OSError, IndexError):
|
||||||
|
return MEDIUM, "mount table unreadable"
|
||||||
|
if any(p == path or p.startswith(path + os.sep) for p in points):
|
||||||
|
return MEDIUM, "is or holds a mount point"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _char(match: re.Match) -> str:
|
||||||
|
return chr(int(match.group(1), 8))
|
||||||
|
|
||||||
|
|
||||||
|
def _contents(path: str, stats: TreeStats, cwds: dict) -> tuple[str, str] | None:
|
||||||
|
if stats.foreign_entries or stats.unreadable:
|
||||||
|
return MEDIUM, "holds foreign or unreadable entries"
|
||||||
|
busy = _busy(cwds, path)
|
||||||
|
return (MEDIUM, busy) if busy else None
|
||||||
|
|
||||||
|
|
||||||
|
def _held(
|
||||||
|
path: str, stats: TreeStats | None, status: str | None, cwds: dict
|
||||||
|
) -> tuple[str, str] | None:
|
||||||
|
if stats is not None and os.path.lexists(os.path.join(path, ".git")):
|
||||||
|
return HIGH, "holds a git checkout: remove it as a worktree"
|
||||||
|
if status is not None and status not in ENDED:
|
||||||
|
return HIGH, f"owner task is {status}"
|
||||||
|
mounted = _mount_hold(path)
|
||||||
|
if mounted:
|
||||||
|
return mounted
|
||||||
|
return _contents(path, stats, cwds) if stats is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def _settled(status: str | None, age: float) -> tuple[str, str]:
|
||||||
|
if age <= TMP_AGE_S:
|
||||||
|
return MEDIUM, "changed within 24 h"
|
||||||
|
if status is None:
|
||||||
|
return MEDIUM, "no owner task known"
|
||||||
|
return LOW, f"owner task {status}, unchanged for 24 h"
|
||||||
|
|
||||||
|
|
||||||
|
def _verdict(
|
||||||
|
path: str, st: os.stat_result, owners: dict[str, str], now: float, cwds: dict
|
||||||
|
) -> tuple[str, str, int, float]:
|
||||||
|
stats, size, newest = _measure(path, st)
|
||||||
|
status = owners.get(path)
|
||||||
|
risk, reason = _held(path, stats, status, cwds) or _settled(status, now - newest)
|
||||||
|
return risk, reason, size, newest
|
||||||
|
|
||||||
|
|
||||||
|
def tmp_items(
|
||||||
|
root: str, owners: dict[str, str], now: float, cwds: dict[int, str]
|
||||||
|
) -> list[dict]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
root: the scratch directory, /tmp on a host; only its direct
|
||||||
|
children the current user owns are listed.
|
||||||
|
owners: absolute path -> task status from read_owners.
|
||||||
|
now: epoch seconds the 24 h age is measured against.
|
||||||
|
cwds: pid -> working directory of the host's processes.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
One item per regular file or directory, never a symlink, socket or
|
||||||
|
foreign entry: low only when its owner task is done or stopped and
|
||||||
|
nothing in it changed for 24 h.
|
||||||
|
"""
|
||||||
|
items = []
|
||||||
|
base = os.path.realpath(root)
|
||||||
|
try:
|
||||||
|
names = sorted(os.listdir(base))
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
for name in names:
|
||||||
|
path = os.path.join(base, name)
|
||||||
|
try:
|
||||||
|
st = os.lstat(path)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
if st.st_uid != os.getuid() or not (
|
||||||
|
stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
risk, reason, size, newest = _verdict(path, st, owners, now, cwds)
|
||||||
|
items.append(
|
||||||
|
item(
|
||||||
|
"tmp",
|
||||||
|
path,
|
||||||
|
risk,
|
||||||
|
reason,
|
||||||
|
size_bytes=size,
|
||||||
|
newest_mtime=newest,
|
||||||
|
owner_status=owners.get(path),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def delete_tmp(
|
||||||
|
entry: dict, owners: dict[str, str], now: float, cwds: dict[int, str]
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
entry: a low tmp item of the plan, deleted only while still low.
|
||||||
|
owners: as tmp_items takes them.
|
||||||
|
now: as tmp_items takes it.
|
||||||
|
cwds: as tmp_items takes them, read again before the delete.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The result: done, or skipped with the reason.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
OSError: when the delete fails.
|
||||||
|
"""
|
||||||
|
path = entry["name"]
|
||||||
|
if not canonical(path):
|
||||||
|
return "skipped: path is not canonical"
|
||||||
|
st = os.lstat(path)
|
||||||
|
if st.st_uid != os.getuid():
|
||||||
|
return "skipped: no longer owned by this user"
|
||||||
|
risk, reason, _, _ = _verdict(path, st, owners, now, cwds)
|
||||||
|
if risk != LOW:
|
||||||
|
return f"skipped: changed since plan ({reason})"
|
||||||
|
if stat.S_ISDIR(st.st_mode):
|
||||||
|
remove_tree(path)
|
||||||
|
elif stat.S_ISREG(st.st_mode):
|
||||||
|
os.unlink(path)
|
||||||
|
else:
|
||||||
|
return "skipped: no longer a file or directory"
|
||||||
|
return "done"
|
||||||
@@ -161,7 +161,6 @@ class InstallationPipeline:
|
|||||||
else:
|
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"]
|
||||||
@@ -8,6 +8,36 @@ try:
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
import tomli as tomllib # type: ignore
|
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
|
||||||
@@ -23,7 +53,12 @@ def update_pyproject_version(
|
|||||||
print(f"[WARN] Could not read pyproject.toml: {exc}")
|
print(f"[WARN] Could not read pyproject.toml: {exc}")
|
||||||
return
|
return
|
||||||
|
|
||||||
project = tomllib.loads(content).get("project")
|
data = tomllib.loads(content)
|
||||||
|
project = data.get("project")
|
||||||
|
source = dynamic_version_source(pyproject_path, data)
|
||||||
|
if source is not None:
|
||||||
|
update_module_version(*source, new_version, preview)
|
||||||
|
return
|
||||||
if project is None or "version" in project.get("dynamic", []):
|
if project is None or "version" in project.get("dynamic", []):
|
||||||
print("[INFO] pyproject.toml declares no static version, skipping.")
|
print("[INFO] pyproject.toml declares no static version, skipping.")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -2,6 +2,7 @@ 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.actions.repository.push import (
|
from pkgmgr.actions.repository.push import (
|
||||||
@@ -12,7 +13,7 @@ from pkgmgr.actions.repository.push import (
|
|||||||
from pkgmgr.core.git import GitRunError
|
from pkgmgr.core.git 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,
|
||||||
@@ -26,87 +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}")
|
|
||||||
|
|
||||||
refuse_unsafe_config(".")
|
|
||||||
# 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:
|
||||||
@@ -116,152 +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)
|
|
||||||
sign_unpushed(".", preview=True)
|
|
||||||
tag_annotated(new_tag, tag_msg, preview=True)
|
|
||||||
push_branch(".", [], sign=True, refs=(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)
|
|
||||||
sign_unpushed(".", preview=False)
|
|
||||||
tag_annotated(new_tag, tag_msg, preview=False)
|
|
||||||
|
|
||||||
push_branch(".", [], sign=True, refs=(new_tag,), preview=False)
|
|
||||||
|
|
||||||
# Update 'latest' only if this is the highest version tag
|
|
||||||
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,7 +1,10 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import threading
|
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 (
|
||||||
@@ -9,25 +12,42 @@ from pkgmgr.actions.repository._parallel import (
|
|||||||
resolve_repos,
|
resolve_repos,
|
||||||
run_on_repos,
|
run_on_repos,
|
||||||
)
|
)
|
||||||
|
from pkgmgr.actions.repository._trusted import (
|
||||||
|
CHECKOUT_FETCH_FLAGS,
|
||||||
|
TRUSTED_FLAGS,
|
||||||
|
PushRefusedError,
|
||||||
|
Target,
|
||||||
|
bases,
|
||||||
|
copy_head,
|
||||||
|
fetch_heads,
|
||||||
|
file_url,
|
||||||
|
open_target,
|
||||||
|
redact_urls,
|
||||||
|
tgit,
|
||||||
|
tgit_bytes,
|
||||||
|
trusted_env,
|
||||||
|
trusted_repo,
|
||||||
|
try_git,
|
||||||
|
unpushed_signatures,
|
||||||
|
)
|
||||||
from pkgmgr.core.git import GitRunError, run
|
from pkgmgr.core.git import GitRunError, run
|
||||||
from pkgmgr.core.git.queries import UNSAFE_CONFIG, local_config
|
from pkgmgr.core.git.queries import UNSAFE_CONFIG, local_config
|
||||||
from pkgmgr.core.git.run import SCAN_FLAGS
|
|
||||||
|
|
||||||
Repository = dict[str, Any]
|
Repository = dict[str, Any]
|
||||||
|
|
||||||
# Re-signing opens pinentry; parallel pushes must not ask for the passphrase at once.
|
# Re-signing opens pinentry; parallel pushes must not ask for the passphrase at once.
|
||||||
_SIGN_LOCK = threading.Lock()
|
_SIGN_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
_AUTHOR = re.compile(rb"(.*?) <([^>]*)> (\d+) ([+-]\d{4})")
|
||||||
class PushRefusedError(RuntimeError):
|
|
||||||
"""Raised when a push would ship unsigned commits or overwrite a mirror."""
|
|
||||||
|
|
||||||
|
|
||||||
def _try_git(repo_dir: str, *args: str) -> str | None:
|
@dataclass(frozen=True)
|
||||||
try:
|
class _Push:
|
||||||
return run(list(args), cwd=repo_dir)
|
extra_args: tuple[str, ...]
|
||||||
except GitRunError:
|
refs: tuple[str, ...]
|
||||||
return None
|
rewrite: bool
|
||||||
|
preview: bool
|
||||||
|
old_tip: str | None
|
||||||
|
|
||||||
|
|
||||||
def refuse_unsafe_config(repo_dir: str) -> None:
|
def refuse_unsafe_config(repo_dir: str) -> None:
|
||||||
@@ -38,9 +58,10 @@ def refuse_unsafe_config(repo_dir: str) -> None:
|
|||||||
Raises:
|
Raises:
|
||||||
PushRefusedError: the repository's own config, which an agent may have
|
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.
|
written, sets a key that makes git run a program or reroute the push.
|
||||||
Filter drivers stay allowed on purpose: git-lfs and git-crypt need
|
Signing and pushing never read that config, so this is only an early
|
||||||
them locally, so a clean filter can still run in the amend's index
|
refusal; filter drivers stay allowed because git-lfs and git-crypt
|
||||||
refresh, as it did before.
|
need them locally.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
unsafe = local_config(repo_dir, UNSAFE_CONFIG)
|
unsafe = local_config(repo_dir, UNSAFE_CONFIG)
|
||||||
if unsafe:
|
if unsafe:
|
||||||
@@ -50,142 +71,171 @@ def refuse_unsafe_config(repo_dir: str) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _push_target(repo_dir: str) -> tuple[str, str]:
|
def _head_commit(target: Target) -> tuple[list[str], dict[str, str], bytes]:
|
||||||
refuse_unsafe_config(repo_dir)
|
"""
|
||||||
branch = run(["rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_dir)
|
Args:
|
||||||
if branch == "HEAD":
|
target: the copied checkout.
|
||||||
raise PushRefusedError(f"{repo_dir}: detached HEAD, nothing to push")
|
|
||||||
remote = (
|
Returns:
|
||||||
_try_git(repo_dir, "config", "--get", f"branch.{branch}.pushRemote")
|
The `git commit-tree` arguments that rebuild HEAD (encoding, tree,
|
||||||
or _try_git(repo_dir, "config", "--get", "remote.pushDefault")
|
parents), its author as environment variables, and its message.
|
||||||
or _try_git(repo_dir, "config", "--get", f"branch.{branch}.remote")
|
|
||||||
or "origin"
|
Raises:
|
||||||
)
|
PushRefusedError: HEAD has no tree or no parseable author.
|
||||||
return branch, remote
|
|
||||||
|
"""
|
||||||
|
fields, message = _commit_fields(target)
|
||||||
|
author = _AUTHOR.fullmatch((fields.get(b"author") or [b""])[0])
|
||||||
|
if not fields.get(b"tree") or author is None:
|
||||||
|
raise PushRefusedError(
|
||||||
|
f"{target.repo_dir}: cannot parse HEAD {target.head[:10]}"
|
||||||
|
)
|
||||||
|
name, email, stamp, zone = (os.fsdecode(part) for part in author.groups())
|
||||||
|
args = [
|
||||||
|
"-c",
|
||||||
|
"i18n.commitEncoding="
|
||||||
|
+ os.fsdecode((fields.get(b"encoding") or [b"UTF-8"])[0]),
|
||||||
|
"commit-tree",
|
||||||
|
os.fsdecode(fields[b"tree"][0]),
|
||||||
|
*(arg for p in fields.get(b"parent", []) for arg in ("-p", os.fsdecode(p))),
|
||||||
|
]
|
||||||
|
env = {
|
||||||
|
"GIT_AUTHOR_NAME": name,
|
||||||
|
"GIT_AUTHOR_EMAIL": email,
|
||||||
|
"GIT_AUTHOR_DATE": f"@{stamp} {zone}",
|
||||||
|
}
|
||||||
|
return args, env, message
|
||||||
|
|
||||||
|
|
||||||
def _unpushed_signatures(
|
def _commit_fields(target: Target) -> tuple[dict[bytes, list[bytes]], bytes]:
|
||||||
repo_dir: str, remote: str, branch: str
|
header, _, message = tgit_bytes(
|
||||||
) -> tuple[str, dict[str, str]]:
|
target.tdir, "cat-file", "commit", target.head
|
||||||
for ref in (
|
).partition(b"\n\n")
|
||||||
f"refs/remotes/{remote}/{branch}",
|
fields: dict[bytes, list[bytes]] = {}
|
||||||
"@{u}",
|
for line in header.split(b"\n"):
|
||||||
f"refs/remotes/{remote}/main",
|
key, _, value = line.partition(b" ")
|
||||||
f"refs/remotes/{remote}/master",
|
fields.setdefault(key, []).append(value)
|
||||||
):
|
return fields, message
|
||||||
base = _try_git(repo_dir, "merge-base", "HEAD", ref)
|
|
||||||
if base:
|
|
||||||
lines = run(
|
def _sign_head(target: Target) -> str:
|
||||||
["log", "--format=%H %G?", f"{base}..HEAD"], cwd=repo_dir
|
args, author, message = _head_commit(target)
|
||||||
).splitlines()
|
cmd = ["git", f"--git-dir={target.tdir}", *TRUSTED_FLAGS, *args, "-S"]
|
||||||
return base, dict(line.split() for line in lines)
|
with _SIGN_LOCK:
|
||||||
raise PushRefusedError(
|
result = subprocess.run(
|
||||||
f"{repo_dir}: no {remote}/{branch}, no upstream and no {remote}/main or "
|
cmd,
|
||||||
f"{remote}/master to sign against"
|
cwd=target.tdir,
|
||||||
|
env=trusted_env(author),
|
||||||
|
input=message,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
signed = os.fsdecode(result.stdout).strip()
|
||||||
|
if result.returncode != 0 or not signed:
|
||||||
|
raise PushRefusedError(
|
||||||
|
f"{target.repo_dir}: signing HEAD {target.head[:10]} failed"
|
||||||
|
)
|
||||||
|
tgit(target.tdir, "update-ref", "refs/pkgmgr/signed", signed)
|
||||||
|
return signed
|
||||||
|
|
||||||
|
|
||||||
|
def _adopt(target: Target, signed: str) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
target: the checkout and its temporary repository.
|
||||||
|
signed: the signed commit; fetched into the checkout, then its branch
|
||||||
|
moves there. That fetch still reads the checkout's config, so
|
||||||
|
CHECKOUT_FETCH_FLAGS pins every key that would fetch from elsewhere
|
||||||
|
or run a program, in case the refuse-list check is stale.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PushRefusedError: the branch moved away from HEAD while it was signed.
|
||||||
|
|
||||||
|
"""
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
*CHECKOUT_FETCH_FLAGS,
|
||||||
|
"fetch",
|
||||||
|
"--quiet",
|
||||||
|
"--no-tags",
|
||||||
|
"--no-write-fetch-head",
|
||||||
|
"--no-recurse-submodules",
|
||||||
|
"--upload-pack=git-upload-pack",
|
||||||
|
"--",
|
||||||
|
file_url(target.tdir),
|
||||||
|
signed,
|
||||||
|
],
|
||||||
|
cwd=target.repo_dir,
|
||||||
|
scan=True,
|
||||||
)
|
)
|
||||||
|
try:
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
"update-ref",
|
||||||
|
"-m",
|
||||||
|
"pkgmgr push: sign HEAD",
|
||||||
|
target.branch_ref,
|
||||||
|
signed,
|
||||||
|
target.head,
|
||||||
|
],
|
||||||
|
cwd=target.repo_dir,
|
||||||
|
scan=True,
|
||||||
|
)
|
||||||
|
except GitRunError as exc:
|
||||||
|
raise PushRefusedError(
|
||||||
|
f"{target.repo_dir}: {target.branch} moved away from {target.head[:10]} "
|
||||||
|
f"while it was signed; left it where it is, signed {signed[:10]} is dropped"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
def sign_unpushed(repo_dir: str, *, preview: bool = False) -> None:
|
def sign_unpushed(repo_dir: str, *, preview: bool = False) -> None:
|
||||||
"""
|
"""
|
||||||
Args:
|
Args:
|
||||||
repo_dir: checkout whose current branch is signed.
|
repo_dir: checkout whose current branch is signed.
|
||||||
preview: print the fetch and the amend instead of running them.
|
preview: read and check as usual, but print the signing instead of doing it.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
branch, remote = _push_target(repo_dir)
|
refuse_unsafe_config(repo_dir)
|
||||||
run(
|
with trusted_repo(repo_dir) as tdir:
|
||||||
["fetch", "--quiet", "--no-recurse-submodules", "--", remote],
|
target = open_target(repo_dir, tdir)
|
||||||
cwd=repo_dir,
|
copy_head(target, tags=False)
|
||||||
preview=preview,
|
_tip, candidates = bases(target)
|
||||||
)
|
base, signatures = unpushed_signatures(target, candidates)
|
||||||
base, signatures = _unpushed_signatures(repo_dir, remote, branch)
|
head = target.head
|
||||||
head = run(["rev-parse", "HEAD"], cwd=repo_dir)
|
older = sum(1 for sha, s in signatures.items() if sha != head and s != "G")
|
||||||
older = sum(1 for sha, s in signatures.items() if sha != head and s != "G")
|
if older:
|
||||||
if older:
|
print(
|
||||||
print(
|
f"[push] WARN {older} older unsigned commit(s) in {base[:10]}..HEAD~ of "
|
||||||
f"[push] WARN {older} older unsigned commit(s) in {base[:10]}..HEAD~ of "
|
f"{repo_dir} stay unsigned: signing them would rewrite history"
|
||||||
f"{repo_dir} stay unsigned: signing them would rewrite history"
|
|
||||||
)
|
|
||||||
if signatures.get(head, "G") == "G":
|
|
||||||
return
|
|
||||||
if run(
|
|
||||||
[
|
|
||||||
*SCAN_FLAGS,
|
|
||||||
"diff",
|
|
||||||
"--cached",
|
|
||||||
"--name-only",
|
|
||||||
"--no-ext-diff",
|
|
||||||
"--ignore-submodules=none",
|
|
||||||
"HEAD",
|
|
||||||
],
|
|
||||||
cwd=repo_dir,
|
|
||||||
):
|
|
||||||
raise PushRefusedError(f"{repo_dir}: staged changes, cannot sign HEAD")
|
|
||||||
|
|
||||||
cmd = [
|
|
||||||
"git",
|
|
||||||
*SCAN_FLAGS,
|
|
||||||
"commit",
|
|
||||||
"--amend",
|
|
||||||
"--no-edit",
|
|
||||||
"--no-verify",
|
|
||||||
"--allow-empty",
|
|
||||||
"-S",
|
|
||||||
]
|
|
||||||
print(f"[push] Signing HEAD {head[:10]} in {repo_dir}")
|
|
||||||
if preview:
|
|
||||||
print(f"[PREVIEW] Would run in {repo_dir!r}: {' '.join(cmd)}")
|
|
||||||
return
|
|
||||||
with _SIGN_LOCK:
|
|
||||||
result = subprocess.run(cmd, cwd=repo_dir, check=False)
|
|
||||||
if result.returncode != 0:
|
|
||||||
raise PushRefusedError(f"{repo_dir}: signing HEAD {head[:10]} failed")
|
|
||||||
|
|
||||||
|
|
||||||
def _lease(
|
|
||||||
repo_dir: str,
|
|
||||||
url: str,
|
|
||||||
branch_ref: str,
|
|
||||||
tracking: str | None,
|
|
||||||
keep: tuple[str, ...],
|
|
||||||
preview: bool,
|
|
||||||
) -> str:
|
|
||||||
if tracking is not None:
|
|
||||||
sha = _try_git(repo_dir, "rev-parse", "--verify", "--quiet", tracking) or ""
|
|
||||||
else:
|
|
||||||
listed = run(["ls-remote", "--", url, branch_ref], cwd=repo_dir).splitlines()
|
|
||||||
sha = next(
|
|
||||||
(ln.split()[0] for ln in listed if ln.split()[1:] == [branch_ref]), ""
|
|
||||||
)
|
|
||||||
if sha and not preview:
|
|
||||||
run(
|
|
||||||
[
|
|
||||||
"fetch",
|
|
||||||
"--quiet",
|
|
||||||
"--no-tags",
|
|
||||||
"--no-recurse-submodules",
|
|
||||||
"--",
|
|
||||||
url,
|
|
||||||
branch_ref,
|
|
||||||
],
|
|
||||||
cwd=repo_dir,
|
|
||||||
)
|
)
|
||||||
if not sha or preview:
|
if signatures.get(head, "G") == "G":
|
||||||
return sha
|
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
|
lost: set[str] | None = None
|
||||||
for tip in keep:
|
for tip in keep:
|
||||||
plus = {
|
plus = {
|
||||||
line[2:]
|
line[2:]
|
||||||
for line in run(["cherry", tip, sha], cwd=repo_dir).splitlines()
|
for line in tgit(target.tdir, "cherry", tip, sha).splitlines()
|
||||||
if line.startswith("+")
|
if line.startswith("+")
|
||||||
}
|
}
|
||||||
lost = plus if lost is None else lost & plus
|
lost = plus if lost is None else lost & plus
|
||||||
if lost:
|
if lost:
|
||||||
raise PushRefusedError(
|
raise PushRefusedError(
|
||||||
f"{url}: {len(lost)} commit(s) exist only there, not overwritten: "
|
f"{redact_urls(url)}: {len(lost)} commit(s) exist only there, "
|
||||||
|
"not overwritten: "
|
||||||
f"{' '.join(s[:10] for s in sorted(lost))}; "
|
f"{' '.join(s[:10] for s in sorted(lost))}; "
|
||||||
"pass --rewrite for a deliberate history rewrite"
|
"pass --rewrite for a deliberate history rewrite"
|
||||||
)
|
)
|
||||||
return sha
|
|
||||||
|
|
||||||
|
|
||||||
def push_branch(
|
def push_branch(
|
||||||
@@ -198,13 +248,6 @@ def push_branch(
|
|||||||
preview: bool = False,
|
preview: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
Push the current branch to every pushurl of its push remote, each with its own lease.
|
|
||||||
|
|
||||||
The fetch URL is leased against the remote-tracking ref, every other
|
|
||||||
pushurl against its own branch tip; each only after `git cherry` shows it
|
|
||||||
holds no commit the new tip lacks. A mirror failure is reported after the
|
|
||||||
others were pushed; a canonical failure stops before any mirror.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
repo_dir: checkout whose current branch is pushed.
|
repo_dir: checkout whose current branch is pushed.
|
||||||
extra_args: flags appended to every `git push`.
|
extra_args: flags appended to every `git push`.
|
||||||
@@ -213,73 +256,134 @@ def push_branch(
|
|||||||
rewrite: replace commits of the old canonical tip; the fetch URL skips
|
rewrite: replace commits of the old canonical tip; the fetch URL skips
|
||||||
the cherry check, mirrors only refuse commits the old tip never had.
|
the cherry check, mirrors only refuse commits the old tip never had.
|
||||||
preview: print the pushes instead of running them.
|
preview: print the pushes instead of running them.
|
||||||
"""
|
|
||||||
branch, remote = _push_target(repo_dir)
|
|
||||||
head = run(["rev-parse", "HEAD"], cwd=repo_dir)
|
|
||||||
if sign:
|
|
||||||
_base, signatures = _unpushed_signatures(repo_dir, remote, branch)
|
|
||||||
if not preview and signatures.get(head, "G") != "G":
|
|
||||||
raise PushRefusedError(
|
|
||||||
f"{repo_dir}: HEAD {head[:10]} is unsigned; run `pkgmgr push` to sign it"
|
|
||||||
)
|
|
||||||
|
|
||||||
fetch_url = run(["remote", "get-url", "--", remote], cwd=repo_dir)
|
"""
|
||||||
push_urls = run(
|
refuse_unsafe_config(repo_dir)
|
||||||
["remote", "get-url", "--push", "--all", "--", remote], cwd=repo_dir
|
with trusted_repo(repo_dir) as tdir:
|
||||||
).splitlines()
|
target = open_target(repo_dir, tdir)
|
||||||
branch_ref = f"refs/heads/{branch}"
|
copy_head(target, tags=True)
|
||||||
tracking = f"refs/remotes/{remote}/{branch}"
|
old_tip = _old_tip(target, sign, preview)
|
||||||
old_tip = _try_git(repo_dir, "rev-parse", "--verify", "--quiet", tracking)
|
plan = _Push(tuple(extra_args), refs, rewrite, preview, old_tip)
|
||||||
if fetch_url not in push_urls:
|
if target.fetch_url not in target.push_urls:
|
||||||
print(
|
print(
|
||||||
f"[push] WARN {remote}: fetch URL is no pushurl; every URL is leased "
|
f"[push] WARN {target.remote}: fetch URL is no pushurl; every URL is "
|
||||||
"as a mirror, tracking ref and upstream stay untouched"
|
"leased as a mirror, tracking ref and upstream stay untouched"
|
||||||
|
)
|
||||||
|
failed: list[str] = []
|
||||||
|
ordered = sorted(target.push_urls, key=lambda u: u != target.fetch_url)
|
||||||
|
for index, url in enumerate(ordered):
|
||||||
|
if not _push_url(target, plan, index, url):
|
||||||
|
failed.append(url)
|
||||||
|
if failed:
|
||||||
|
raise PushRefusedError(
|
||||||
|
f"{repo_dir}: push failed for {redact_urls(', '.join(failed))}"
|
||||||
)
|
)
|
||||||
|
|
||||||
failed: list[str] = []
|
|
||||||
for url in sorted(push_urls, key=lambda u: u != fetch_url):
|
|
||||||
if url == fetch_url:
|
|
||||||
keep: tuple[str, ...] = () if rewrite else (head,)
|
|
||||||
else:
|
|
||||||
keep = (head, old_tip) if rewrite and old_tip else (head,)
|
|
||||||
try:
|
|
||||||
expect = _lease(
|
|
||||||
repo_dir,
|
|
||||||
url,
|
|
||||||
branch_ref,
|
|
||||||
tracking if url == fetch_url else None,
|
|
||||||
keep,
|
|
||||||
preview,
|
|
||||||
)
|
|
||||||
run(
|
|
||||||
[
|
|
||||||
"push",
|
|
||||||
"--follow-tags",
|
|
||||||
"--no-recurse-submodules",
|
|
||||||
f"--force-with-lease={branch_ref}:{expect}",
|
|
||||||
*extra_args,
|
|
||||||
"--",
|
|
||||||
url,
|
|
||||||
branch_ref,
|
|
||||||
*refs,
|
|
||||||
],
|
|
||||||
cwd=repo_dir,
|
|
||||||
preview=preview,
|
|
||||||
)
|
|
||||||
except (GitRunError, PushRefusedError) as exc:
|
|
||||||
if url == fetch_url:
|
|
||||||
raise
|
|
||||||
print(f"[push] FAILED {url}\n{exc}")
|
|
||||||
failed.append(url)
|
|
||||||
continue
|
|
||||||
print(f"[push] {url} <- {branch} {head[:10]}")
|
|
||||||
if url == fetch_url and not preview:
|
|
||||||
run(["update-ref", tracking, head], cwd=repo_dir)
|
|
||||||
if not _try_git(repo_dir, "rev-parse", "--abbrev-ref", "@{u}"):
|
|
||||||
run(["branch", f"--set-upstream-to={remote}/{branch}"], cwd=repo_dir)
|
|
||||||
|
|
||||||
if failed:
|
def _old_tip(target: Target, sign: bool, preview: bool) -> str | None:
|
||||||
raise PushRefusedError(f"{repo_dir}: push failed for {', '.join(failed)}")
|
"""
|
||||||
|
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(
|
def _push_one(
|
||||||
@@ -302,9 +406,6 @@ def push_repo_dirs(
|
|||||||
jobs: int = 1,
|
jobs: int = 1,
|
||||||
rewrite: bool = False,
|
rewrite: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
|
||||||
Sign and push each ``(identifier, repo_dir)``, optionally in parallel.
|
|
||||||
"""
|
|
||||||
run_on_repos(
|
run_on_repos(
|
||||||
repos,
|
repos,
|
||||||
lambda rd: _push_one(rd, extra_args, sign, rewrite, preview),
|
lambda rd: _push_one(rd, extra_args, sign, rewrite, preview),
|
||||||
@@ -323,9 +424,6 @@ def push_in_parallel(
|
|||||||
jobs: int = 1,
|
jobs: int = 1,
|
||||||
rewrite: bool = False,
|
rewrite: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
|
||||||
Sign and push each selected repository, optionally in parallel.
|
|
||||||
"""
|
|
||||||
push_repo_dirs(
|
push_repo_dirs(
|
||||||
resolve_repos(selected_repos, repositories_base_dir, all_repos),
|
resolve_repos(selected_repos, repositories_base_dir, all_repos),
|
||||||
extra_args,
|
extra_args,
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2019-2024 The Bootstrap Authors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
{% set status_letters = {"added": "A", "deleted": "D", "modified": "M", "renamed": "R", "copied": "C", "untracked": "U"} %}
|
{% set status_letters = {"added": "A", "deleted": "D", "modified": "M", "renamed": "R", "copied": "C", "untracked": "U"} %}
|
||||||
{% set signs = {"add": "+", "del": "-", "ctx": "", "meta": ""} %}
|
{% 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 %}
|
{% set style %}
|
||||||
:root {
|
:root {
|
||||||
color-scheme: light dark;
|
color-scheme: light dark;
|
||||||
@@ -93,6 +97,7 @@ input[type="search"] { width: 260px; max-width: 100%; padding: 5px 10px; border:
|
|||||||
input[type="search"]:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
|
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 { 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: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; }
|
main { padding-top: 24px; padding-bottom: 80px; }
|
||||||
.group { margin-bottom: 36px; }
|
.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; }
|
h2 { display: flex; flex-wrap: wrap; align-items: baseline; gap: 12px; margin: 0 0 12px; font-size: 17px; font-weight: 600; }
|
||||||
@@ -187,6 +192,7 @@ details.commit > summary { padding: 10px 14px; }
|
|||||||
})();
|
})();
|
||||||
{% endset %}
|
{% endset %}
|
||||||
{% macro stat(added, removed) %}<span class="stat"><span class="add">+{{ added }}</span><span class="del">−{{ removed }}</span></span>{% endmacro %}
|
{% 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 plural(count, word) %}{{ count }} {{ word }}{{ "" if count == 1 else "s" }}{% endmacro %}
|
||||||
{% macro file_block(file, open) %}
|
{% macro file_block(file, open) %}
|
||||||
<details class="file" id="{{ file.anchor }}" data-path="{{ file.search }}"{% if open %} open{% endif %}>
|
<details class="file" id="{{ file.anchor }}" data-path="{{ file.search }}"{% if open %} open{% endif %}>
|
||||||
@@ -282,8 +288,8 @@ details.commit > summary { padding: 10px 14px; }
|
|||||||
<div class="spacer"></div>
|
<div class="spacer"></div>
|
||||||
<input id="filter" type="search" placeholder="Filter files by path ( / )" autocomplete="off" spellcheck="false" aria-label="Filter files by path">
|
<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>
|
<span id="filter-count" class="muted"></span>
|
||||||
<button type="button" id="expand-all">Expand all</button>
|
<button type="button" id="expand-all" class="icon" title="Expand all" aria-label="Expand all">{{ icon("arrows-expand") }}</button>
|
||||||
<button type="button" id="collapse-all">Collapse all</button>
|
<button type="button" id="collapse-all" class="icon" title="Collapse all" aria-label="Collapse all">{{ icon("arrows-collapse") }}</button>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
<main>
|
<main>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from .config import handle_config
|
|||||||
from .make import handle_make
|
from .make import handle_make
|
||||||
from .mirror import handle_mirror_command
|
from .mirror import handle_mirror_command
|
||||||
from .publish import handle_publish
|
from .publish import handle_publish
|
||||||
from .release import handle_release
|
from .release import handle_release, release_at_cwd
|
||||||
from .repos import handle_repos_command
|
from .repos import handle_repos_command
|
||||||
from .review import handle_review
|
from .review import handle_review
|
||||||
from .tools import handle_tools_command
|
from .tools import handle_tools_command
|
||||||
@@ -29,4 +29,5 @@ __all__ = [
|
|||||||
"handle_tools_command",
|
"handle_tools_command",
|
||||||
"handle_version",
|
"handle_version",
|
||||||
"handle_worktree",
|
"handle_worktree",
|
||||||
|
"release_at_cwd",
|
||||||
]
|
]
|
||||||
@@ -11,7 +11,7 @@ from pkgmgr.actions.branch import (
|
|||||||
open_branch,
|
open_branch,
|
||||||
tree,
|
tree,
|
||||||
)
|
)
|
||||||
from pkgmgr.actions.branch.gc import main_repo_root
|
from pkgmgr.actions.branch.gc import local_repo_root, main_repo_root
|
||||||
from pkgmgr.cli.context import CLIContext
|
from pkgmgr.cli.context import CLIContext
|
||||||
from pkgmgr.core.git.errors import GitBaseError
|
from pkgmgr.core.git.errors import GitBaseError
|
||||||
from pkgmgr.core.repository.dir import get_repo_dir
|
from pkgmgr.core.repository.dir import get_repo_dir
|
||||||
@@ -60,14 +60,23 @@ def refresh_tree(roots: list[str]) -> None:
|
|||||||
print(f"WARN tree file not rewritten for {root}: {exc}", file=sys.stderr)
|
print(f"WARN tree file not rewritten for {root}: {exc}", file=sys.stderr)
|
||||||
|
|
||||||
|
|
||||||
def scan_repo_roots(args, ctx: CLIContext) -> list[str]:
|
def scan_repo_roots(args, ctx: CLIContext, local: bool = False) -> list[str]:
|
||||||
"""
|
"""
|
||||||
Resolve the repositories a scan covers: the current one, or every
|
Resolve the repositories a scan covers: the current one, or every
|
||||||
pkgmgr-managed one with --all. Exits with 2 outside a repository.
|
pkgmgr-managed one with --all. Exits with 2 outside a repository.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
args: parsed arguments; `all` selects every managed repository.
|
||||||
|
ctx: CLI context.
|
||||||
|
local: resolve the current repository as scope `local` does, also in
|
||||||
|
a submodule or with a separate git dir, refusing a mismatch.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The main worktree roots to scan.
|
||||||
"""
|
"""
|
||||||
if not args.all:
|
if not args.all:
|
||||||
try:
|
try:
|
||||||
return [main_repo_root(".")]
|
return [(local_repo_root if local else main_repo_root)(".")]
|
||||||
except GitBaseError as exc:
|
except GitBaseError as exc:
|
||||||
print(f"Not inside a git repository: {exc}", file=sys.stderr)
|
print(f"Not inside a git repository: {exc}", file=sys.stderr)
|
||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
@@ -84,7 +93,7 @@ def scan_options(args) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def run_cleanup(args, ctx: CLIContext, scope: str) -> None:
|
def run_cleanup(args, ctx: CLIContext, scope: str) -> None:
|
||||||
roots = scan_repo_roots(args, ctx)
|
roots = scan_repo_roots(args, ctx, local=scope == "local")
|
||||||
code = cleanup(
|
code = cleanup(
|
||||||
roots,
|
roots,
|
||||||
scope=scope,
|
scope=scope,
|
||||||
@@ -94,7 +103,7 @@ def run_cleanup(args, ctx: CLIContext, scope: str) -> None:
|
|||||||
hooks=pinned_hooks(ctx),
|
hooks=pinned_hooks(ctx),
|
||||||
**scan_options(args),
|
**scan_options(args),
|
||||||
)
|
)
|
||||||
if args.apply:
|
if args.apply and scope != "local":
|
||||||
refresh_tree(roots)
|
refresh_tree(roots)
|
||||||
sys.exit(code)
|
sys.exit(code)
|
||||||
|
|
||||||
@@ -107,8 +116,9 @@ def handle_branch(args, ctx: CLIContext) -> None:
|
|||||||
- pkgmgr branch open [<name>] [--base <branch>]
|
- pkgmgr branch open [<name>] [--base <branch>]
|
||||||
- pkgmgr branch close [<name>] [--base <branch>] [--force|-f]
|
- pkgmgr branch close [<name>] [--base <branch>] [--force|-f]
|
||||||
- pkgmgr branch drop [<name>] [--base <branch>] [--force|-f]
|
- pkgmgr branch drop [<name>] [--base <branch>] [--force|-f]
|
||||||
- pkgmgr branch cleanup [--apply] [--json] [--all] [--branch N]... [--exclude N]...
|
- pkgmgr branch cleanup [--apply] [--json] [--local] [--all] [--branch N]...
|
||||||
[--merged-into REF]... [--sizes] [--min-age HOURS]
|
[--exclude N]... [--merged-into REF]... [--sizes]
|
||||||
|
[--min-age HOURS]
|
||||||
- pkgmgr branch purge [--all] [--branch N]... [--exclude N]...
|
- pkgmgr branch purge [--all] [--branch N]... [--exclude N]...
|
||||||
[--merged-into REF]... [--sizes] [--min-age HOURS]
|
[--merged-into REF]... [--sizes] [--min-age HOURS]
|
||||||
- pkgmgr branch tree [--format json|yaml] [--output FILE]
|
- pkgmgr branch tree [--format json|yaml] [--output FILE]
|
||||||
@@ -124,7 +134,7 @@ def handle_branch(args, ctx: CLIContext) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
if args.subcommand == "cleanup":
|
if args.subcommand == "cleanup":
|
||||||
run_cleanup(args, ctx, "branch")
|
run_cleanup(args, ctx, "local" if args.local else "branch")
|
||||||
|
|
||||||
if args.subcommand == "purge":
|
if args.subcommand == "purge":
|
||||||
roots = scan_repo_roots(args, ctx)
|
roots = scan_repo_roots(args, ctx)
|
||||||
|
|||||||
@@ -5,14 +5,123 @@ import sys
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from pkgmgr.actions.publish import publish as run_publish
|
from pkgmgr.actions.publish import publish as run_publish
|
||||||
|
from pkgmgr.actions.release import ReleaseOptions
|
||||||
from pkgmgr.actions.release import release as run_release
|
from pkgmgr.actions.release import release as run_release
|
||||||
from pkgmgr.cli.context import CLIContext
|
from pkgmgr.cli.context import CLIContext
|
||||||
|
from pkgmgr.core.git import GitRunError, run
|
||||||
from pkgmgr.core.repository.dir import get_repo_dir
|
from pkgmgr.core.repository.dir import get_repo_dir
|
||||||
from pkgmgr.core.repository.identifier import get_repo_identifier
|
from pkgmgr.core.repository.identifier import get_repo_identifier
|
||||||
|
from pkgmgr.core.repository.selected import has_explicit_selection
|
||||||
|
|
||||||
Repository = dict[str, Any]
|
Repository = dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
def _at_cwd_checkout(args, selected: list[Repository]) -> list[Repository]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
args: parsed CLI arguments.
|
||||||
|
selected: the repositories dispatch picked.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
selected unchanged after an explicit selection or outside git; else each
|
||||||
|
repository pointed at the current directory's git toplevel, so a release
|
||||||
|
from a nested clone never commits in the configured main checkout.
|
||||||
|
|
||||||
|
"""
|
||||||
|
if has_explicit_selection(args):
|
||||||
|
return selected
|
||||||
|
try:
|
||||||
|
toplevel = run(["rev-parse", "--show-toplevel"])
|
||||||
|
except GitRunError:
|
||||||
|
return selected
|
||||||
|
return [{**repo, "directory": toplevel} for repo in selected]
|
||||||
|
|
||||||
|
|
||||||
|
def release_at_cwd(args, ctx: CLIContext, selected: list[Repository]) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
args: parsed CLI arguments.
|
||||||
|
ctx: the CLI context.
|
||||||
|
selected: the repositories dispatch picked; without an explicit
|
||||||
|
selection each is released in the current directory's checkout.
|
||||||
|
|
||||||
|
"""
|
||||||
|
handle_release(args, ctx, _at_cwd_checkout(args, selected))
|
||||||
|
|
||||||
|
|
||||||
|
def _release_options(args) -> ReleaseOptions:
|
||||||
|
return ReleaseOptions(
|
||||||
|
pyproject_path="pyproject.toml",
|
||||||
|
changelog_path="CHANGELOG.md",
|
||||||
|
release_type=args.release_type or "patch",
|
||||||
|
message=args.message or None,
|
||||||
|
preview=getattr(args, "preview", False),
|
||||||
|
force=getattr(args, "force", False),
|
||||||
|
close=getattr(args, "close", False),
|
||||||
|
retry=bool(getattr(args, "retry", False)),
|
||||||
|
expect_tree=getattr(args, "expect_tree", None),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_repo_dir(ctx: CLIContext, repo: Repository, identifier: str) -> str | None:
|
||||||
|
"""
|
||||||
|
Returns:
|
||||||
|
The repository's existing directory, or None after a skip warning.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
repo_dir = repo.get("directory") or get_repo_dir(
|
||||||
|
ctx.repositories_base_dir, repo
|
||||||
|
)
|
||||||
|
except (AttributeError, KeyError, TypeError) as exc:
|
||||||
|
print(
|
||||||
|
f"[WARN] Skipping repository {identifier}: failed to resolve directory: {exc}"
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not os.path.isdir(repo_dir):
|
||||||
|
print(f"[WARN] Skipping repository {identifier}: directory missing.")
|
||||||
|
return None
|
||||||
|
return repo_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _release_type_usable(args, identifier: str) -> bool:
|
||||||
|
retry = bool(getattr(args, "retry", False))
|
||||||
|
if retry and args.release_type:
|
||||||
|
print(
|
||||||
|
f"[WARN] Ignoring release_type '{args.release_type}' for {identifier} — --retry skips version bumps."
|
||||||
|
)
|
||||||
|
if not retry and not args.release_type:
|
||||||
|
print(
|
||||||
|
f"[WARN] Skipping {identifier}: release_type is required unless --retry is set."
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _release_repo(args, repo: Repository, repo_dir: str, identifier: str) -> None:
|
||||||
|
options = _release_options(args)
|
||||||
|
action_label = "retry-release" if options.retry else "release"
|
||||||
|
print(f"[pkgmgr] Running {action_label} for repository {identifier}...")
|
||||||
|
|
||||||
|
cwd_before = os.getcwd()
|
||||||
|
try:
|
||||||
|
os.chdir(repo_dir)
|
||||||
|
run_release(options)
|
||||||
|
|
||||||
|
if not getattr(args, "no_publish", False):
|
||||||
|
print(f"[pkgmgr] Running publish for repository {identifier}...")
|
||||||
|
is_tty = sys.stdin.isatty()
|
||||||
|
run_publish(
|
||||||
|
repo=repo,
|
||||||
|
repo_dir=repo_dir,
|
||||||
|
preview=options.preview,
|
||||||
|
interactive=is_tty,
|
||||||
|
allow_prompt=is_tty,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
os.chdir(cwd_before)
|
||||||
|
|
||||||
|
|
||||||
def handle_release(
|
def handle_release(
|
||||||
args,
|
args,
|
||||||
ctx: CLIContext,
|
ctx: CLIContext,
|
||||||
@@ -31,60 +140,7 @@ def handle_release(
|
|||||||
|
|
||||||
for repo in selected:
|
for repo in selected:
|
||||||
identifier = get_repo_identifier(repo, ctx.all_repositories)
|
identifier = get_repo_identifier(repo, ctx.all_repositories)
|
||||||
|
repo_dir = _resolve_repo_dir(ctx, repo, identifier)
|
||||||
try:
|
if repo_dir is None or not _release_type_usable(args, identifier):
|
||||||
repo_dir = repo.get("directory") or get_repo_dir(
|
|
||||||
ctx.repositories_base_dir, repo
|
|
||||||
)
|
|
||||||
except (AttributeError, KeyError, TypeError) as exc:
|
|
||||||
print(
|
|
||||||
f"[WARN] Skipping repository {identifier}: failed to resolve directory: {exc}"
|
|
||||||
)
|
|
||||||
continue
|
continue
|
||||||
|
_release_repo(args, repo, repo_dir, identifier)
|
||||||
if not os.path.isdir(repo_dir):
|
|
||||||
print(f"[WARN] Skipping repository {identifier}: directory missing.")
|
|
||||||
continue
|
|
||||||
|
|
||||||
retry = bool(getattr(args, "retry", False))
|
|
||||||
if retry and args.release_type:
|
|
||||||
print(
|
|
||||||
f"[WARN] Ignoring release_type '{args.release_type}' for {identifier} — --retry skips version bumps."
|
|
||||||
)
|
|
||||||
if not retry and not args.release_type:
|
|
||||||
print(
|
|
||||||
f"[WARN] Skipping {identifier}: release_type is required unless --retry is set."
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
action_label = "retry-release" if retry else "release"
|
|
||||||
print(f"[pkgmgr] Running {action_label} for repository {identifier}...")
|
|
||||||
|
|
||||||
cwd_before = os.getcwd()
|
|
||||||
try:
|
|
||||||
os.chdir(repo_dir)
|
|
||||||
|
|
||||||
run_release(
|
|
||||||
pyproject_path="pyproject.toml",
|
|
||||||
changelog_path="CHANGELOG.md",
|
|
||||||
release_type=args.release_type or "patch",
|
|
||||||
message=args.message or None,
|
|
||||||
preview=getattr(args, "preview", False),
|
|
||||||
force=getattr(args, "force", False),
|
|
||||||
close=getattr(args, "close", False),
|
|
||||||
retry=retry,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not getattr(args, "no_publish", False):
|
|
||||||
print(f"[pkgmgr] Running publish for repository {identifier}...")
|
|
||||||
is_tty = sys.stdin.isatty()
|
|
||||||
run_publish(
|
|
||||||
repo=repo,
|
|
||||||
repo_dir=repo_dir,
|
|
||||||
preview=getattr(args, "preview", False),
|
|
||||||
interactive=is_tty,
|
|
||||||
allow_prompt=is_tty,
|
|
||||||
)
|
|
||||||
|
|
||||||
finally:
|
|
||||||
os.chdir(cwd_before)
|
|
||||||
@@ -3,9 +3,11 @@ from __future__ import annotations
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
from pkgmgr.actions.branch.gc import main_repo_root
|
from pkgmgr.actions.branch.gc import main_repo_root
|
||||||
from pkgmgr.actions.gc.report import disk_report, render_text
|
from pkgmgr.actions.gc.report import disk_report, render_text
|
||||||
|
from pkgmgr.actions.gc.risk import RiskRequest, risk_cleanup
|
||||||
from pkgmgr.actions.worktree.flow_actions import (
|
from pkgmgr.actions.worktree.flow_actions import (
|
||||||
worktree_flow_clear,
|
worktree_flow_clear,
|
||||||
worktree_flow_set,
|
worktree_flow_set,
|
||||||
@@ -118,7 +120,28 @@ def handle_worktree(args, ctx: CLIContext) -> None:
|
|||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|
||||||
|
|
||||||
|
def _risk_request(args, ctx: CLIContext) -> RiskRequest:
|
||||||
|
return RiskRequest(
|
||||||
|
level=args.risk,
|
||||||
|
apply=args.apply,
|
||||||
|
as_json=args.json,
|
||||||
|
owners_file=args.owners,
|
||||||
|
hooks=pinned_hooks(ctx),
|
||||||
|
min_age=args.min_age,
|
||||||
|
tmp_root=tempfile.gettempdir(),
|
||||||
|
**scan_options(args),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def handle_gc(args, ctx: CLIContext) -> None:
|
def handle_gc(args, ctx: CLIContext) -> None:
|
||||||
|
if args.risk:
|
||||||
|
if args.report:
|
||||||
|
print("--risk cannot be combined with --report", file=sys.stderr)
|
||||||
|
sys.exit(2)
|
||||||
|
sys.exit(risk_cleanup(scan_repo_roots(args, ctx), _risk_request(args, ctx)))
|
||||||
|
if args.owners:
|
||||||
|
print("--owners only with --risk", file=sys.stderr)
|
||||||
|
sys.exit(2)
|
||||||
if not args.report:
|
if not args.report:
|
||||||
run_cleanup(args, ctx, "all")
|
run_cleanup(args, ctx, "all")
|
||||||
if args.apply:
|
if args.apply:
|
||||||
|
|||||||
@@ -14,27 +14,17 @@ from pkgmgr.cli.commands import (
|
|||||||
handle_make,
|
handle_make,
|
||||||
handle_mirror_command,
|
handle_mirror_command,
|
||||||
handle_publish,
|
handle_publish,
|
||||||
handle_release,
|
|
||||||
handle_repos_command,
|
handle_repos_command,
|
||||||
handle_review,
|
handle_review,
|
||||||
handle_tools_command,
|
handle_tools_command,
|
||||||
handle_version,
|
handle_version,
|
||||||
handle_worktree,
|
handle_worktree,
|
||||||
|
release_at_cwd,
|
||||||
)
|
)
|
||||||
from pkgmgr.cli.context import CLIContext
|
from pkgmgr.cli.context import CLIContext
|
||||||
from pkgmgr.cli.proxy import maybe_handle_proxy
|
from pkgmgr.cli.proxy import maybe_handle_proxy
|
||||||
from pkgmgr.core.repository.dir import get_repo_dir
|
from pkgmgr.core.repository.dir import get_repo_dir
|
||||||
from pkgmgr.core.repository.selected import get_selected_repos
|
from pkgmgr.core.repository.selected import get_selected_repos, has_explicit_selection
|
||||||
|
|
||||||
|
|
||||||
def _has_explicit_selection(args) -> bool:
|
|
||||||
return bool(
|
|
||||||
getattr(args, "all", False)
|
|
||||||
or getattr(args, "identifiers", [])
|
|
||||||
or getattr(args, "category", [])
|
|
||||||
or getattr(args, "tag", [])
|
|
||||||
or getattr(args, "string", "")
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _select_repo_for_current_directory(ctx: CLIContext) -> list[dict[str, Any]]:
|
def _select_repo_for_current_directory(ctx: CLIContext) -> list[dict[str, Any]]:
|
||||||
@@ -100,7 +90,7 @@ def dispatch_command(args, ctx: CLIContext) -> None:
|
|||||||
if args.command in commands_with_selection:
|
if args.command in commands_with_selection:
|
||||||
selected = (
|
selected = (
|
||||||
get_selected_repos(args, ctx.all_repositories)
|
get_selected_repos(args, ctx.all_repositories)
|
||||||
if _has_explicit_selection(args)
|
if has_explicit_selection(args)
|
||||||
else _select_repo_for_current_directory(ctx)
|
else _select_repo_for_current_directory(ctx)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
@@ -143,7 +133,7 @@ def dispatch_command(args, ctx: CLIContext) -> None:
|
|||||||
return
|
return
|
||||||
|
|
||||||
if args.command == "release":
|
if args.command == "release":
|
||||||
handle_release(args, ctx, selected)
|
release_at_cwd(args, ctx, selected)
|
||||||
return
|
return
|
||||||
|
|
||||||
if args.command == "publish":
|
if args.command == "publish":
|
||||||
|
|||||||
@@ -105,6 +105,41 @@ def add_branch_subparsers(
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
add_apply_options(branch_cleanup)
|
add_apply_options(branch_cleanup)
|
||||||
|
branch_cleanup.add_argument(
|
||||||
|
"--local",
|
||||||
|
action="store_true",
|
||||||
|
help=(
|
||||||
|
"Delete only local branches whose tip is an ancestor of origin's "
|
||||||
|
"remote-tracking default (else the only remote's) or a --merged-into "
|
||||||
|
"REF, against the planned sha; refuse a repository without such a "
|
||||||
|
"default, one git fails on, one whose holds cannot be read, one "
|
||||||
|
"whose git dir is neither its common dir nor directly under "
|
||||||
|
"<common>/worktrees/ and one with a symlink in or below refs, "
|
||||||
|
"packed-refs, reftable or logs/refs, and still print the plan; skip "
|
||||||
|
"a symbolic branch, a branch any symbolic ref of any worktree names, "
|
||||||
|
"a branch a worktree, worktree registration, rebase or bisect holds, "
|
||||||
|
"a --merged-into target, a branch with branch.<name>.deleteMerged "
|
||||||
|
"false in any worktree's or the system config and the local "
|
||||||
|
"upstream of a branch that stays, also of one --branch or --exclude "
|
||||||
|
"leaves out; "
|
||||||
|
"run git without inherited GIT_* variables but "
|
||||||
|
"GIT_CEILING_DIRECTORIES; the keep config reads run once with the "
|
||||||
|
"caller's GIT_CONFIG_* variables and once with the default system "
|
||||||
|
"and passwd-home config, and either read's keep counts; read no "
|
||||||
|
"forge token; "
|
||||||
|
"never fetch, push, delete a remote branch, run docker or hooks, or "
|
||||||
|
"refresh the branch tree file; exit 1 when an item failed, else 2 "
|
||||||
|
"when a repository was refused, else 0; exit 2 without a plan when, "
|
||||||
|
"without --all, the current directory is in no git repository, its "
|
||||||
|
"git dir is neither its common dir nor directly under "
|
||||||
|
"<common>/worktrees/, its main worktree belongs to another "
|
||||||
|
"repository or its path or git output is not UTF-8, on --apply "
|
||||||
|
"outside the host PID namespace, on a --merged-into REF that is not "
|
||||||
|
"exactly one branch or remote-tracking ref (X~0, X^0, X@{0}, a sha), "
|
||||||
|
"and on a --branch "
|
||||||
|
"that matches nothing; meant for working clones"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
branch_purge = branch_subparsers.add_parser(
|
branch_purge = branch_subparsers.add_parser(
|
||||||
"purge",
|
"purge",
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
|
from pkgmgr.actions.gc.risk.levels import LEVELS
|
||||||
|
|
||||||
from .branch_cmd import add_apply_options, add_min_age_option, add_scan_options
|
from .branch_cmd import add_apply_options, add_min_age_option, add_scan_options
|
||||||
|
|
||||||
|
|
||||||
@@ -16,6 +18,11 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
|
|||||||
add_apply_options(gc)
|
add_apply_options(gc)
|
||||||
add_scan_options(gc)
|
add_scan_options(gc)
|
||||||
add_min_age_option(gc)
|
add_min_age_option(gc)
|
||||||
|
_add_report_options(gc)
|
||||||
|
_add_risk_options(gc)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_report_options(gc: argparse.ArgumentParser) -> None:
|
||||||
gc.add_argument(
|
gc.add_argument(
|
||||||
"--report",
|
"--report",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -44,3 +51,26 @@ def add_gc_subparser(subparsers: argparse._SubParsersAction) -> None:
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="With --report: also read `docker system df`",
|
help="With --report: also read `docker system df`",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_risk_options(gc: argparse.ArgumentParser) -> None:
|
||||||
|
gc.add_argument(
|
||||||
|
"--risk",
|
||||||
|
choices=LEVELS,
|
||||||
|
help=(
|
||||||
|
"Plan branches, worktrees, docker volumes, unused images, idle build "
|
||||||
|
"cache, stopped containers and /tmp entries with a risk class each "
|
||||||
|
"and print the items up to RISK; --apply removes exactly the low "
|
||||||
|
"items of that plan and needs --risk low; with --branch only the "
|
||||||
|
"matching git items are planned"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
gc.add_argument(
|
||||||
|
"--owners",
|
||||||
|
metavar="FILE",
|
||||||
|
help=(
|
||||||
|
"With --risk: JSON object of /tmp path -> owner task status; only "
|
||||||
|
"an entry whose task is done or stopped and that is unchanged for "
|
||||||
|
"24 h is low"
|
||||||
|
),
|
||||||
|
)
|
||||||
@@ -5,20 +5,7 @@ import argparse
|
|||||||
from .common import add_identifier_arguments
|
from .common import add_identifier_arguments
|
||||||
|
|
||||||
|
|
||||||
def add_release_subparser(
|
def _add_version_arguments(release_parser: argparse.ArgumentParser) -> None:
|
||||||
subparsers: argparse._SubParsersAction,
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Register the release command.
|
|
||||||
"""
|
|
||||||
release_parser = subparsers.add_parser(
|
|
||||||
"release",
|
|
||||||
help=(
|
|
||||||
"Create a release for repository/ies by incrementing version "
|
|
||||||
"and updating the changelog."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
release_parser.add_argument(
|
release_parser.add_argument(
|
||||||
"release_type",
|
"release_type",
|
||||||
nargs="?",
|
nargs="?",
|
||||||
@@ -36,8 +23,8 @@ def add_release_subparser(
|
|||||||
help="Optional release message to add to the changelog and tag.",
|
help="Optional release message to add to the changelog and tag.",
|
||||||
)
|
)
|
||||||
|
|
||||||
add_identifier_arguments(release_parser)
|
|
||||||
|
|
||||||
|
def _add_flow_arguments(release_parser: argparse.ArgumentParser) -> None:
|
||||||
release_parser.add_argument(
|
release_parser.add_argument(
|
||||||
"--close",
|
"--close",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -52,8 +39,7 @@ def add_release_subparser(
|
|||||||
"--force",
|
"--force",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
help=(
|
help=(
|
||||||
"Skip the interactive preview+confirmation step and run the "
|
"Run the release directly, without the interactive preview and its prompt."
|
||||||
"release directly."
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -63,6 +49,19 @@ def add_release_subparser(
|
|||||||
help="Do not run publish automatically after a successful release.",
|
help="Do not run publish automatically after a successful release.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_safety_arguments(release_parser: argparse.ArgumentParser) -> None:
|
||||||
|
release_parser.add_argument(
|
||||||
|
"--expect-tree",
|
||||||
|
metavar="TREE",
|
||||||
|
default=None,
|
||||||
|
help=(
|
||||||
|
"Refuse to release unless HEAD's tree (git rev-parse HEAD^{tree}) "
|
||||||
|
"equals this full sha after the pull and before any file is "
|
||||||
|
"written; with --retry, before anything is pushed."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
release_parser.add_argument(
|
release_parser.add_argument(
|
||||||
"--retry",
|
"--retry",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -74,3 +73,19 @@ def add_release_subparser(
|
|||||||
"post-tag push or PyPI upload failed mid-flight."
|
"post-tag push or PyPI upload failed mid-flight."
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def add_release_subparser(
|
||||||
|
subparsers: argparse._SubParsersAction,
|
||||||
|
) -> None:
|
||||||
|
release_parser = subparsers.add_parser(
|
||||||
|
"release",
|
||||||
|
help=(
|
||||||
|
"Create a release for repository/ies by incrementing version "
|
||||||
|
"and updating the changelog."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
_add_version_arguments(release_parser)
|
||||||
|
add_identifier_arguments(release_parser)
|
||||||
|
_add_flow_arguments(release_parser)
|
||||||
|
_add_safety_arguments(release_parser)
|
||||||
@@ -68,7 +68,7 @@ def create_ink(
|
|||||||
# Mark local repo scripts as executable if needed
|
# Mark local repo scripts as executable if needed
|
||||||
try:
|
try:
|
||||||
if os.path.realpath(command).startswith(os.path.realpath(repo_dir)):
|
if os.path.realpath(command).startswith(os.path.realpath(repo_dir)):
|
||||||
os.chmod(command, 0o755)
|
os.chmod(command, 0o700)
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
if not quiet:
|
if not quiet:
|
||||||
print(f"Failed to set permissions on '{command}': {e}")
|
print(f"Failed to set permissions on '{command}': {e}")
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextvars
|
||||||
import os
|
import os
|
||||||
|
import pwd
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
from .errors import GitNotRepositoryError, GitRunError
|
from .errors import GitNotRepositoryError, GitRunError
|
||||||
|
|
||||||
@@ -52,10 +57,20 @@ SCAN_UNSET = (
|
|||||||
"GIT_PAGER",
|
"GIT_PAGER",
|
||||||
"PAGER",
|
"PAGER",
|
||||||
)
|
)
|
||||||
|
STRICT_KEEP = ("GIT_CEILING_DIRECTORIES",)
|
||||||
|
CONFIG_READ_KEEP = re.compile(
|
||||||
|
r"GIT_CONFIG_(GLOBAL|SYSTEM|PARAMETERS|COUNT|KEY_\d+|VALUE_\d+)"
|
||||||
|
)
|
||||||
|
CALLER_CONFIG = "caller"
|
||||||
|
DEFAULT_CONFIG = "default"
|
||||||
|
CONFIG_VIEWS = (CALLER_CONFIG, DEFAULT_CONFIG)
|
||||||
SCAN_TIMEOUT = 60
|
SCAN_TIMEOUT = 60
|
||||||
# ref and remote names come from repositories an agent may write: one named
|
# ref and remote names come from repositories an agent may write: one named
|
||||||
# like --output=<path> would otherwise make rev-list create that file
|
# like --output=<path> would otherwise make rev-list create that file
|
||||||
END_OF_OPTIONS = "--end-of-options"
|
END_OF_OPTIONS = "--end-of-options"
|
||||||
|
_STRICT_ENV: contextvars.ContextVar[bool] = contextvars.ContextVar(
|
||||||
|
"pkgmgr_git_strict_env", default=False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _is_not_repo_error(stderr: str) -> bool:
|
def _is_not_repo_error(stderr: str) -> bool:
|
||||||
@@ -63,9 +78,61 @@ def _is_not_repo_error(stderr: str) -> bool:
|
|||||||
return "not a git repository" in msg
|
return "not a git repository" in msg
|
||||||
|
|
||||||
|
|
||||||
def _scan_env() -> dict[str, str]:
|
@contextmanager
|
||||||
env = {key: value for key, value in os.environ.items() if key not in SCAN_UNSET}
|
def strict_env() -> Iterator[None]:
|
||||||
return {**env, **SCAN_ENV}
|
token = _STRICT_ENV.set(True)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
_STRICT_ENV.reset(token)
|
||||||
|
|
||||||
|
|
||||||
|
def _strict_keeps(key: str, caller: bool) -> bool:
|
||||||
|
return key in STRICT_KEEP or (
|
||||||
|
caller and CONFIG_READ_KEEP.fullmatch(key) is not None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _passwd_home() -> str | None:
|
||||||
|
try:
|
||||||
|
return pwd.getpwuid(os.getuid()).pw_dir
|
||||||
|
except KeyError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_env(strict: bool = False, view: str | None = None) -> dict[str, str]:
|
||||||
|
"""
|
||||||
|
Build the environment of a scan or strict git call.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
strict: drop every inherited `GIT_*` variable but STRICT_KEEP.
|
||||||
|
view: None, CALLER_CONFIG or DEFAULT_CONFIG, as run takes it.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The inherited environment without SCAN_UNSET, plus SCAN_ENV; for a
|
||||||
|
config view with the system config; for DEFAULT_CONFIG also without
|
||||||
|
any `GIT_*` but STRICT_KEEP and XDG_CONFIG_HOME, HOME set to the
|
||||||
|
passwd home (unset without a passwd entry).
|
||||||
|
"""
|
||||||
|
caller = view == CALLER_CONFIG
|
||||||
|
scrub = strict or view == DEFAULT_CONFIG
|
||||||
|
env = {
|
||||||
|
key: value
|
||||||
|
for key, value in os.environ.items()
|
||||||
|
if key not in SCAN_UNSET
|
||||||
|
and not (scrub and key.startswith("GIT_") and not _strict_keeps(key, caller))
|
||||||
|
}
|
||||||
|
env = {**env, **SCAN_ENV}
|
||||||
|
if view is None:
|
||||||
|
return env
|
||||||
|
del env["GIT_CONFIG_NOSYSTEM"]
|
||||||
|
if view == DEFAULT_CONFIG:
|
||||||
|
env.pop("XDG_CONFIG_HOME", None)
|
||||||
|
env.pop("HOME", None)
|
||||||
|
home = _passwd_home()
|
||||||
|
if home:
|
||||||
|
env["HOME"] = home
|
||||||
|
return env
|
||||||
|
|
||||||
|
|
||||||
def run(
|
def run(
|
||||||
@@ -75,6 +142,7 @@ def run(
|
|||||||
preview: bool = False,
|
preview: bool = False,
|
||||||
scan: bool = False,
|
scan: bool = False,
|
||||||
input_text: str | None = None,
|
input_text: str | None = None,
|
||||||
|
config_view: str | None = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""
|
||||||
Run a Git command and return its stdout as a stripped string.
|
Run a Git command and return its stdout as a stripped string.
|
||||||
@@ -85,9 +153,17 @@ def run(
|
|||||||
preview: print the command instead of running it.
|
preview: print the command instead of running it.
|
||||||
scan: read a repository an agent may have written: no fsmonitor, hook,
|
scan: read a repository an agent may have written: no fsmonitor, hook,
|
||||||
pager, lazy fetch, replace object, system config or prompt, stdin
|
pager, lazy fetch, replace object, system config or prompt, stdin
|
||||||
closed, a timeout.
|
closed, a timeout. Inside strict_env() every call, scan or not,
|
||||||
|
also runs without any inherited `GIT_*` variable but
|
||||||
|
`GIT_CEILING_DIRECTORIES`, which only narrows discovery.
|
||||||
input_text: text fed to stdin, e.g. for `cat-file --batch-check`;
|
input_text: text fed to stdin, e.g. for `cat-file --batch-check`;
|
||||||
replaces the closed stdin of scan mode.
|
replaces the closed stdin of scan mode.
|
||||||
|
config_view: for a pure config read, the config it sees, both with
|
||||||
|
the system config: CALLER_CONFIG also keeps, inside strict_env(),
|
||||||
|
`GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_PARAMETERS`,
|
||||||
|
`GIT_CONFIG_COUNT` and its `GIT_CONFIG_KEY_<n>` and
|
||||||
|
`GIT_CONFIG_VALUE_<n>`; DEFAULT_CONFIG reads the default system
|
||||||
|
and passwd-home global config whatever the environment says.
|
||||||
|
|
||||||
Raises GitRunError (or a subclass) if execution fails or times out.
|
Raises GitRunError (or a subclass) if execution fails or times out.
|
||||||
"""
|
"""
|
||||||
@@ -98,10 +174,15 @@ def run(
|
|||||||
print(f"[PREVIEW] Would run in {cwd!r}: {cmd_str}")
|
print(f"[PREVIEW] Would run in {cwd!r}: {cmd_str}")
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
strict = _STRICT_ENV.get()
|
||||||
hardened: dict = (
|
hardened: dict = (
|
||||||
{"env": _scan_env(), "stdin": subprocess.DEVNULL, "timeout": SCAN_TIMEOUT}
|
{
|
||||||
|
"env": _scan_env(strict, config_view),
|
||||||
|
"stdin": subprocess.DEVNULL,
|
||||||
|
"timeout": SCAN_TIMEOUT,
|
||||||
|
}
|
||||||
if scan
|
if scan
|
||||||
else {}
|
else ({"env": _scan_env(True, config_view)} if strict else {})
|
||||||
)
|
)
|
||||||
if input_text is not None:
|
if input_text is not None:
|
||||||
hardened.pop("stdin", None)
|
hardened.pop("stdin", None)
|
||||||
|
|||||||
@@ -1,15 +1,19 @@
|
|||||||
# src/pkgmgr/core/remote_provisioning/http/client.py
|
# src/pkgmgr/core/remote_provisioning/http/client.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
import json
|
import json
|
||||||
import ssl
|
import ssl
|
||||||
import urllib.error
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from .errors import HttpError
|
from .errors import HttpError
|
||||||
|
|
||||||
|
ALLOWED_SCHEMES = frozenset({"http", "https"})
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class HttpResponse:
|
class HttpResponse:
|
||||||
@@ -31,6 +35,11 @@ class HttpClient:
|
|||||||
headers: dict[str, str] | None = None,
|
headers: dict[str, str] | None = None,
|
||||||
payload: dict[str, Any] | None = None,
|
payload: dict[str, Any] | None = None,
|
||||||
) -> HttpResponse:
|
) -> HttpResponse:
|
||||||
|
scheme = urllib.parse.urlsplit(url).scheme
|
||||||
|
if scheme not in ALLOWED_SCHEMES:
|
||||||
|
raise HttpError(
|
||||||
|
status=0, message=f"unsupported URL scheme {scheme!r}", body=""
|
||||||
|
)
|
||||||
data: bytes | None = None
|
data: bytes | None = None
|
||||||
final_headers: dict[str, str] = dict(headers or {})
|
final_headers: dict[str, str] = dict(headers or {})
|
||||||
|
|
||||||
@@ -41,7 +50,9 @@ class HttpClient:
|
|||||||
req = urllib.request.Request(url=url, data=data, method=method.upper())
|
req = urllib.request.Request(url=url, data=data, method=method.upper())
|
||||||
for k, v in final_headers.items():
|
for k, v in final_headers.items():
|
||||||
req.add_header(k, v)
|
req.add_header(k, v)
|
||||||
|
return self._send(req)
|
||||||
|
|
||||||
|
def _send(self, req: urllib.request.Request) -> HttpResponse:
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(
|
with urllib.request.urlopen(
|
||||||
req,
|
req,
|
||||||
@@ -49,21 +60,32 @@ class HttpClient:
|
|||||||
context=ssl.create_default_context(),
|
context=ssl.create_default_context(),
|
||||||
) as resp:
|
) as resp:
|
||||||
raw = resp.read().decode("utf-8", errors="replace")
|
raw = resp.read().decode("utf-8", errors="replace")
|
||||||
|
return HttpResponse(
|
||||||
parsed: dict[str, Any] | None = None
|
status=int(resp.status), text=raw, json=_json_object(raw)
|
||||||
if raw:
|
)
|
||||||
try:
|
|
||||||
loaded = json.loads(raw)
|
|
||||||
parsed = loaded if isinstance(loaded, dict) else None
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
parsed = None
|
|
||||||
|
|
||||||
return HttpResponse(status=int(resp.status), text=raw, json=parsed)
|
|
||||||
except urllib.error.HTTPError as exc:
|
except urllib.error.HTTPError as exc:
|
||||||
try:
|
raise HttpError(
|
||||||
body = exc.read().decode("utf-8", errors="replace")
|
status=int(exc.code), message=str(exc), body=_error_body(exc)
|
||||||
except (OSError, ValueError):
|
) from exc
|
||||||
body = ""
|
except (OSError, http.client.HTTPException) as exc:
|
||||||
raise HttpError(status=int(exc.code), message=str(exc), body=body) from exc
|
message = str(exc) or type(exc).__name__
|
||||||
except urllib.error.URLError as exc:
|
raise HttpError(status=0, message=message, body="") from exc
|
||||||
raise HttpError(status=0, message=str(exc), body="") from exc
|
|
||||||
|
|
||||||
|
def _json_object(raw: str) -> dict[str, Any] | None:
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
loaded = json.loads(raw)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
return loaded if isinstance(loaded, dict) else None
|
||||||
|
|
||||||
|
|
||||||
|
def _error_body(exc: urllib.error.HTTPError) -> str:
|
||||||
|
try:
|
||||||
|
return exc.read().decode("utf-8", errors="replace")
|
||||||
|
except http.client.IncompleteRead as truncated:
|
||||||
|
return truncated.partial.decode("utf-8", errors="replace")
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return ""
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
# src/pkgmgr/core/remote_provisioning/providers/github.py
|
# src/pkgmgr/core/remote_provisioning/providers/github.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from ..http.client import HttpClient
|
from ..http.client import HttpClient
|
||||||
@@ -103,7 +104,7 @@ class GitHubProvider(RemoteProvider):
|
|||||||
user_url = f"{api}/user/repos"
|
user_url = f"{api}/user/repos"
|
||||||
|
|
||||||
# Try org first, then fall back to user creation.
|
# Try org first, then fall back to user creation.
|
||||||
try:
|
with contextlib.suppress(HttpError):
|
||||||
resp = self._http.request_json(
|
resp = self._http.request_json(
|
||||||
"POST", org_url, headers=self._headers(token), payload=payload
|
"POST", org_url, headers=self._headers(token), payload=payload
|
||||||
)
|
)
|
||||||
@@ -114,8 +115,6 @@ class GitHubProvider(RemoteProvider):
|
|||||||
message="Repository created (org).",
|
message="Repository created (org).",
|
||||||
url=str(html_url) if html_url else None,
|
url=str(html_url) if html_url else None,
|
||||||
)
|
)
|
||||||
except HttpError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
resp = self._http.request_json(
|
resp = self._http.request_json(
|
||||||
"POST", user_url, headers=self._headers(token), payload=payload
|
"POST", user_url, headers=self._headers(token), payload=payload
|
||||||
|
|||||||
@@ -136,6 +136,25 @@ def _maybe_filter_ignored(args, repos: list[Repository]) -> list[Repository]:
|
|||||||
return filter_ignored(repos)
|
return filter_ignored(repos)
|
||||||
|
|
||||||
|
|
||||||
|
def has_explicit_selection(args) -> bool:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
args: parsed CLI arguments.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True when --all, an identifier, --category, --tag or --string picks
|
||||||
|
the repositories instead of the current directory.
|
||||||
|
|
||||||
|
"""
|
||||||
|
return bool(
|
||||||
|
getattr(args, "all", False)
|
||||||
|
or getattr(args, "identifiers", [])
|
||||||
|
or getattr(args, "category", [])
|
||||||
|
or getattr(args, "tag", [])
|
||||||
|
or getattr(args, "string", "")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_selected_repos(args, all_repositories: list[Repository]) -> list[Repository]:
|
def get_selected_repos(args, all_repositories: list[Repository]) -> list[Repository]:
|
||||||
"""
|
"""
|
||||||
Compute the list of repositories selected by CLI arguments.
|
Compute the list of repositories selected by CLI arguments.
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
@@ -127,7 +128,7 @@ def get_installed_nix_profile_version(*candidates: str) -> InstalledVersion | No
|
|||||||
# Preferred: JSON output
|
# Preferred: JSON output
|
||||||
rc, out, _ = _run_nix(["nix", "profile", "list", "--json"])
|
rc, out, _ = _run_nix(["nix", "profile", "list", "--json"])
|
||||||
if rc == 0 and out.strip():
|
if rc == 0 and out.strip():
|
||||||
try:
|
with contextlib.suppress(json.JSONDecodeError, AttributeError):
|
||||||
data = json.loads(out)
|
data = json.loads(out)
|
||||||
elements = data.get("elements") or data.get("items") or {}
|
elements = data.get("elements") or data.get("items") or {}
|
||||||
if isinstance(elements, dict):
|
if isinstance(elements, dict):
|
||||||
@@ -145,8 +146,6 @@ def get_installed_nix_profile_version(*candidates: str) -> InstalledVersion | No
|
|||||||
guess = _extract_version_from_store_path(sp)
|
guess = _extract_version_from_store_path(sp)
|
||||||
if guess:
|
if guess:
|
||||||
return InstalledVersion(name=name, version=guess)
|
return InstalledVersion(name=name, version=guess)
|
||||||
except (json.JSONDecodeError, AttributeError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Fallback: text mode
|
# Fallback: text mode
|
||||||
rc, out, _ = _run_nix(["nix", "profile", "list"])
|
rc, out, _ = _run_nix(["nix", "profile", "list"])
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
# src/pkgmgr/core/version/source.py
|
# src/pkgmgr/core/version/source.py
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
|
||||||
@@ -9,11 +10,59 @@ import yaml
|
|||||||
from pkgmgr.core.repository.paths import resolve_repo_paths
|
from pkgmgr.core.repository.paths import resolve_repo_paths
|
||||||
|
|
||||||
|
|
||||||
|
def version_literal(name: str) -> re.Pattern[str]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
name: the module attribute holding the version, e.g. __version__.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A pattern whose groups are the assignment up to the opening quote, the
|
||||||
|
version and the closing quote of `name = "X.Y.Z"`.
|
||||||
|
"""
|
||||||
|
return re.compile(rf"""(?m)^(\s*{re.escape(name)}\s*=\s*["'])([^"']+)(["'])""")
|
||||||
|
|
||||||
|
|
||||||
|
def dynamic_version_source(pyproject_path: str, data: dict) -> tuple[str, str] | None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
pyproject_path: the pyproject.toml file.
|
||||||
|
data: its parsed content.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(module file, attribute name) that setuptools reads the version from
|
||||||
|
when [project].dynamic lists version and [tool.setuptools.dynamic]
|
||||||
|
sets version = {attr = "pkg.module.NAME"}, with
|
||||||
|
[tool.setuptools].package-dir applied; None otherwise.
|
||||||
|
"""
|
||||||
|
project = data.get("project") or {}
|
||||||
|
if "version" not in project.get("dynamic", []):
|
||||||
|
return None
|
||||||
|
setuptools = (data.get("tool") or {}).get("setuptools") or {}
|
||||||
|
attr = ((setuptools.get("dynamic") or {}).get("version") or {}).get("attr")
|
||||||
|
if not isinstance(attr, str) or "." not in attr:
|
||||||
|
return None
|
||||||
|
module, _, name = attr.rpartition(".")
|
||||||
|
parts = module.split(".")
|
||||||
|
dirs = setuptools.get("package-dir") or {}
|
||||||
|
if parts[0] in dirs:
|
||||||
|
base = os.path.join(dirs[parts[0]], *parts[1:])
|
||||||
|
else:
|
||||||
|
base = os.path.join(dirs.get("", ""), *parts)
|
||||||
|
root = os.path.dirname(os.path.abspath(pyproject_path))
|
||||||
|
for candidate in (f"{base}.py", os.path.join(base, "__init__.py")):
|
||||||
|
path = os.path.join(root, candidate)
|
||||||
|
if os.path.isfile(path):
|
||||||
|
return path, name
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def read_pyproject_version(repo_dir: str) -> str | None:
|
def read_pyproject_version(repo_dir: str) -> str | None:
|
||||||
"""
|
"""
|
||||||
Read the version from pyproject.toml in repo_dir, if present.
|
Read the version from pyproject.toml in repo_dir, if present.
|
||||||
|
|
||||||
Expects a PEP 621-style [project] table with a 'version' field.
|
Expects a PEP 621-style [project] table with a 'version' field, or a
|
||||||
|
dynamic version that setuptools reads from a module attribute
|
||||||
|
(dynamic_version_source()).
|
||||||
"""
|
"""
|
||||||
paths = resolve_repo_paths(repo_dir)
|
paths = resolve_repo_paths(repo_dir)
|
||||||
path = paths.pyproject_toml
|
path = paths.pyproject_toml
|
||||||
@@ -30,7 +79,14 @@ def read_pyproject_version(repo_dir: str) -> str | None:
|
|||||||
data = tomllib.load(f)
|
data = tomllib.load(f)
|
||||||
project = data.get("project") or {}
|
project = data.get("project") or {}
|
||||||
version = project.get("version")
|
version = project.get("version")
|
||||||
return str(version).strip() if version else None
|
if version:
|
||||||
|
return str(version).strip()
|
||||||
|
source = dynamic_version_source(path, data)
|
||||||
|
if source is None:
|
||||||
|
return None
|
||||||
|
with open(source[0], encoding="utf-8") as f:
|
||||||
|
match = version_literal(source[1]).search(f.read())
|
||||||
|
return match.group(2).strip() if match else None
|
||||||
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
|
except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -204,14 +260,12 @@ def read_ansible_galaxy_version(repo_dir: str) -> str | None:
|
|||||||
"""
|
"""
|
||||||
galaxy_yml = os.path.join(repo_dir, "galaxy.yml")
|
galaxy_yml = os.path.join(repo_dir, "galaxy.yml")
|
||||||
if os.path.isfile(galaxy_yml):
|
if os.path.isfile(galaxy_yml):
|
||||||
try:
|
with contextlib.suppress(OSError, UnicodeDecodeError, yaml.YAMLError):
|
||||||
with open(galaxy_yml, encoding="utf-8") as f:
|
with open(galaxy_yml, encoding="utf-8") as f:
|
||||||
data = yaml.safe_load(f) or {}
|
data = yaml.safe_load(f) or {}
|
||||||
version = data.get("version")
|
version = data.get("version")
|
||||||
if isinstance(version, str) and version.strip():
|
if isinstance(version, str) and version.strip():
|
||||||
return version.strip()
|
return version.strip()
|
||||||
except (OSError, UnicodeDecodeError, yaml.YAMLError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
meta_yml = os.path.join(repo_dir, "meta", "main.yml")
|
meta_yml = os.path.join(repo_dir, "meta", "main.yml")
|
||||||
if os.path.isfile(meta_yml):
|
if os.path.isfile(meta_yml):
|
||||||
|
|||||||
@@ -74,17 +74,17 @@ class TestIntegrationReleaseCommand(unittest.TestCase):
|
|||||||
self._run_pkgmgr(["release", "patch", "--preview"])
|
self._run_pkgmgr(["release", "patch", "--preview"])
|
||||||
|
|
||||||
mock_run_release.assert_called_once()
|
mock_run_release.assert_called_once()
|
||||||
_args, kwargs = mock_run_release.call_args
|
options = mock_run_release.call_args.args[0]
|
||||||
|
|
||||||
# CLI wiring
|
# CLI wiring
|
||||||
self.assertEqual(kwargs.get("release_type"), "patch")
|
self.assertEqual(options.release_type, "patch")
|
||||||
self.assertTrue(
|
self.assertTrue(
|
||||||
kwargs.get("preview"),
|
options.preview,
|
||||||
"preview should be True when --preview is used",
|
"preview should be True when --preview is used",
|
||||||
)
|
)
|
||||||
# Default: no --close → close=False
|
# Default: no --close → close=False
|
||||||
self.assertFalse(
|
self.assertFalse(
|
||||||
kwargs.get("close"),
|
options.close,
|
||||||
"close must be False when --close is not given",
|
"close must be False when --close is not given",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -116,17 +116,17 @@ class TestIntegrationReleaseCommand(unittest.TestCase):
|
|||||||
self._run_pkgmgr(["release", "minor", "--preview", "--close"])
|
self._run_pkgmgr(["release", "minor", "--preview", "--close"])
|
||||||
|
|
||||||
mock_run_release.assert_called_once()
|
mock_run_release.assert_called_once()
|
||||||
_args, kwargs = mock_run_release.call_args
|
options = mock_run_release.call_args.args[0]
|
||||||
|
|
||||||
# CLI wiring
|
# CLI wiring
|
||||||
self.assertEqual(kwargs.get("release_type"), "minor")
|
self.assertEqual(options.release_type, "minor")
|
||||||
self.assertTrue(
|
self.assertTrue(
|
||||||
kwargs.get("preview"),
|
options.preview,
|
||||||
"preview should be True when --preview is used",
|
"preview should be True when --preview is used",
|
||||||
)
|
)
|
||||||
# With --close → close=True
|
# With --close → close=True
|
||||||
self.assertTrue(
|
self.assertTrue(
|
||||||
kwargs.get("close"),
|
options.close,
|
||||||
"close must be True when --close is given",
|
"close must be True when --close is given",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -4,7 +4,6 @@ import io
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
|
||||||
import unittest
|
import unittest
|
||||||
from contextlib import redirect_stdout
|
from contextlib import redirect_stdout
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
@@ -14,25 +13,7 @@ from pkgmgr.actions.branch import gc
|
|||||||
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||||
from pkgmgr.cli.commands.branch import handle_branch
|
from pkgmgr.cli.commands.branch import handle_branch
|
||||||
from pkgmgr.cli.parser import create_parser
|
from pkgmgr.cli.parser import create_parser
|
||||||
|
from tests.support.git_sandbox import git, isolated_root, origin_and_repo
|
||||||
GIT_ENV = {
|
|
||||||
**os.environ,
|
|
||||||
"GIT_AUTHOR_NAME": "t",
|
|
||||||
"GIT_AUTHOR_EMAIL": "t@example.org",
|
|
||||||
"GIT_COMMITTER_NAME": "t",
|
|
||||||
"GIT_COMMITTER_EMAIL": "t@example.org",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def git(cwd: str, *args: str) -> str:
|
|
||||||
return subprocess.run(
|
|
||||||
["git", "-c", "commit.gpgsign=false", *args],
|
|
||||||
cwd=cwd,
|
|
||||||
env=GIT_ENV,
|
|
||||||
check=True,
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
).stdout.strip()
|
|
||||||
|
|
||||||
|
|
||||||
def docker_available() -> bool:
|
def docker_available() -> bool:
|
||||||
@@ -45,15 +26,8 @@ def docker_available() -> bool:
|
|||||||
|
|
||||||
class GcFixture:
|
class GcFixture:
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
self._tmp = tempfile.TemporaryDirectory()
|
self.root = isolated_root(self, {})
|
||||||
self.root = os.path.realpath(self._tmp.name)
|
self.origin, self.repo = origin_and_repo(self.root)
|
||||||
self.origin = os.path.join(self.root, "origin.git")
|
|
||||||
self.repo = os.path.join(self.root, "repo")
|
|
||||||
git(self.root, "init", "--bare", "-b", "main", self.origin)
|
|
||||||
git(self.root, "init", "-b", "main", self.repo)
|
|
||||||
git(self.repo, "remote", "add", "origin", self.origin)
|
|
||||||
self._commit("init")
|
|
||||||
git(self.repo, "push", "-u", "origin", "main")
|
|
||||||
|
|
||||||
self._branch_with_commit("merged")
|
self._branch_with_commit("merged")
|
||||||
git(self.repo, "merge", "--no-ff", "-m", "merge merged", "merged")
|
git(self.repo, "merge", "--no-ff", "-m", "merge merged", "merged")
|
||||||
@@ -81,9 +55,6 @@ class GcFixture:
|
|||||||
merged_heads={self.squashed_sha: 7}, open_heads={"wip": 3}
|
merged_heads={self.squashed_sha: 7}, open_heads={"wip": 3}
|
||||||
)
|
)
|
||||||
|
|
||||||
def tearDown(self) -> None:
|
|
||||||
self._tmp.cleanup()
|
|
||||||
|
|
||||||
def _commit(self, name: str) -> None:
|
def _commit(self, name: str) -> None:
|
||||||
with open(os.path.join(self.repo, f"{name}.txt"), "w") as fh:
|
with open(os.path.join(self.repo, f"{name}.txt"), "w") as fh:
|
||||||
fh.write(name)
|
fh.write(name)
|
||||||
@@ -146,111 +117,6 @@ class GcFixture:
|
|||||||
|
|
||||||
|
|
||||||
class TestBranchGc(GcFixture, unittest.TestCase):
|
class TestBranchGc(GcFixture, unittest.TestCase):
|
||||||
def test_classifies_every_branch(self) -> None:
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["main"].state, "protected")
|
|
||||||
self.assertEqual(items["merged"].state, "merged-clean")
|
|
||||||
self.assertEqual(items["merged"].merged_by, "ancestor")
|
|
||||||
self.assertEqual(
|
|
||||||
items["merged"].actions,
|
|
||||||
["worktree", "local-branch", "remote-branch:origin"],
|
|
||||||
)
|
|
||||||
self.assertTrue(items["merged"].eligible)
|
|
||||||
self.assertEqual(items["squashed"].merged_by, "pr#7")
|
|
||||||
self.assertTrue(items["squashed"].eligible)
|
|
||||||
self.assertEqual(items["fresh"].state, "unmerged")
|
|
||||||
self.assertEqual(items["fresh"].reason, "no own commits")
|
|
||||||
self.assertEqual(items["wip"].state, "unmerged")
|
|
||||||
self.assertEqual(items["wip"].skip, "open-pr #3")
|
|
||||||
self.assertEqual(items["dirty"].state, "dirty")
|
|
||||||
|
|
||||||
def test_merged_into_counts_commits_in_an_integration_line(self) -> None:
|
|
||||||
self._integration_line()
|
|
||||||
before = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
self.assertEqual(before["feat"].state, "unmerged")
|
|
||||||
self.assertIsNone(before["feat"].merged_into)
|
|
||||||
|
|
||||||
for ref in ("line", "origin/line"):
|
|
||||||
with self.subTest(ref=ref):
|
|
||||||
items = self._items(
|
|
||||||
self._plan(host_ns=True, cwds={}, merged_into=[ref])
|
|
||||||
)
|
|
||||||
self.assertEqual(items["feat"].state, "merged-clean")
|
|
||||||
self.assertEqual(items["feat"].merged_by, f"line:{ref}")
|
|
||||||
self.assertEqual(items["feat"].merged_into, ref)
|
|
||||||
self.assertTrue(items["feat"].eligible)
|
|
||||||
self.assertEqual(items["line"].state, "protected")
|
|
||||||
self.assertEqual(items["start"].state, "unmerged")
|
|
||||||
self.assertEqual(items["merged"].merged_into, "origin/main")
|
|
||||||
|
|
||||||
def test_unknown_merged_into_ref_is_a_warning(self) -> None:
|
|
||||||
plan = self._plan(host_ns=True, cwds={}, merged_into=["no-such-line"])
|
|
||||||
|
|
||||||
self.assertIn("merged-into ref no-such-line not found", plan.warnings)
|
|
||||||
self.assertEqual(self._items(plan)["merged"].state, "merged-clean")
|
|
||||||
|
|
||||||
def test_sizes_and_min_age(self) -> None:
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}, sizes=True))
|
|
||||||
self.assertGreater(items["merged"].size_bytes, 0)
|
|
||||||
self.assertIsNone(items["squashed"].size_bytes)
|
|
||||||
self.assertIn("size ", gc._line(items["merged"]))
|
|
||||||
|
|
||||||
young = self._items(self._plan(host_ns=True, cwds={}, min_age=1000))
|
|
||||||
self.assertEqual(young["merged"].skip, "younger than 1000 h")
|
|
||||||
self.assertFalse(young["merged"].eligible)
|
|
||||||
old = self._items(self._plan(host_ns=True, cwds={}, min_age=0))
|
|
||||||
self.assertIsNone(old["merged"].skip)
|
|
||||||
|
|
||||||
def test_busy_worktree_is_skipped(self) -> None:
|
|
||||||
cwds = {4242: os.path.join(self.merged_wt, "sub")}
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds=cwds))
|
|
||||||
|
|
||||||
self.assertTrue(items["merged"].skip.startswith("process: pid 4242"))
|
|
||||||
self.assertFalse(items["merged"].eligible)
|
|
||||||
|
|
||||||
def test_lock_with_live_pid_is_skipped(self) -> None:
|
|
||||||
self._lock(f"claude agent x (pid {os.getpid()} on host)")
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["locked"].skip, f"lock: pid {os.getpid()} alive")
|
|
||||||
|
|
||||||
def test_lock_with_dead_pid_is_overridden(self) -> None:
|
|
||||||
self._lock("claude agent x (pid 999999999 on host)")
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertIsNone(items["locked"].skip)
|
|
||||||
self.assertTrue(items["locked"].eligible)
|
|
||||||
|
|
||||||
def test_lock_outside_host_namespace_is_unknown(self) -> None:
|
|
||||||
self._lock("claude agent x (pid 999999999 on host)")
|
|
||||||
items = self._items(self._plan(host_ns=False, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["locked"].skip, "lock: liveness unknown")
|
|
||||||
|
|
||||||
def test_lock_without_pid_is_respected(self) -> None:
|
|
||||||
self._lock("manual hold")
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["locked"].skip, "lock: manual hold")
|
|
||||||
|
|
||||||
def test_forge_unavailable_skips_everything(self) -> None:
|
|
||||||
self.forge = ForgeFacts(unavailable="no GitHub token")
|
|
||||||
items = self._items(self._plan(host_ns=True, cwds={}))
|
|
||||||
|
|
||||||
self.assertEqual(items["merged"].skip, "forge unavailable")
|
|
||||||
self.assertIsNone(items["squashed"].merged_by)
|
|
||||||
|
|
||||||
def test_stale_metadata_is_listed_not_pruned(self) -> None:
|
|
||||||
stub = os.path.join(self.repo, ".git", "worktrees", "stub")
|
|
||||||
os.makedirs(stub)
|
|
||||||
open(os.path.join(stub, "commondir"), "w").close()
|
|
||||||
plan = self._plan(host_ns=True, cwds={})
|
|
||||||
|
|
||||||
stale = [i for i in plan.items if i.state == "stale"]
|
|
||||||
self.assertEqual([i.worktree for i in stale], [stub])
|
|
||||||
self.assertTrue(os.path.isdir(stub))
|
|
||||||
|
|
||||||
def test_execute_removes_worktree_and_branches(self) -> None:
|
def test_execute_removes_worktree_and_branches(self) -> None:
|
||||||
plan = self._plan(host_ns=True, cwds={})
|
plan = self._plan(host_ns=True, cwds={})
|
||||||
item = self._items(plan)["merged"]
|
item = self._items(plan)["merged"]
|
||||||
@@ -453,7 +319,7 @@ class TestBranchGc(GcFixture, unittest.TestCase):
|
|||||||
hook = os.path.join(self.repo, ".git", "hooks", "reference-transaction")
|
hook = os.path.join(self.repo, ".git", "hooks", "reference-transaction")
|
||||||
with open(hook, "w") as fh:
|
with open(hook, "w") as fh:
|
||||||
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
||||||
os.chmod(hook, 0o755)
|
os.chmod(hook, 0o700)
|
||||||
plan = self._plan(host_ns=True, cwds={})
|
plan = self._plan(host_ns=True, cwds={})
|
||||||
item = self._items(plan)["merged"]
|
item = self._items(plan)["merged"]
|
||||||
|
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ class TestBranchTree(unittest.TestCase):
|
|||||||
patch.object(gc, "_process_cwds", return_value={}),
|
patch.object(gc, "_process_cwds", return_value={}),
|
||||||
patch.object(
|
patch.object(
|
||||||
tree,
|
tree,
|
||||||
"secret_service_token",
|
"_forge_access",
|
||||||
return_value=(None, "Secret Service locked"),
|
return_value=(None, "Secret Service locked"),
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
@@ -389,7 +389,7 @@ class TestBranchTree(unittest.TestCase):
|
|||||||
open_heads={},
|
open_heads={},
|
||||||
)
|
)
|
||||||
with (
|
with (
|
||||||
patch.object(tree, "secret_service_token", return_value=("t0ken", None)),
|
patch.object(tree, "_forge_access", return_value=("t0ken", None)),
|
||||||
patch.object(tree, "facts_with_token", return_value=facts) as live,
|
patch.object(tree, "facts_with_token", return_value=facts) as live,
|
||||||
):
|
):
|
||||||
first = self._by_branch(self._entry())
|
first = self._by_branch(self._entry())
|
||||||
@@ -408,7 +408,7 @@ class TestBranchTree(unittest.TestCase):
|
|||||||
(False, "Secret Service locked"),
|
(False, "Secret Service locked"),
|
||||||
)
|
)
|
||||||
self.assertEqual(data["repos"][0]["forge"], "cached")
|
self.assertEqual(data["repos"][0]["forge"], "cached")
|
||||||
with patch.object(tree, "secret_service_token", return_value=("t0ken", None)):
|
with patch.object(tree, "_forge_access", return_value=("t0ken", None)):
|
||||||
self.assertTrue(json.loads(self._tree())["delete_ready"])
|
self.assertTrue(json.loads(self._tree())["delete_ready"])
|
||||||
|
|
||||||
def test_an_unwritable_cache_keeps_the_scan_and_names_it(self) -> None:
|
def test_an_unwritable_cache_keeps_the_scan_and_names_it(self) -> None:
|
||||||
@@ -417,7 +417,7 @@ class TestBranchTree(unittest.TestCase):
|
|||||||
self._write(self.root, "cache-is-a-file", "")
|
self._write(self.root, "cache-is-a-file", "")
|
||||||
with (
|
with (
|
||||||
patch.dict(os.environ, {"XDG_CACHE_HOME": blocker}),
|
patch.dict(os.environ, {"XDG_CACHE_HOME": blocker}),
|
||||||
patch.object(tree, "secret_service_token", return_value=("t0ken", None)),
|
patch.object(tree, "_forge_access", return_value=("t0ken", None)),
|
||||||
patch.object(tree, "facts_with_token", return_value=ForgeFacts()),
|
patch.object(tree, "facts_with_token", return_value=ForgeFacts()),
|
||||||
):
|
):
|
||||||
entry = self._entry()
|
entry = self._entry()
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ class TestBranchTreeFlow(GcFixture, unittest.TestCase):
|
|||||||
patch.object(gc, "host_pid_namespace", return_value=True),
|
patch.object(gc, "host_pid_namespace", return_value=True),
|
||||||
patch.object(gc, "list_compose_containers", return_value=[]),
|
patch.object(gc, "list_compose_containers", return_value=[]),
|
||||||
patch.object(gc, "_process_cwds", return_value={}),
|
patch.object(gc, "_process_cwds", return_value={}),
|
||||||
patch.object(tree, "secret_service_token", return_value=(None, "locked")),
|
patch.object(tree, "_forge_access", return_value=(None, "locked")),
|
||||||
):
|
):
|
||||||
patcher.start()
|
patcher.start()
|
||||||
self.addCleanup(patcher.stop)
|
self.addCleanup(patcher.stop)
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ class TestInstalledVersionDegradation(unittest.TestCase):
|
|||||||
self.assertIsNone(get_installed_python_version("kpmx"))
|
self.assertIsNone(get_installed_python_version("kpmx"))
|
||||||
|
|
||||||
def test_non_json_nix_profile_output_falls_back_to_text_mode(self) -> None:
|
def test_non_json_nix_profile_output_falls_back_to_text_mode(self) -> None:
|
||||||
import pkgmgr.core.version.installed as mod
|
from pkgmgr.core.version import installed as mod
|
||||||
|
|
||||||
with (
|
with (
|
||||||
patch.object(mod.shutil, "which", return_value="/usr/bin/nix"),
|
patch.object(mod.shutil, "which", return_value="/usr/bin/nix"),
|
||||||
@@ -173,7 +173,7 @@ class TestInstalledVersionDegradation(unittest.TestCase):
|
|||||||
self.assertIsNone(mod.get_installed_nix_profile_version("pkgmgr"))
|
self.assertIsNone(mod.get_installed_nix_profile_version("pkgmgr"))
|
||||||
|
|
||||||
def test_json_list_instead_of_object_is_tolerated(self) -> None:
|
def test_json_list_instead_of_object_is_tolerated(self) -> None:
|
||||||
import pkgmgr.core.version.installed as mod
|
from pkgmgr.core.version import installed as mod
|
||||||
|
|
||||||
# Valid JSON, wrong shape: data.get() raises AttributeError on a list.
|
# Valid JSON, wrong shape: data.get() raises AttributeError on a list.
|
||||||
with (
|
with (
|
||||||
@@ -566,7 +566,7 @@ class TestReleaseFileWriteDegradation(unittest.TestCase):
|
|||||||
self.assertIn("Could not read spec file for changelog update", buf.getvalue())
|
self.assertIn("Could not read spec file for changelog update", buf.getvalue())
|
||||||
|
|
||||||
def test_unwritable_spec_changelog_is_reported(self) -> None:
|
def test_unwritable_spec_changelog_is_reported(self) -> None:
|
||||||
import pkgmgr.actions.release.files.rpm_changelog as mod
|
from pkgmgr.actions.release.files import rpm_changelog as mod
|
||||||
|
|
||||||
path = _write(
|
path = _write(
|
||||||
os.path.join(self.dir, "pkg.spec"),
|
os.path.join(self.dir, "pkg.spec"),
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import unittest
|
|||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
import pkgmgr.actions.install as install_module
|
import pkgmgr.actions.install as install_module
|
||||||
from pkgmgr.actions.install import install_repos
|
|
||||||
from pkgmgr.actions.install.installers.base import BaseInstaller
|
from pkgmgr.actions.install.installers.base import BaseInstaller
|
||||||
|
|
||||||
|
|
||||||
@@ -141,7 +140,7 @@ class TestInstallReposIntegration(unittest.TestCase):
|
|||||||
old_installers = install_module.INSTALLERS
|
old_installers = install_module.INSTALLERS
|
||||||
install_module.INSTALLERS = [DummyInstaller()]
|
install_module.INSTALLERS = [DummyInstaller()]
|
||||||
try:
|
try:
|
||||||
install_repos(
|
install_module.install_repos(
|
||||||
selected_repos=selected_repos,
|
selected_repos=selected_repos,
|
||||||
repositories_base_dir=tmp_base,
|
repositories_base_dir=tmp_base,
|
||||||
bin_dir=tmp_bin,
|
bin_dir=tmp_bin,
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ class TestIntegrationMirrorProbeDetailAndProvision(unittest.TestCase):
|
|||||||
]
|
]
|
||||||
|
|
||||||
def probe_side_effect(url: str, cwd: str = "."):
|
def probe_side_effect(url: str, cwd: str = "."):
|
||||||
if "github.com" in url:
|
if url == "git@github.com:alice/repo.git":
|
||||||
# show "empty repo reachable" note; setup_cmd prints [OK] and does not print reason for ok
|
# show "empty repo reachable" note; setup_cmd prints [OK] and does not print reason for ok
|
||||||
return (
|
return (
|
||||||
True,
|
True,
|
||||||
@@ -180,7 +180,7 @@ class TestIntegrationMirrorProbeDetailAndProvision(unittest.TestCase):
|
|||||||
]
|
]
|
||||||
|
|
||||||
def probe_side_effect(url: str, cwd: str = "."):
|
def probe_side_effect(url: str, cwd: str = "."):
|
||||||
if "github.com" in url:
|
if url == "git@github.com:alice/repo.git":
|
||||||
return True, ""
|
return True, ""
|
||||||
return False, "(exit 128) fatal: Could not read from remote repository."
|
return False, "(exit 128) fatal: Could not read from remote repository."
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ import shutil
|
|||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
from contextlib import redirect_stdout
|
from contextlib import redirect_stdout, suppress
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.release.options import ReleaseOptions
|
||||||
from pkgmgr.actions.release.retry import retry_release
|
from pkgmgr.actions.release.retry import retry_release
|
||||||
from pkgmgr.actions.release.workflow import _release_impl
|
from pkgmgr.actions.release.workflow import _release_impl
|
||||||
from pkgmgr.actions.repository.push import (
|
from pkgmgr.actions.repository.push import (
|
||||||
@@ -21,50 +22,94 @@ from pkgmgr.cli.context import CLIContext
|
|||||||
from pkgmgr.cli.parser import create_parser
|
from pkgmgr.cli.parser import create_parser
|
||||||
from pkgmgr.cli.proxy import maybe_handle_proxy
|
from pkgmgr.cli.proxy import maybe_handle_proxy
|
||||||
|
|
||||||
|
_REAL_RUN = subprocess.run
|
||||||
|
GIT = shutil.which("git")
|
||||||
|
SSH_KEYGEN = shutil.which("ssh-keygen")
|
||||||
|
|
||||||
|
|
||||||
def git(cwd: str, *args: str) -> str:
|
def git(cwd: str, *args: str) -> str:
|
||||||
return subprocess.run(
|
return _REAL_RUN(
|
||||||
["git", *args], cwd=cwd, check=True, capture_output=True, text=True
|
[GIT, *args], cwd=cwd, check=True, capture_output=True, text=True
|
||||||
).stdout.strip()
|
).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(shutil.which("ssh-keygen"), "ssh-keygen signs the commits")
|
def keygen(path: Path) -> None:
|
||||||
class TestPushMirrorLeases(unittest.TestCase):
|
_REAL_RUN(
|
||||||
|
[SSH_KEYGEN, "-q", "-t", "ed25519", "-N", "", "-f", str(path)],
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ssh_url(path: str) -> str:
|
||||||
|
return f"t@localhost:{path}"
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(GIT and SSH_KEYGEN, "git and ssh-keygen sign the commits")
|
||||||
|
class SignedRemotesCase(unittest.TestCase):
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
self._tmp = tempfile.TemporaryDirectory()
|
self._tmp = tempfile.TemporaryDirectory()
|
||||||
self.addCleanup(self._tmp.cleanup)
|
self.addCleanup(self._tmp.cleanup)
|
||||||
root = Path(os.path.realpath(self._tmp.name))
|
root = Path(os.path.realpath(self._tmp.name))
|
||||||
self.root = str(root)
|
self.root = str(root)
|
||||||
key = root / "key"
|
self.key = root / "key"
|
||||||
subprocess.run(
|
keygen(self.key)
|
||||||
["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)],
|
|
||||||
check=True,
|
|
||||||
)
|
|
||||||
(root / "allowed").write_text(f"t@example.org {(root / 'key.pub').read_text()}")
|
(root / "allowed").write_text(f"t@example.org {(root / 'key.pub').read_text()}")
|
||||||
(root / "gitconfig").write_text(
|
self.gitconfig = root / ".gitconfig"
|
||||||
|
self._write_gitconfig(root)
|
||||||
|
self.env = {
|
||||||
|
**{
|
||||||
|
key: value
|
||||||
|
for key, value in os.environ.items()
|
||||||
|
if key not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")
|
||||||
|
},
|
||||||
|
"GIT_CONFIG_GLOBAL": str(self.gitconfig),
|
||||||
|
"GIT_CONFIG_NOSYSTEM": "1",
|
||||||
|
}
|
||||||
|
for patcher in (
|
||||||
|
patch.dict(os.environ, self.env, clear=True),
|
||||||
|
patch("pkgmgr.core.git.run._passwd_home", return_value=self.root),
|
||||||
|
):
|
||||||
|
patcher.start()
|
||||||
|
self.addCleanup(patcher.stop)
|
||||||
|
self._init_remotes(root)
|
||||||
|
|
||||||
|
def _write_gitconfig(self, root: Path) -> None:
|
||||||
|
fakessh = root / "fakessh"
|
||||||
|
fakessh.write_text(
|
||||||
|
"#!/bin/sh\n"
|
||||||
|
"shift $(($# - 1))\n"
|
||||||
|
f'exec env -i PATH="$PATH" HOME={root} sh -c "$1"\n'
|
||||||
|
)
|
||||||
|
fakessh.chmod(0o755)
|
||||||
|
self.gitconfig.write_text(
|
||||||
"[user]\n\tname = t\n\temail = t@example.org\n"
|
"[user]\n\tname = t\n\temail = t@example.org\n"
|
||||||
f"\tsigningkey = {key}\n"
|
f"\tsigningkey = {self.key}\n"
|
||||||
"[gpg]\n\tformat = ssh\n"
|
"[gpg]\n\tformat = ssh\n"
|
||||||
f'[gpg "ssh"]\n\tallowedSignersFile = {root / "allowed"}\n'
|
f'[gpg "ssh"]\n\tallowedSignersFile = {root / "allowed"}\n'
|
||||||
"[commit]\n\tgpgsign = false\n"
|
"[commit]\n\tgpgsign = false\n"
|
||||||
"[init]\n\tdefaultBranch = main\n"
|
"[init]\n\tdefaultBranch = main\n"
|
||||||
|
f"[core]\n\tsshCommand = {fakessh}\n"
|
||||||
|
"[ssh]\n\tvariant = simple\n"
|
||||||
)
|
)
|
||||||
env = patch.dict(
|
|
||||||
os.environ,
|
|
||||||
{"GIT_CONFIG_GLOBAL": str(root / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1"},
|
|
||||||
)
|
|
||||||
env.start()
|
|
||||||
self.addCleanup(env.stop)
|
|
||||||
|
|
||||||
|
def _init_remotes(self, root: Path) -> None:
|
||||||
self.canonical = str(root / "canonical.git")
|
self.canonical = str(root / "canonical.git")
|
||||||
self.mirror = str(root / "mirror.git")
|
self.mirror = str(root / "mirror.git")
|
||||||
self.repo = str(root / "repo")
|
self.repo = str(root / "repo")
|
||||||
git(self.root, "init", "-q", "--bare", self.canonical)
|
git(self.root, "init", "-q", "--bare", self.canonical)
|
||||||
git(self.root, "init", "-q", "--bare", self.mirror)
|
git(self.root, "init", "-q", "--bare", self.mirror)
|
||||||
git(self.root, "init", "-q", self.repo)
|
git(self.root, "init", "-q", self.repo)
|
||||||
git(self.repo, "remote", "add", "origin", self.canonical)
|
git(self.repo, "remote", "add", "origin", ssh_url(self.canonical))
|
||||||
git(self.repo, "remote", "set-url", "--add", "--push", "origin", self.canonical)
|
for bare in (self.canonical, self.mirror):
|
||||||
git(self.repo, "remote", "set-url", "--add", "--push", "origin", self.mirror)
|
git(
|
||||||
|
self.repo,
|
||||||
|
"remote",
|
||||||
|
"set-url",
|
||||||
|
"--add",
|
||||||
|
"--push",
|
||||||
|
"origin",
|
||||||
|
ssh_url(bare),
|
||||||
|
)
|
||||||
self.init = self._commit("init")
|
self.init = self._commit("init")
|
||||||
git(self.repo, "push", "-q", self.canonical, "main")
|
git(self.repo, "push", "-q", self.canonical, "main")
|
||||||
git(self.repo, "push", "-q", self.mirror, "main")
|
git(self.repo, "push", "-q", self.mirror, "main")
|
||||||
@@ -78,6 +123,17 @@ class TestPushMirrorLeases(unittest.TestCase):
|
|||||||
git(cwd, "commit", "-q", *flags, "-m", name)
|
git(cwd, "commit", "-q", *flags, "-m", name)
|
||||||
return git(cwd, "rev-parse", "HEAD")
|
return git(cwd, "rev-parse", "HEAD")
|
||||||
|
|
||||||
|
def _tip(self, bare: str, ref: str = "refs/heads/main") -> str:
|
||||||
|
return _REAL_RUN(
|
||||||
|
[GIT, "rev-parse", "--verify", "--quiet", ref],
|
||||||
|
cwd=bare,
|
||||||
|
check=False,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
class TestPushMirrorLeases(SignedRemotesCase):
|
||||||
def _push(self, rewrite: bool = False) -> str:
|
def _push(self, rewrite: bool = False) -> str:
|
||||||
with redirect_stdout(io.StringIO()) as out:
|
with redirect_stdout(io.StringIO()) as out:
|
||||||
sign_unpushed(self.repo)
|
sign_unpushed(self.repo)
|
||||||
@@ -102,15 +158,6 @@ class TestPushMirrorLeases(unittest.TestCase):
|
|||||||
|
|
||||||
self.assertEqual(cm.exception.code, 0)
|
self.assertEqual(cm.exception.code, 0)
|
||||||
|
|
||||||
def _tip(self, bare: str, ref: str = "refs/heads/main") -> str:
|
|
||||||
return subprocess.run(
|
|
||||||
["git", "rev-parse", "--verify", "--quiet", ref],
|
|
||||||
cwd=bare,
|
|
||||||
check=False,
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
).stdout.strip()
|
|
||||||
|
|
||||||
def _assert_shipped_signed(self) -> None:
|
def _assert_shipped_signed(self) -> None:
|
||||||
head = git(self.repo, "rev-parse", "HEAD")
|
head = git(self.repo, "rev-parse", "HEAD")
|
||||||
self.assertEqual(self._tip(self.canonical), head)
|
self.assertEqual(self._tip(self.canonical), head)
|
||||||
@@ -226,7 +273,7 @@ class TestPushMirrorLeases(unittest.TestCase):
|
|||||||
git(self.repo, "fetch", "-q", "origin")
|
git(self.repo, "fetch", "-q", "origin")
|
||||||
self._commit("new")
|
self._commit("new")
|
||||||
upstream = subprocess.run(
|
upstream = subprocess.run(
|
||||||
["git", "rev-parse", "--abbrev-ref", "@{u}"],
|
[GIT, "rev-parse", "--abbrev-ref", "@{u}"],
|
||||||
cwd=self.repo,
|
cwd=self.repo,
|
||||||
check=False,
|
check=False,
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
@@ -302,12 +349,24 @@ class TestPushMirrorLeases(unittest.TestCase):
|
|||||||
head = git(self.repo, "rev-parse", "HEAD")
|
head = git(self.repo, "rev-parse", "HEAD")
|
||||||
git(self.repo, "config", "diff.ignoreSubmodules", "all")
|
git(self.repo, "config", "diff.ignoreSubmodules", "all")
|
||||||
git(self.repo, "update-index", "--add", "--cacheinfo", f"160000,{head},sub")
|
git(self.repo, "update-index", "--add", "--cacheinfo", f"160000,{head},sub")
|
||||||
|
tree = git(self.repo, "rev-parse", "HEAD^{tree}")
|
||||||
|
|
||||||
with self.assertRaises(PushRefusedError) as cm:
|
self._push()
|
||||||
self._push()
|
|
||||||
|
|
||||||
self.assertIn("staged changes", str(cm.exception))
|
self._assert_shipped_signed()
|
||||||
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), head)
|
self.assertNotEqual(git(self.repo, "rev-parse", "HEAD"), head)
|
||||||
|
self.assertEqual(git(self.repo, "rev-parse", "HEAD^{tree}"), tree)
|
||||||
|
self.assertEqual(
|
||||||
|
git(
|
||||||
|
self.repo,
|
||||||
|
"diff",
|
||||||
|
"--cached",
|
||||||
|
"--name-only",
|
||||||
|
"--ignore-submodules=none",
|
||||||
|
"HEAD",
|
||||||
|
),
|
||||||
|
"sub",
|
||||||
|
)
|
||||||
|
|
||||||
def test_unstaged_edit_stays_out_of_the_signed_head(self) -> None:
|
def test_unstaged_edit_stays_out_of_the_signed_head(self) -> None:
|
||||||
self._commit("feature")
|
self._commit("feature")
|
||||||
@@ -339,10 +398,8 @@ class TestPushMirrorLeases(unittest.TestCase):
|
|||||||
hooks_fire = marker.exists()
|
hooks_fire = marker.exists()
|
||||||
marker.unlink(missing_ok=True)
|
marker.unlink(missing_ok=True)
|
||||||
|
|
||||||
try:
|
with suppress(PushRefusedError):
|
||||||
self._push()
|
self._push()
|
||||||
except PushRefusedError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
self.assertFalse(marker.exists(), f"config hooks fire on commit: {hooks_fire}")
|
self.assertFalse(marker.exists(), f"config hooks fire on commit: {hooks_fire}")
|
||||||
|
|
||||||
@@ -364,7 +421,7 @@ class TestPushMirrorLeases(unittest.TestCase):
|
|||||||
self.assertFalse(marker.exists())
|
self.assertFalse(marker.exists())
|
||||||
|
|
||||||
def test_remote_named_like_an_option_is_pushed(self) -> None:
|
def test_remote_named_like_an_option_is_pushed(self) -> None:
|
||||||
git(self.repo, "config", "remote.-r.url", self.canonical)
|
git(self.repo, "config", "remote.-r.url", ssh_url(self.canonical))
|
||||||
git(self.repo, "config", "remote.-r.fetch", "+refs/heads/*:refs/remotes/-r/*")
|
git(self.repo, "config", "remote.-r.fetch", "+refs/heads/*:refs/remotes/-r/*")
|
||||||
git(self.repo, "config", "branch.main.pushRemote", "-r")
|
git(self.repo, "config", "branch.main.pushRemote", "-r")
|
||||||
git(self.repo, "fetch", "-q", "--", "-r")
|
git(self.repo, "fetch", "-q", "--", "-r")
|
||||||
@@ -383,7 +440,11 @@ class TestPushMirrorLeases(unittest.TestCase):
|
|||||||
|
|
||||||
with redirect_stdout(io.StringIO()), self.assertRaises(PushRefusedError):
|
with redirect_stdout(io.StringIO()), self.assertRaises(PushRefusedError):
|
||||||
_release_impl(
|
_release_impl(
|
||||||
pyproject_path=os.path.join(self.repo, "pyproject.toml"), force=True
|
ReleaseOptions(
|
||||||
|
pyproject_path=os.path.join(self.repo, "pyproject.toml"),
|
||||||
|
force=True,
|
||||||
|
expect_tree=None,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), head)
|
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), head)
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ from collections.abc import Sequence
|
|||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
import pkgmgr.actions.install as install_mod
|
import pkgmgr.actions.install as install_mod
|
||||||
from pkgmgr.actions.install import install_repos
|
|
||||||
from pkgmgr.actions.install.installers.makefile import MakefileInstaller
|
from pkgmgr.actions.install.installers.makefile import MakefileInstaller
|
||||||
from pkgmgr.actions.install.installers.nix import NixFlakeInstaller
|
from pkgmgr.actions.install.installers.nix import NixFlakeInstaller
|
||||||
from pkgmgr.actions.install.installers.os_packages.arch_pkgbuild import (
|
from pkgmgr.actions.install.installers.os_packages.arch_pkgbuild import (
|
||||||
@@ -89,7 +88,7 @@ class TestRecursiveCapabilitiesIntegration(unittest.TestCase):
|
|||||||
),
|
),
|
||||||
patch.object(install_mod, "clone_repos"),
|
patch.object(install_mod, "clone_repos"),
|
||||||
):
|
):
|
||||||
install_repos(
|
install_mod.install_repos(
|
||||||
selected_repos=selected_repos,
|
selected_repos=selected_repos,
|
||||||
repositories_base_dir=self.tmp_root,
|
repositories_base_dir=self.tmp_root,
|
||||||
bin_dir=self.bin_dir,
|
bin_dir=self.bin_dir,
|
||||||
|
|||||||
@@ -1,10 +1,21 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
from contextlib import redirect_stdout
|
||||||
|
from pathlib import Path
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.release.git_ops import ensure_clean_and_synced
|
||||||
|
from pkgmgr.cli.context import CLIContext
|
||||||
|
|
||||||
|
GIT = shutil.which("git")
|
||||||
|
|
||||||
|
|
||||||
class TestIntegrationReleasePublishHook(unittest.TestCase):
|
class TestIntegrationReleasePublishHook(unittest.TestCase):
|
||||||
def _ctx(self) -> SimpleNamespace:
|
def _ctx(self) -> SimpleNamespace:
|
||||||
@@ -65,5 +76,90 @@ class TestIntegrationReleasePublishHook(unittest.TestCase):
|
|||||||
m_publish.assert_not_called()
|
m_publish.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(GIT, "git builds the clones under test")
|
||||||
|
class TestReleaseCwdCheckout(unittest.TestCase):
|
||||||
|
def _sh(self, cwd: str, *argv: str) -> None:
|
||||||
|
subprocess.run([GIT, *argv], cwd=cwd, check=True, capture_output=True)
|
||||||
|
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self._tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self._tmp.cleanup)
|
||||||
|
base = os.path.realpath(self._tmp.name)
|
||||||
|
identity = {
|
||||||
|
f"GIT_{role}_{field}": value
|
||||||
|
for role in ("AUTHOR", "COMMITTER")
|
||||||
|
for field, value in (("NAME", "t"), ("EMAIL", "t@example.org"))
|
||||||
|
}
|
||||||
|
scrubbed = patch.dict(
|
||||||
|
os.environ,
|
||||||
|
{**identity, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"},
|
||||||
|
)
|
||||||
|
scrubbed.start()
|
||||||
|
self.addCleanup(scrubbed.stop)
|
||||||
|
self.addCleanup(os.chdir, os.getcwd())
|
||||||
|
|
||||||
|
self.main = os.path.join(base, "app")
|
||||||
|
self._sh(base, "init", "-q", "-b", "main", self.main)
|
||||||
|
Path(self.main, "app.py").write_text("v1\n")
|
||||||
|
self._sh(self.main, "add", "app.py")
|
||||||
|
self._sh(self.main, "commit", "-q", "--no-gpg-sign", "-m", "init")
|
||||||
|
self.clone = os.path.join(self.main, ".worktrees", "release")
|
||||||
|
self._sh(base, "clone", "-q", self.main, self.clone)
|
||||||
|
Path(self.main, "app.py").write_text("unfinished work\n")
|
||||||
|
self.ctx = CLIContext(
|
||||||
|
config_merged={},
|
||||||
|
repositories_base_dir=os.path.join(base, "repos"),
|
||||||
|
all_repositories=[
|
||||||
|
{
|
||||||
|
"provider": "github.com",
|
||||||
|
"account": "t",
|
||||||
|
"repository": "app",
|
||||||
|
"directory": self.main,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
binaries_dir=os.path.join(base, "bin"),
|
||||||
|
user_config_path=os.path.join(base, "config.yaml"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _released_in(self, cwd: str, *argv: str) -> str:
|
||||||
|
from pkgmgr.cli.dispatch import dispatch_command
|
||||||
|
from pkgmgr.cli.parser import create_parser
|
||||||
|
|
||||||
|
seen: list[str] = []
|
||||||
|
os.chdir(cwd)
|
||||||
|
args = create_parser("test").parse_args(["release", *argv, "--no-publish"])
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
"pkgmgr.cli.commands.release.run_release",
|
||||||
|
side_effect=lambda *_args, **_kwargs: seen.append(os.getcwd()),
|
||||||
|
),
|
||||||
|
redirect_stdout(io.StringIO()),
|
||||||
|
):
|
||||||
|
dispatch_command(args, self.ctx)
|
||||||
|
self.assertEqual(len(seen), 1)
|
||||||
|
return seen[0]
|
||||||
|
|
||||||
|
def test_release_from_a_nested_clone_runs_in_the_clone(self) -> None:
|
||||||
|
self.assertEqual(self._released_in(self.clone, "patch"), self.clone)
|
||||||
|
|
||||||
|
def test_explicit_identifier_keeps_the_configured_checkout(self) -> None:
|
||||||
|
self.assertEqual(self._released_in(self.clone, "patch", "app"), self.main)
|
||||||
|
|
||||||
|
def test_tracked_changes_refuse_the_release(self) -> None:
|
||||||
|
os.chdir(self.main)
|
||||||
|
|
||||||
|
with self.assertRaises(RuntimeError) as cm:
|
||||||
|
ensure_clean_and_synced(preview=False)
|
||||||
|
|
||||||
|
self.assertIn("app.py", str(cm.exception))
|
||||||
|
self.assertEqual(Path(self.main, "app.py").read_text(), "unfinished work\n")
|
||||||
|
|
||||||
|
def test_clean_clone_passes_the_check(self) -> None:
|
||||||
|
os.chdir(self.clone)
|
||||||
|
|
||||||
|
with redirect_stdout(io.StringIO()):
|
||||||
|
ensure_clean_and_synced(preview=False)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -14,7 +14,7 @@ class TestIntegrationReposCreatePreview(unittest.TestCase):
|
|||||||
try:
|
try:
|
||||||
repos_mod = importlib.import_module("pkgmgr.cli.commands.repos")
|
repos_mod = importlib.import_module("pkgmgr.cli.commands.repos")
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
self.skipTest(f"CLI module not available: {exc}")
|
raise unittest.SkipTest(f"CLI module not available: {exc}") from exc
|
||||||
|
|
||||||
handle = getattr(repos_mod, "handle_repos_command", None)
|
handle = getattr(repos_mod, "handle_repos_command", None)
|
||||||
if handle is None:
|
if handle is None:
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import io
|
import io
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
@@ -160,6 +161,27 @@ class TestReview(unittest.TestCase):
|
|||||||
self.assertNotIn("big 11</td>", html)
|
self.assertNotIn("big 11</td>", html)
|
||||||
self.assertIn("20 more lines not shown", html)
|
self.assertIn("20 more lines not shown", html)
|
||||||
|
|
||||||
|
def test_toolbar_buttons_are_labelled_icons(self) -> None:
|
||||||
|
html = self._render("page.html", None, [])
|
||||||
|
|
||||||
|
for key, label in (("expand", "Expand all"), ("collapse", "Collapse all")):
|
||||||
|
with self.subTest(button=key):
|
||||||
|
button = re.search(
|
||||||
|
rf'<button type="button" id="{key}-all"([^>]*)>(.*?)</button>',
|
||||||
|
html,
|
||||||
|
re.DOTALL,
|
||||||
|
)
|
||||||
|
self.assertIsNotNone(button)
|
||||||
|
attrs, inner = button.groups()
|
||||||
|
self.assertIn(f'title="{label}"', attrs)
|
||||||
|
self.assertIn(f'aria-label="{label}"', attrs)
|
||||||
|
self.assertRegex(
|
||||||
|
inner, rf'^<svg class="bi bi-arrows-{key}"[^>]* aria-hidden="true"'
|
||||||
|
)
|
||||||
|
self.assertEqual(re.sub(r"<[^>]+>", "", inner).strip(), "")
|
||||||
|
self.assertNotIn("<link", html)
|
||||||
|
self.assertNotIn("<img", html)
|
||||||
|
|
||||||
def test_errors_exit_two(self) -> None:
|
def test_errors_exit_two(self) -> None:
|
||||||
plain = os.path.join(self.root, "plain")
|
plain = os.path.join(self.root, "plain")
|
||||||
os.makedirs(plain)
|
os.makedirs(plain)
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ class ReviewRepoCase(unittest.TestCase):
|
|||||||
|
|
||||||
def _trap(self, path: str, tail: str) -> str:
|
def _trap(self, path: str, tail: str) -> str:
|
||||||
write(path, f"#!/bin/sh\ntouch '{self.marker}'\n{tail}\n".encode())
|
write(path, f"#!/bin/sh\ntouch '{self.marker}'\n{tail}\n".encode())
|
||||||
os.chmod(path, 0o755)
|
os.chmod(path, 0o700)
|
||||||
return path
|
return path
|
||||||
|
|
||||||
def _assert_fires(self, *args: str) -> None:
|
def _assert_fires(self, *args: str) -> None:
|
||||||
|
|||||||
@@ -331,7 +331,7 @@ class TestWorktreeUp(WorktreeFixture, unittest.TestCase):
|
|||||||
script = os.path.join(self.repo, name)
|
script = os.path.join(self.repo, name)
|
||||||
with open(script, "w") as fh:
|
with open(script, "w") as fh:
|
||||||
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
||||||
os.chmod(script, 0o755)
|
os.chmod(script, 0o700)
|
||||||
git(self.repo, "add", name)
|
git(self.repo, "add", name)
|
||||||
git(self.repo, "commit", "-m", name)
|
git(self.repo, "commit", "-m", name)
|
||||||
git(self.repo, "push", "origin", "main")
|
git(self.repo, "push", "origin", "main")
|
||||||
@@ -370,7 +370,7 @@ class TestWorktreeUp(WorktreeFixture, unittest.TestCase):
|
|||||||
fake = os.path.join(planted, "true")
|
fake = os.path.join(planted, "true")
|
||||||
with open(fake, "w") as fh:
|
with open(fake, "w") as fh:
|
||||||
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
fh.write(f"#!/bin/sh\ntouch {marker}\n")
|
||||||
os.chmod(fake, 0o755)
|
os.chmod(fake, 0o700)
|
||||||
if os.getuid() == 0:
|
if os.getuid() == 0:
|
||||||
os.chown(planted, 65534, 65534)
|
os.chown(planted, 65534, 65534)
|
||||||
os.chown(fake, 65534, 65534)
|
os.chown(fake, 65534, 65534)
|
||||||
|
|||||||
Whitespace-only changes.
@@ -0,0 +1,81 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
AUTHOR = {
|
||||||
|
"GIT_AUTHOR_NAME": "t",
|
||||||
|
"GIT_AUTHOR_EMAIL": "t@example.org",
|
||||||
|
"GIT_COMMITTER_NAME": "t",
|
||||||
|
"GIT_COMMITTER_EMAIL": "t@example.org",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def git(cwd: str, *args: str) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
cwd: the repository to run in.
|
||||||
|
args: the git arguments; signing stays off and AUTHOR applies.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The stripped standard output.
|
||||||
|
"""
|
||||||
|
return subprocess.run(
|
||||||
|
["git", "-c", "commit.gpgsign=false", *args],
|
||||||
|
cwd=cwd,
|
||||||
|
env={**os.environ, **AUTHOR},
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def origin_and_repo(root: str) -> tuple[str, str]:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
root: the directory that holds both repositories.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The paths of the bare `origin.git` and of `repo`, whose `main`
|
||||||
|
tracks origin and carries one pushed commit adding `init.txt`.
|
||||||
|
"""
|
||||||
|
origin = os.path.join(root, "origin.git")
|
||||||
|
repo = os.path.join(root, "repo")
|
||||||
|
git(root, "init", "--bare", "-b", "main", origin)
|
||||||
|
git(root, "init", "-b", "main", repo)
|
||||||
|
git(repo, "remote", "add", "origin", origin)
|
||||||
|
with open(os.path.join(repo, "init.txt"), "w") as fh:
|
||||||
|
fh.write("init")
|
||||||
|
git(repo, "add", "init.txt")
|
||||||
|
git(repo, "commit", "-m", "init")
|
||||||
|
git(repo, "push", "-u", "origin", "main")
|
||||||
|
return origin, repo
|
||||||
|
|
||||||
|
|
||||||
|
def isolated_root(case: unittest.TestCase, env: dict[str, str]) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
case: the test whose cleanups remove the directory and restore the
|
||||||
|
working directory and environment.
|
||||||
|
env: variables set over the environment, from which every GIT_*
|
||||||
|
variable is dropped.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The realpath of a fresh temporary directory, now the working
|
||||||
|
directory, whose empty `home` child is HOME.
|
||||||
|
"""
|
||||||
|
scratch = tempfile.TemporaryDirectory()
|
||||||
|
case.addCleanup(scratch.cleanup)
|
||||||
|
root = os.path.realpath(scratch.name)
|
||||||
|
case.addCleanup(os.chdir, os.getcwd())
|
||||||
|
os.chdir(root)
|
||||||
|
home = os.path.join(root, "home")
|
||||||
|
os.makedirs(home)
|
||||||
|
kept = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
||||||
|
environ = patch.dict(os.environ, {**kept, **env, "HOME": home}, clear=True)
|
||||||
|
environ.start()
|
||||||
|
case.addCleanup(environ.stop)
|
||||||
|
return root
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import unittest
|
||||||
|
from contextlib import ExitStack, redirect_stderr, redirect_stdout
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch import gc
|
||||||
|
from pkgmgr.core.git import run
|
||||||
|
from tests.support.git_sandbox import AUTHOR, isolated_root
|
||||||
|
|
||||||
|
MERGED = 12
|
||||||
|
REGISTRATIONS = 40
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(shutil.which("git"), "git builds the repository under test")
|
||||||
|
class TestHeldBranchesReadOnce(unittest.TestCase):
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.root = isolated_root(self, AUTHOR)
|
||||||
|
self.repo = os.path.join(self.root, "repo")
|
||||||
|
self._shape()
|
||||||
|
|
||||||
|
def git(self, *args: str) -> str:
|
||||||
|
return run(["-c", "commit.gpgsign=false", *args], cwd=self.repo)
|
||||||
|
|
||||||
|
def _write(self, path: str, text: str) -> None:
|
||||||
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(text)
|
||||||
|
|
||||||
|
def _shape(self) -> None:
|
||||||
|
origin = os.path.join(self.root, "origin.git")
|
||||||
|
run(["init", "-q", "--bare", "-b", "main", origin], cwd=self.root)
|
||||||
|
run(["init", "-q", "-b", "main", self.repo], cwd=self.root)
|
||||||
|
self.git("remote", "add", "origin", origin)
|
||||||
|
self._write(os.path.join(self.repo, "c1"), "c1")
|
||||||
|
self.git("add", "c1")
|
||||||
|
self.git("commit", "-q", "-m", "c1")
|
||||||
|
self.git("checkout", "-q", "-b", "side")
|
||||||
|
self._write(os.path.join(self.repo, "f1"), "f1")
|
||||||
|
self.git("add", "f1")
|
||||||
|
self.git("commit", "-q", "-m", "f1")
|
||||||
|
f1 = self.git("rev-parse", "HEAD")
|
||||||
|
self.git("checkout", "-q", "main")
|
||||||
|
self.git("merge", "-q", "--no-ff", "-m", "m1", "side")
|
||||||
|
self.git("branch", "-q", "-D", "side")
|
||||||
|
self.git("push", "-q", "origin", "main")
|
||||||
|
self.git("fetch", "-q", "origin")
|
||||||
|
self.git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main")
|
||||||
|
for index in range(MERGED):
|
||||||
|
self.git("branch", f"merged-{index:03d}", f1)
|
||||||
|
self.git("symbolic-ref", "refs/heads/alias", "refs/heads/merged-001")
|
||||||
|
base = os.path.join(self.repo, ".git", "worktrees")
|
||||||
|
for index in range(REGISTRATIONS):
|
||||||
|
reg = os.path.join(base, f"wt{index:03d}")
|
||||||
|
head = "ref: refs/heads/merged-002\n" if index == 7 else f"{f1}\n"
|
||||||
|
self._write(os.path.join(reg, "HEAD"), head)
|
||||||
|
self._write(os.path.join(reg, "commondir"), "../..\n")
|
||||||
|
self._write(
|
||||||
|
os.path.join(reg, "gitdir"), f"{self.root}/gone/wt{index:03d}/.git\n"
|
||||||
|
)
|
||||||
|
self._write(
|
||||||
|
os.path.join(base, "wt011", "rebase-merge", "head-name"),
|
||||||
|
"refs/heads/merged-003\n",
|
||||||
|
)
|
||||||
|
self._write(os.path.join(self.repo, ".git", "BISECT_START"), "merged-004\n")
|
||||||
|
|
||||||
|
def _run(self, *, cached: bool, apply: bool) -> tuple[dict, int]:
|
||||||
|
out = io.StringIO()
|
||||||
|
with ExitStack() as stack:
|
||||||
|
held = stack.enter_context(
|
||||||
|
patch.object(gc, "_held_branches", wraps=gc._held_branches)
|
||||||
|
)
|
||||||
|
if not cached:
|
||||||
|
stack.enter_context(
|
||||||
|
patch.object(gc, "cache", side_effect=lambda func: func)
|
||||||
|
)
|
||||||
|
stack.enter_context(
|
||||||
|
patch.object(gc, "host_pid_namespace", return_value=True)
|
||||||
|
)
|
||||||
|
stack.enter_context(patch.object(gc, "_process_cwds", return_value={}))
|
||||||
|
stack.enter_context(redirect_stdout(out))
|
||||||
|
stack.enter_context(redirect_stderr(io.StringIO()))
|
||||||
|
code = gc.cleanup(
|
||||||
|
[self.repo],
|
||||||
|
scope="local",
|
||||||
|
apply=apply,
|
||||||
|
as_json=True,
|
||||||
|
include=[],
|
||||||
|
exclude=[],
|
||||||
|
merged_into=[],
|
||||||
|
sizes=False,
|
||||||
|
min_age=None,
|
||||||
|
hooks={},
|
||||||
|
)
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
return json.loads(out.getvalue()), held.call_count
|
||||||
|
|
||||||
|
def _items(self, plan: dict) -> dict:
|
||||||
|
return {i["branch"]: i for i in plan["repos"][0]["items"]}
|
||||||
|
|
||||||
|
def test_one_read_gives_the_plan_of_one_read_per_branch(self) -> None:
|
||||||
|
per_branch, old_reads = self._run(cached=False, apply=False)
|
||||||
|
once, new_reads = self._run(cached=True, apply=False)
|
||||||
|
|
||||||
|
self.assertEqual(once, per_branch)
|
||||||
|
self.assertEqual(new_reads, 1)
|
||||||
|
self.assertGreaterEqual(old_reads, MERGED - 1)
|
||||||
|
items = self._items(once)
|
||||||
|
self.assertIn("symbolic ref", items["alias"]["skip"])
|
||||||
|
self.assertIn("target of symbolic ref", items["merged-001"]["skip"])
|
||||||
|
self.assertIn("checked out in", items["merged-002"]["skip"])
|
||||||
|
self.assertIn("rebase in progress", items["merged-003"]["skip"])
|
||||||
|
self.assertIn("bisect in progress", items["merged-004"]["skip"])
|
||||||
|
deletable = sorted(n for n, i in items.items() if i["actions"])
|
||||||
|
free = [0, *range(5, MERGED)]
|
||||||
|
self.assertEqual(deletable, [f"merged-{i:03d}" for i in free])
|
||||||
|
|
||||||
|
def test_branch_held_after_the_plan_is_not_deleted(self) -> None:
|
||||||
|
rebuilt: list[str] = []
|
||||||
|
rebuild = gc._rebuild
|
||||||
|
|
||||||
|
def pin_before_first_recheck(*args: object) -> object:
|
||||||
|
if not rebuilt:
|
||||||
|
rebuilt.append(
|
||||||
|
self.git("symbolic-ref", "refs/tags/pin", "refs/heads/merged-005")
|
||||||
|
)
|
||||||
|
return rebuild(*args)
|
||||||
|
|
||||||
|
with patch.object(gc, "_rebuild", side_effect=pin_before_first_recheck):
|
||||||
|
plan, reads = self._run(cached=True, apply=True)
|
||||||
|
|
||||||
|
items = self._items(plan)
|
||||||
|
self.assertGreater(reads, 1)
|
||||||
|
self.assertEqual(
|
||||||
|
items["merged-005"]["result"],
|
||||||
|
"skipped: changed since plan (target of symbolic ref refs/tags/pin)",
|
||||||
|
)
|
||||||
|
self.assertIn("merged-005", self.git("for-each-ref", "refs/heads"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import unittest
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch import gc
|
||||||
|
|
||||||
|
SHA = "a" * 40
|
||||||
|
|
||||||
|
|
||||||
|
def _repo(merged_heads: dict[str, int]) -> SimpleNamespace:
|
||||||
|
return SimpleNamespace(
|
||||||
|
first_parent=set(),
|
||||||
|
default="origin/main",
|
||||||
|
repo="/repo",
|
||||||
|
forge=SimpleNamespace(merged_heads=merged_heads),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestMergedByOrder(unittest.TestCase):
|
||||||
|
def _merged_by(self, *, line, patch_merged, merged_heads):
|
||||||
|
with (
|
||||||
|
patch.object(gc, "_is_ancestor", return_value=False),
|
||||||
|
patch.object(gc, "_in_line", return_value=line),
|
||||||
|
patch.object(gc, "_patch_merged", return_value=patch_merged),
|
||||||
|
):
|
||||||
|
return gc._merged_by(_repo(merged_heads), SHA)
|
||||||
|
|
||||||
|
def test_line_wins_over_forge(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self._merged_by(line="release", patch_merged=False, merged_heads={SHA: 7}),
|
||||||
|
"line:release",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_patch_wins_over_forge(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self._merged_by(line=None, patch_merged=True, merged_heads={SHA: 7}),
|
||||||
|
"patch",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_forge_only_when_git_has_no_evidence(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self._merged_by(line=None, patch_merged=False, merged_heads={SHA: 7}),
|
||||||
|
"pr#7",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unmerged_without_any_evidence(self):
|
||||||
|
self.assertIsNone(
|
||||||
|
self._merged_by(line=None, patch_merged=False, merged_heads={})
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from contextlib import redirect_stderr, redirect_stdout
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from pkgmgr.actions.branch import gc, gc_forge
|
||||||
|
from pkgmgr.actions.branch.gc_forge import ForgeFacts
|
||||||
|
from pkgmgr.core.credentials.types import NoCredentialsError
|
||||||
|
from tests.integration.test_branch_gc import GcFixture
|
||||||
|
from tests.support.git_sandbox import git
|
||||||
|
|
||||||
|
GITHUB_URL = "https://github.com/example/demo.git"
|
||||||
|
|
||||||
|
|
||||||
|
class TestBranchGcPlan(GcFixture, unittest.TestCase):
|
||||||
|
def test_classifies_every_branch(self) -> None:
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["main"].state, "protected")
|
||||||
|
self.assertEqual(items["merged"].state, "merged-clean")
|
||||||
|
self.assertEqual(items["merged"].merged_by, "ancestor")
|
||||||
|
self.assertEqual(
|
||||||
|
items["merged"].actions,
|
||||||
|
["worktree", "local-branch", "remote-branch:origin"],
|
||||||
|
)
|
||||||
|
self.assertTrue(items["merged"].eligible)
|
||||||
|
self.assertEqual(items["squashed"].merged_by, "pr#7")
|
||||||
|
self.assertTrue(items["squashed"].eligible)
|
||||||
|
self.assertEqual(items["fresh"].state, "unmerged")
|
||||||
|
self.assertEqual(items["fresh"].reason, "no own commits")
|
||||||
|
self.assertEqual(items["wip"].state, "unmerged")
|
||||||
|
self.assertEqual(items["wip"].skip, "open-pr #3")
|
||||||
|
self.assertEqual(items["dirty"].state, "dirty")
|
||||||
|
|
||||||
|
def test_merged_into_counts_commits_in_an_integration_line(self) -> None:
|
||||||
|
self._integration_line()
|
||||||
|
before = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
self.assertEqual(before["feat"].state, "unmerged")
|
||||||
|
self.assertIsNone(before["feat"].merged_into)
|
||||||
|
|
||||||
|
for ref in ("line", "origin/line"):
|
||||||
|
with self.subTest(ref=ref):
|
||||||
|
items = self._items(
|
||||||
|
self._plan(host_ns=True, cwds={}, merged_into=[ref])
|
||||||
|
)
|
||||||
|
self.assertEqual(items["feat"].state, "merged-clean")
|
||||||
|
self.assertEqual(items["feat"].merged_by, f"line:{ref}")
|
||||||
|
self.assertEqual(items["feat"].merged_into, ref)
|
||||||
|
self.assertTrue(items["feat"].eligible)
|
||||||
|
self.assertEqual(items["line"].state, "protected")
|
||||||
|
self.assertEqual(items["start"].state, "unmerged")
|
||||||
|
self.assertEqual(items["merged"].merged_into, "origin/main")
|
||||||
|
|
||||||
|
def test_unknown_merged_into_ref_is_a_warning(self) -> None:
|
||||||
|
plan = self._plan(host_ns=True, cwds={}, merged_into=["no-such-line"])
|
||||||
|
|
||||||
|
self.assertIn("merged-into ref no-such-line not found", plan.warnings)
|
||||||
|
self.assertEqual(self._items(plan)["merged"].state, "merged-clean")
|
||||||
|
|
||||||
|
def test_sizes_and_min_age(self) -> None:
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}, sizes=True))
|
||||||
|
self.assertGreater(items["merged"].size_bytes, 0)
|
||||||
|
self.assertIsNone(items["squashed"].size_bytes)
|
||||||
|
self.assertIn("size ", gc._line(items["merged"]))
|
||||||
|
|
||||||
|
young = self._items(self._plan(host_ns=True, cwds={}, min_age=1000))
|
||||||
|
self.assertEqual(young["merged"].skip, "younger than 1000 h")
|
||||||
|
self.assertFalse(young["merged"].eligible)
|
||||||
|
old = self._items(self._plan(host_ns=True, cwds={}, min_age=0))
|
||||||
|
self.assertIsNone(old["merged"].skip)
|
||||||
|
|
||||||
|
def test_busy_worktree_is_skipped(self) -> None:
|
||||||
|
cwds = {4242: os.path.join(self.merged_wt, "sub")}
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds=cwds))
|
||||||
|
|
||||||
|
self.assertTrue(items["merged"].skip.startswith("process: pid 4242"))
|
||||||
|
self.assertFalse(items["merged"].eligible)
|
||||||
|
|
||||||
|
def test_lock_with_live_pid_is_skipped(self) -> None:
|
||||||
|
self._lock(f"claude agent x (pid {os.getpid()} on host)")
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["locked"].skip, f"lock: pid {os.getpid()} alive")
|
||||||
|
|
||||||
|
def test_lock_with_dead_pid_is_overridden(self) -> None:
|
||||||
|
self._lock("claude agent x (pid 999999999 on host)")
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertIsNone(items["locked"].skip)
|
||||||
|
self.assertTrue(items["locked"].eligible)
|
||||||
|
|
||||||
|
def test_lock_outside_host_namespace_is_unknown(self) -> None:
|
||||||
|
self._lock("claude agent x (pid 999999999 on host)")
|
||||||
|
items = self._items(self._plan(host_ns=False, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["locked"].skip, "lock: liveness unknown")
|
||||||
|
|
||||||
|
def test_lock_without_pid_is_respected(self) -> None:
|
||||||
|
self._lock("manual hold")
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["locked"].skip, "lock: manual hold")
|
||||||
|
|
||||||
|
def test_forge_unavailable_skips_everything(self) -> None:
|
||||||
|
self.forge = ForgeFacts(unavailable="no GitHub token")
|
||||||
|
items = self._items(self._plan(host_ns=True, cwds={}))
|
||||||
|
|
||||||
|
self.assertEqual(items["merged"].skip, "forge unavailable")
|
||||||
|
self.assertIsNone(items["squashed"].merged_by)
|
||||||
|
|
||||||
|
def _github_without_token(self) -> None:
|
||||||
|
git(self.repo, "branch", "local-done", "merged")
|
||||||
|
git(self.repo, "checkout", "-b", "local-wip", "main")
|
||||||
|
self._commit("local-wip")
|
||||||
|
git(self.repo, "checkout", "main")
|
||||||
|
git(self.repo, "branch", "--track", "tracked", "origin/merged")
|
||||||
|
git(self.repo, "push", "origin", "merged:refs/heads/remote-done")
|
||||||
|
git(self.repo, "remote", "set-url", "origin", GITHUB_URL)
|
||||||
|
|
||||||
|
def _cleanup_without_token(self, apply: bool) -> tuple[int, dict]:
|
||||||
|
out = io.StringIO()
|
||||||
|
with (
|
||||||
|
patch.dict(os.environ, {"GIT_ALLOW_PROTOCOL": "file"}),
|
||||||
|
patch.object(gc, "host_pid_namespace", return_value=True),
|
||||||
|
patch.object(gc, "list_compose_containers", return_value=[]),
|
||||||
|
patch.object(gc, "_process_cwds", return_value={}),
|
||||||
|
patch.object(gc, "_docker", return_value=""),
|
||||||
|
patch.object(gc_forge, "TokenResolver") as resolver,
|
||||||
|
patch.object(gc_forge, "HttpClient") as http,
|
||||||
|
redirect_stdout(out),
|
||||||
|
redirect_stderr(io.StringIO()),
|
||||||
|
):
|
||||||
|
resolver.return_value.get_token.side_effect = NoCredentialsError("none")
|
||||||
|
code = gc.cleanup(
|
||||||
|
[self.repo],
|
||||||
|
scope="branch",
|
||||||
|
apply=apply,
|
||||||
|
as_json=True,
|
||||||
|
include=[],
|
||||||
|
exclude=[],
|
||||||
|
merged_into=[],
|
||||||
|
sizes=False,
|
||||||
|
min_age=None,
|
||||||
|
hooks={},
|
||||||
|
)
|
||||||
|
resolver.return_value.get_token.assert_called_once()
|
||||||
|
http.assert_not_called()
|
||||||
|
return code, json.loads(out.getvalue())["repos"][0]
|
||||||
|
|
||||||
|
def test_local_only_merged_branch_needs_no_forge(self) -> None:
|
||||||
|
self._github_without_token()
|
||||||
|
code, plan = self._cleanup_without_token(apply=False)
|
||||||
|
items = {i["branch"]: i for i in plan["items"] if i["branch"]}
|
||||||
|
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
self.assertIn("forge unavailable: no GitHub token (none)", plan["warnings"])
|
||||||
|
self.assertIsNone(items["local-done"]["skip"])
|
||||||
|
self.assertEqual(items["local-done"]["merged_by"], "ancestor")
|
||||||
|
self.assertEqual(items["local-done"]["actions"], ["local-branch"])
|
||||||
|
self.assertEqual(items["remote-done"]["state"], "merged-clean")
|
||||||
|
self.assertEqual(items["tracked"]["state"], "merged-clean")
|
||||||
|
self.assertEqual(items["local-wip"]["state"], "unmerged")
|
||||||
|
for name in ("merged", "remote-done", "tracked", "local-wip", "squashed"):
|
||||||
|
with self.subTest(branch=name):
|
||||||
|
self.assertEqual(items[name]["skip"], "forge unavailable")
|
||||||
|
|
||||||
|
def test_apply_without_token_deletes_only_the_local_only_merged_branch(
|
||||||
|
self,
|
||||||
|
) -> None:
|
||||||
|
self._github_without_token()
|
||||||
|
before = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
||||||
|
code, plan = self._cleanup_without_token(apply=True)
|
||||||
|
after = set(git(self.repo, "for-each-ref", "--format=%(refname)").split())
|
||||||
|
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
self.assertEqual(
|
||||||
|
[(i["branch"], i["result"]) for i in plan["items"] if i["result"]],
|
||||||
|
[("local-done", "done")],
|
||||||
|
)
|
||||||
|
self.assertEqual(before - after, {"refs/heads/local-done"})
|
||||||
|
self.assertEqual(after - before, set())
|
||||||
|
self.assertEqual(
|
||||||
|
git(self.origin, "branch", "--list", "remote-done"), "remote-done"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_stale_metadata_is_listed_not_pruned(self) -> None:
|
||||||
|
stub = os.path.join(self.repo, ".git", "worktrees", "stub")
|
||||||
|
os.makedirs(stub)
|
||||||
|
open(os.path.join(stub, "commondir"), "w").close()
|
||||||
|
plan = self._plan(host_ns=True, cwds={})
|
||||||
|
|
||||||
|
stale = [i for i in plan.items if i.state == "stale"]
|
||||||
|
self.assertEqual([i.worktree for i in stale], [stub])
|
||||||
|
self.assertTrue(os.path.isdir(stub))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user