Metadata-Version: 2.5
Name: repoutils
Version: 0.5.3
Summary: Repository tooling for Python projects that use uv, just and GitHub Actions
Project-URL: Repository, https://github.com/sjktools/repoutils
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# repoutils

`repoutils` is a package of repository checks and CI helper commands for Python projects that use `uv`, `just` and GitHub Actions.
Run a command as `repoutils <command>`.

These checks and helper commands previously lived in the `scripts/` directories of several personal projects, such as [exolot](https://github.com/skissane/exolot).
This package collects them in one place so that each project can depend on one package instead of maintaining separate copies.

`repoutils` has no runtime dependencies and uses only the Python standard library (Python 3.12 or later).
It should keep zero dependencies because projects run it in CI jobs that hold write-capable tokens or check out untrusted Dependabot branches.
Those CI jobs should not install any other packages.

## Installing

Put `repoutils` in a separate dependency group in `pyproject.toml`, and include that group in `dev`:

```toml
[dependency-groups]
repoutils = ["repoutils>=0.1.0"]
dev = [{ include-group = "repoutils" }, "pytest>=9"]
```

Run a command with `uv run repoutils <command>`.
In a CI job with a write-capable token, run `uv run --only-group repoutils repoutils <command>` instead.
That command installs only `repoutils`, verifies its hashes against `uv.lock`, and does not install the project or other dependencies.

## Commands

Run `repoutils --help` to list all commands, and run `repoutils <command> --help` to show the options for one command.

| Command | What it does |
| --- | --- |
| `check-whitespace` | Fails on trailing whitespace, a leading blank line, or a missing or extra final newline in any Git-tracked text file. |
| `check-sentence-per-line` | Fails if a Markdown file has two sentences on one line. It reads the files named on the command line, or else the configured files (by default `AGENTS.md` and `README.md`). |
| `check-doubled-spaces` | Fails if the prose in a Markdown file has two or more spaces between words, and with `--fix`, makes each of them one space. It reads the files named on the command line, or else the configured files (by default `AGENTS.md` and `README.md`). |
| `check-prose` | Fails if the prose in a configured Markdown file has long sentences, many joined clauses, or too many short sentences. |
| `check-blame-ignore-revs` | Fails unless `.git-blame-ignore-revs` lists only full commit hashes that are ancestors of a target commit. |
| `check-screenshots-dir` | Fails unless `.gitignore` is the only tracked file in the screenshots directory and ignores all other files in that directory. |
| `git-config-setup` | Sets the local `blame.ignoreRevsFile` Git setting (idempotent, so a justfile can run it before every recipe). |
| `long-files` | Lists the files over a line limit as Markdown (with changed files first), or posts that list to a pull request. |
| `check-justfile` | Fails unless the justfile has the standard recipes for the features of the project, and `check`, `fix`, `ci` and `patch-coverage` run the standard recipes that they depend on (see [Justfile](#justfile)). |
| `ruff-check` | Runs `ruff check --no-cache` with the arguments you give it, and fails if `ruff` fails or gives any warning, such as for an invalid `noqa` directive, which `ruff` only warns about. It runs the `ruff` on `PATH`, such as the one in the dev dependency group of the project under `uv run`. |
| `check-pins` | Fails unless every `setup-uv` and `setup-just` workflow step pins the versions required by `pyproject.toml` and the justfile (see [Pinning uv and just](#pinning-uv-and-just)), and the actions that the project uses from the repository of a locked package that is installed come from the commit of that package, or only from the tag of its version if the package does not record its commit (see [Checking actions against a locked package](#checking-actions-against-a-locked-package)). |
| `check-checkout-credentials` | Fails on any `actions/checkout` step that does not set `persist-credentials`. |
| `autofix` | Starts the PR Fixes workflow on a pull request, waits for the workflow that pushes its fixes, and prints the new head commit of the branch. `autofix resolve` and `autofix check-branch` make the checks of the two workflows (see [Running PR Fixes with a command](#running-pr-fixes-with-a-command)). |
| `testpypi` | Starts the Publish workflow on the branch of a pull request, which publishes a dev version of the branch to TestPyPI, and prints the link to the run (see [Starting a TestPyPI release with a command](#starting-a-testpypi-release-with-a-command)). |
| `push-bundle` | Fetches the head of a Git bundle, checks that it adds commits to a start commit and, optionally, that it changes only the paths you allow, and pushes it to a branch with a lease on the start commit (see [Pushing a Git bundle](#pushing-a-git-bundle)). |
| `bump-version` | Bumps `[project] version` in `pyproject.toml` by one patch, minor or major level, and the entry of the project in `uv.lock` to match, without running `uv`. With `--dev <N>`, it bumps both to a dev version of the new version, numbered `N`, such as `0.4.1.devN`. With `--pr`, it opens a pull request into the default branch, unless one for that version is already open (see [Bumping the version](#bumping-the-version)). |
| `release-tag` | `push` tags the checked-out commit `v<version>`, with the version from `pyproject.toml`, and pushes the tag over SSH with a deploy key, unless the tag exists. `release` creates the GitHub release for the tag, unless it exists (see [Tagging a release](#tagging-a-release)). |
| `claude-route` | Reads a comment from standard input and prints `review`, `other` or `none` to route between the Claude workflows. |
| `requirements-min-versions` | Checks or updates the `>=` minimum versions in `pyproject.toml` to match the versions in `uv.lock`. |
| `dependabot-relock` | Re-locks `uv.lock` on a Dependabot branch with the current `uv` version, using the exact package versions from Dependabot. |
| `check-lock-platforms` | Fails if `uv.lock` contains wheels for platforms that the project does not allow. |
| `dependabot-uv` | `show` prints the `uv` version from the newest successful Dependabot `uv` update run, `check` fails unless the minimum in `[tool.uv] required-version` is that version, and `bump` changes the project to that `uv` version (with `--pr`, in a new pull request, unless one for that version is already open). |
| `downstream` | `list` checks the downstream repositories that a variable names, and prints them as JSON for a job matrix. `plan` also works out the version that a run of the workflow bumps to, from the event that started the run. `bump` changes the pins of a downstream project to a release of this package, or to a dev version on TestPyPI, and re-locks it, and moves its uses of the actions of this package to the tag of the release, or for a dev version, to the commit that `--commit` names. With `--pr`, it opens a pull request (for a dev version, a draft test pull request), unless one for that release or a newer one is already open, and closes or comments on open pull requests for earlier versions of the same kind (releases, or dev versions), unless one for a newer version of that kind is open. `finish` waits for the checks on the pull request, and re-runs failed jobs. It closes the test pull request of a dev version if all its checks pass, and leaves the pull request of a release open. |
| `github-releases` | `check` fails if a project whose release assets this project pins has a newer release, and `bump` pins the assets of that release (with `--pr`, in a new pull request, unless one for that release is already open). |
| `post-comment` | Posts a Markdown file to a pull request, and edits the previous comment (posting nothing with `--update-only` when none exists) or hides it when you pass `--hide-previous`. |
| `added-strings` | Lists the added lines in a pull request that match strings configured in `pyproject.toml` (such as `# noqa:`), or posts the list to the pull request. |
| `post-patch-coverage` | Formats the Markdown patch coverage report from `diff-cover`, adds the project coverage and the change from the base commit, posts the report to a pull request, and warns when coverage drops or falls below a limit. |
| `post-coverage-status` | Posts the project and patch coverage of a commit as GitHub commit statuses for information only. |
| `wait-for-base-coverage` | Waits until the base commit of a pull request has a `coverage/project` commit status so that `post-patch-coverage` can compare coverage. |
| `post-screenshots` | Uploads PNG files from a directory and posts them to a pull request in a comment. |
| `recreate-pr` | Recreates a pull request as a draft from the same branch and closes the original pull request. |
| `github-settings` | Runs `check`, `ensure` or `dump` across all GitHub settings commands below. `check` and `ensure` skip commands not configured in `pyproject.toml`, and `dump` runs all commands. |
| `labels` | Checks or creates the issue labels defined in `pyproject.toml`, or prints the labels that exist in the repository. |
| `repo-settings` | Checks or updates the repository settings defined in `pyproject.toml`, or prints the current settings of the repository. |
| `rulesets` | Checks, creates or updates the branch and tag rulesets defined in `pyproject.toml`, or prints the current rulesets of the repository. |
| `environments` | Checks, creates or updates the deployment environments defined in `pyproject.toml`, or prints the current environments of the repository. |
| `actions-settings` | Checks or updates the GitHub Actions settings defined in `pyproject.toml`, or prints the current settings of the repository. |
| `secrets` | Checks that the repository has the Actions, Dependabot and environment secrets listed in `pyproject.toml`, or prints the secret names in the repository. Also checks that workflows use only those secrets, inspects token secrets in a workflow (or starts that workflow and prints its report), or exports secret values encrypted with `age` (or starts that workflow and decrypts its backup). |
| `variables` | Checks that the repository has the Actions and environment variables listed in `pyproject.toml` with non-empty values, or prints the variable names in the repository. Also checks that workflows use only those variables. |
| `deploy-keys` | Checks or creates the deploy keys declared in `pyproject.toml` and the secrets that store their private keys, or prints the deploy keys in the repository. |
| `security-settings` | Checks or updates the security settings defined in `pyproject.toml` (such as secret protection), or prints the current security settings of the repository. |
| `check-attestations` | Fails unless every distribution file in `dist/` has a PEP 740 publish attestation. |
| `check-install` | Installs a wheel (`--wheel`) or a released version from an index (`--version`) in an isolated environment, and fails unless it has the `build_info.json` file that the `repoutils-build-info` hook writes, with a commit (see [Recording the build commit](#recording-the-commit-in-a-build)). For a wheel, the commit must be the commit of the checkout, and the file must say whether the checkout has uncommitted changes. For a released version, the command retries while the installation fails, such as while the index does not yet serve the version, and also while a command that it runs exits with a non-zero code, as each one installs the version again, unless another command gives the wrong output. The package needs no command, but for a package with one, `--version-line` requires its `--version` output to give the version and commit as `repoutils --version` does, each `--run` runs it, which must exit with code `0`, and each `--run-with-commit` also requires its output to give the whole commit. |
| `version` | Prints the version of repoutils, the Git commit it was built from, where it is installed, and the Python version. When repoutils runs from a source checkout, it reads the version from `pyproject.toml` and the commit from Git. |

These commands require a GitHub token:

- any command that posts to a pull request, and `post-coverage-status`
- the `github-settings`, `labels`, `repo-settings`, `actions-settings`, `rulesets`, `environments`, `secrets`, `variables`, `deploy-keys`, `security-settings`, `dependabot-uv`, `github-releases`, `autofix` and `testpypi` commands
- `bump-version --pr` and `downstream bump --pr`
- `release-tag release`

These commands read the token from `$GITHUB_TOKEN`, or run `gh auth token` when `$GITHUB_TOKEN` is not set.
`push-bundle` also needs a token, and reads it from `$GITHUB_TOKEN` only.
`wait-for-base-coverage` sends `$GITHUB_TOKEN` when it is set, and does not run `gh auth token`.
Of the `secrets` and `variables` subcommands, only `check`, `dump`, `secrets inspect-remote` and `secrets export-remote` use the token.
`dependabot-uv bump --version <version>` uses the token only with `--pr`.
With `--pr`, `bump-version`, `dependabot-uv bump`, `github-releases bump` and `downstream bump` also need the token to have the Pull requests `write` permission.
Their `git push` to `origin` uses Git's own credentials, which need the Contents `write` permission.
A push that changes a workflow file also needs the Workflows `write` permission.

`long-files` and `added-strings` read the Git checkout in the current directory by default.
Pass `--directory <dir>` to read another checkout instead.
The command then reads the files, the Git history and the `pyproject.toml` settings of that checkout.

### Posting from a trusted checkout

A workflow job that posts to a pull request holds a token that can write.
Do not run code from the pull request in that job, because that code can use the token.
That code includes the `justfile`, the scripts and any `repoutils` source that the pull request changes.
Instead, check out the base commit of the pull request (`github.event.pull_request.base.sha`), and run `repoutils` from that checkout.

- `post-patch-coverage` and `post-coverage-status` read the coverage reports, and the `pyproject.toml` settings of the base checkout.
  A change to `[tool.repoutils.coverage]` in a pull request therefore reaches what these commands post only after the pull request merges.
  Make the reports in a job without write permission, and pass them to the posting job as artifacts.
- `long-files` and `added-strings` read the files of the pull request.
  Check out the head of the pull request into a subdirectory, and pass that subdirectory with `--directory`.
  The command then reads that checkout only as data, and runs no code from it.

On a `pull_request` run, the workflow file itself still comes from the pull request.
These steps therefore do not protect against a pull request that changes the workflow.
The `ci.yml` workflow in this repository shows these jobs.

### Bumping uv with Dependabot

`dependabot-uv bump --pr` can run on a schedule, so that the `uv` version of the project follows the `uv` version of Dependabot.
The `.github/workflows/bump-uv.yml` workflow in this repository shows how.
Copy it to another project, and change its `setup-uv` version and the way that it runs `repoutils`.

- Schedule the workflow a few hours after the weekly `uv` update of Dependabot.
  Set `day` and `time` for the `uv` entry in `.github/dependabot.yml`, so that the update runs at a known time.
- Split the workflow into two jobs, so that no job runs the new `uv` while it holds a token that can push.
- The first job runs `dependabot-uv bump` with a read-only `GITHUB_TOKEN` that has the Actions `read` and Contents `read` permissions.
  That command re-locks `uv.lock` with the new `uv`.
  The job passes `uv.lock` to the second job as an artifact.
- The second job runs `dependabot-uv bump --pr --version <version> --lock-file <file>`, with the `uv` version that the first job found.
  With `--lock-file`, the command copies that file to `uv.lock`, and does not run `uv`.
  The command makes all other changes itself.
- The second job uses a token that is stored in an environment that only the default branch can deploy to.
  The pull request changes workflow files, so the token needs the Workflows `write` permission.
  The token also needs the Contents `write` and Pull requests `write` permissions.
- Do not use the `GITHUB_TOKEN` of the workflow to open the pull request, because GitHub starts no CI for a pull request that a `GITHUB_TOKEN` opens.

Do not run `dependabot-uv check` in pull request CI.
A new `uv` version for Dependabot would then make unrelated pull requests fail.

### Bumping pinned GitHub releases

`github-releases bump --pr` can run on a schedule, so that the project follows the releases of the projects whose release assets it pins.
Dependabot does not track release assets.
This workflow shows how:

```yaml
name: Bump GitHub releases

on:
  schedule:
    - cron: "17 7 * * 1"
  workflow_dispatch:

concurrency:
  group: bump-github-releases

permissions: {}

jobs:
  bump:
    if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
    runs-on: ubuntu-latest
    environment: github-releases-bump
    # GITHUB_RELEASES_BUMP_TOKEN does the writing.
    permissions:
      contents: read
    timeout-minutes: 5

    steps:
      - uses: actions/checkout@v7.0.1
        with:
          token: ${{ secrets.GITHUB_RELEASES_BUMP_TOKEN }}
          persist-credentials: true

      # Runs the repoutils wheel that uv.lock pins, checked against its
      # SHA-256 hash, from the zip file itself, with the runner's python3.
      # PYTHONSAFEPATH keeps the checkout off Python's import path.
      - name: Open the pull requests
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_RELEASES_BUMP_TOKEN }}
          PYTHONSAFEPATH: "1"
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          read -r url hash < <(python3 -c '
          import tomllib
          [package] = [p for p in tomllib.load(open("uv.lock", "rb"))["package"] if p["name"] == "repoutils"]
          [wheel] = package["wheels"]
          print(wheel["url"], wheel["hash"].removeprefix("sha256:"))')
          curl --fail --silent --show-error --location --output "$RUNNER_TEMP/repoutils.zip" "$url"
          echo "$hash  $RUNNER_TEMP/repoutils.zip" | sha256sum --check --strict --quiet
          PYTHONPATH="$RUNNER_TEMP/repoutils.zip" python3 -m repoutils github-releases bump --pr
```

- The workflow runs only on the default branch, and only the `repoutils` version in the `uv.lock` of the default branch.
  It runs no other code from the project, and no code from the projects whose releases it pins.
  One job is therefore enough, unlike the two jobs of `bump-uv.yml`.
- `repoutils` uses only the standard library, so `python3` runs it from its wheel without installing anything.
- Store the token in an environment that only the default branch can deploy to.
  The token needs the Contents `write` and Pull requests `write` permissions.
  If a pins file is in `.github/workflows`, the token also needs the Workflows `write` permission.
- Do not use the `GITHUB_TOKEN` of the workflow to open the pull request, because GitHub starts no CI for a pull request that a `GITHUB_TOKEN` opens.

### Bumping downstream projects after a release

When one person maintains a package and the projects that depend on it, a release can open a pull request in each of those downstream projects at once.
The `.github/workflows/bump-downstream.yml` workflow in this repository shows how.
A downstream project needs no workflow of its own, but it must use `uv`.

- The `DOWNSTREAM_REPOS` Actions variable lists the downstream repositories as `owner/name`, separated by spaces.
  To add or remove a downstream project, change the variable.
- The workflow runs when the Publish workflow succeeds on a `v*` tag.
  It also runs by hand, with the version as input.
  A `release: published` trigger does not work if a `GITHUB_TOKEN` creates the release, because GitHub starts no workflow for an event that a `GITHUB_TOKEN` causes.
- The workflow has four jobs, and each job runs one composite action from this repository.
  The actions run `repoutils` from their own commit with the `python3` of the runner, and install nothing but `uv` and the `gh-actions-lock` extension of `gh`.
- The `plan` job runs the `downstream-plan` action, which runs `downstream plan`.
  The command gives the repositories as a job matrix, and works out the version from the event that started the run.
- The `bump` job runs the `downstream-bump` action once for each downstream project.
  The action checks out the default branch of the downstream project, runs `downstream bump`, and uploads `uv.lock` and `actions.lock`, if the downstream project has them, as an artifact.
  Re-locking runs the build backends of the downstream project, so this job has only a read-only `GITHUB_TOKEN`.
  That token can check out only a public repository, so each downstream repository must be public.
- The `push` job runs the `downstream-push` action once for each downstream project, in an environment that only the default branch can deploy to.
  The action checks out the downstream project with a token from that environment, and runs `downstream bump --pr --lock-file <file> --actions-lock-file <file>`.
  The command copies `uv.lock` and `actions.lock` from the artifact as data, and checks `actions.lock` with `gh actions-lock --verify`.
  The action fails if the default branch of the downstream project changed after the `bump` job.
- The `finish` job runs the `downstream-finish` action once for each downstream project, in the same environment as the `push` job.
  The action runs `downstream finish`, which waits for the checks on the pull request, and re-runs failed jobs once.
  For a release, it leaves the pull request open for review, and the job fails if any check still fails.
  The command waits up to an hour for the checks, so the job has a 70-minute timeout.
  Later runs of the workflow wait for it, because they share the `bump-downstream` concurrency group.

The workflow also makes a test run when someone starts the Publish workflow by hand on `main` and the run succeeds.
That run publishes a dev version of `main` to TestPyPI.

- The test run bumps each downstream project to that dev version, with the same `plan`, `bump` and `push` jobs, and opens a draft test pull request.
  It moves the `uses:` of the actions of this repository to the commit that Publish ran on.
- The `finish` job then runs `downstream finish`, which closes the test pull request if all its checks pass, and leaves it open if any check still fails after a re-run.
- The test run succeeds only if it closes every test pull request.
- The workflow makes no test run for a Publish run on another branch.
  The test pull request comes from a branch of the downstream repository, so the CI of the downstream project would run the unreviewed code of that branch with the secrets of the downstream project.
- To make a test run again, run the workflow by hand with the dev version and the commit that its build came from.
  The workflow fails if that commit is not on `main`.

`downstream finish --repo <owner/name> --version <version>` runs in a checkout of the upstream project, as `downstream bump` does:

- It finds the open pull request for the version by its marker and its branch.
  For a dev version, it finds the test pull request, and fails if there is none.
  For a release, it exits with code `0` if there is none, because a downstream project that already has the release gets no pull request.
- It waits for the checks that the rulesets of the downstream repository require on the base branch to appear, because GitHub adds a check some time after a pull request opens.
  It also waits for at least one check to appear.
- It then waits for every check run and commit status on the head commit of the pull request to finish.
  A check run passes if its conclusion is `success`, `neutral` or `skipped`, and a commit status passes if its state is `success`.
  It decides only when two reads in a row find the same finished checks, because a workflow can add its check after the checks of another workflow finish.
- A required check that names an app counts only as a check run from that app, because the API does not say which app posted a commit status.
- If all the checks pass on a test pull request, it comments on the pull request, closes it without merging it, and deletes its branch.
  It never closes the pull request of a release, which it leaves open for review.
- If only GitHub Actions jobs fail, it re-runs the failed jobs of their workflow runs, and waits for the checks again.
  It does this once, or `--retries` times (from `0` to `9`), because a check can fail for a short-lived reason, such as a package index server that does not yet list the new version.
  It re-runs nothing if a commit status or a check run of another app fails, because the pull request cannot pass then.
  The re-runs count toward the same `--timeout`, so a re-run gets only the time that is left, and it re-runs nothing once no time is left.
- If any check still fails, it leaves the pull request open, lists the checks that failed, and exits with code `1`.
- If the pull request of a release closes or merges while the command waits, it stops waiting and exits with code `0`.
  If a test pull request closes, the command fails.
- It fails if the checks do not finish within `--timeout` seconds (default `3600`).
  It reads the checks every `--interval` seconds (default `30`).
- To close a test pull request, its token needs the Contents `write` and Pull requests `write` permissions on the downstream repository.
  To re-run failed jobs, it also needs the Actions `write` permission, and without it the command prints a warning and does not re-run them.
  It reads the checks and the rules with the same token, so the downstream repository must be public, or the token must also be able to read them.

`downstream bump` runs in a checkout of the upstream project, and changes the downstream checkout that `--directory` names:

- It takes the package name from `[project] name` in the `pyproject.toml` of the upstream project, unless you pass `--package`.
- It changes the `==` pins of the package in `[build-system] requires`, and the `>=` minimums in the dependencies, optional dependencies and dependency groups.
  It changes nothing else in `pyproject.toml`, except for a dev version, as described below.
- It then re-locks `uv.lock`, and upgrades only the package.
  It uses the `uv` version that `[tool.uv] required-version` of the downstream project names, or the `uv` on the `PATH` if the project names none.
  PyPI can be a minute or two late to list a release, so the command tries the re-lock again for about two minutes.
- Before it changes anything, it checks the provenance that PyPI has for each file of the release.
  Each file must name the upstream repository (`--upstream`, default `$GITHUB_REPOSITORY`) as its trusted publisher.
  The pull request skips any Dependabot cooldown of the downstream project, so this check replaces the delay of the cooldown.
- It moves each `uses:` that names the upstream repository, in `.github/workflows` and in local actions, to the tag `v<version>`.
  For example, it moves `uses: owner/name/.github/actions/downstream-bump@v0.3.0` to `@v0.4.0`.
  It changes nothing else in those files.
  It fails if a `uses:` of the upstream repository has a ref that is not a tag of the form `vX.Y.Z`, or has a newer tag.
- If it moved a `uses:`, it then regenerates `.github/workflows/actions.lock` with `gh actions-lock`, which also locks the actions that the actions of the upstream use.
  With `--actions-lock-file <file>`, it copies the file over `actions.lock` instead, and checks it with `gh actions-lock --verify`.
  It fails if the file locks an action at another commit than `actions.lock` does, for an action whose ref the bump does not change.
  Both need `gh` with the `gh-actions-lock` extension, and a token that can read the repositories of the actions.
- It does nothing if every pin and every `uses:` of the upstream repository is already at the version, and fails if any pin is newer.
- A dev version, such as `0.4.1.dev123`, is a test build on TestPyPI, and the command handles it as a release, with these differences:
  - It checks the provenance that TestPyPI has, not the provenance that PyPI has.
  - It adds to `pyproject.toml` an explicit `[[tool.uv.index]]` for TestPyPI, unless one is there, and a `[tool.uv.sources]` entry that takes the package from that index.
    The index must be explicit, because an index that is not explicit would let any package on TestPyPI replace the package from PyPI.
    `uv` applies the source to `[build-system] requires` too.
    A build that `pip` or `python -m build` runs does not see the source.
  - No tag exists for a dev version, so the command moves each `uses:` of the upstream repository to the commit that `--commit` names, the commit that the build came from.
    `--commit` is needed only if the downstream project uses the actions of the upstream repository.
  - A dev version `X.Y.Z.devN` is older than `X.Y.Z` and newer than any earlier version.
- The bump of a release fails while `[tool.uv.sources]` still takes the package from TestPyPI, so remove that source by hand first.
- With `--pr`, it commits only `pyproject.toml`, `uv.lock`, the files with a `uses:` that it moved, and `actions.lock`, to a new branch.
  For a release, the branch is `downstream/<package>-<version>`, and the body of the pull request starts with a hidden marker, `<!-- <comment-prefix>-downstream-<package> -->`.
- With `--pr` and a dev version, it opens a draft pull request instead, from the branch `downstream-test/<package>-<version>`, titled `TEST PR: DO NOT MERGE: SKIP AI CODE REVIEW`.
  The body of the pull request starts with the hidden marker `<!-- <comment-prefix>-downstream-test-<package> -->`, and then a note that asks code-review AIs not to review it.
  CodeRabbit skips a draft pull request by default.
  To make CodeRabbit skip the pull request by its title too, add `ignore_title_keywords` to the CodeRabbit configuration of the downstream project.

With `--pr`, `downstream bump` finds the open pull requests that earlier runs opened, by that marker and by their branch.
The bump of a release finds only the pull requests for releases, and the bump of a dev version finds only the pull requests for dev versions.
Neither finds a pull request for a dev version from a branch `downstream/<package>-<version>`, which an earlier, unreleased build of repoutils opened, so close any such pull request by hand.
It handles the pull requests that it finds as follows:

- If one of them is for a newer version, the command changes nothing.
- If one of them is for the same version, the command opens no pull request, but handles each earlier pull request, as a run that failed part of the way through would have.
  It also adds a link to each earlier pull request that it leaves open to the body of that pull request, if the body has no link to it yet.
- Otherwise, the command opens the new pull request first, and then handles each earlier pull request.
- An earlier pull request is untouched if `downstream bump` made each of its commits, apart from merges that the Update branch button of GitHub made.
  The command finds its own commits by their `Bumped-By: repoutils downstream bump` trailer.
  A commit that someone amended or rebased keeps the trailer, but gets a new committer or commit time, so it counts as another commit.
  This includes a rebase by the Update branch button, because an amended commit looks the same after that rebase.
  It reads the commits and not the changes, because a merge or a re-lock also changes `uv.lock`.
- The command deletes the branch of an untouched pull request, closes the pull request, and comments "Superseded by #N".
  If the branch changed after the command read its commits, the command does not delete it, and leaves the pull request open.
- The command does not close a pull request that has other commits, for example from `/autofix` or a person.
  It comments that the new pull request bumps the package, and that the changes of the earlier pull request probably need to move across.
  The body of the new pull request links the earlier pull request too.
- If the command fails after it opens the new pull request, run it again to handle the earlier pull requests.

To set up the same workflow for another package:

1. Publish the package to PyPI with trusted publishing and attestations.
2. Copy `bump-downstream.yml`, and change `Publish` to the name of the workflow that publishes the package.
   The test run expects a run of that workflow that someone starts by hand to publish the next patch release as a dev version numbered by the run ID, such as `0.4.1.dev123`, to TestPyPI, as the Publish workflow of this repository does.
   The Publish workflow of this repository sets that version with `repoutils bump-version patch --dev <run ID>`, and `downstream plan` works out the same version from `pyproject.toml` at the commit of the run.
   If the workflow does something else, remove the test run.
   If the default branch of the package is not `main`, change both `refs/heads/main` and `head_branch == 'main'` in the `if` of the `plan` job to that branch too.
3. Replace each `uses: $/.github/actions/<action>` with `uses: sjktools/repoutils/.github/actions/<action>@<tag>`, and replace the sparse checkouts with a checkout of `pyproject.toml`.
   Use a release tag, such as `v0.4.0`, so that `downstream bump` can move it when repoutils releases.
4. Set the `DOWNSTREAM_REPOS` variable.
5. Create a `downstream` environment that only the default branch can deploy to, and store the `DOWNSTREAM_TOKEN` secret in it.
   The token needs the Contents `write` and Pull requests `write` permissions on each downstream repository.
   It also needs the Actions `write` permission, so that `downstream finish` can re-run failed jobs.
   On a private downstream repository, it also needs the Commit statuses `read` and Checks `read` permissions, so that `downstream finish` can read the checks.
   It also needs the Workflows `write` permission on each downstream repository where the pull request changes a file in `.github/workflows`, such as a workflow or `actions.lock` that uses the actions of the package.
   A fine-grained token has one resource owner, so downstream repositories of a second owner need a second token.
   For each owner, use a copy of the workflow with its own variable, environment and token.
6. In each downstream project, tell Dependabot to ignore the package, so that only the workflow bumps it.

### Running PR Fixes with a command

In this repository, a `/autofix` comment on a pull request, from a commenter whose author association is `OWNER` or `MEMBER`, starts the PR Fixes workflow (`fix.yml`) on the branch of the pull request.
That workflow runs `just fix` with no secrets, and uploads its commits as an artifact.
The PR Fixes Push workflow (`fix-push.yml`) on the default branch then checks those commits and pushes them to the branch.

`repoutils autofix <pull request>` does the same as the comment, for a client that can start a workflow but cannot post the exact comment.
For example, Claude Code on the web adds a footer to each comment that it posts.

- The command starts `fix.yml` on the branch of the pull request, with the head commit and the number of the pull request as inputs.
  It refuses a pull request that is closed, comes from a fork, or comes from the default branch.
- When that run finishes, the command finds the `fix-push.yml` run for it by the run name `PR Fixes Push for run <run ID>`.
  It does this even if the run failed, because the `report` job of `fix-push.yml` comments on the pull request about a failed run too.
  GitHub starts that run itself, because `fix-push.yml` has a `workflow_run` trigger.
- GitHub starts no `workflow_run` workflow for a run that a `GITHUB_TOKEN` starts.
  For such a run, or when no `fix-push.yml` run appears within two minutes, the command starts `fix-push.yml` on the default branch with the run ID as input.
- The command waits for the `fix-push.yml` run, and then reads the head commit of the pull request.
  If the head commit changed, the command prints the new head commit on standard output.
  Run `git pull` to get the fixes.

The command does not push, so its token needs only the Actions `write` and Pull requests `read` permissions.
`--workflow` and `--push-workflow` name other workflow files, which must work as these two do.
The command fails if either run fails, or if the fixes are not pushed within `--timeout` minutes (default `45`).

Two options are for a workflow that runs the command for a `/autofix` comment:

- `--comment-id <ID>` reacts to the comment with a rocket once the fix run starts.
  The token then needs the Pull requests `write` permission.
  If the reaction fails, the command only warns.
- `--report <file>` writes the Markdown for a comment on the pull request when the command fails, unless the `report` job of the `fix-push.yml` run succeeded.
  The comment says how far the command got, and links to the run of the workflow, which the command reads from `$GITHUB_SERVER_URL`, `$GITHUB_REPOSITORY` and `$GITHUB_RUN_ID`.
  If GitHub refused to start a run, the comment gives the reason from GitHub.

GitHub does not start a workflow whose `uses:` are not all in `.github/workflows/actions.lock`.
So a branch that changes the `uses:` of `fix.yml`, for example to move to a new release of the actions of repoutils, can stop `fix.yml` from starting.
The command and the comment of `--report` recognise this error, and say how to fix it: run `gh actions-lock` on the branch where `gh` is logged in to GitHub, then commit and push `actions.lock`.

A `/autofix` comment updates `actions.lock` on the branch itself, because `autofix-comment.yml` runs from the default branch, with the `actions.lock` of the default branch.
Two more options are for this:

- `--relock <file>` makes the command exit `0` when GitHub refuses to start `fix.yml` for this error.
  The command then appends `relock=true` and `head_sha=<head commit>` to the file, such as `$GITHUB_OUTPUT`, for a later job that updates `actions.lock`.
- `--relocked <run ID>` is for a job after that later job, in the same run.
  The command starts `fix-push.yml` with that run ID, which pushes the commit of the `relock` job of the run, and then starts `fix.yml` on the new head commit.
  If the `relock` job failed or changed nothing, the command starts `fix.yml` without a push.
  If GitHub refuses again, the comment says so, and nothing updates `actions.lock` a second time.

In `autofix-comment.yml`, the `dispatch` job runs the command with `--relock`.
If GitHub refuses to start `fix.yml` for this error, the `relock` job runs the `autofix-relock` composite action:

- The action checks out the head commit of the pull request, and runs `gh actions-lock` with the read-only `GITHUB_TOKEN` of the job.
- If `actions.lock` changed, it commits the file, and uploads the commit as a Git bundle in the `fixes-<head commit>` artifact.
  If the file did not change, it uploads nothing.
- The job has no secrets and only the Contents `read` permission, and runs no code from the branch.
  `gh actions-lock` only reads the workflow files, and reads the actions that they use through the API.
  A private action in another repository may need more access than that token has, and the relock then fails.

The `retry` job then runs the command with `--relocked`.
`fix-push.yml` pushes that commit only if it is one commit on the head commit of the pull request, and changes only `actions.lock`.
The `actions.lock` change shows in the diff of the pull request, and the push triggers CI, as a push of fixes does.

In GitHub Actions, the command prints its errors and warnings as annotations.

The `autofix-start` composite action is the job of `autofix-comment.yml`.
It does nothing unless the comment is `/autofix`, ignoring whitespace.
It runs `repoutils autofix` with `--comment-id` and `--report`, and posts the report with `repoutils post-comment`, with the marker of the comment that the `report` job of `fix-push.yml` posts.
With its `relock` input set to `true`, it also passes `--relock`, and with its `relocked-run` input, it passes `--relocked` instead.
The `post-comment` composite action runs `repoutils post-comment`, and is the last step of that `report` job.
Each report, of a success or a failure, is a new comment below the `/autofix` comment, because GitHub notifies the subscribers of the pull request about a new comment but not about an edit.
The report hides the earlier reports as outdated.

The two workflows check the fix run and its pull request with two subcommands, which the `autofix-check` and `autofix-resolve` composite actions run from their own commit with the `python3` of the runner:

- `repoutils autofix check-branch` is the first step of `fix.yml`.
  It fails unless the run is on a branch other than the default branch, at `--head-sha` if given.
  It then finds the pull request, with `--pr-number` if given, and prints its base branch as `base_branch`.
- `repoutils autofix resolve --run-id <run ID>` is the `resolve` job of `fix-push.yml`.
  It fails unless the run is a finished `workflow_dispatch` run of `fix.yml` on a branch of the repository other than the default branch, or a relock run.
  It finds the pull request, even if the run failed, so that the `report` job can comment on it.
  If the run succeeded, it fails if the branch moved on from the commit where the run started, unless another `fix-push.yml` run for the same fix run already pushed the fixes.
  It prints `kind` (`fix` or `relock`), `run_id`, `pr_number`, `branch`, `start_sha`, `conclusion`, `url`, `number`, `head_sha` and `base`.
  If the run succeeded, it also prints `fixes`, `already_pushed` and `artifact`, the name of the artifact with the bundle to push.
- A relock run is an `issue_comment` run of `autofix-comment.yml` (`--relock-workflow`) on the default branch, with the run name `Comment on #<pull request>`.
  Its `relock` job must have finished, though the run itself has not.
  Its `conclusion` and `url` are those of the `relock` job.
  Its `start_sha` is the commit in the name of its `fixes-<commit>` artifact, because the head commit of the run is on the default branch.
  Without that artifact, it is the head commit of the pull request.

Both subcommands print their outputs as `name=value` lines, for `$GITHUB_OUTPUT`.
Both find the pull request in the same way.
With a pull request number, the pull request must be open, and come from the branch in the same repository.
Without a number, the branch must have exactly one open pull request from the same repository, counted over every page of results.

A project that uses these actions must keep these names:

- The workflow files are `fix.yml` and `fix-push.yml`, and their workflow names are `PR Fixes` and `PR Fixes Push`.
- The run name of `fix.yml` is `PR Fixes #<number>`, or `PR Fixes` without a number.
- The run name of `fix-push.yml` is `PR Fixes Push for run <fix run ID>`, its job that pushes the fixes is `push`, and its job that comments on the pull request is `report`.
- The artifact that holds the bundle is `fixes`.
- The workflow file of the relock run is `autofix-comment.yml`, its run name is `Comment on #<number>`, its job that relocks `actions.lock` is `relock`, and the artifact of that job is `fixes-<commit>`.

### Starting a TestPyPI release with a command

In this repository, a `/testpypi` comment on a pull request, from a commenter whose author association is `OWNER` or `MEMBER`, starts the Publish workflow (`publish-pypi.yml`) on the branch of the pull request.
A run that is started that way publishes a dev version of the branch to TestPyPI, checks that it installs from there, and never publishes to PyPI.

`repoutils testpypi <pull request>` does the same as the comment, for a client that cannot post the exact comment, such as Claude Code on the web.

- The command refuses a closed pull request.
  It also refuses a pull request from a fork, because the branch of a fork is not in the repository.
- It starts the workflow on the branch, and prints the link to the run on standard output.
  It does not wait for the run.
- `--workflow` names another workflow file.
- It appends a note with the link to the file that `--step-summary` names, by default `$GITHUB_STEP_SUMMARY`.
- `--comment-id <ID>` reacts to the comment with a rocket once the run starts, and replies on the pull request with the link.
  If either fails, the command only warns.

The token needs the Actions `write` permission, and the Pull requests `read` permission, or `write` with `--comment-id`.
In GitHub Actions, the command prints its errors and warnings as annotations.

The `testpypi-dispatch` composite action is the job of `testpypi-comment.yml`.
It does nothing unless the comment is `/testpypi`, ignoring whitespace, and then runs `repoutils testpypi` with `--comment-id`, from its own commit with the `python3` of the runner.

### Pushing a Git bundle

A job that runs the code of a branch must not hold a token that can push.
So the job commits its changes, and uploads them as a Git bundle artifact.
A separate push job, which runs no code from the branch, checks the bundle and pushes it.
The `push-bundle` composite action does this push job's work:

```yaml
  push:
    needs: fix
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v7.0.1
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          persist-credentials: false
      - uses: sjktools/repoutils/.github/actions/push-bundle@v<version>
        with:
          token: ${{ secrets.PUSH_TOKEN }}
          artifact: fix
          branch: ${{ github.head_ref }}
          start: ${{ github.event.pull_request.head.sha }}
          single-commit: "true"
          allow-paths: |
            pyproject.toml
            uv.lock
```

The action downloads the artifact, and runs `repoutils push-bundle` from its own commit with the `python3` of the runner.
With `run-id`, it downloads the artifact from that workflow run, and the job needs the Actions `read` permission.
Check out the start commit first, without persisted credentials.
If the bundle contains a merge, check out the full history (`fetch-depth: 0`).

The command fails, and pushes nothing, unless all of these are true:

- The head of the bundle adds commits to `--start`.
- With `--expected-head`, the head is that commit.
- With `--single-commit`, the head is one commit on `--start`.
- With `--clean-merge-of <base>`, the head is at most one merge of a commit on the base (or a fast-forward to one), and then at most one other commit.
  The merge must be exactly the merge that Git makes.
- No changed path is under a `--deny-path` unless it is also under an `--allow-path`.
  With `--allow-path` and no `--deny-path`, every path outside the `--allow-path` paths is denied.
  With `--clean-merge-of`, these rules apply only to the commit after the merge.

The command reads the token from `$GITHUB_TOKEN`, and gives it to Git in an HTTP header from the environment, not in an argument.
It pushes with `--force-with-lease` on `--start`, so the push fails if the branch moved.
It runs no Git hooks.
Push with a token other than a `GITHUB_TOKEN` if the push must start workflow runs.
A workflow that a branch can change, such as a `pull_request` workflow, can expose the token to anyone who can push to the branch.
For a token that can push to other branches, put the push job in a workflow that runs from the default branch, and keep the token in an environment that only the default branch can deploy to, as the PR Fixes Push workflow does.
The token needs the Contents `write` permission, and also the Workflows `write` permission if the bundle changes a file in `.github/workflows`, such as `actions.lock`.

### Bumping the version

A Bump Version workflow, run by hand from the default branch, can open a pull request that bumps the version of the project.
The `bump-version` composite action does the work of its one job:

```yaml
on:
  workflow_dispatch:
    inputs:
      bump:
        required: true
        default: patch
        type: choice
        options: [patch, minor, major]

jobs:
  bump-version:
    runs-on: ubuntu-latest
    environment: release
    permissions:
      contents: read
    steps:
      - uses: sjktools/repoutils/.github/actions/bump-version@v<version>
        with:
          bump: ${{ inputs.bump }}
          token: ${{ secrets.GH_ACTIONS_TOKEN }}
          auto-merge: squash
```

The action checks out the default branch with the token, and runs `repoutils bump-version --pr` from its own commit with the `python3` of the runner.
It installs nothing, so no cache runs alongside the token.

- The command reads `[project] version` from `pyproject.toml`, which must be of the form X.Y.Z, and bumps the level that you give.
- It changes the version in `pyproject.toml`, and the version in the entry of the project itself in `uv.lock`, if the project has a `uv.lock`.
  It edits both files as text and does not run `uv`, so no build backend runs alongside the token.
- With `--pr`, it fails, and changes nothing, unless the checkout is on the default branch of the repository.
- It commits the change to a new branch, `release-version-<version>`, pushes the branch, and opens a pull request into the default branch.
  If a pull request from that branch is already open, it changes nothing.
- When it opens a pull request, `--auto-merge <method>`, or the `auto-merge` input of the action, turns on auto-merge with that merge method.

A pull request that a `GITHUB_TOKEN` opens starts no workflow run, so the token is another token, with the Contents `write` and Pull requests `write` permissions.
Keep it in an environment that only the default branch can deploy to.
Once the pull request merges, the release job can tag the version (see [Tagging a release](#tagging-a-release)).

### Tagging a release

A release job can tag the version of the project and create its GitHub release once a version bump merges to the default branch.
The `release-tag` composite action does this job's work:

```yaml
  release:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: release
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v7.0.1
        with:
          persist-credentials: false
          fetch-depth: 0
          fetch-tags: true
      - uses: sjktools/repoutils/.github/actions/release-tag@v<version>
        with:
          deploy-key: ${{ secrets.RELEASE_DEPLOY_KEY }}
```

The action runs `repoutils release-tag push` and then `repoutils release-tag release`, in separate steps, from its own commit with the `python3` of the runner.
It installs nothing, so no cache runs alongside the deploy key.
Each subcommand does nothing if its work is already done, so a rerun of a failed job finishes it.

- `push` reads the version from `[project] version` in `pyproject.toml`, and does nothing if the checkout has the tag `v<version>`.
  So check out with the tags fetched.
  Otherwise, it creates an annotated tag on the checked-out commit as `github-actions[bot]`, and pushes the tag to `github.com` over SSH.
- `push` reads the private key from `$RELEASE_DEPLOY_KEY`, and gives it to an `ssh-agent` on standard input, so the key is never written to a file.
  It trusts only the published Ed25519 host key of GitHub, and runs no Git hooks.
- `release` does nothing if the release exists, and fails if the tag is not on GitHub.
  Otherwise, it creates the release, with notes that GitHub generates.
  The token needs the Contents `write` permission.

A push with a deploy key starts workflow runs, so the tag can trigger a workflow that publishes the release.
Keep the deploy key in an environment that only the default branch can deploy to.
A tag ruleset that lets only a deploy key create `v*` tags, and lets nobody update or delete them, then stops any other branch or token from tagging a release (see [Rulesets](#rulesets) and [Deploy keys](#deploy-keys)).

## Configuration

Put all configuration settings in `pyproject.toml`.
Every setting is optional:

```toml
[tool.repoutils]
# Prefix of the hidden markers used to find this project's PR comments,
# e.g. <!-- repoutils-patch-coverage -->.
comment-prefix = "repoutils"
# The branch to compare with when there's no PR base.
default-branch = "main"
# The optional repoutils features this project uses: "pypi-publication" is the
# only one. `repoutils check-justfile` uses them; see below.
features = []

# The names of the commit statuses `repoutils post-coverage-status` posts, and
# when `repoutils post-patch-coverage` warns (false for never); see below.
[tool.repoutils.coverage]
project-status = "coverage/project"
patch-status = "coverage/patch"
warn-project-drop = 2
warn-patch-below = 1

[tool.repoutils.sentence-per-line]
files = ["AGENTS.md", "README.md"]

# The files `repoutils check-doubled-spaces` checks; see below.
[tool.repoutils.doubled-spaces]
files = ["AGENTS.md", "README.md"]
allow-after-sentence = false

# The limits `repoutils check-prose` holds these files to; see below.
[tool.repoutils.prose]
files = ["AGENTS.md", "README.md"]
max-words-per-sentence = 18

[tool.repoutils.screenshots]
dir = "screenshots"

# The standard recipes and dependencies the justfile leaves out on purpose; see below.
[tool.repoutils.justfile]
omit = ["prose-check"]
omit-dependencies = { check = ["pyright"] }

[tool.repoutils.lock-platforms]
# "os" allows any arch, and "os:arch" allows one arch ("*" for any).
# "linux" matches manylinux and musllinux.
supported = ["any", "linux:x86_64", "linux:aarch64", "macosx"]
tolerated = ["ios", "pyemscripten"]

[tool.repoutils.long-files]
include = ["*.py"]
exclude = ["*/migrations/*"]
limit = 500
limits = { "tests/*" = 700 }
policy = "Split a long file only where that makes the code better."

# The strings `repoutils added-strings` points out in the lines a PR adds; see below.
[tool.repoutils.added-strings]
exclude = ["pyproject.toml", "*.md"]

[[tool.repoutils.added-strings.strings]]
string = "TODO"

[[tool.repoutils.added-strings.strings]]
regex = '^\s*if TYPE_CHECKING\b'
name = "if TYPE_CHECKING:"

[[tool.repoutils.added-strings.strings]]
regex = "# type: ?ignore"
message = "please fix the type error instead, if you can"
include = ["*.py"]

# The labels that `repoutils labels` checks or creates; color and description are optional.
[[tool.repoutils.labels]]
name = "bug"
color = "d73a4a"
description = "Something isn't working"

[[tool.repoutils.labels]]
name = "dependencies"

# The repository settings that `repoutils repo-settings` checks or changes (see below).
[tool.repoutils.repo-settings]
description = "Repository tooling for Python projects"
homepage = "https://pypi.org/project/repoutils/"
issues = true
wiki = false
pull-request-creation = "collaborators"
squash-merge = { allow = true, title = "pr-title", message = "pr-body" }
merge-commit.allow = false
rebase-merge.allow = false
delete-branch-on-merge = true

# The Actions settings that `repoutils actions-settings` checks or changes (see below).
[tool.repoutils.actions-settings]
allowed-actions = "all"
require-sha-pinning = true
default-token-permissions = "read"
oidc.immutable-subject = true

# A ruleset `repoutils rulesets` checks or creates, giving only what isn't a default; see below.
[tool.repoutils.rulesets.main]
include = ["~DEFAULT_BRANCH"]
bypass = [{ role = "admin", mode = "pull-request" }]

[tool.repoutils.rulesets.main.rules]
deletion = true
non-fast-forward = true
pull-request = { allowed-merge-methods = ["squash"] }
required-status-checks = { required-status-checks = [{ context = "test", app = "github-actions" }] }

# The names of the secrets `repoutils secrets` checks the repository has; see below.
[tool.repoutils.secrets]
actions = []
dependabot = ["DEPENDABOT_FIX_TOKEN"]
environments.release = ["RELEASE_TOKEN"]
other = ["ORG_DEPLOY_KEY"]

# The names (never the values) of the variables `repoutils variables` checks the repository has; see below.
[tool.repoutils.variables]
actions = ["DEPLOY_URL", "NEXT_RELEASE_URL"]
unused = ["NEXT_RELEASE_URL"]

# The security settings that `repoutils security-settings` checks or changes; see below.
[tool.repoutils.security-settings]
dependabot-alerts = true
secret-protection = true
push-protection = true
immutable-releases = true

# The deployment environments `repoutils environments` checks or creates; see below.
[tool.repoutils.environments.pypi]
allowed-tags = ["v*"]

[tool.repoutils.environments.testpypi]

# A deploy key `repoutils deploy-keys` checks or creates, and the secret that holds its private half; see below.
[tool.repoutils.deploy-keys.release]
write = true
secret = { environment = "release", name = "RELEASE_DEPLOY_KEY" }

# A project whose release assets `repoutils github-releases` pins; see below.
[tool.repoutils.github-releases.sonarlint]
repo = "SonarSource/sonarlint-vscode"
file = "sonarlint-pins.toml"
assets = ["sonarlint-vscode-*.vsix"]
```

### Prose

`repoutils check-prose` measures the prose in each configured Markdown file.
It fails when the sentences in a file are too long or contain too many joined clauses.
Machine-generated text often uses that style, which is difficult to read.

The command also fails when a file has too many very short sentences.
Authors sometimes split sentences into fragments only to stay below the word limit, which is also difficult to read.
One limit therefore caps the percentage of short sentences in a file.
That limit excludes list items, because short sentences are normal in lists.
That limit also excludes sentences that end with a colon before a list or a code block.
Treat all limits as maximum values rather than targets, and do not edit sentences when the file already passes.

The command skips code blocks, headings, tables, block quotes, HTML comments, and HTML blocks.
An HTML block starts with a line that starts with an HTML block tag, such as `<div>`, and ends at the next blank line.
A block that starts with `<pre>`, `<script>`, `<style>` or `<textarea>` ends at the closing tag instead.
A block quote continues until the next blank line, list item or heading.
The command counts an inline code span as one word and a URL as one word.
It ignores text that has no closing punctuation or has fewer than three words, such as a short list item.

The command splits sentences according to standard English punctuation.
A sentence ends at a full stop, question mark or exclamation mark when the next sentence starts with an uppercase letter, digit or inline code.
A colon at the end of a paragraph or list item also ends a sentence.
A newline after any of those punctuation marks always starts a new sentence, regardless of the first character on the next line.
In a wrapped paragraph, a sentence that starts mid-line with a lowercase word (such as `uv`) is counted as part of the previous sentence.

| Setting | Default | What it limits |
|---|---|---|
| `max-words-per-sentence` | 18 | Mean number of words per sentence. |
| `max-long-sentences` | 12 | Percentage of sentences with more than `long-sentence-words` words (default 30). |
| `max-short-sentences` | 25 | Percentage of sentences with fewer than `short-sentence-words` words (default 8), excluding list items and sentences ending with a colon. |
| `max-commas-per-sentence` | 1.3 | Mean number of commas per sentence. |
| `max-semicolons-per-sentence` | 0.05 | Mean number of semicolons per sentence. |
| `max-joints-per-sentence` | 0.6 | Mean number of clause joints per sentence. |

A clause joint is a semicolon, a colon, a dash, or a comma before a conjunction such as "and", "but", "because" or "which".
Set any limit to `false` to disable that limit.
A file with fewer than `min-sentences` sentences (default 15) is too short to measure and always passes.
The settings `min-sentences`, `long-sentence-words` and `short-sentence-words` must be integers.

The limits apply to the average rates across the whole file rather than to individual sentences.
A file can contain a few long sentences and still pass.
For each limit that a file exceeds, the command prints the five sentences that contribute the most to that rate.
The two limits for long sentences share one list of sentences under the first exceeded limit.
Pass `--exit-zero` to print the same output and exit with code `0`.
Pass `--stats` to print all rates for every file.
`--stats` also prints the sentence-length CV, which no setting limits: the standard deviation of sentence length divided by the mean sentence length.

When the command cannot read a file (for example, when the file is not valid UTF-8), it prints `<file>: cannot read (<reason>)`.
The command still reads the remaining files, and exits with code `1` even when you pass `--exit-zero`.
`repoutils check-sentence-per-line` and `repoutils check-doubled-spaces` handle unreadable files in the same way.

The default limits for long sentences come from a sample of 17 documents, both pre-LLM README files and recent machine-generated documents.
The default limit for short sentences comes from a smaller sample of rewrites of this README, so adjust the limits to fit your project.

### Doubled spaces

`repoutils check-doubled-spaces` fails when the prose in a configured Markdown file has two or more spaces between two characters that are not spaces.
Such spaces are easy to miss, as Markdown shows them as one space.
A rewrite that removes words or commas often leaves them behind.
The command lists each line that has them, with its line number.
Pass `--fix` to make each of them one space, which the standard `doubled-spaces-fix` recipe does.

The command skips the parts of a file where extra spaces are often deliberate, or change what a reader sees:

- the parts that `repoutils check-prose` skips, such as code blocks, tables, block quotes and HTML blocks (see [Prose](#prose))
- link definitions, inline code spans, inline HTML tags, and the destinations of links and images

The command ignores the indent and the list marker at the start of a line.
By default, it also reports two spaces after the end of a sentence.
To allow them, set `allow-after-sentence` to `true`, or pass `--allow-after-sentence`.

### Justfile

`repoutils check-justfile` checks the justfile in the current directory against the standard justfile of `repoutils`.
It reads the justfile with `just --dump --dump-format json`, which evaluates no assignments, so the command runs nothing from the justfile.
Pass `--just <path>` to run a `just` that is not on `PATH`, and `--justfile <path>` to check a justfile that `just` does not find from the current directory.
A recipe passes `--just {{ quote(just_executable()) }} --justfile {{ quote(justfile()) }}`, so it checks the justfile that runs it.
The settings always come from the `pyproject.toml` in the current directory, as with every other command, even with `--justfile`.

The command fails in these cases:

- A standard recipe is not in the justfile as a recipe or an alias.
- `check`, `fix`, `ci` or `patch-coverage` does not run one of its standard dependencies, directly or through another recipe.
- `fix` runs a recipe that fixes something, but `check` does not run the recipe that checks the same thing.
  The pairs are `fmt` and `fmt-check`, `just-fmt` and `just-fmt-check`, `lint-fix` and `lint`, `actions-lock` and `actions-lock-check`, `requirements-fix` and `requirements-check`, and `doubled-spaces-fix` and `doubled-spaces-check`.
- The justfile has no `repoutils` variable.
- No `eager` assignment in the justfile runs `repoutils git-config-setup` with `shell()`.
- The directory of the justfile has no `.git-blame-ignore-revs` file.
  Create an empty one, which `repoutils check-blame-ignore-revs` accepts.

The command does not compare the body or the doc comment of a recipe with the standard recipe, because a project can have a reason to change them.
It does not check the value of the `repoutils` variable either, because projects run `repoutils` in different ways.
For each missing recipe, the command prints the standard text of the recipe, with the `default-branch` of the project, so that you can paste it into the justfile.
The command also prints the standard `eager` assignment when the justfile has none that runs `repoutils git-config-setup`.
The command matches that assignment loosely, because projects run `repoutils` in different ways.
The command accepts the `repoutils` variable followed by a string that starts with ` git-config-setup`, or a single string that runs `repoutils git-config-setup`.
The command accepts an assignment of any name, though the standard name is `_`.

The `pypi-publication` feature in the `features` setting of `[tool.repoutils]` adds the standard recipes `build`, `check-attestations`, `smoke` and `check-release`, and makes `ci` depend on `build` and `smoke`.

An unknown feature name is an error, so a typo does not turn a feature off.
List a standard recipe that the project leaves out on purpose in `omit`, and a standard dependency that it leaves out in `omit-dependencies`.
An omitted recipe or dependency does not excuse a missing pair, so if `fix` runs `fmt`, `check` must run `fmt-check`, even when `fmt-check` is in `omit`.
When `omit` lists `blame-ignore-revs-check`, the command does not check the `eager` assignment or `.git-blame-ignore-revs`, because `git-config-setup` only sets up `git blame` to read that file.
Pass `--exit-zero` to print the same output and exit with code `0`.
The command exits with code `1` even with `--exit-zero` when it cannot run `just` or read the output of `just`, or when a setting is not valid.

A new release of `repoutils` can add a standard recipe.
The `just check` of a project then fails until you add the recipe, or list it in `omit`.

The standard `blame-ignore-revs-check` recipe, which `check` runs, needs the full Git history to check that each commit is an ancestor of the target.
Its target is the `BLAME_IGNORE_REVS_TARGET` environment variable, or `HEAD` when that variable is not set, because `check` cannot pass the recipe an argument.
On a pull request, set the target to the base branch, because a commit from the pull request is not on the base branch after a squash merge.
The CI job that runs `just check` needs these settings:

```yaml
      - uses: actions/checkout@...
        with:
          persist-credentials: false
          # Full history, for `just check`'s blame-ignore-revs-check.
          fetch-depth: 0
      ...
      - name: Run checks
        env:
          BLAME_IGNORE_REVS_TARGET: ${{ github.base_ref && format('origin/{0}', github.base_ref) || 'HEAD' }}
        run: just check
```

### Added strings

`repoutils added-strings` searches the lines added in the working tree since the merge base of `--base` and `HEAD`.
It lists every added line that matches any configured pattern in `strings`.
Each entry in `strings` specifies either `string` (a literal substring) or `regex` (a Python regular expression).
The default `message` asks the author to verify that the matched text is necessary.
Unlike a literal substring, a regular expression can match code syntax without matching documentation or test strings that mention that syntax.
For example, `^\s*if TYPE_CHECKING\b` matches only the `if TYPE_CHECKING` statement, and `repoutils` uses a regular expression in its own `pyproject.toml` for `# noqa` comments.
For a `regex` entry, `name` sets the label shown in the report instead of the raw regular expression.

The `include` and `exclude` settings take glob patterns for file paths, where `*` matches across `/`.
The patterns in `[tool.repoutils.added-strings]` apply to all entries, and the patterns on a single entry narrow the search for that entry.
Exclude `pyproject.toml` and documentation files because those files often mention the configured strings.

The report is for information only, so the command exits with code `0` even when it finds matches.
The command exits non-zero when it cannot run the check, such as on an invalid setting, failed `git` command or failed GitHub request.
When you pass `--post <PR>`, the command posts a pull request comment only when the pull request adds a matching string.
If a later push removes all matches, the command updates the previous comment to state that none remain.

### Coverage status

`repoutils post-coverage-status <sha>` posts two commit statuses (`coverage/project` and `coverage/patch`) on the specified commit.
The command reads the project coverage from `coverage.xml` for the whole project.
It reads the patch coverage from the `diff-cover` JSON report (`--patch-report`) for the lines changed in the pull request or commit.

Run this command in CI on every default-branch commit and on the head commit of every pull request.
The default branch statuses then record the coverage history of the project.
Skip this step on pull requests from forks and Dependabot, because their tokens lack write permission.
Pass `--base` with the pull request base or parent commit to include the coverage change in the project status.
If the base commit has no `coverage/project` status, the status omits the coverage change.

Both statuses always use the `success` state because they record coverage without failing the commit.
Their description strings use a fixed format so that other tools can parse them:

```text
96.52% (2114/2172 lines, 610/650 branches), +0.12 points from 1a2b3c4
92.30% (12/13 lines)
```

The project coverage number is the total from `coverage.py`, which combines covered lines and covered branches.
The command truncates this number to two decimal places instead of rounding it, so `100.00%` appears only when coverage is complete.
The branch count appears only when `coverage.xml` includes branch coverage.
The change is the difference between the two displayed percentages.
The patch coverage number counts lines in the same way as `diff-cover`, and shows `no changed lines to cover` when the diff has no executable lines.

A token with permission to post commit statuses can post a status with any context name, including the name of a required check.
Therefore, run this command in a separate job that installs no other packages and receives the coverage reports as artifacts.
That job requires the `statuses: write` permission, which GitHub does not grant to pull requests from forks or from Dependabot.
Pass `--dry-run` to print the statuses without posting them to GitHub.

### Patch coverage comment

`repoutils post-patch-coverage <PR>` posts the Markdown report from `diff-cover` to the pull request, and updates that existing comment on subsequent runs.
When you pass `--coverage-report coverage.xml`, the comment also shows the project coverage.
When you also pass `--base <sha>`, the comment shows the `coverage/project` status of that base commit and the change from it.
The command never compares against an older commit, because an older commit would include changes from other merged pull requests.
When the base commit has no coverage status, the comment notes that fact and shows only the coverage of the pull request.

The comment includes a warning and prints a `::warning::` workflow command in two cases:

- Project coverage dropped from the base commit by more than `warn-project-drop` percentage points (default 2).
- Patch coverage is more than `warn-patch-below` points (default 1) below the base project coverage, or the pull request project coverage when the base has no status.

These conditions only produce warnings, so low coverage never causes the command to fail.
The command exits non-zero only when it cannot produce or post the report, such as on a bad file, bad setting or failed request.
Pass `--output <file>` to append the comment text to a file (such as `$GITHUB_STEP_SUMMARY`) instead of posting it.
Use `--output` on pull requests from forks and Dependabot, where the workflow token cannot post pull request comments.

The CI workflow on the base commit can still be in progress when the pull request finishes its coverage run.
Run `repoutils wait-for-base-coverage <owner/repo> <base>` before `post-patch-coverage`.
This command polls the `coverage/project` commit status on the base commit and exits as soon as that status exists.
While the status is absent, the command checks the `post-coverage-status` check run (`--check-name`) on that commit, exiting when that check run finishes.
The command also stops after 10 minutes (`--timeout`).
If the check run finishes or the wait times out without a status, the command prints a warning and exits with code `0`.
A broken base commit therefore does not fail the checks on the pull request.
This command requires the `checks: read` and `statuses: read` permissions.

### GitHub settings

`repoutils github-settings check` runs `check` for every GitHub settings command configured in `pyproject.toml`, following the order in the command table above.
It prints the names of the unconfigured commands that it skips, and fails if `pyproject.toml` configures none of them.
It runs all configured commands and fails if any command fails.
It forwards `--repo` and `--exit-zero` to every command, and forwards `--fail-on-unexpected` to the commands that support that option.

`repoutils github-settings ensure` runs `ensure` for each configured command in the same order, excluding `secrets` and `variables` because those commands have no `ensure` subcommand.
It stops immediately at the first command that fails.
Stopping on failure prevents `deploy-keys ensure` from storing a secret in an environment before `environments ensure` applies the protection rules for that environment.

`repoutils github-settings dump` runs `dump` for every settings command regardless of `pyproject.toml`, with a blank line between the outputs.
You can paste the output directly into `pyproject.toml`.

### Labels

`repoutils labels ensure` creates every label defined in `pyproject.toml` that does not exist in the repository, using a grey color when `pyproject.toml` omits `color`.
When an existing label has an empty description on GitHub, `ensure` sets the description from `pyproject.toml`.

By default, `ensure` reports other differences without modifying them:

- label names that differ in letter case
- differences in color
- differences in non-empty descriptions

Pass `--strict` to update those existing labels to match `pyproject.toml`.
`ensure` never modifies or deletes a label that `pyproject.toml` does not define.
If a request fails mid-run, earlier label changes remain in place, and you can run `ensure` again to finish the rest.

`repoutils labels check` does not modify the repository.
It fails in the exact cases where `ensure` (with the same `--strict` option) would create or update a label.
It also prints the differences that `ensure` leaves unchanged, without failing on them.

When you pass `--fail-on-unexpected`, `check` also lists any labels in the repository that `pyproject.toml` does not define (matching names case-insensitively) and fails if any exist.
Use `--fail-on-unexpected` when `pyproject.toml` must define every label in the repository.
`ensure` still ignores unexpected labels, so you must delete them on GitHub or add them to `pyproject.toml`.

When you pass `--exit-zero`, `check` prints the same report and exits with code `0`, unless an error (such as a bad token) stops it from comparing.
Using `--exit-zero` is safer than `|| true` in a shell script because `|| true` also hides runtime and authentication errors.

In GitHub Actions, `ensure` requires the `issues: write` permission, and `check` requires `issues: read` on a private repository.

`repoutils labels dump` prints every label in the repository as `[[tool.repoutils.labels]]` entries, including the name, color, and non-empty description of each label.
You can paste the output into `pyproject.toml` and edit the entries as needed.
If you paste the output without changes, `repoutils labels check --strict` passes.
`dump` does not read or modify `pyproject.toml`.

### Repository settings

`[tool.repoutils.repo-settings]` configures the settings on the General settings page of a repository, primarily in the Features and Pull Requests sections.
Every setting is optional, but `check` and `ensure` fail if the table contains no settings.
Any setting omitted from the table keeps its current value on GitHub.

| Setting | Values | On GitHub |
|---|---|---|
| `description`, `homepage` | string (`""` for empty) | Populates the repository About box. |
| `issues`, `projects`, `wiki`, `discussions`, `pull-requests` | `true` or `false` | Whether each repository feature is enabled. |
| `pull-request-creation` | `"all"` or `"collaborators"` | Who can create pull requests. |
| `merge-commit.allow`, `squash-merge.allow`, `rebase-merge.allow` | `true` or `false` | Which pull request merge methods are enabled. |
| `merge-commit.title` | `"merge-message"` or `"pr-title"` | Default title of a merge commit (`"merge-message"` produces `Merge pull request #123 from branch`). |
| `merge-commit.message` | `"pr-title"`, `"pr-body"` or `"blank"` | Default message body of a merge commit. |
| `squash-merge.title` | `"pr-title"` or `"commit-or-pr-title"` | Default title of a squash commit (`"commit-or-pr-title"` uses the commit title when the pull request has one commit). |
| `squash-merge.message` | `"pr-body"`, `"commit-messages"` or `"blank"` | Default message body of a squash commit. |
| `allow-auto-merge` | `true` or `false` | Allow auto-merge on pull requests. |
| `allow-update-branch` | `true` or `false` | Always suggest updating pull request branches. |
| `delete-branch-on-merge` | `true` or `false` | Automatically delete head branches after merge. |
| `require-web-commit-signoff` | `true` or `false` | Require contributors to sign off on web-based commits. |

The GitHub API accepts a commit message setting only when the request also includes the corresponding commit title setting.
When `pyproject.toml` sets only `squash-merge.message` (or `merge-commit.message`), `repoutils` sends that message together with the title currently set on GitHub.
GitHub rejects some combinations of title and message, and `ensure` reports that rejection as an HTTP 422 error.

`repo-settings` intentionally excludes destructive or structural settings.
It cannot rename, transfer or archive a repository, change its default branch or visibility, or make it a template.
It rejects any configuration table that contains those keys.

`repoutils repo-settings ensure` updates all differing settings in a single API request.
It then verifies the response and fails if GitHub did not apply every change.
GitHub silently ignores some requested changes instead of returning an error, such as when an organization policy forbids the change.

`repoutils repo-settings check` does not modify the repository, and fails in the exact cases where `ensure` would update a setting.
`--exit-zero` works in the same way as in `labels check`.

`ensure` requires a token with administration write access to the repository, such as a fine-grained personal access token with the Administration `write` permission.
The `GITHUB_TOKEN` provided by GitHub Actions cannot have the Administration permission.

`repoutils repo-settings dump` prints every setting from the table above with its current value in the repository.
The output is a `[tool.repoutils.repo-settings]` table with a sub-table for each merge method.
Paste the output into `pyproject.toml` and remove the settings that you do not want to manage.
If you paste the output without changes, `repoutils repo-settings check` passes.
`dump` does not read or modify `pyproject.toml`.
If GitHub omits a setting from its response or returns an unsupported value, `dump` omits that setting and prints a warning to standard error.

### Actions settings

`[tool.repoutils.actions-settings]` configures the GitHub Actions settings page of the repository (Settings > Actions > General).
It follows the same model as `[tool.repoutils.repo-settings]`.
Every setting is optional, but `check` and `ensure` fail if the table contains no settings.
Any setting omitted from the table keeps its current value on GitHub.

| Setting | Values | On GitHub |
|---|---|---|
| `allowed-actions` | `"all"`, `"owner"`, `"selected"` or `"disabled"` | Determines whether all actions and reusable workflows can run, only those belonging to the repository owner, only those in `selected-actions`, or none (Actions is disabled). |
| `require-sha-pinning` | `true` or `false` | Require actions to be pinned to a full-length commit SHA. |
| `selected-actions.github-owned` | `true` or `false` | Allow actions created by GitHub. |
| `selected-actions.verified-creators` | `true` or `false` | Allow actions created by Marketplace verified creators. |
| `selected-actions.patterns` | list of strings | Patterns for other allowed actions and reusable workflows (such as `"astral-sh/*"`), in any order. |
| `default-token-permissions` | `"read"` or `"write"` | Controls whether `GITHUB_TOKEN` gets read-only or read-write permissions by default. |
| `can-approve-pull-requests` | `true` or `false` | Allow GitHub Actions to create and approve pull requests. |
| `fork-pr-approval` | `"first-time-contributors-new-to-github"`, `"first-time-contributors"` or `"all-external-contributors"` | Which external contributors require approval before workflows run on their fork pull requests. |
| `retention-days` | positive integer | Number of days that GitHub retains checks, workflow runs, commit statuses, artifacts and logs. |
| `cache-retention-days` | positive integer | Number of days that GitHub retains an unused Actions cache. |
| `cache-size-gb` | positive integer | Maximum total cache storage in gigabytes before GitHub evicts the oldest caches. |
| `oidc.use-default-subject` | `true` or `false` | Use the default template for the OpenID Connect (OIDC) token subject claim. |
| `oidc.include-claim-keys` | list of strings | Ordered list of claim keys for a custom OIDC subject template (requires `oidc.use-default-subject = false`). |
| `oidc.immutable-subject` | `true` or `false` | Use the immutable OIDC subject claim based on the numeric repository ID instead of the repository name. |

The `selected-actions` settings require `allowed-actions = "selected"`, because GitHub stores them only in that mode.

`repoutils actions-settings ensure` updates all differing settings, sending one API request for each endpoint that requires a change.
It fails if GitHub does not apply every requested change.
An organization policy can lock some settings, such as write permissions for `GITHUB_TOKEN`.
GitHub rejects changes to a locked setting with an HTTP 409 error, and `ensure` reports that error.
Some settings do not exist on all repositories, such as `fork-pr-approval` on a private repository.
GitHub returns HTTP 404 for those endpoints, so `check` and `ensure` fail when `pyproject.toml` configures them, and `dump` omits them.

`repoutils actions-settings check` does not modify the repository, and fails in the exact cases where `ensure` would update a setting.
`--exit-zero` works in the same way as in `labels check`.

`check` and `dump` require a token with read access to repository administration settings, plus read access to Actions when reading `oidc` settings.
For a fine-grained personal access token, grant Administration and Actions `read` for `check` and `dump`, and `write` for `ensure`.
The `GITHUB_TOKEN` provided by GitHub Actions cannot have the Administration permission.

`repoutils actions-settings dump` prints every setting from the table above with its current value in the repository.
It omits `selected-actions` unless `allowed-actions` is `"selected"`, and omits `oidc.include-claim-keys` when the repository uses the default OIDC template.
Paste the output into `pyproject.toml` and remove the settings that you do not want to manage.
If you paste the output without changes, `repoutils actions-settings check` passes.
`dump` does not read or modify `pyproject.toml`.
If GitHub omits a setting from its response or returns an unsupported value, `dump` omits that setting and prints a warning to standard error.

### Rulesets

Each `[tool.repoutils.rulesets.<name>]` table defines one branch ruleset or tag ruleset in the repository (Settings > Rules > Rulesets).
The table specifies only the settings that differ from the defaults of a new ruleset.
Omitted rules are disabled, omitted `exclude` and `bypass` lists are empty, and other omitted settings use their defaults.
The table defines the complete ruleset, and `ensure` disables any rule that the table omits.

`repoutils rulesets` ignores push rulesets.
It also ignores rulesets inherited from an organization and legacy branch protection rules.

| Setting | Values | On GitHub |
|---|---|---|
| `target` | `"branch"` (default) or `"tag"` | Whether the ruleset applies to branches or tags. |
| `enforcement` | `"active"` (default), `"evaluate"` or `"disabled"` | Enforcement state of the ruleset. |
| `include`, `exclude` | branch or tag name patterns (such as `["main", "release/*"]` or `["v*"]`), `"~ALL"`, or `"~DEFAULT_BRANCH"` (for branch rulesets only) | Which branches or tags the ruleset targets. The `refs/heads/` or `refs/tags/` prefix is optional, and `include` is required. |
| `bypass` | list of actor tables (see below) | Which actors can bypass the ruleset. |
| `rules.<rule>` | `true`, or a table of rule parameters | Each rule enabled in the ruleset. |

Each table in `bypass` identifies one actor.
Specify the actor with `role` (`"admin"`, `"maintain"`, `"write"` or a custom role ID), `app` (a GitHub App slug), `team` (a team slug), `org-admin = true` or `deploy-keys = true`.
Each entry can also specify `mode` as `"always"` (default), `"pull-request"` or `"exempt"`.

For example, these two tag rulesets prevent anyone from updating or deleting a `v*` tag, and let only deploy keys create one.
They must be separate rulesets because a `bypass` list applies to all rules in its ruleset.

```toml
[tool.repoutils.rulesets.release-tags-immutable]
target = "tag"
include = ["v*"]

[tool.repoutils.rulesets.release-tags-immutable.rules]
update = true
deletion = true

[tool.repoutils.rulesets.release-tags-create]
target = "tag"
include = ["v*"]
bypass = [{ deploy-keys = true }]

[tool.repoutils.rulesets.release-tags-create.rules]
creation = true
```

Rule names and parameter names use the kebab-case forms of the names in the GitHub REST API and ruleset JSON exports.
For example, the API rule `non_fast_forward` is written as `rules.non-fast-forward`.
A tag ruleset can contain only the rules that GitHub supports for tags.
Those tag rules are `creation`, `update`, `deletion`, `required-linear-history`, `required-deployments`, `required-signatures`, `required-status-checks`, `non-fast-forward`, `tag-name-pattern` and the three commit metadata pattern rules.
The `tag-name-pattern` rule applies only to tag rulesets, and `check` rejects any rule placed in the wrong ruleset target.
Any omitted rule parameter uses the default value from the GitHub ruleset creation page, which is `false`, `0` or empty.
Two parameters have non-empty defaults: `pull-request.allowed-merge-methods` defaults to all three merge methods, and `merge-queue` defaults to the standard values on the GitHub page.

Above each rule or parameter whose GitHub UI label is known to `repoutils`, `dump` writes that label as a comment.
The following table lists the setting names that differ most from their labels in the GitHub UI:

| In `pyproject.toml` | On GitHub's ruleset page |
|---|---|
| `rules.deletion` | Restrict deletions |
| `rules.non-fast-forward` | Block force pushes |
| `required-status-checks.strict-required-status-checks-policy` | Require branches to be up to date before merging |
| `required-status-checks.do-not-enforce-on-create` | Do not require status checks on creation |
| `pull-request.dismiss-stale-reviews-on-push` | Dismiss stale pull request approvals when new commits are pushed |
| `pull-request.require-last-push-approval` | Require approval of the most recent reviewable push |
| `pull-request.required-review-thread-resolution` | Require conversation resolution before merging |
| `merge-queue.max-entries-to-build` | Build concurrency |
| `merge-queue.grouping-strategy` | Require all queue entries to pass required checks (`"ALLGREEN"`) or not (`"HEADGREEN"`) |

Configure each required status check as `{ context = "test", app = "github-actions" }`.
The `app` key is the slug of the GitHub App that must report the check status.
Omit `app` to accept the status check from any source.
`check` and `ensure` resolve the numeric app ID from the slug automatically, and reject a numeric app ID in `pyproject.toml`.

`repoutils rulesets ensure` creates every missing ruleset.
It replaces every ruleset that differs from `pyproject.toml`, sending all parameters for every configured rule.
It then reads the updated ruleset back and fails if GitHub did not apply a change.
It ignores rule parameters that `repoutils` does not recognize, so `ensure` can reset unknown parameters to their defaults.
It never deletes an existing ruleset.

`repoutils rulesets check` does not modify the repository, and fails in the exact cases where `ensure` would create or update a ruleset.
`--exit-zero` and `--fail-on-unexpected` work in the same way as in `labels check`.
For `rulesets check`, `--fail-on-unexpected` fails when the repository has branch or tag rulesets that `pyproject.toml` does not define.

The `check`, `ensure` and `dump` subcommands require a token with repository administration access, because GitHub shows the `bypass` list only to administrators.
For a fine-grained personal access token, grant Administration `write` for `ensure`, and grant Administration `read` for `check` and `dump`.
The `GITHUB_TOKEN` provided by GitHub Actions cannot have the Administration permission.
When a `bypass` entry references a team, the token also requires the organization Members `read` permission to resolve the team slug.

`repoutils rulesets dump` prints every branch and tag ruleset in the repository as `[tool.repoutils.rulesets.<name>]` tables.
You can paste the output into `pyproject.toml`.
If you paste the output without changes, `repoutils rulesets check --fail-on-unexpected` passes, unless `dump` printed a warning about an unsupported value.
Pass `--from-file` to convert JSON ruleset files exported from the GitHub ruleset UI instead of querying the repository API.
Using `--from-file` lets you design a ruleset in the GitHub UI on any repository and convert the exported JSON into `pyproject.toml` format.
`dump` does not read or modify `pyproject.toml`.

The GitHub REST API provides no endpoint to look up a GitHub App slug from its numeric app ID.
Instead, `dump` collects app slugs from the check runs on the latest commit of the default branch and of each branch named in the rulesets.
When `dump` cannot find the slug for an app or team ID, it prints the numeric ID and writes a warning to standard error.
Replace that numeric ID with the corresponding slug before you run `check`.

### Environments

Each `[tool.repoutils.environments.<name>]` table defines one deployment environment in the repository, which a GitHub Actions job references with `environment:`.
An empty table verifies or creates the environment without checking or changing its settings.
Any setting omitted from the table keeps its current value on GitHub.
Environment names match case-insensitively, as on GitHub, and GitHub cannot rename an existing environment.

| Setting | Values | On GitHub |
|---|---|---|
| `deployment-branches` | `"all"`, `"protected"` or `"selected"` | Controls which branches and tags can deploy to this environment (all, protected only, or a custom selection). |
| `allowed-branches`, `allowed-tags` | lists of name patterns, such as `["v*"]` | Selected branch and tag patterns allowed to deploy. Each list defines the complete set of patterns, and setting either list implies `deployment-branches = "selected"`. |
| `wait-timer` | integer from 0 to 43200 (minutes) | Number of minutes that a job waits before deploying to the environment. |
| `reviewers` | list of up to six user logins (`"login"`) or organization teams (`"owner/team-slug"`) | Required reviewers, where one reviewer must approve each deployment. |
| `prevent-self-review` | `true` or `false` | Prevent the user who triggered the workflow run from approving the deployment. |
| `can-admins-bypass` | `true` or `false` | Allow repository administrators to bypass the environment protection rules. |

Wait timers and required reviewers require a public repository or a paid GitHub plan.
On an unsupported plan, GitHub rejects those settings and `ensure` reports the HTTP error.

`repoutils environments ensure` creates every missing environment and updates every setting that differs from `pyproject.toml`.
It adds and removes branch and tag patterns so that the environment matches `allowed-branches` and `allowed-tags`.
It then verifies the environment and fails if GitHub did not apply a change.
It never deletes an environment, and never modifies environment secrets, environment variables or custom deployment protection rules.

`repoutils environments check` does not modify the repository, and fails in the exact cases where `ensure` would create or update an environment.
`--exit-zero` and `--fail-on-unexpected` work in the same way as in `labels check`.

`ensure` requires a token with administration write access to the repository, such as a fine-grained personal access token with the Administration `write` permission.
The `GITHUB_TOKEN` provided by GitHub Actions cannot have the Administration permission.

`repoutils environments dump` prints every environment in the repository along with all of its settings.
It includes `allowed-branches` and `allowed-tags` only when `deployment-branches` is `"selected"`.
Paste the output into `pyproject.toml` and remove the settings that you do not want to manage.
If you paste the output without changes, `repoutils environments check --fail-on-unexpected` passes.
`dump` does not read or modify `pyproject.toml`.

### Secrets

`[tool.repoutils.secrets]` lists the names of the secrets that the workflows in the repository use.
The `actions` key lists repository Actions secrets.
The `dependabot` key lists Dependabot secrets, which are available to workflows triggered by Dependabot.
Each `environments.<name>` key lists the secrets stored in the deployment environment `<name>`.
The command ignores any list that the table omits.
Secret names match case-insensitively, as on GitHub.
The `other` key lists secrets used by workflows that are not stored in the repository itself, such as organization secrets.
The `check` and `dump` subcommands ignore `other`, and only `check-workflows` reads `other`.

`repoutils secrets` reads only secret names from the GitHub API.
The GitHub API never returns secret values, so `repoutils secrets` has no `ensure` subcommand.
Set a missing secret with `gh secret set NAME` or on the repository settings page.
Pass `--app dependabot` for a Dependabot secret, or pass `--env ENVIRONMENT` for an environment secret.

`repoutils secrets check` fails if the repository lacks any secret or environment listed in the table.
It does not create missing environments, whereas `repoutils environments ensure` can create them.
`--exit-zero` and `--fail-on-unexpected` work in the same way as in `labels check`.
For `secrets check`, `--fail-on-unexpected` fails when a configured secret store contains a secret that its list does not name.
For example, `dependabot = []` requires the repository to have no Dependabot secrets.
When the table includes any `environments` key, `--fail-on-unexpected` covers the secrets of every environment in the repository, including environments not listed in the table.
Setting `environments = {}` requires every environment to have no secrets.

`check` and `dump` require a token that can list the secrets in the repository.
For a fine-grained personal access token, grant the Secrets `read` and Dependabot secrets `read` permissions.
Checking or dumping environment secrets also requires the Actions `read` and Environments `read` permissions.
The `GITHUB_TOKEN` provided by GitHub Actions cannot have those permissions.

`repoutils secrets dump` prints the name of every secret in the repository as a `[tool.repoutils.secrets]` table.
The output includes `actions`, `dependabot`, and an `environments.<name>` list for each environment that holds at least one secret.
You can paste the output into `pyproject.toml`.
If you paste the output without changes, `repoutils secrets check --fail-on-unexpected` passes.
`dump` does not read or modify `pyproject.toml`.

`repoutils secrets check-workflows` requires no GitHub token, so you can run it alongside local lint checks.
It scans every workflow file in `.github/workflows` for secret references written as `secrets.NAME` or `secrets['NAME']`.
It fails if a workflow references a secret not listed in `[tool.repoutils.secrets]`.
It also fails if `[tool.repoutils.secrets]` lists a secret which no workflow references.
This check keeps `[tool.repoutils.secrets]` synchronized with `.github/workflows`.
A workflow job can access an environment secret only when the job specifies that environment in `environment:`.
Therefore, `check-workflows` also fails when a job references an environment-only secret without specifying one of the environments that hold that secret.
When a job sets `environment:` to an expression, `check-workflows` cannot determine the environment name statically and skips environment secret checks for that job.
The command ignores `GITHUB_TOKEN` (which GitHub provides automatically) and ignores text inside YAML comments.

`repoutils secrets environments` also requires no GitHub token.
It prints the environments in `[tool.repoutils.secrets]` as a JSON array, such as `["release", "autofix"]`, for a workflow matrix that runs `inspect` once for each environment.
With `--with-repository`, the array starts with `""`, which stands for a job that deploys to no environment and inspects the repository secrets.
The `inspect-secrets.yml` workflow of this repository passes that array to its matrix with `fromJSON`, so the jobs always match `pyproject.toml`.

`repoutils secrets inspect` runs inside a GitHub Actions workflow and reports metadata about each secret without printing secret values.
Use `inspect` to identify which token or key a secret contains and to detect tokens that will expire soon.
Pass the job secrets to the command in the environment variable `SECRETS_JSON: ${{ toJSON(secrets) }}`.
By default, `inspect` reports on the secrets in `actions` and `other`, or on the secrets for one environment when you pass `--environment NAME`.
`inspect` also reports on every other secret in `SECRETS_JSON` that `pyproject.toml` does not list for the job, except the built-in `GITHUB_TOKEN`, and warns that each one is unexpected.
An unexpected secret does not make `inspect` fail, even when GitHub rejects it or `inspect` cannot inspect it.
A job that deploys to an environment also receives the repository and organization secrets, so `inspect --environment NAME` expects the secrets in `actions` and `other` as well, but does not report on them.
A workflow job receives the secrets of an environment only when the job deploys to that environment, so inspect each environment in a separate job.
Nothing in a run tells which level each secret comes from, and the `GITHUB_TOKEN` of a run cannot list secret names.
So `inspect-remote` lists the secret names that the repository and each environment have, and passes them to the workflow as JSON in its `secret-names` input.
The workflow gives that input to `inspect` in the environment variable `SECRET_NAMES: ${{ inputs.secret-names }}`.
When `SECRET_NAMES` is set, `inspect --environment NAME` does these things:

- It reports a listed secret that the environment does not have as missing, and names the repository or the organization as the source of the secret that the job gets instead.
- It does not report a secret that the environment does not list and does not have, because the repository job reports that secret.
- It warns that a secret which the environment has but does not list is unexpected, even when `actions` or `other` lists it.

An environment secret replaces a repository secret of the same name in the job, so `inspect` reports a secret that both levels have as the secret of the environment.
When `SECRET_NAMES` is empty or not set, as in a run that you start from the Actions page, `inspect --environment NAME` reports each listed secret that the job has as a secret of the environment, and its report says that it cannot tell inherited secrets apart.
`inspect` without `--environment` ignores `SECRET_NAMES`.
Workflows not triggered by Dependabot cannot read Dependabot secrets, so `inspect` skips `dependabot`.

When a secret value has the format of a GitHub token, `inspect` sends a read-only API request with that token.
It reports the token type (from the token prefix), the token owner, and the expiration date.
It also reports the scopes of a classic personal access token, or the number of repositories of a GitHub App installation token.
The GitHub API does not report which repositories a fine-grained token can access, so `inspect` does not report them.
`inspect` also reports the first 12 hexadecimal digits of the SHA-256 hash of each GitHub token, so you can see whether two secrets hold the same token.
A GitHub token is too random for anyone to recover it from its hash, but other secret values can be less random, so `inspect` does not hash them.
For the same reason, `inspect` does not hash a value shorter than 40 characters, even when it has a token prefix, as every GitHub token is at least that long.
An installation token expires after one hour, so `inspect` always reports an installation token stored in a secret as expiring.
When a secret value is an OpenSSH private key, `inspect` reports the public key fingerprint, which also appears on the GitHub deploy keys page.
For any other secret value, `inspect` reports only the secret name.
The command writes a Markdown summary table to `$GITHUB_STEP_SUMMARY` (or to `--summary FILE`), which has the same visibility as the workflow logs.

`inspect` fails in these cases, for a secret that `pyproject.toml` lists for the job:

- GitHub rejects a token.
- A token expires within 14 days (`--expires-within DAYS`).
- A token has surrounding whitespace.

Passing `--exit-zero` ignores those three findings, but the command still exits non-zero on a failed network request or an unparseable expiration date.

The `inspect-secrets` composite action of this repository runs `inspect` as the only step of a job.
It checks out `pyproject.toml`, runs `inspect`, and uploads the step summary as the artifact `step-summaries-<job>` (`step-summaries-<job>-<environment>` with an environment), so the job needs the Contents `read` permission.
In the name of the artifact, the action percent-encodes each `%`, and each character that an artifact name cannot hold, such as `/`.
Pass it the secrets as `secrets-json: ${{ toJSON(secrets) }}`, as a composite action cannot read them, and pass `environment` and `secret-names` where the job has them.

`repoutils secrets inspect-remote` runs `inspect` from your own machine.
It starts the workflow that runs `inspect` (`--workflow FILE`, default `inspect-secrets.yml`) on the default branch of the repository (`--ref BRANCH` to change it), and waits for the run to finish.
Then it prints the step summaries that the jobs of the run upload as `step-summaries-*` artifacts.
GitHub can hold a run for approval, and a job can wait for approval to deploy to an environment.
In both cases, `inspect-remote` prints the address of the run, where you can approve it, and continues to wait.
GitHub can answer that a run it has just started does not exist, so for 30 seconds after it starts the workflow, `inspect-remote` treats that answer as a delay and asks again.
Pass `--run-id ID` to print the summaries of an existing run instead of starting one.
`inspect-remote` fails in these cases:

- The run does not succeed.
- The run keeps no step summaries, for example because it ran on a branch other than `main`, where the jobs of `inspect-secrets.yml` do not run.
- The run does not finish within 30 minutes (`--timeout MINUTES`).

It uses `$GITHUB_TOKEN`, or `gh auth token` when that variable is not set, and the token needs the Actions write permission to start the workflow, or only the Actions read permission with `--run-id`.
When it starts the workflow, it lists the secret names for the `secret-names` input, so the token also needs the Secrets `read`, Actions `read` and Environments `read` permissions, which `--run-id` does not need.
Pass `--no-secret-names` to start the workflow without that input, for example when the workflow does not declare it, as GitHub rejects an input that a workflow does not declare.

`repoutils secrets export` also runs inside a GitHub Actions workflow and writes an encrypted backup of the secret values using [age](https://age-encryption.org).
Pass the job secrets in `SECRETS_JSON` in the same way as for `inspect`.
The command exports the `actions` list, or exports `environments.NAME` when you pass `--environment NAME`, and fails if `SECRETS_JSON` lacks any listed secret.
`export-remote` passes the secret names to the workflow in the same way as `inspect-remote`, and the workflow gives them to `export` in `SECRET_NAMES`.
When `SECRET_NAMES` is set, `export --environment NAME` fails if the environment does not have a listed secret, rather than export the repository or organization secret that the job gets instead.
When `SECRET_NAMES` is empty or not set, its summary says that it cannot tell inherited secrets apart.
It does not export `other` because those secrets belong to the organization rather than the repository.
It formats the secrets as a TOML table (`[actions]` or `[environments.NAME]`) and pipes the TOML text to the standard input of `age`.
The command never writes plaintext secrets to disk, and writes only the encrypted output file (`--output FILE`).

Each `--recipient` argument takes an `age` recipient string (`age1...`) or an SSH public key and passes it directly to `age`.
Pass `--github-key USER/SHA256:...` to encrypt to the SSH public key of the GitHub user `USER` that matches that `ssh-keygen -l` fingerprint.
The command downloads the user's public keys from `https://github.com/USER.keys` and fails if none of the keys matches the fingerprint.
`age` supports only `ssh-ed25519` and `ssh-rsa` SSH keys, and requires a plaintext private key file for decryption.
A key stored on a hardware security key or in a password manager agent cannot decrypt the backup.
Use a dedicated `age-keygen` key in that case.
Pass `--armor` to write ASCII-armored output instead of binary output (`age --decrypt` accepts both formats).
Pass `--age PATH` to specify the path to the `age` executable when `age` is not on `PATH`.
The command writes the exported secret names and the decryption command to `$GITHUB_STEP_SUMMARY` (or to `--summary FILE`).

Pass `--self-test` instead of `--output FILE` to check that the export works, for example in a CI job on every pull request.
It exports a made-up value for each listed secret, never a real one, so it needs no `SECRETS_JSON`.
It encrypts them to a throwaway key from `age-keygen` (`--age-keygen PATH`), to each `--recipient` and to each `--github-key`, with `--armor`.
Then it decrypts the output with the throwaway key, and fails in these cases:

- The output is not ASCII-armored.
- The `age` header does not name each SSH key given, by the tag that `age` derives from the key.
- The decrypted TOML does not give back exactly the made-up values.

As in a real export, the plaintext reaches `age` only on its standard input.

The command writes the encrypted file only to the runner, so add a workflow step after `export` to upload that file as a workflow artifact.
Any signed-in GitHub user can download artifacts from a public repository, so set a short `retention-days` and delete the artifact after download.
Deleting old artifacts prevents a future compromise of the private key from decrypting earlier backups left on GitHub.

`repoutils secrets export-remote` runs `export` from your own machine, and prints the decrypted secrets.
It starts the workflow that runs `export` (`--workflow FILE`, default `export-secrets.yml`) and waits for the run, in the same way as `inspect-remote`, with the same `--ref`, `--run-id`, `--timeout` and `--interval` options.
Then it downloads the encrypted files that the jobs of the run upload as `secrets-*` artifacts, and decrypts each file with `age`.
It decrypts with `~/.ssh/id_ed25519` and `~/.ssh/id_rsa`, whichever of the two files exist, or with each `--identity FILE` instead.
It writes the plaintext only to standard output, as one TOML document with a table for the repository and for each environment.
If any file fails to decrypt, it prints no secrets.
Pass `--save DIR` to also write the encrypted files to `DIR`, which the command creates if it does not exist.
Each file replaces any earlier file of the same name in `DIR`, so the latest backup replaces an earlier one.
When it finds no private key and you pass `--save DIR`, it only saves the encrypted files.
When it finds no private key and you do not pass `--save DIR`, it fails before it starts the workflow.
After it decrypts or saves every file, it deletes the `secrets-*` artifacts from the run, unless you pass `--keep-artifacts`.
`export-remote` fails in these cases:

- The run does not succeed.
- The run keeps no `secrets-*` artifacts, for example because it ran on a branch other than `main`, where the jobs of `export-secrets.yml` do not run.
- The run does not finish within 30 minutes (`--timeout MINUTES`).
- `age` fails to decrypt a file.

It uses `$GITHUB_TOKEN`, or `gh auth token` when that variable is not set, and the token needs the Actions write permission to start the workflow and to delete the artifacts.
It needs the same permissions as `inspect-remote` to list the secret names, and also takes `--no-secret-names`.
When it starts the run with the `secret-names` input, it also reads when each environment secret was last set, before the run starts and after it ends.
It fails if an environment secret was deleted or set again in the meantime, as the job could then have exported the inherited secret of that name.
It then prints and saves no secrets, and deletes the `secrets-*` artifacts even with `--keep-artifacts`, so that a later `--run-id` cannot print them.
It does the same if it cannot list the environment secrets again to check.
If it cannot delete an artifact, it names that artifact in the error, for you to delete by hand.
With `--run-id` or `--no-secret-names`, it does not make this check.
With `--run-id` and `--keep-artifacts`, the token needs only the Actions read permission.

### Variables

`[tool.repoutils.variables]` lists the GitHub Actions variables that the workflows in the repository use, following the same structure as `[tool.repoutils.secrets]`.
The `actions` key lists repository variables, and each `environments.<name>` key lists variables for the deployment environment `<name>`.
The `other` key lists variables used by workflows that are not stored in the repository (such as organization variables), and only `check-workflows` reads `other`.
The configuration table stores only variable names and never stores variable values, so `repoutils variables` has no `ensure` subcommand.
Set a missing variable with `gh variable set NAME` (with `--env ENVIRONMENT` for an environment variable) or on the repository settings page.

`repoutils variables check` fails if the repository lacks any variable or environment listed in the table.
Unlike secret values, variable values are readable through the API, so `check` also fails when a variable value is empty or contains only whitespace.
`--exit-zero` and `--fail-on-unexpected` work in the same way as in `secrets check`.

`check` requires a token with the Variables `read` permission.
Checking environment variables also requires the Actions `read` and Environments `read` permissions.
The `GITHUB_TOKEN` provided by GitHub Actions cannot have those permissions.

`repoutils variables dump` prints the name of every variable in the repository as a `[tool.repoutils.variables]` table.
It reads the variables from the API but omits their values from the output.

`repoutils variables check-workflows` requires no GitHub token, just like `secrets check-workflows`.
It scans `.github/workflows` for variable references written as `vars.NAME` or `vars['NAME']`.
It fails if a workflow references a variable that no configured list names, or if a configured list names a variable that no workflow references.
If you create a variable before any workflow uses it, list its name in `unused` in addition to its store list (`actions` or `environments.<name>`).
`check-workflows` then allows the unused variable, and fails once a workflow references that variable so that you remove it from `unused`.
The command also fails when a job references an environment-only variable without specifying one of the environments that hold that variable in `environment:`.
GitHub Actions evaluates a job's `if`, `runs-on`, `name`, and `environment` name expressions before loading the job environment ([actions/runner#2472](https://github.com/actions/runner/issues/2472)).
Variables scoped to a deployment environment always evaluate to empty strings in those fields.
Therefore, `check-workflows` also fails when any of those fields references an environment-only variable, even when the job deploys to that environment.

### Deploy keys

Each `[tool.repoutils.deploy-keys.<title>]` table declares one repository deploy key whose GitHub title is `<title>`.
Set `write = true` to grant write access to the key, or omit `write` to make the key read-only.
The `secret` key specifies the Actions secret that stores the private half of the deploy key, written as `{ name = "NAME" }` for a repository secret.
Add `environment = "ENVIRONMENT"` inside `secret` to store the private key in a deployment environment secret.
`pyproject.toml` does not store the public key material, so rotating a key requires no commit to the repository.
An empty `[tool.repoutils.deploy-keys]` table declares that the repository has no write-capable deploy keys.

`repoutils deploy-keys ensure` creates every missing deploy key that specifies `secret`.
It runs `ssh-keygen` to generate an Ed25519 key pair in a private temporary directory, and deletes that directory before exiting.
It uploads the public key to the repository and pipes the private key on standard input to `gh secret set`.
It passes its GitHub token to `gh` in the `GH_TOKEN` environment variable.
If `gh secret set` fails, `ensure` deletes the newly created deploy key from the repository.
Creating or rotating a key requires `ssh-keygen` and `gh`, whereas `check` and `dump` do not run either tool.

GitHub cannot change the read/write access of an existing deploy key.
If a key has the wrong access, the behavior of `ensure` depends on whether the key has a `secret`.
If it has a `secret`, `ensure` generates a new key pair, replaces the deploy key, and updates that `secret`.
If it lacks a `secret`, `ensure` re-adds the existing public key with the configured access.
Run `ensure --rotate <title>` to replace a deploy key and its secret, adding the new key before deleting the old key.
`ensure` refuses to create a missing key that omits `secret`, because the generated private key would not be saved anywhere.
It also fails when the target environment for `secret` does not exist, which `repoutils environments ensure` can create.
It never deletes a deploy key that `pyproject.toml` does not declare.

`repoutils deploy-keys check` does not modify the repository.
It fails in the following cases:

- a declared key is missing, has the wrong read/write access, or shares its title with another key in the repository
- the configured secret is missing
- the secret was updated before the deploy key was created – such a secret may not hold the private key of that deploy key

Because `ensure` cannot recover a lost private key to fix a missing or outdated secret, it instructs you to run `ensure --rotate <title>`.
`check` always fails on any undeclared write-capable deploy key, because a ruleset deploy-key bypass covers all write-capable deploy keys in the repository.
Pass `--fail-on-unexpected` to fail on undeclared read-only deploy keys as well.
`--exit-zero` works in the same way as in `labels check`.

`ensure` requires a token that can administer the repository, such as a fine-grained token with the Administration `write` and Secrets `write` permissions.
Storing a private key in an environment secret requires the Environments `write` and Actions `read` permissions instead of Secrets `write`.
`check` requires `read` access for the same permissions.

`repoutils deploy-keys dump` prints every deploy key in the repository as `[tool.repoutils.deploy-keys.<title>]` tables with their access settings.
The GitHub API does not link a deploy key to a secret, so add the `secret` setting to each dumped table manually.
If multiple deploy keys share the same title, `dump` prints that title once and writes a warning to standard error.
`dump` does not read or modify `pyproject.toml`.

### Security settings

`[tool.repoutils.security-settings]` configures the repository security settings on the Advanced Security settings page that the GitHub REST API supports, plus release immutability.
Every setting takes `true` or `false`.
Every setting is optional, but `check` and `ensure` fail if the table contains no settings.
Any setting omitted from the table keeps its current value on GitHub.

| Setting | On GitHub's settings pages |
|---|---|
| `private-vulnerability-reporting` | Private vulnerability reporting |
| `dependabot-alerts` | Dependabot alerts |
| `dependabot-security-updates` | Dependabot security updates |
| `codeql-default-setup` | CodeQL analysis, with the default setup (`true`) or not set up (`false`) |
| `secret-protection` | Secret Protection |
| `push-protection` | Push protection, under Secret Protection |
| `immutable-releases` | Enable release immutability, under Releases on the General page |

The Advanced Security page includes additional settings that the GitHub REST API cannot read or update independently, so `[tool.repoutils.security-settings]` rejects them.
Those unsupported settings are the dependency graph, automatic dependency submission, Dependabot malware alerts, grouped security updates, and Copilot Autofix.
Enabling `dependabot-alerts` automatically enables the dependency graph.
The `codeql-default-setup` setting only enables or disables CodeQL default setup, and leaves the analyzed languages and query suite to GitHub.
Enabling `immutable-releases` prevents anyone from modifying the assets of a published release or moving or deleting its Git tag.
Release immutability protects a tag only after release publication, so it does not replace a tag ruleset that restricts who can push release tags.

Some security settings depend on another setting.
`dependabot-security-updates` requires `dependabot-alerts`, and `push-protection` requires `secret-protection`.
The configuration table cannot enable a dependent setting while disabling the setting that it requires.
If the table enables a dependent setting and omits the required setting while that required setting is disabled on GitHub, `ensure` fails.
`ensure` disables settings before enabling settings, and applies changes in dependency order.

`repoutils security-settings ensure` updates every differing setting and then reads all settings back from GitHub.
It fails if GitHub did not apply every requested change.
GitHub can ignore or reject a change when the repository plan lacks the feature, such as CodeQL on a private repository without Code Security.
GitHub can also ignore a change when an organization policy or security configuration controls the setting, such as organization-wide immutable releases.
When enabling `codeql-default-setup`, GitHub configures CodeQL asynchronously, so `ensure` polls for up to two minutes until the setup completes.

`repoutils security-settings check` does not modify the repository, and fails in the exact cases where `ensure` would update a setting.
`--exit-zero` works in the same way as in `labels check`.

The `check`, `ensure` and `dump` subcommands require a token with repository administration access, because GitHub hides these settings from other tokens.
For a fine-grained personal access token, grant Administration `write` for `ensure`, and grant Administration `read` for `check` and `dump`.
The `GITHUB_TOKEN` provided by GitHub Actions cannot have the Administration permission.
When a token lacks permission to view a security setting, `check` fails instead of treating the setting as disabled.

`repoutils security-settings dump` prints every setting from the table above with its current repository value, under a comment with its GitHub UI label.
Paste the output into `pyproject.toml` and remove the settings that you do not want to manage.
If you paste the output without changes, `repoutils security-settings check` passes.
`dump` does not read or modify `pyproject.toml`.
If GitHub refuses to return a setting, `dump` omits that setting and prints a warning to standard error.

### GitHub releases

Each `[tool.repoutils.github-releases.<name>]` table names a project on GitHub whose release assets this project pins by digest.
`<name>` must start with a letter or digit, and can contain only letters, digits, `_`, `.` and `-`, as it is part of the name of the branch that `bump --pr` creates.

| Setting | Value |
|---|---|
| `repo` | The repository of the project, as `owner/name`. Required. |
| `file` | The path of the pins file, relative to `pyproject.toml` and inside its directory. Required. Each table needs its own pins file. |
| `assets` | A list of glob patterns, such as `["*.vsix"]`, for the names of the assets to pin. Required. |
| `cooldown-days` | The number of days after its publication that a release must wait before `check` and `bump` use it. The default is `7`, as in the cooldown of Dependabot. |

`check` and `bump` use the newest release of `repo` that meets all these conditions:

- It is not a draft.
- It is not a prerelease.
- It was published at least `cooldown-days` days ago.

They use that release only if it was published after the release that the pins file has in use.
They therefore never replace a newer release that you pinned by hand, such as a prerelease.

`repoutils github-releases check` fails if a table has a newer release to use.
With `--exit-zero`, it reports that release, but exits `0`.
It still exits `1` if it cannot read the pins file or the releases.
Do not run `check` in pull request CI, because a new release would then make unrelated pull requests fail.

`repoutils github-releases bump` adds the newer release to the pins file and makes it the release in use.
It takes the digest of each asset from the GitHub API, and never downloads an asset.
It fails if a pattern in `assets` matches no asset of the release, or if GitHub gives no `sha256` digest for a matching asset.
GitHub gives digests only for assets uploaded since June 2025.
With `--pr`, `bump` commits each change to a new branch, `github-releases/<name>/<tag>`, pushes the branch to `origin`, and opens a pull request into the current branch.
It does nothing for a table if a pull request from that branch is already open.
It fails if the branch exists without an open pull request, such as after you close the pull request, until you delete the branch.
Both commands use every table, or only the tables whose names you give.

`repoutils` writes the pins file, and the project reads it at runtime.
The pins file is TOML:

```toml
# Generated by `repoutils github-releases bump`, which rewrites this whole file,
# so a comment or change of layout here doesn't last.

repo = "SonarSource/sonarlint-vscode"
current = "4.20.0"

[releases."4.20.0"]
"sonarlint-vscode-4.20.0.vsix" = "sha256:<64 hexadecimal digits>"

[releases."4.19.0"]
"sonarlint-vscode-4.19.0.vsix" = "sha256:<64 hexadecimal digits>"
```

- `current` is the tag of the release in use.
- Each `releases` table maps the name of each asset of a release to its SHA-256 digest, in the form that the GitHub API gives.
- The file keeps the earlier releases, newest first, so that the project can go back to one.
- An asset of a release downloads from `https://github.com/<repo>/releases/download/<tag>/<name>`.

## Pinning uv and just

`check-pins` finds the version of uv and just that each step in `.github/workflows` and in the composite actions in `.github/actions` installs.
It fails unless each version is the minimum that the project requires:

- For uv, the minimum is the lower bound of `required-version` in the `[tool.uv]` table of `pyproject.toml`.
- For just, the minimum is the `minimum-version` setting of the justfile.

It reads the version from these steps:

- A step that uses `astral-sh/setup-uv` gives the version of uv as its `version` input.
- A step that uses `extractions/setup-just` gives the version of just as its `just-version` input.
- A step that uses the `prepare-publish` action of this repository gives the version of uv as its `uv-version` input, and the version of just as its `just-version` input.
  If the step does not set an input, the action installs the version that repoutils pins, and `check-pins` fails.

In a composite action, a step can take the version from an input of the action, as `${{ inputs.<name> }}`.
`check-pins` then reads the version from the `default` of that input.
A step that uses that local action and sets the input must give the same version.

`dependabot-uv bump` changes the version of uv in each of these places.

## Recording the commit in a build

`repoutils` includes a build hook for [hatchling](https://hatch.pypa.io/latest/plugins/build-hook/reference/) that writes the Git commit of a build to a JSON file in the sdist and the wheel.
`repoutils version` reads this file in builds of `repoutils` itself.
Another project that builds with hatchling can use the hook too:

```toml
[build-system]
requires = ["hatchling", "repoutils==<version>"]
build-backend = "hatchling.build"

[tool.hatch.build.hooks.repoutils-build-info]
file = "src/example/build_info.json"
```

`file` is the path of the JSON file in the project.
The project reads the file at runtime itself, for example with `importlib.resources`, as the hook only writes it.
The file has two keys:

- `commit` is the full hash of the commit that Git has checked out.
- `dirty` is `true` if a file in the project differs from that commit, and `false` if no file differs.
  Untracked files count as differences, but files that `.gitignore` excludes do not.

Both values are `null` when the project is not in a Git repository with a commit, or when Git is not installed.

- A wheel that is built from an sdist gets the file from the sdist, and the hook does not run Git.
- An editable install gets no file, because the commit would be out of date after the next commit.
- The file contains no timestamp, so two builds of the same commit give the same file.

`check-install --wheel dist` checks that a wheel has the file, with the commit of the checkout, and `check-install --version <version>` checks that a release has it.

### Checking actions against a locked package

A project can use a package from `uv.lock` and also the GitHub Actions from the repository of that package.
`check-pins` then checks that the project runs both from the same commit.
It reads only local files:

1. For each package in `uv.lock` that is installed in the environment that runs `check-pins`, it takes the GitHub repository from the `Repository` project URL of the package.
2. It finds each action from that repository that a workflow uses directly in `.github/workflows/actions.lock`, the lock file that [`gh actions-lock`](https://github.com/github/gh-actions-lock) writes.
3. It finds the `build_info.json` file of the package through the `RECORD` file of the installed wheel, so the hook can write the file anywhere in the package.
4. It fails if the commit of an action differs from the commit in `build_info.json`, or if `dirty` is `true`.

If the package has no `build_info.json`, or its `commit` is `null`, `check-pins` checks only that the ref of each action is `v<version>`, and prints a warning.
The check fails on any of these errors:

- The installed version of a package whose repository has an action in `actions.lock` is not a version in `uv.lock`.
- `actions.lock` or `uv.lock` cannot be read.
- The package has more than one `build_info.json`, or a `build_info.json` that cannot be read.

A project without `actions.lock` or `uv.lock` has nothing to check.

## Development

See [AGENTS.md](AGENTS.md).
