Compare commits

..
2 Commits
Author SHA1 Message Date
jaredandClaude Opus 5.5 9dea56ce98 feat: review_only input and an enumeration check in the monthly prompt
tests / unittest (push) Successful in 23s
review_only names listed documents the drafter may read but not edit. They stay
in stage 1, are listed separately in the prompt, and a change to one fails the
run like a change outside docs. Each entry must match a docs pattern.

The monthly prompt now makes checking every list and count in the top-level
documents against the repository the drafter's main job. Mode-specific text
moves to prompts/mode-pr.md and prompts/mode-monthly.md; the pr text is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:40:09 -05:00
jaredandClaude Opus 5.5 f39409e62c feat: reusable review workflow
tests / unittest (push) Successful in 19s
Callers use Civilytics/docs-review/.gitea/workflows/review.yml@v1 with secrets: inherit.
Stage 1 on every pull request; for drafter: claude, a 180-second wait and then the sandboxed
drafter; closed pull requests close their docs PR; schedule and dispatch run the monthly
pass. Tested live against Gitea 28.3 (drafter none, a misspelled drafter, claude, close).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:12:57 -05:00
20 changed files with 689 additions and 55 deletions

No files matched your search

+237
View File
@@ -0,0 +1,237 @@
# The reusable docs-review workflow. A repository calls it from its own workflow with
# `uses: Civilytics/docs-review/.gitea/workflows/review.yml@v1`; README.md has the
# caller and the inputs.
#
# Secrets reach only the steps that need them. The bot token is in the clone step and
# the two steps that run the tool. The Claude credentials are in the drafting step only,
# and that step runs only when `drafter` normalizes to `claude`. Every `if:` reads the
# normalized drafter, never the raw input.
name: docs-review
on:
workflow_call:
inputs:
drafter:
description: "claude, local or none; anything else behaves as none"
type: string
required: false
default: none
docs:
description: "Newline-separated paths or globs of the living documents"
type: string
required: true
generated:
description: "Newline-separated paths of documents that are rebuilt, never hand-edited"
type: string
required: false
default: ""
top_level:
description: "The subset of docs the monthly pass re-reads in full"
type: string
required: false
default: README.md
review_only:
description: "Newline-separated paths or globs within docs that the drafter may read but not edit"
type: string
required: false
default: ""
source_dirs:
description: "Newline-separated directories whose new files count toward uncovered"
type: string
required: false
default: "R\nscripts"
workstream:
description: "Scope in draft commit messages, docs(<workstream>): ..."
type: string
required: false
default: docs
tracking_issue:
description: "Issue number the monthly pass's commits cite"
type: string
required: false
default: ""
doc_guide:
description: "Path to the document naming each listed document's reader and purpose"
type: string
required: false
default: ""
model:
description: "Model for drafter: claude"
type: string
required: false
default: claude-sonnet-5-5
# Gitea 28.3 does not tell a called workflow its own ref (github.workflow_ref and
# job_workflow_sha are empty, and GITHUB_WORKFLOW_SHA is the caller's commit), so
# the caller names the tool version twice.
tool_ref:
description: "Branch or tag of docs-review to run; keep it equal to the @ref in uses:"
type: string
required: false
default: v1
secrets:
DOCS_REVIEW_BOT_TOKEN:
required: false
CLAUDE_CODE_OAUTH_TOKEN:
required: false
ANTHROPIC_API_KEY:
required: false
defaults:
run:
shell: bash
jobs:
review:
runs-on: ubuntu-latest
# node:22 carries python3 (3.11) and git, and npm for the Claude Code install.
container: node:22
# The drafter's own timeout is 25 minutes; the debounce adds 3.
timeout-minutes: 40
env:
TOOL_REPO: Civilytics/docs-review
TOOL_REF: ${{ inputs.tool_ref }}
EVENT: ${{ github.event_name }}
ACTION: ${{ github.event.action }}
PR: ${{ github.event.pull_request.number }}
BASE: ${{ github.event.pull_request.base.ref }}
HEAD_REF: ${{ github.event.pull_request.head.ref }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
INPUT_DRAFTER: ${{ inputs.drafter }}
INPUT_DOCS: ${{ inputs.docs }}
INPUT_GENERATED: ${{ inputs.generated }}
INPUT_TOP_LEVEL: ${{ inputs.top_level }}
INPUT_REVIEW_ONLY: ${{ inputs.review_only }}
INPUT_SOURCE_DIRS: ${{ inputs.source_dirs }}
INPUT_WORKSTREAM: ${{ inputs.workstream }}
INPUT_TRACKING_ISSUE: ${{ inputs.tracking_issue }}
INPUT_DOC_GUIDE: ${{ inputs.doc_guide }}
INPUT_MODEL: ${{ inputs.model }}
# The calling repository's files are untrusted. Every python3 call takes -P, so
# Python imports nothing from the working directory and a docs_review/ or os.py in
# a pull request cannot replace the tool.
steps:
- name: Versions
run: |
python3 --version
git --version
node --version
- name: Fetch docs-review
run: |
set -eu
tool="$RUNNER_TEMP/docs-review"
git clone -q --depth 1 --branch "$TOOL_REF" -- \
"$GITHUB_SERVER_URL/$TOOL_REPO.git" "$tool"
echo "docs-review $TOOL_REF at $(git -C "$tool" rev-parse --short HEAD)"
echo "PYTHONPATH=$tool" >> "$GITHUB_ENV"
- name: Normalize the drafter
id: drafter
run: |
set -eu
drafter="$(python3 -P -c 'import os; from docs_review.inputs import normalize_drafter; print(normalize_drafter(os.environ.get("INPUT_DRAFTER")))')"
echo "drafter: ${INPUT_DRAFTER:-<unset>} -> $drafter"
echo "drafter=$drafter" >> "$GITHUB_OUTPUT"
# Full history, so merge bases and the docs branch's ancestry resolve. The token
# travels as an http.<server>/.extraHeader in this command's environment, so it is
# sent only to the Gitea server and never written to .git/config or a remote URL.
- name: Clone the calling repository
if: github.event_name != 'pull_request' || github.event.action != 'closed'
env:
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
run: |
set -eu
if [ -z "$DOCS_REVIEW_BOT_TOKEN" ]; then
echo "::error::the DOCS_REVIEW_BOT_TOKEN secret is not set"
exit 1
fi
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraHeader" \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
src="$(mktemp -d)"
if ! git clone -q -- "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" "$src"; then
echo "::error::the bot token could not clone $GITHUB_REPOSITORY; it needs the" \
"write:repository scope and write access to the repository"
exit 1
fi
cd "$src"
if [ "$EVENT" = "pull_request" ]; then
git fetch -q origin "refs/pull/$PR/head"
git fetch -q origin "+refs/heads/$BASE:refs/remotes/origin/$BASE"
git checkout -q --detach "$HEAD_SHA"
fi
git log --oneline -1
cd - >/dev/null
cp -a "$src/." . && rm -rf "$src"
- name: Close the docs PR of a closed pull request
if: github.event_name == 'pull_request' && github.event.action == 'closed'
env:
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
run: python3 -P -m docs_review closed --number "$PR"
# Stage 1 runs on every PR event. With drafter none it is the whole run and posts
# the comment; otherwise it only checks that the flags compute, and the drafting
# step after the debounce posts.
- name: Stage 1
if: >-
(github.event_name == 'pull_request' && github.event.action != 'closed')
|| ((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
&& steps.drafter.outputs.drafter == 'none')
env:
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
DOCS_REVIEW_STAGE: "1"
run: |
set -eu
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraHeader" \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
if [ "$EVENT" = "pull_request" ]; then
python3 -P -m docs_review pr --number "$PR" --base "$BASE" \
--head-ref "$HEAD_REF" --head-sha "$HEAD_SHA"
else
base="$(git rev-parse --abbrev-ref origin/HEAD)"
python3 -P -m docs_review monthly --month "$(date -u +%Y-%m)" --base "${base#origin/}"
fi
# A re-push inside this wait cancels the run (the caller's concurrency group)
# before anything is spent.
- name: Debounce
if: >-
github.event_name == 'pull_request' && github.event.action != 'closed'
&& steps.drafter.outputs.drafter != 'none'
run: sleep 180
# `local` runs here too, without the Claude credentials and without the install.
- name: Draft
if: >-
steps.drafter.outputs.drafter != 'none'
&& (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
|| (github.event_name == 'pull_request' && github.event.action != 'closed'))
env:
DRAFTER: ${{ steps.drafter.outputs.drafter }}
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
CLAUDE_CODE_OAUTH_TOKEN: ${{ steps.drafter.outputs.drafter == 'claude' && secrets.CLAUDE_CODE_OAUTH_TOKEN || '' }}
ANTHROPIC_API_KEY: ${{ steps.drafter.outputs.drafter == 'claude' && secrets.ANTHROPIC_API_KEY || '' }}
CLAUDE_CODE_VERSION: 2.1.322
DISABLE_UPDATES: "1"
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1"
run: |
set -eu
# A fresh HOME, so no settings, credentials or history from the image reach
# Claude Code.
export HOME="$(mktemp -d "$RUNNER_TEMP/home.XXXXXX")"
# With no credential the tool posts the flags with a note and fails, so the
# install would be wasted.
if [ "$DRAFTER" = "claude" ] && [ -n "$CLAUDE_CODE_OAUTH_TOKEN$ANTHROPIC_API_KEY" ]; then
npm install -g --no-fund --no-audit "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION"
claude --version
fi
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraHeader" \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
if [ "$EVENT" = "pull_request" ]; then
python3 -P -m docs_review pr --number "$PR" --base "$BASE" \
--head-ref "$HEAD_REF" --head-sha "$HEAD_SHA"
else
base="$(git rev-parse --abbrev-ref origin/HEAD)"
python3 -P -m docs_review monthly --month "$(date -u +%Y-%m)" --base "${base#origin/}"
fi
+59 -12
View File
@@ -5,12 +5,6 @@ the documents the change makes stale. If the repository opts in, it also has Cla
Code draft the edits. It is a Python package with no dependencies outside the standard
library.
## Status
The Python package and its tests are published here. The reusable Gitea Actions
workflow is not yet published, so the install snippet below is provisional and may
change.
## What it does
Stage 1 compares the pull request's changes with the documents you list. It uses no model
@@ -40,6 +34,11 @@ uncovered and unguided flags for the whole repository in one issue. With
- It never merges anything.
- It posts nothing when nothing is flagged.
For a pull request from a branch of the same repository, Gitea runs the caller workflow
from the pull request's head, so anyone who can push a branch can change the caller's
inputs. The safeguards in this README bound what the pull request's content can do, not
what an edited caller workflow file can do.
## What is sent to Anthropic
Nothing is sent unless the repository sets `drafter: claude`. With it, the drafter
@@ -48,34 +47,82 @@ receives the diff (or a list of changed files), the listed documents, the reposi
Claude runs with file tools only (read, search, edit), with no shell, and its permission
rules confine those tools to its working directory. That directory is a copy of the tree
with no `.git` and no symlinks, and only listed documents are copied back out of it.
with no `.git` and no symlinks, and only listed documents not marked `review_only` are
copied back out of it.
Its environment is an allowlist: system basics and its own Claude credential. The Gitea
token never reaches it, drafted files are checked for credential values before they are
committed, and everything posted to Gitea has credential values replaced with `***`.
## Install
Install instructions will be added with the reusable workflow. Until then, the package
can be run by hand: `python3 -m docs_review pr|closed|monthly --help`.
Add a workflow to the repository you want reviewed, at `.gitea/workflows/docs-review.yml`:
```yaml
name: docs-review
on:
pull_request:
branches: [main]
types: [opened, synchronize, reopened, closed]
schedule:
- cron: "0 9 1 * *" # the monthly pass, on the first of the month
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
docs:
uses: Civilytics/docs-review/.gitea/workflows/review.yml@v1
with:
tool_ref: v1
drafter: none
docs: |
README.md
docs/*.md
doc_guide: docs/README.md
secrets: inherit
```
- `closed` in the pull request types lets the workflow close a docs pull request whose
feature pull request merged or closed first.
- The `concurrency` block cancels a run when the pull request is pushed again. With
`drafter: claude` the workflow waits three minutes between stage 1 and drafting, so a
quick re-push cancels a run before it has spent anything.
- `tool_ref` must name the same version as the `@` in `uses:`. Gitea does not tell a
called workflow which ref it was called at, so the workflow fetches the tool's code at
`tool_ref`.
- A `workflow_dispatch` run is the monthly pass for the current month.
The job runs in the `node:22` image. It clones the repository with the bot token, so
it needs no checkout action, and it installs Claude Code
(`@anthropic-ai/claude-code`, a pinned version) only when `drafter` is `claude` and a
Claude credential is set. With `drafter: claude` and no credential, it posts the stage 1
comment with a note saying so and fails. The drafter's cost and turn count are printed
in the log and appended to `$GITHUB_STEP_SUMMARY`.
The package can also be run by hand: `python3 -m docs_review pr|closed|monthly --help`.
## Inputs
| Input | Default | Meaning |
|---|---|---|
| `drafter` | `none` | `none` flags only. `claude` also drafts edits. `local` is accepted but not yet built. |
| `drafter` | `none` | `none` flags only. `claude` also drafts edits. `local` is accepted but not yet built: it fails the job with "local drafter not built yet". Any other value, including a misspelling, behaves as `none`. |
| `docs` | required | Newline-separated patterns for the living documents. |
| `generated` | none | Patterns for generated files. |
| `top_level` | `README.md` | The subset of `docs` the monthly pass re-reads in full. |
| `source_dirs` | `R scripts` | Directories whose files count as source. |
| `review_only` | none | Newline-separated patterns for documents in `docs` that the drafter may read but not edit, such as a vision statement in the owner's own words. Stage 1 flags them like any listed document; the drafter reports what is stale in them instead of editing them, and a run that changes one fails like one that changes a file outside `docs`. Each entry must match a `docs` pattern. |
| `source_dirs` | `R` and `scripts` | Newline-separated directories whose files count as source. |
| `workstream` | `docs` | Scope in draft commit messages, as `docs(<workstream>): ...`. |
| `tracking_issue` | none | Issue number the monthly pass's commit messages cite. |
| `doc_guide` | none | Path to the document that says who reads each listed document and what it is for. The drafter writes for that reader. |
| `model` | `claude-sonnet-5-5` | Model used when `drafter` is `claude`. |
| `tool_ref` | `v1` | The docs-review branch or tag to run; the same as the `@` in `uses:`. |
## Secrets
- `DOCS_REVIEW_BOT_TOKEN` is required. It is a token for a Gitea bot account with
repository write, issue write and user read permissions.
write access to the repository and the token scopes `write:repository`,
`write:issue` and `read:user`. An organization secret serves every repository in the
organization.
- `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` is needed only for
`drafter: claude`.
+24 -1
View File
@@ -6,12 +6,15 @@ import json
import re
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
from docs_review.flags import Flag
from docs_review.git import Commit
from docs_review.inputs import matches_any
from docs_review.report import render_sections
PROMPTS = Path(__file__).resolve().parent.parent / "prompts"
MODES = ("pr", "monthly")
DIFF_CAP_BYTES = 200_000
LAST_HEAD = "<!-- docs-review:last-head={sha} -->"
_LAST_HEAD_RE = re.compile(r"<!-- docs-review:last-head=([0-9a-f]{40}) -->")
@@ -31,6 +34,21 @@ GUIDE_NOTE = (
"purpose; write each edit for that reader."
)
NO_GUIDE_NOTE = "No guide is set; make the smallest edit and match the surrounding document's voice."
REVIEW_ONLY_NOTE = (
"\nDocuments you may read but not edit:\n\n{paths}\n\n"
"If one of them is stale, do not edit it; add an entry to the summary's `declined` "
"list, with its path as `flag`, saying what is stale.\n"
)
def load_template(mode: str) -> str:
"""prompts/task.md with this mode's instructions, prompts/mode-<mode>.md, in place
of its {mode_text} field."""
if mode not in MODES:
raise ValueError(f"unknown mode {mode!r}; expected one of {', '.join(MODES)}")
task = (PROMPTS / "task.md").read_text(encoding="utf-8")
mode_text = (PROMPTS / f"mode-{mode}.md").read_text(encoding="utf-8")
return task.replace("{mode_text}", mode_text, 1)
def diff_payload(diff_text: str, numstat: str) -> str:
@@ -47,9 +65,13 @@ def diff_payload(diff_text: str, numstat: str) -> str:
def build_prompt(
template: str, *, mode: str, pr: int | None, flags_json: str, payload: str,
docs: tuple[str, ...], top_level: tuple[str, ...], guide_path: str | None,
review_only: tuple[str, ...] = (),
) -> str:
"""Fill the template's named fields. Only the template is parsed for braces."""
"""Fill the template's named fields. Only the template is parsed for braces.
`docs` are the documents the drafter may edit; `review_only` the listed documents it
may only read, rendered as their own section or, when there are none, as nothing."""
note = GUIDE_NOTE.format(path=guide_path) if guide_path else NO_GUIDE_NOTE
read_only = REVIEW_ONLY_NOTE.format(paths="\n".join(review_only)) if review_only else ""
return template.format_map({
"mode": mode,
"pr": "none" if pr is None else pr,
@@ -58,6 +80,7 @@ def build_prompt(
"docs": "\n".join(docs),
"top_level": "\n".join(top_level),
"guide_note": note,
"review_only": read_only,
})
+39 -4
View File
@@ -26,6 +26,8 @@ CREDENTIAL_NOTE = "drafted edits contained a credential value; nothing committed
DIRTY_NOTE = "working tree not clean before drafting"
EXPORT_NOTE = "drafter failed: could not export the tree for drafting: {reason}"
EXPORT_REASON_MAX = 200
NO_CREDENTIAL_NOTE = "drafter: claude but no Claude credential is set"
CREDENTIAL_VARS = ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY")
REFUSED_NOTE = "drafter failed: refusing to copy back `{path}` (symlink or outside the repository)"
@@ -78,6 +80,31 @@ def write_system_prompt(cwd: Path, guide_path: str | None,
return Path(name)
def has_claude_credential(env: Mapping[str, str]) -> bool:
return any((env.get(k) or "").strip() for k in CREDENTIAL_VARS)
def write_step_summary(result: DraftResult, env: Mapping[str, str]) -> None:
"""Print the run's cost and turns, whichever Claude reported, and append them to
$GITHUB_STEP_SUMMARY when the runner sets it."""
lines = []
if result.cost_usd is not None:
lines.append(f"- total_cost_usd: {result.cost_usd:.2f}")
if result.turns is not None:
lines.append(f"- num_turns: {result.turns}")
if not lines:
return
print("drafter " + ", ".join(l[2:] for l in lines))
path = env.get("GITHUB_STEP_SUMMARY")
if not path:
return
try:
with open(path, "a", encoding="utf-8") as fh:
fh.write("### docs-review drafter\n\n" + "\n".join(lines) + "\n")
except OSError as err:
print(f"warning: could not write the step summary: {err}", file=sys.stderr)
def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
system_prompt_file: Path | None) -> DraftResult:
"""Run the configured drafter in cwd. Task 12 adds `local`."""
@@ -97,12 +124,16 @@ def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
def disallowed(change: sandbox.TreeChange, listed: frozenset[str],
patterns: tuple[str, ...], root: Path) -> list[str]:
patterns: tuple[str, ...], root: Path,
review_only: tuple[str, ...] = ()) -> list[str]:
"""Changed paths the drafter may not touch. A listed document may change or go; a
new file must match a docs pattern; anything written must be a regular file."""
new file must match a docs pattern; anything written must be a regular file. Nothing
matching a review_only pattern may change, appear or go."""
bad = []
for p in change.paths:
ok = p in listed or (p in change.new and matches_any(p, patterns))
if ok and matches_any(p, review_only):
ok = False
if ok and p not in change.deleted and not sandbox.is_regular(root, p):
ok = False
if not ok:
@@ -129,6 +160,8 @@ class Drafted:
def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
env: Mapping[str, str]) -> Drafted:
"""Run the drafter on an export of HEAD and copy its allowed changes into cwd."""
if inputs.drafter == "claude" and not has_claude_credential(env):
return Drafted(None, (), NO_CREDENTIAL_NOTE)
if git.run(["status", "--porcelain"], cwd).strip():
return Drafted(None, (), DIRTY_NOTE)
box = prompt_file = None
@@ -143,13 +176,15 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
before = sandbox.snapshot(box)
prompt_file = write_system_prompt(box, inputs.doc_guide, env)
result = run_drafter(inputs, prompt, box, env, prompt_file)
write_step_summary(result, env)
if not result.ok:
return Drafted(result, (), f"drafter failed: {result.error}")
change = sandbox.compare(before, sandbox.snapshot(box))
bad = disallowed(change, listed, inputs.docs, box)
bad = disallowed(change, listed, inputs.docs, box, inputs.review_only)
if bad:
names = ", ".join(f"`{p}`" for p in bad)
return Drafted(result, (), f"drafter failed: it changed files outside `docs`: {names}")
where = "outside `docs`" + (" or in `review_only`" if inputs.review_only else "")
return Drafted(result, (), f"drafter failed: it changed files {where}: {names}")
if leaks_credential(change.new + change.changed, box, env):
return Drafted(result, (), CREDENTIAL_NOTE)
try:
+4 -2
View File
@@ -102,8 +102,10 @@ class Gitea:
never trusted."""
login, _ = self.identity()
for pr in self._pages(f"/repos/{self._repo}/pulls?state={state}"):
head_repo = (pr["head"].get("repo") or {}).get("full_name")
if (pr.get("user") or {}).get("login") == login and head_repo == self._repo:
head_repo = (pr["head"].get("repo") or {}).get("full_name") or ""
# Gitea owner and repository names are case-insensitive.
if ((pr.get("user") or {}).get("login") == login
and head_repo.lower() == self._repo.lower()):
yield pr
def find_open_pr_prefix(self, head_prefix: str) -> dict | None:
+30 -7
View File
@@ -43,8 +43,16 @@ def run(args: list[str], cwd: Path, extra_env: Mapping[str, str] | None = None)
def checkout_new(branch: str, rev: str, cwd: Path) -> None:
"""Create or reset branch at rev and switch to it."""
run(["checkout", "-q", "-B", branch, EOO, rev], cwd)
"""Create or reset branch at rev and switch to it.
git before 2.43 reads a revision after --end-of-options in checkout as a pathspec
("Cannot update paths and switch to branch"), and node:22 ships 2.39. So an
option-like branch or rev is refused here instead, and the trailing -- keeps rev a
revision."""
for value in (branch, rev):
if not value or value.startswith("-"):
raise GitError(f"refusing to check out {value!r}")
run(["checkout", "-q", "-B", branch, rev, "--"], cwd)
def merge(rev: str, author: tuple[str, str], cwd: Path) -> None:
@@ -54,6 +62,12 @@ def merge(rev: str, author: tuple[str, str], cwd: Path) -> None:
"-c", "commit.gpgsign=false", "merge", "--no-edit", EOO, rev], cwd)
def fetch(branch: str, cwd: Path) -> None:
"""Fetch one branch from origin into FETCH_HEAD; the branch can never read as an
option."""
run(["fetch", "-q", "origin", EOO, branch], cwd)
def merge_base(a: str, b: str, cwd: Path) -> str:
return run(["merge-base", EOO, a, b], cwd).strip()
@@ -112,17 +126,26 @@ def commit(paths: list[str], message: str, author: tuple[str, str], cwd: Path) -
)
def push(branch: str, cwd: Path, token: str | None) -> None:
def header_key(server: str | None) -> str:
"""The config key for the auth header: scoped to the Gitea server when it is known,
so the header is never sent to any other host."""
if server:
return f"http.{server.rstrip('/')}/.extraHeader"
return "http.extraHeader"
def push(branch: str, cwd: Path, token: str | None, server: str | None = None) -> None:
"""Push branch to origin under an explicit refspec, never forced.
The token travels as an http.extraHeader set through GIT_CONFIG_* variables on this
call only, so it never reaches argv or .git/config. A branch starting with + or -
could force the push or read as an option, so it is refused."""
The token travels as an extraHeader set through GIT_CONFIG_* variables on this call
only, so it never reaches argv or .git/config; with server (GITHUB_SERVER_URL) the
header is scoped to that URL. A branch starting with + or - could force the push or
read as an option, so it is refused."""
if not branch or branch.startswith(("+", "-")):
raise GitError(f"refusing to push branch {branch!r}")
extra = None
if token:
extra = {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "http.extraHeader",
extra = {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": header_key(server),
"GIT_CONFIG_VALUE_0": f"Authorization: token {token}"}
ref = f"refs/heads/{branch}"
run(["push", "origin", f"{ref}:{ref}"], cwd, extra_env=extra)
+19
View File
@@ -25,6 +25,8 @@ class Inputs:
tracking_issue: int | None
doc_guide: str | None
model: str
# Listed documents the drafter may read but not edit; each entry is within docs.
review_only: tuple[str, ...] = ()
def normalize_drafter(raw: str | None) -> str:
@@ -48,6 +50,14 @@ def parse_inputs(env: Mapping[str, str]) -> Inputs:
if not docs:
raise ValueError("input 'docs' is required: list at least one document pattern")
review_only = _lines(env.get("INPUT_REVIEW_ONLY"))
for entry in review_only:
if not matches_any(entry, docs):
raise ValueError(
f"input 'review_only' entry {entry!r} matches no 'docs' pattern; "
"every review_only entry must also be a listed document"
)
issue_raw = _text(env, "INPUT_TRACKING_ISSUE")
try:
tracking_issue = int(issue_raw) if issue_raw else None
@@ -64,9 +74,18 @@ def parse_inputs(env: Mapping[str, str]) -> Inputs:
tracking_issue=tracking_issue,
doc_guide=_text(env, "INPUT_DOC_GUIDE") or None,
model=_text(env, "INPUT_MODEL") or DEFAULT_MODEL,
review_only=review_only,
)
def split_review_only(
paths: tuple[str, ...], review_only: tuple[str, ...]
) -> tuple[tuple[str, ...], tuple[str, ...]]:
"""The listed documents split into (editable, review-only), each in the given order."""
read_only = tuple(p for p in paths if matches_any(p, review_only))
return tuple(p for p in paths if p not in read_only), read_only
def _glob_files(pattern: str, repo_root: Path) -> list[str]:
"""Repository-relative POSIX paths of files matching one pattern."""
return [
+11 -8
View File
@@ -8,12 +8,12 @@ from collections.abc import Mapping
from pathlib import Path
from docs_review import git
from docs_review.draft import build_prompt, parse_summary, render_pr_body
from docs_review.draft import build_prompt, load_template, parse_summary, render_pr_body
from docs_review.drafter import draft_in_sandbox
from docs_review.flags import Flag, compute_flags, group_uncovered, whole_repo_changes
from docs_review.inputs import Inputs, expand_patterns
from docs_review.inputs import Inputs, expand_patterns, split_review_only
from docs_review.report import MONTHLY_MARKER, render_issue, stage1_json
from docs_review.run_pr import TASK_PROMPT, read_guide, read_texts
from docs_review.run_pr import read_guide, read_texts
MONTHLY_PREFIX = "docs-review/monthly-"
MONTH_PATTERN = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
@@ -64,13 +64,13 @@ def post_issue(forge, flags: tuple[Flag, ...], month: str, note: str | None = No
def _checkout(base: str, month: str, reuse: dict | None, ident, cwd: Path) -> str | None:
"""The branch to draft on, or None when a reused branch no longer merges."""
git.run(["fetch", "-q", "origin", base], cwd)
git.fetch(base, cwd)
if reuse is None:
branch = f"{MONTHLY_PREFIX}{month}"
git.checkout_new(branch, f"origin/{base}", cwd)
return branch
branch = reuse["head"]["ref"]
git.run(["fetch", "-q", "origin", branch], cwd)
git.fetch(branch, cwd)
git.checkout_new(branch, "FETCH_HEAD", cwd)
try:
git.merge(f"origin/{base}", ident, cwd)
@@ -92,7 +92,8 @@ def _commit_message(inputs: Inputs, month: str) -> str:
def _deliver(forge, inputs, base, month, branch, reuse, ident, flags, result, changed, cwd,
env):
git.commit(changed, _commit_message(inputs, month), ident, cwd)
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"))
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"),
env.get("GITHUB_SERVER_URL"))
head = git.run(["rev-parse", "HEAD"], cwd).strip()
body = render_pr_body(parse_summary(result.text), result, flags, head, changed)
title = f"docs: monthly review {month}"
@@ -122,9 +123,11 @@ def run_monthly(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path,
MERGE_CONFLICT_NOTE.format(branch=reuse["head"]["ref"], base=base))
return 0
flags_json = json.dumps(stage1_json(flags, mode="monthly", head_sha=month))
editable, read_only = split_review_only(docs, inputs.review_only)
prompt = build_prompt(
TASK_PROMPT.read_text(encoding="utf-8"), mode="monthly", pr=None,
flags_json=flags_json, payload=NO_DIFF_PAYLOAD, docs=docs,
load_template("monthly"), mode="monthly", pr=None,
flags_json=flags_json, payload=NO_DIFF_PAYLOAD, docs=editable,
review_only=read_only,
top_level=inputs.top_level, guide_path=inputs.doc_guide,
)
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
+10 -8
View File
@@ -12,16 +12,15 @@ from pathlib import Path
from docs_review import git
from docs_review.changes import changed_names, parse_name_status
from docs_review.draft import (
DraftResult, build_prompt, diff_payload, parse_last_head, parse_summary,
render_pr_body, should_skip,
DraftResult, build_prompt, diff_payload, load_template, parse_last_head,
parse_summary, render_pr_body, should_skip,
)
from docs_review.drafter import draft_in_sandbox
from docs_review.flags import Flag, compute_flags
from docs_review.inputs import Inputs, expand_patterns
from docs_review.inputs import Inputs, expand_patterns, split_review_only
from docs_review.report import STAGE1_MARKER, render_clean, render_comment, stage1_json
from docs_review.tree import read_in_tree
TASK_PROMPT = Path(__file__).resolve().parent.parent / "prompts" / "task.md"
CLOSED_BRANCH_NOTE = (
"docs-review/pr-{n} was closed without merging; delete that branch to get new drafts."
)
@@ -117,7 +116,7 @@ def _checkout_docs_branch(resume: bool, args: PrArgs, ident, cwd: Path) -> bool:
if not resume:
git.checkout_new(branch, args.head_sha, cwd)
return True
git.run(["fetch", "-q", "origin", branch], cwd)
git.fetch(branch, cwd)
git.checkout_new(branch, "FETCH_HEAD", cwd)
try:
git.merge(args.head_sha, ident, cwd)
@@ -135,7 +134,8 @@ def _deliver(forge, inputs, args, docs_pr, ident, flags, result, changed, cwd, e
branch = docs_branch(args.number)
git.commit(changed, f"docs({inputs.workstream}): proposed edits (#{args.number})",
ident, cwd)
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"))
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"),
env.get("GITHUB_SERVER_URL"))
body = render_pr_body(parse_summary(result.text), result, flags, args.head_sha, changed)
if docs_pr is not None:
forge.edit_pr(docs_pr["number"], body=body)
@@ -209,9 +209,11 @@ def run_pr(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path, args: PrArg
MERGE_CONFLICT_NOTE.format(n=args.number), docs_pr=pr_no)
return 0
editable, read_only = split_review_only(docs, inputs.review_only)
prompt = build_prompt(
TASK_PROMPT.read_text(encoding="utf-8"), mode="pr", pr=args.number,
flags_json=flags_json, payload=payload, docs=docs, top_level=inputs.top_level,
load_template("pr"), mode="pr", pr=args.number,
flags_json=flags_json, payload=payload, docs=editable, review_only=read_only,
top_level=inputs.top_level,
guide_path=inputs.doc_guide,
)
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
+13
View File
@@ -0,0 +1,13 @@
In "monthly" mode there is no pull request. Your main job is to check every enumeration
in these top-level documents against what is actually in the repository:
{top_level}
An enumeration is any list of files, scripts, modules, filename prefixes, outputs or
steps, and any stated count. Use Glob to list the files each one describes. Where a list
or count no longer matches, correct it: add what is missing, remove what no longer
exists, fix the number. A list presented as complete must be complete. If a list is
deliberately partial, it should say so; when adding every missing item would make it
unwieldy (more than about 15 new entries), add that phrase instead.
Then correct anything else in these documents that no longer matches the repository.
+1
View File
@@ -0,0 +1 @@
In "pr" mode, find what this pull request makes stale in the documents listed below.
+2 -7
View File
@@ -1,17 +1,12 @@
You keep a repository's living documents current. Mode: {mode}. Pull request: {pr}.
In "pr" mode, find what this pull request makes stale in the documents listed below.
In "monthly" mode there is no pull request; re-read each of these top-level documents
against the repository as it stands and correct what no longer matches:
{top_level}
{mode_text}
Documents you may edit:
{docs}
Edit only the documents listed above. Do not change any other file.
{review_only}
{guide_note}
Make the smallest edit that corrects the stale fact, or adds the missing piece where the
+5 -2
View File
@@ -7,7 +7,8 @@ sentinel (file touched when invoked), env_file (file receiving the env var names
cwd_file (file receiving the working directory), argv_file (file receiving argv as
JSON), prompt_copy (file receiving the --append-system-prompt-file contents),
edit (path to append a line to), write (text to append to `edit` instead),
delete (path to remove), fail (print an error result and exit 1).
delete (path to remove), fail (print an error result and exit 1), stdin_copy (file
receiving the prompt read on stdin).
"""
import json
@@ -15,9 +16,11 @@ import os
import sys
from pathlib import Path
sys.stdin.read()
prompt = sys.stdin.read()
config_path = Path(__file__).resolve().with_name("fake_claude.json")
config = json.loads(config_path.read_text()) if config_path.exists() else {}
if config.get("stdin_copy"):
Path(config["stdin_copy"]).write_text(prompt, encoding="utf-8")
if config.get("sentinel"):
Path(config["sentinel"]).write_text("invoked\n", encoding="utf-8")
+111
View File
@@ -4,6 +4,7 @@ import shutil
import subprocess
import tempfile
import unittest
from unittest import mock
from pathlib import Path
from docs_review.cli import main
@@ -54,6 +55,7 @@ class CliCase(unittest.TestCase):
"DOCS_REVIEW_CLAUDE_BIN": str(self.fake_claude),
"DOCS_REVIEW_BOT_TOKEN": "bot-token-value-123456",
"RUNNER_TEMP": str(tmp),
"ANTHROPIC_API_KEY": "test-api-key-value-123456",
}
def claude(self, **config):
@@ -168,6 +170,28 @@ class ClaudeDrafterTests(CliCase):
self.fake.email)
self.assertEqual(self.comment_bodies(), [])
def test_resume_fetches_with_end_of_options_and_scoped_push(self):
self.assertEqual(self.run_pr(self.feature_commit()), 0)
calls = []
real = subprocess.run
def record(argv, **kw):
calls.append((list(argv), kw.get("env") or {}))
return real(argv, **kw)
server = "https://gitea.example.org"
sha = self.feature_commit()
with mock.patch("docs_review.git.subprocess.run", side_effect=record):
self.assertEqual(self.run_pr(sha, GITHUB_SERVER_URL=server), 0)
# The harness's own `git fetch -q origin` (run_pr's setup) names no branch.
fetches = [a for a, _ in calls if a[:2] == ["git", "fetch"] and a[-1] != "origin"]
self.assertTrue(fetches)
for argv in fetches:
self.assertEqual(argv[-2:], ["--end-of-options", BRANCH])
pushes = [e for a, e in calls if a[:2] == ["git", "push"]]
self.assertEqual(len(pushes), 1)
self.assertEqual(pushes[0]["GIT_CONFIG_KEY_0"], f"http.{server}/.extraHeader")
def test_rerun_appends_and_keeps_hand_edit(self):
self.assertEqual(self.run_pr(self.feature_commit()), 0)
git(self.seed, "fetch", "-q", "origin", BRANCH)
@@ -221,6 +245,41 @@ class ClaudeDrafterTests(CliCase):
self.assertEqual(len(self.comment_bodies()), 1)
class CredentialAndSummaryTests(CliCase):
def setUp(self):
super().setUp()
self.claude(edit="docs/README.md")
def test_missing_credential_posts_stage1_note_and_fails(self):
sha = self.feature_commit()
env = {k: v for k, v in self.env.items()
if k not in ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY")}
self.env = env
self.assertEqual(self.run_pr(sha, CLAUDE_CODE_OAUTH_TOKEN="", ANTHROPIC_API_KEY=""), 1)
bodies = self.comment_bodies()
self.assertEqual(len(bodies), 1)
self.assertIn("drafter: claude but no Claude credential is set", bodies[0])
self.assertIn("Touched", bodies[0])
self.assertFalse(self.sentinel.exists())
self.assertEqual(self.fake.prs, [])
def test_oauth_token_alone_is_enough(self):
sha = self.feature_commit()
self.env.pop("ANTHROPIC_API_KEY")
self.assertEqual(self.run_pr(sha, CLAUDE_CODE_OAUTH_TOKEN="oauth-token-value-1"), 0)
self.assertEqual(len(self.fake.prs), 1)
def test_cost_and_turns_reach_the_step_summary(self):
summary = Path(self.env["RUNNER_TEMP"]) / "step-summary.md"
summary.write_text("earlier step\n", encoding="utf-8")
sha = self.feature_commit()
self.assertEqual(self.run_pr(sha, GITHUB_STEP_SUMMARY=str(summary)), 0)
text = summary.read_text(encoding="utf-8")
self.assertTrue(text.startswith("earlier step\n"))
self.assertIn("total_cost_usd: 0.12", text)
self.assertIn("num_turns: 3", text)
class DocsPrLifecycleTests(CliCase):
def setUp(self):
super().setUp()
@@ -414,6 +473,58 @@ class SandboxTests(CliCase):
self.assertEqual(self.fake.prs, [])
class ReviewOnlyTests(CliCase):
"""docs/vision.md is a listed document the drafter may read but not edit."""
def setUp(self):
super().setUp()
git(self.seed, "checkout", "-q", "main")
self.write(self.seed, "docs/vision.md", "Where `R/a.R` is going.\n")
git(self.seed, "add", ".")
git(self.seed, "commit", "-q", "-m", "vision")
git(self.seed, "push", "-q", "origin", "main")
git(self.seed, "checkout", "-q", "feat")
git(self.seed, "merge", "-q", "--ff-only", "main")
git(self.seed, "push", "-q", "origin", "feat")
self.env["INPUT_REVIEW_ONLY"] = "docs/vision.md"
self.prompt_file = Path(self._tmp.name) / "drafter-prompt"
def test_prompt_lists_it_as_read_only(self):
self.claude(stdin_copy=str(self.prompt_file))
self.assertEqual(self.run_pr(self.feature_commit()), 0)
prompt = self.prompt_file.read_text()
editable = prompt.split("Documents you may edit:")[1].split("Edit only")[0]
self.assertIn("docs/README.md", editable)
self.assertNotIn("docs/vision.md", editable)
self.assertIn("Documents you may read but not edit:\n\ndocs/vision.md", prompt)
def test_it_is_still_flagged_in_stage1(self):
self.claude()
self.assertEqual(self.run_pr(self.feature_commit()), 0)
self.assertIn("docs/vision.md", self.comment_bodies()[0])
def test_editing_it_fails_and_commits_nothing(self):
self.claude(edit="docs/vision.md")
self.assertEqual(self.run_pr(self.feature_commit()), 1)
self.assertTrue(any("docs/vision.md" in b for b in self.comment_bodies()))
self.assertNotIn(BRANCH, " ".join(self.remote_branches()))
self.assertEqual(git(self.work, "status", "--porcelain"), "")
self.assertEqual(self.fake.prs, [])
def test_deleting_it_fails(self):
self.claude(delete="docs/vision.md")
self.assertEqual(self.run_pr(self.feature_commit()), 1)
self.assertTrue((self.work / "docs" / "vision.md").exists())
self.assertEqual(self.fake.prs, [])
def test_new_file_matching_a_review_only_glob_is_refused(self):
self.env["INPUT_REVIEW_ONLY"] = "docs/v*.md"
self.claude(edit="docs/vnew.md")
self.assertEqual(self.run_pr(self.feature_commit()), 1)
self.assertFalse((self.work / "docs" / "vnew.md").exists())
self.assertEqual(self.fake.prs, [])
class SystemPromptTests(CliCase):
def setUp(self):
super().setUp()
+8
View File
@@ -153,6 +153,14 @@ class ClaudeMonthlyTests(MonthlyCase):
self.assertIn("R/a.R", self.fake.issues[0]["body"])
self.assertEqual(git(self.work, "status", "--porcelain"), "")
def test_review_only_doc_edit_fails_and_commits_nothing(self):
self.claude(edit="docs/README.md")
self.assertEqual(self.run_monthly("2026-12", INPUT_REVIEW_ONLY="docs/README.md"), 1)
self.assertEqual(self.fake.prs, [])
self.assertNotIn("monthly", " ".join(self.remote_branches()))
self.assertIn("docs/README.md", self.fake.issues[0]["body"])
self.assertEqual(git(self.work, "status", "--porcelain"), "")
def test_delivered_pr_closes_the_open_monthly_issue(self):
self.claude(fail=True)
self.assertEqual(self.run_monthly("2026-11"), 1)
+45 -3
View File
@@ -9,6 +9,7 @@ from docs_review.draft import (
build_prompt,
claude_argv,
diff_payload,
load_template,
outside_docs,
parse_claude_output,
parse_last_head,
@@ -59,14 +60,55 @@ class PromptTest(unittest.TestCase):
self.assertIn("monthly|none|", out)
def test_shipped_template_renders(self):
from pathlib import Path
t = Path(__file__).resolve().parent.parent / "prompts" / "task.md"
out = build_prompt(t.read_text(), mode="pr", pr=7, flags_json="{}", payload="{x}",
out = build_prompt(load_template("pr"), mode="pr", pr=7, flags_json="{}", payload="{x}",
docs=("a.md",), top_level=("README.md",), guide_path=None)
self.assertIn("```json", out)
self.assertIn("{x}", out)
self.assertNotIn("{mode}", out)
def test_review_only_section(self):
t = "{docs}|{review_only}"
none = build_prompt(t, mode="pr", pr=1, flags_json="{}", payload="",
docs=("a.md",), top_level=(), guide_path=None)
self.assertEqual(none, "a.md|")
out = build_prompt(t, mode="pr", pr=1, flags_json="{}", payload="",
docs=("a.md",), top_level=(), guide_path=None,
review_only=("v.md", "w.md"))
self.assertIn("Documents you may read but not edit:\n\nv.md\nw.md", out)
self.assertIn("declined", out)
class TemplateModeTest(unittest.TestCase):
def _render(self, mode, review_only=()):
return build_prompt(load_template(mode), mode=mode, pr=None if mode == "monthly" else 7,
flags_json="{}", payload="p", docs=("README.md", "docs/a.md"),
top_level=("README.md",), guide_path=None,
review_only=review_only)
def test_monthly_asks_for_enumeration_check_and_lists_review_only(self):
out = self._render("monthly", ("docs/vision.md",))
self.assertIn("check every enumeration", out)
self.assertIn("Glob", out)
self.assertIn("A list presented as complete must be complete", out)
self.assertIn("Documents you may read but not edit:\n\ndocs/vision.md", out)
self.assertIn("README.md", out)
for field in ("{top_level}", "{mode_text}", "{review_only}", "{docs}"):
self.assertNotIn(field, out)
def test_pr_has_no_enumeration_check(self):
out = self._render("pr", ("docs/vision.md",))
self.assertNotIn("enumeration", out)
self.assertIn("find what this pull request makes stale", out)
self.assertIn("Documents you may read but not edit:\n\ndocs/vision.md", out)
def test_review_only_section_absent_when_empty(self):
for mode in ("pr", "monthly"):
self.assertNotIn("read but not edit", self._render(mode))
def test_unknown_mode_raises(self):
with self.assertRaises(ValueError):
load_template("weekly")
class ArgvTest(unittest.TestCase):
def test_argv_matches_spec(self):
+2 -1
View File
@@ -22,7 +22,8 @@ class ExportFailureTest(unittest.TestCase):
tmp = Path(self._tmp.name)
self.repo = make_repo(tmp / "repo")
(tmp / "runner").mkdir()
self.env = {"RUNNER_TEMP": str(tmp / "runner"), "PATH": "/usr/bin:/bin"}
self.env = {"RUNNER_TEMP": str(tmp / "runner"), "PATH": "/usr/bin:/bin",
"ANTHROPIC_API_KEY": "test-api-key-value-123456"}
def draft_with(self, err):
made = []
+7
View File
@@ -174,6 +174,13 @@ class TestPrsAndIssues(unittest.TestCase):
self.assertIsNone(g.find_open_pr("docs-review/pr-12"))
self.assertIsNone(g.find_open_pr_prefix("docs-review/"))
def test_head_repo_matches_ignoring_case(self):
routes = {("GET", BASE + "/api/v1/user"): USER,
("GET", API + "/pulls?state=all&limit=50&page=1"):
[pr(5, "docs-review/pr-12", repo="O/R")]}
g, _ = client(routes)
self.assertEqual(g.find_pr("docs-review/pr-12")["number"], 5)
def test_open_pr_and_edit(self):
g, f = client({
("POST", API + "/pulls"): {"number": 12},
+40
View File
@@ -49,6 +49,20 @@ class TestGit(unittest.TestCase):
call()
self.assertFalse(out.exists())
def test_checkout_new_creates_branch_at_rev(self):
git.checkout_new("docs-review/pr-3", "HEAD~1", self.repo)
self.assertEqual(git.run(["rev-parse", "--abbrev-ref", "HEAD"], self.repo).strip(),
"docs-review/pr-3")
self.assertEqual(git.run(["rev-parse", "HEAD"], self.repo).strip(),
git.run(["rev-parse", "main~1"], self.repo).strip())
def test_checkout_new_refuses_option_like_values(self):
out = Path(self._tmp.name) / "x"
for branch, rev in (("b", f"--output={out}"), ("-b", "HEAD"), ("b", "")):
with self.assertRaises(git.GitError):
git.checkout_new(branch, rev, self.repo)
self.assertFalse(out.exists())
def test_merge_base_and_ls_files(self):
head = git.run(["rev-parse", "HEAD"], self.repo).strip()
self.assertEqual(git.merge_base("HEAD", "HEAD~1", self.repo),
@@ -136,6 +150,32 @@ class TestGitHardening(unittest.TestCase):
git.run(["status"], self.repo)
self.assertNotIn("GIT_CONFIG_COUNT", calls[-1][1])
def test_fetch_ends_options_before_the_branch(self):
git.run(["push", "-q", "origin", "main"], self.repo)
calls = self._record()
git.fetch("main", self.repo)
argv, _ = calls[-1]
self.assertEqual(argv[-2:], [git.EOO, "main"])
self.assertEqual(git.run(["rev-parse", "FETCH_HEAD"], self.repo).strip(),
git.run(["rev-parse", "main"], self.repo).strip())
out = Path(self._tmp.name) / "x"
with self.assertRaises(git.GitError):
git.fetch(f"--upload-pack=touch {out}", self.repo)
self.assertFalse(out.exists())
def test_push_scopes_header_to_the_server(self):
calls = self._record()
git.run(["checkout", "-q", "-b", "docs-review/pr-4"], self.repo)
git.push("docs-review/pr-4", self.repo, self.TOKEN, "https://gitea.example.org/")
env = calls[-1][1]
self.assertEqual(env["GIT_CONFIG_KEY_0"], "http.https://gitea.example.org/.extraHeader")
self.assertEqual(env["GIT_CONFIG_VALUE_0"], f"Authorization: token {self.TOKEN}")
def test_header_key_falls_back_to_unscoped(self):
self.assertEqual(git.header_key(None), "http.extraHeader")
self.assertEqual(git.header_key(""), "http.extraHeader")
self.assertEqual(git.header_key("https://h.example"), "http.https://h.example/.extraHeader")
def test_push_without_token_adds_no_header(self):
calls = self._record()
git.push("main", self.repo, None)
+22
View File
@@ -6,6 +6,7 @@ from docs_review.inputs import (
matches_any,
normalize_drafter,
parse_inputs,
split_review_only,
unmatched_patterns,
)
from tests.helpers import tmp_tree
@@ -64,6 +65,27 @@ class ParseInputsTest(unittest.TestCase):
self.assertIsNone(i.tracking_issue)
self.assertIsNone(i.doc_guide)
def test_review_only_defaults_to_empty(self):
self.assertEqual(parse_inputs({"INPUT_DOCS": "a.md"}).review_only, ())
def test_review_only_entries_within_docs(self):
i = parse_inputs({"INPUT_DOCS": "README.md\ndocs/*.md\npm/**/*.md",
"INPUT_REVIEW_ONLY": " docs/vision.md \n\nREADME.md\npm/v*.md\n"})
self.assertEqual(i.review_only, ("docs/vision.md", "README.md", "pm/v*.md"))
def test_review_only_entry_outside_docs_raises(self):
for entry in ("other/vision.md", "docs/sub/vision.md", "*.md"):
with self.assertRaisesRegex(ValueError, f"review_only.*{entry.replace('*', '[*]')}"):
parse_inputs({"INPUT_DOCS": "README.md\ndocs/*.md",
"INPUT_REVIEW_ONLY": f"docs/a.md\n{entry}"})
def test_split_review_only(self):
editable, read_only = split_review_only(
("README.md", "docs/a.md", "docs/vision.md"), ("docs/v*.md",))
self.assertEqual(editable, ("README.md", "docs/a.md"))
self.assertEqual(read_only, ("docs/vision.md",))
self.assertEqual(split_review_only(("a.md",), ()), (("a.md",), ()))
def test_non_integer_tracking_issue_raises(self):
with self.assertRaisesRegex(ValueError, "tracking_issue"):
parse_inputs({"INPUT_DOCS": "a.md", "INPUT_TRACKING_ISSUE": "abc"})