diff --git a/.agents/README.md b/.agents/README.md index 98937323af..6b9ab72d62 100644 --- a/.agents/README.md +++ b/.agents/README.md @@ -481,7 +481,7 @@ JSON, REPL access, and so on. | [`review-plan`](skills/review-plan/SKILL.md) | Evaluates a plan before anyone writes code: completeness, ordering, risks. Approves it or asks for changes. | "review this plan before we start" | | [`implement-plan`](skills/implement-plan/SKILL.md) | Shows you the full flow first — the issue and branch it will create (or the branch it continues on), the execution style, and the task checklist — and, after your go-ahead, executes a ready plan. Default: every task, one commit. On request ("step by step"): one task, one commit, your confirmation between tasks. On request ("direct"): no issue and no branch, commits on the current branch. | "implement the plan" · "step by step, one commit per task" · "direct, no branch" | | [`review-code`](skills/review-code/SKILL.md) | Reviews a diff, branch, or PR and returns findings ranked by impact. | "review my changes before I push" | -| [`create-pr`](skills/create-pr/SKILL.md) | Opens a pull request for the current branch — with checks on base branch, commits, issue, and push state — or updates an existing PR's title and description. | "open a PR for this branch" | +| [`create-pr`](skills/create-pr/SKILL.md) | Opens a pull request for the current branch with `scripts/gh.py create-pr` (base autodetection, optional issue link) or updates an existing PR's title and description. | "open a PR for this branch" | | [`resolve-git-conflicts`](skills/resolve-git-conflicts/SKILL.md) | Untangles merge or rebase conflicts: explains both sides, proposes a resolution, applies it after you approve. Never runs `git rebase --continue`. | "resolve these conflicts" | ### References diff --git a/.agents/skills/create-pr/SKILL.md b/.agents/skills/create-pr/SKILL.md index 00d8fd7dc6..82ef8567e3 100644 --- a/.agents/skills/create-pr/SKILL.md +++ b/.agents/skills/create-pr/SKILL.md @@ -1,108 +1,66 @@ --- name: create-pr -description: PR flow — open a new PR for the current task branch (validates base branch, commits, issue and push state) or update an existing PR's title or description to match Penpot conventions. Use it when the user asks to open or create a PR, in any phrasing. +description: PR flow — open a new PR for the current task branch or update an existing PR's title or description to match Penpot conventions. Use it when the user asks to open or create a PR, in any phrasing. --- -# Create PR +# Skill: create-pr -Two modes. **Open mode** takes the current task branch to a new, validated -PR. **Update mode** rewrites an existing PR's title or description. Gather -information, validate, and act in one pass. If validation fails, STOP with a -single coherent message that lists every problem and states exactly what -information is missing — never fix or work around problems silently. +Entry point for all GitHub PR work. Authentication, base-branch detection, +push state and the existing-PR check are handled by `python3 scripts/gh.py +create-pr` and by `gh` itself — do not perform them here. The canonical rules +for titles, bodies, merge strategy and issue linking live in +`mem:workflow/creating-prs` (file: +`.serena/memories/workflow/creating-prs.md`). This skill routes to the right +flow. -Both modes require an authenticated `gh` CLI (`gh auth status`) and never -push — the user pushes from their own shell. +## When to Use -## When to use - -- The user asks to open or create a NEW PR for the current task branch, in - any phrasing ("open a PR", "create the pull request", "put this up for - review") — or invokes `@create-pr`. → **Open mode**. -- The user asks to fix or update an EXISTING PR's title or description to - match conventions. → **Update mode**. +- **Open mode** — the user asks to open or create a NEW PR for the current + task branch, in any phrasing ("open a PR", "create the pull request", + "put this up for review") — or invokes `@create-pr`. + → **Open mode** below. +- **Update mode** — the user asks to fix or update an existing PR's title or + description. → **Update mode** below. If the running agent cannot write (for example, the plan agent), say so and stop — this skill needs the build agent. +The user pushes from their own shell. Never push, force-push or modify a +remote. If the command reports that the branch was not pushed, tell the user +to push it and invoke the skill again. + +For draft PRs, warn that CI does not run on them and only add `--draft` when +the user agrees. + ## Open mode -### 1. Gather context (read-only) - -- Current branch: `git rev-parse --abbrev-ref HEAD`. -- Target base branch: run `./scripts/detect-target-branch` from the repo root. - It prints the nearest ancestor branch of HEAD (exit 0) or fails (exit 1). -- Commits: `git log --oneline ..HEAD`. -- Push state (local): `git rev-parse --verify origin/` and compare - with HEAD. It reads the local remote-tracking ref — no network, no SSH. It - reflects the last push or fetch this clone knows about. -- Issue: from the session context, or from the branch name — `issue-NNNN` - maps to issue NNNN; recover its title and body with `gh issue view NNNN`. - -### 2. Validate — stop with one message if anything fails - -Run all checks before reporting, then report every failure together: - -1. **Base branch not usable.** If the script fails (exit 1), or its output — - after stripping an optional `remotes/origin/` prefix — is not one of the - canonical branches (`develop`, `staging`, `main`), stop and ask the user - to re-run with more context — for example, passing the base branch - explicitly in their invocation. An explicit base given by the user - overrides the script's output. -2. **On a base branch.** There is no task branch to merge — say so and stop. -3. **No commits.** The branch has no commits ahead of the base — say so and - stop. -4. **No clear issue.** There is no issue in the session context, and the - branch name has no `issue-NNNN` pattern (or `gh issue view` finds nothing) - — say so and stop. Exception: the user's invocation says `no issue` / - `without issue` — then continue without an issue reference. -5. **Branch not pushed.** The remote-tracking ref `origin/` is - missing, or `git rev-parse origin/` differs from HEAD — the - branch was never pushed, or has commits the remote does not have. Never - push yourself; ask the user to push and to invoke `@create-pr` again - afterwards, then stop. - -### 3. Already-open PR - -Check whether a PR already exists for this branch (`gh pr list --head -`). If one exists, report its URL and stop — do not create a second -one. Title or description fixes belong to Update mode. - -### 4. Write and create the PR - -Write the title and body following `mem:workflow/creating-prs` (title format, -description structure, writing principles) and `mem:workflow/creating-commits` -(commit type emojis). Derive the title and body from the commits and, when -there is one, from the issue body. Include `Closes #NNNN` for readable context, -but do not treat it as the link; use `python3 scripts/gh.py link-issue ` after creating the PR. - -Repeat the `AI-assisted-by:` trailer in the body, once per model that worked -on the branch, so the PR states the assistance where a reviewer reads it. The -branch commits keep their own trailers, and a squash merge carries every one -of them into the landed message. - -Before offering or accepting a draft PR, warn that CI doesn't run on them. Add -`--draft` only when the user agrees to that. +1. Write the title and the body following `mem:workflow/creating-prs`: + `:emoji:` title, the `**Note:**` line, and the `## What` / `## Why` / + `## How` sections. Derive them from the commits and the issue body when + there is one. Repeat the `AI-assisted-by:` trailer once per model that + worked on the branch. Put the body in a temp file to avoid shell quoting. +2. Decide whether the PR resolves an issue. If it does, include `Closes + #NNNN` in the body for human readers and pass `--issue NNNN` so the + command creates the GitHub link. If the user's invocation says `no issue` + / `without issue`, pass no `--issue`. +3. Run the command: ```bash -gh pr create --repo penpot/penpot --base "" --title "" \ - --project "Main" --body-file /tmp/pr-body.md +python3 scripts/gh.py create-pr \ + --title "<TITLE>" --body-file /tmp/pr-body.md [--issue NNNN] [--base BASE] ``` -`--base` is the branch resolved in step 1: without it the PR opens against the -repository default, which is wrong for a branch cut from `staging`. `--project -"Main"` is required by `mem:workflow/creating-prs`. +`--base` is optional: by default the command detects the nearest ancestor +branch of `HEAD`, ported from `scripts/detect-target-branch`. Pass it only +when the detected base is not the one you want. `--head` defaults to the +current branch and `--draft` marks the PR as draft. -If an issue is present, run the explicit assignment command from -`mem:workflow/creating-prs` before reporting success: +If the command fails with `detected base '<name>' is not a local branch; pass +--base explicitly`, rerun it with `--base <name>` using the name from the +error. Do not ask the user and do not add pre-flight checks for this case. -```bash -python3 scripts/gh.py link-issue <ISSUE_NUMBER> <PR_NUMBER> -``` - -### 5. Report - -Report the PR URL and stop. +4. Report the URL from the command's output and stop. If it fails, report + the `gh` error as-is; do not add local pre-flight checks. ## Update mode @@ -127,7 +85,7 @@ python3 scripts/gh.py link-issue <ISSUE_NUMBER> <PR_NUMBER> ## User context -Extra context in the user's invocation (the message that triggered this skill) -plays the role command arguments play elsewhere: overrides such as `no issue` / -`without issue`, an explicit base branch (`from origin/staging`), a PR number -for Update mode, and so on. +Extra context in the user's invocation (the message that triggered this +skill) plays the role command arguments play elsewhere: overrides such as +`no issue` / `without issue`, an explicit base branch (`from origin/staging`), +a PR number for Update mode, and so on. diff --git a/.serena/memories/critical-info.md b/.serena/memories/critical-info.md index ce3284686a..0d353c377d 100644 --- a/.serena/memories/critical-info.md +++ b/.serena/memories/critical-info.md @@ -59,7 +59,7 @@ The memory is structured in a way that you can get the critical information abou - `scripts/paren-repair` — Fix mismatched delimiters in Clojure/CLJS files and reformat with cljfmt. Run before lint checks when LLM edits break parens. See `mem:scripts/paren-repair`. - `scripts/psql` — PostgreSQL client wrapper with devenv defaults. Companion: `scripts/db-schema` for DDL dumps. See `mem:scripts/psql`. - `scripts/taiga.py` — Fetch public issues, user stories, and tasks from the Penpot Taiga project without authentication. See `mem:scripts/taiga`. -- `scripts/gh.py` — GitHub operations helper: list milestone issues, fetch PR details, compare against CHANGES.md, create issues with their Issue Type in one command. Requires `gh` CLI. See `mem:scripts/gh`. +- `scripts/gh.py` — GitHub operations helper: list milestone issues, fetch PR details, compare against CHANGES.md, create issues with their Issue Type and pull requests with optional issue linking in one command. Requires `gh` CLI. See `mem:scripts/gh`. - `scripts/coverage-summary.mjs` — Renders an lcov file as a markdown table grouped by source area, for `$GITHUB_STEP_SUMMARY` (`--title`, `--lcov`, optional `--note`, `--unloaded`). Used by the backend, common and frontend test workflows; module coverage commands are in `mem:backend/testing`, `mem:common/testing`, `mem:frontend/testing`. - `scripts/coverage-comment.mjs` — Keeps one PR comment (`<!-- coverage-report -->`) with the coverage table of Backend, Common, Frontend and Render WASM, in the format of the Vitest Coverage Report Action (status, metric, %, covered/total, changed-file coverage, run/commit footer). Each test job updates its own project: the data of all three lives base64-encoded in a hidden `coverage-data` block, and the job re-reads after `SETTLE_MS` and rewrites if a concurrent job dropped its data; extra report comments from simultaneous creates are merged and deleted. Targets (`THRESHOLDS`, per project and metric, status colour only, never fail CI) are on lines only: 70 Backend, 70 Common, 50 Frontend, 40 Render WASM; other metrics get the blue dot. Statements are Clojure forms for Backend/Common (`--emma-xml`) and llvm regions for Render WASM (`--llvm-json`). Shared lcov parsing: `scripts/coverage-lcov.mjs`. The test workflows run it only for PRs from branches of this repo (job-level `pull-requests: write`, `continue-on-error`): fork PRs get a read-only token, so they only get the run-page summary. A fork-safe `workflow_run` commenter would run only from the default branch's copy of the workflow. - `scripts/project-anomalies.py` — Main-board anomaly check for a milestone (`check` writes `tmp/<MILESTONE>-ANOMALIES.md`). Bulk resolution via `scripts/gh.py`. See `mem:scripts/project-anomalies`. diff --git a/.serena/memories/scripts/gh.md b/.serena/memories/scripts/gh.md index 22b8aef03a..9a7d6f8aab 100644 --- a/.serena/memories/scripts/gh.md +++ b/.serena/memories/scripts/gh.md @@ -11,6 +11,7 @@ repository via GraphQL and REST APIs through the authenticated `gh` CLI. - Comparing milestone issues against CHANGES.md to find missing entries. - Explicitly linking a GitHub issue to a pull request. - Creating an issue with its Issue Type set in a single command. +- Creating a pull request with optional issue linking in a single command. - Listing or inspecting GitHub Security Advisories (GHSA). - Fetching issue comments (the `## Breaking change note` markdown for the changelog). @@ -124,6 +125,40 @@ python3 scripts/gh.py create-issue --type bug --title "..." \ **Output**: JSON object on stdout; progress and errors on stderr. A bad type, a `gh` failure, or a type that was not applied exits non-zero. +### `create-pr` + +Create a pull request and optionally link its issue in one command. + +```bash +python3 scripts/gh.py create-pr \ + --title "Expand backend email tests" --body-file /tmp/pr-body.md \ + [--issue 13202] [--base staging] [--head issue-13202] \ + [--project Main] [--draft] +``` + +`gh pr create` is run with `--repo penpot/penpot`, `--base`, `--head`, +`--title`, `--project` (default `Main`) and `--body-file`, plus `--draft` +when requested. +`--base` defaults to `detect_target_branch()`, a port of +`scripts/detect-target-branch` that uses `git name-rev` plus a graph-walk +fallback; it is local-only and needs no network. It strips trailing `~`/`^` +suffixes and `remotes/<remote>/`, `heads/`, `refs/heads/` and `tags/` prefixes, +then checks the result is a local branch. If it is not, the command fails with +`detected base '<name>' is not a local branch; pass --base explicitly`, and the +caller retries with that `--base`. Pass `--base` to override the detection. +`--head` defaults to the current branch. The PR number is parsed +from the URL returned by `gh`. The URL is printed to stderr immediately, before +any issue linking. When `--issue N` is given, the command calls +`link_issue_to_pr(N, PR)` after creation; a failure there leaves the PR in +place and exits non-zero with the URL in the error message. + +**Output**: JSON object on stdout with `number`, `url`, `title`, `base`, +`head` and `linked_issue`; progress and errors on stderr. A blank title, an +undetectable base, a URL without a number or a `gh` failure exits non-zero. +The command does not check authentication or push state: `gh` reports those +errors itself. Keep `scripts/detect-target-branch` and `detect_target_branch` +in sync — the heuristic is implemented twice by decision. + ### `advisories` List or inspect GitHub Security Advisories for the repository. diff --git a/.serena/memories/workflow/creating-prs.md b/.serena/memories/workflow/creating-prs.md index e8e34181e6..4eaf7f84e2 100644 --- a/.serena/memories/workflow/creating-prs.md +++ b/.serena/memories/workflow/creating-prs.md @@ -10,13 +10,15 @@ PR only on explicit request. ## Target Branch -Auto-detect the base branch with `scripts/detect-target-branch`: - -```bash -TARGET=$(scripts/detect-target-branch) -``` - -This outputs `staging` or `develop` by walking the local commit graph (pure local, no remote/network). Do not ask the user for the target branch unless the tool fails. +The `create-pr` shortcut detects the base branch automatically: it ports the +heuristic of `scripts/detect-target-branch` into `detect_target_branch()` in +`scripts/gh.py` (local commit graph, no remote/network), usually yielding +`staging` or `develop`. Do not ask the user for the target branch unless the +command fails. Pass `--base` only when the detected branch is not the one +wanted; explicit user context overrides the detection. If detection fails +with `detected base '<name>' is not a local branch; pass --base explicitly`, +rerun with `--base <name>` using the name from the error; do not ask the +user and do not add pre-flight checks for this case. ## Metadata @@ -107,20 +109,22 @@ When the PR requests a regular merge instead of a squash merge, its ## Creating the PR +Write the body to a temp file and run the shortcut. It detects the base, runs +`gh pr create` with `--project Main`, parses the PR number and, with +`--issue N`, creates the explicit issue link (see `mem:scripts/gh`): + ```bash cat > /tmp/pr-body.md << 'PR_BODY' <body content here> PR_BODY -TARGET=$(scripts/detect-target-branch) - -gh pr create \ - --repo penpot/penpot \ - --base "$TARGET" \ - --head <branch> \ - --title "<title>" \ - --project "Main" \ - --body-file /tmp/pr-body.md +python3 scripts/gh.py create-pr \ + --title "<title>" --body-file /tmp/pr-body.md \ + [--issue NNNN] [--base <branch>] [--project <project>] rm -f /tmp/pr-body.md ``` + +Do not pre-check authentication, push state or an existing PR: the command +and `gh` report those errors. Never push yourself; ask the user if the +command reports that the branch was not pushed. diff --git a/scripts/detect-target-branch b/scripts/detect-target-branch index 65ff49c0ca..30e95d428f 100755 --- a/scripts/detect-target-branch +++ b/scripts/detect-target-branch @@ -7,6 +7,8 @@ set -euo pipefail # # Uses git name-rev to find the nearest ref (branch/tag) that is an ancestor of # HEAD, falling back to a graph walk if name-rev returns the current branch. +# The ref description is normalized to a local branch name and checked +# against the local branches before it is printed. # # Pure local — no remote, no SSH, no network. Works even when the current # branch shares its tip commit with the target (not yet diverged). @@ -17,7 +19,8 @@ set -euo pipefail # # Exit status: # 0 — target found -# 1 — no target found (orphan commit, no other branches) +# 1 — no target found (orphan commit, no other branches), or the detected +# ref is not a local branch (pass --base explicitly) verbose=false @@ -39,9 +42,30 @@ done current=$(git rev-parse --abbrev-ref HEAD) +# git name-rev describes refs, not branch names: "remotes/origin/staging~1", +# "develop^2~1" and "tags/v2.0" are all possible outputs. +normalize_ref() { + local name="$1" + name=${name%%[~^]*} + case "$name" in + refs/heads/*) name=${name#refs/heads/} ;; + heads/*) name=${name#heads/} ;; + remotes/*) + name=${name#remotes/} + if [[ "$name" == */* ]]; then + name=${name#*/} + else + name="" + fi + ;; + tags/*) name=${name#tags/} ;; + esac + printf '%s' "$name" +} + # Use name-rev to find the nearest ref — it has smart tie-breaking -raw=$(git name-rev --name-only HEAD 2>/dev/null) -target=${raw%%~[0-9]*} # strip ~N distance suffix +raw=$(git name-rev --name-only HEAD 2>/dev/null || true) +target=$(normalize_ref "$raw") # If name-rev returned the current branch itself, walk backwards if [ "$target" = "$current" ] || [ -z "$target" ]; then @@ -61,6 +85,16 @@ if [ "$target" = "$current" ] || [ -z "$target" ]; then fi fi +target=$(normalize_ref "$target") +if [ -z "$target" ]; then + echo "error: unable to determine target branch" >&2 + exit 1 +fi +if ! git show-ref --verify --quiet "refs/heads/$target"; then + echo "error: detected base '$target' is not a local branch; pass --base explicitly" >&2 + exit 1 +fi + if [ "$verbose" = true ]; then target_commit=$(git rev-parse "$target" 2>/dev/null || true) if [ -n "$target_commit" ]; then diff --git a/scripts/gh.py b/scripts/gh.py index 3881fb158a..c0e86940ac 100755 --- a/scripts/gh.py +++ b/scripts/gh.py @@ -12,6 +12,7 @@ Subcommands: advisories List or inspect GitHub security advisories link-issue Explicitly link a GitHub issue to a pull request create-issue Create an issue and set its Issue Type in one command + create-pr Create a pull request, optionally linking its issue Usage: python3 scripts/gh.py issues <milestone-title> (default: state=closed) @@ -37,6 +38,8 @@ Usage: python3 scripts/gh.py link-issue 11235 11243 python3 scripts/gh.py create-issue --type task \ --title "Expand backend email tests" --body-file /tmp/issue-body.md + python3 scripts/gh.py create-pr --title "Expand backend email tests" \ + --body-file /tmp/pr-body.md --issue 13202 [--base staging] Prerequisites: - gh CLI authenticated (gh auth status) @@ -135,6 +138,17 @@ def run_gh_rest(path: str) -> Any: fail_gh(err.stderr) +def run_git(*args: str) -> str: + """Run a ``git`` command and return its stripped stdout. + + Raises `GhCommandFailed` on failure so callers can degrade gracefully. + """ + result = subprocess.run(["git", *args], capture_output=True, text=True) + if result.returncode != 0: + raise GhCommandFailed(result.stderr) + return result.stdout.strip() + + # ───────────────────────────────────────────── # Subcommand: create-issue # ───────────────────────────────────────────── @@ -255,6 +269,166 @@ def cmd_create_issue(args: argparse.Namespace) -> None: print(json.dumps(result, indent=2)) +# ───────────────────────────────────────────── +# Subcommand: create-pr +# ───────────────────────────────────────────── + +PR_URL_RE = re.compile(r"/pull/(\d+)") + + +def normalize_branch_ref(ref: str) -> str: + """Turn a ``git name-rev`` description into a local branch name. + + ``name-rev`` can return ``remotes/origin/staging~1``, ``develop^2~1`` or + ``tags/v2.0``; none of them is a valid ``--base`` value. + """ + name = re.split(r"[~^]", ref.strip(), maxsplit=1)[0] + for prefix in ("refs/heads/", "heads/"): + if name.startswith(prefix): + return name[len(prefix):] + if name.startswith("remotes/"): + name = name[len("remotes/"):] + return name.split("/", 1)[1] if "/" in name else "" + if name.startswith("tags/"): + return name[len("tags/"):] + return name + + +def local_branch_exists(name: str) -> bool: + """Return whether ``name`` is a local branch (no network involved).""" + try: + run_git("show-ref", "--verify", "--quiet", f"refs/heads/{name}") + return True + except GhCommandFailed: + return False + + +def detect_target_branch() -> str: + """Return the nearest ancestor branch of HEAD, using only local git. + + Port of ``scripts/detect-target-branch``: ``git name-rev`` picks the + closest ref and a graph walk is the fallback when it resolves to the + current branch. The result is normalized and checked against the local + branches because ``name-rev`` describes refs, not branch names. + """ + current = run_git("rev-parse", "--abbrev-ref", "HEAD") + try: + raw = run_git("name-rev", "--name-only", "HEAD") + except GhCommandFailed: + raw = "" + target = normalize_branch_ref(raw) if raw else "" + if not target or target == current: + target = "" + for commit in run_git("rev-list", "HEAD").splitlines(): + branches = run_git( + "branch", "--points-at", commit, "--format=%(refname:short)" + ).splitlines() + found = next( + ( + branch.strip() + for branch in branches + if branch.strip() and branch.strip() != current + ), + None, + ) + if found: + target = normalize_branch_ref(found) + break + if not target: + raise RuntimeError("unable to determine target branch") + if not local_branch_exists(target): + raise RuntimeError( + f"detected base {target!r} is not a local branch; pass --base explicitly" + ) + return target + + +def create_pr( + title: str, + body_file: str, + base: str | None = None, + head: str | None = None, + issue_number: int | None = None, + project: str = "Main", + draft: bool = False, +) -> dict: + """Create a PR and optionally link its issue in one sequence of calls. + + The base defaults to the nearest ancestor branch of HEAD and the head to + the current branch, so the caller only needs to supply the title and the + body. A failed issue link leaves the PR in place and reports its URL. + """ + if not title.strip(): + raise ValueError("pull request title must not be empty") + resolved_base = (base or detect_target_branch()).strip() + if not resolved_base: + raise ValueError("pull request base must not be empty") + resolved_head = (head or run_git("rev-parse", "--abbrev-ref", "HEAD")).strip() + + cmd = [ + "gh", "pr", "create", + "--repo", REPO, + "--base", resolved_base, + "--head", resolved_head, + "--title", title, + "--project", project, + "--body-file", body_file, + ] + if draft: + cmd.append("--draft") + stdout = run_gh_command(cmd) + url = stdout.strip().splitlines()[-1].strip() + match = PR_URL_RE.search(url) + if not match: + raise RuntimeError( + f"could not read PR number from gh output: {url!r};" + " check whether the PR was created" + ) + number = int(match.group(1)) + print(f"Created PR #{number}: {url}", file=sys.stderr) + + linked_issue = None + if issue_number is not None: + try: + link_issue_to_pr(issue_number, number) + except SystemExit: + raise RuntimeError( + f"issue linking failed; the PR was created at {url}" + ) from None + except (ValueError, RuntimeError) as error: + raise RuntimeError(f"{error}; the PR was created at {url}") from error + linked_issue = issue_number + + return { + "number": number, + "url": url, + "title": title, + "base": resolved_base, + "head": resolved_head, + "linked_issue": linked_issue, + } + + +def cmd_create_pr(args: argparse.Namespace) -> None: + """Handle the ``create-pr`` subcommand.""" + print("Creating pull request...", file=sys.stderr) + try: + result = create_pr( + args.title, + args.body_file, + base=args.base, + head=args.head, + issue_number=args.issue, + project=args.project, + draft=args.draft, + ) + except (ValueError, RuntimeError, GhCommandFailed) as error: + print(f"ERROR: {error}", file=sys.stderr) + sys.exit(1) + + print(json.dumps(result, indent=2)) + + # ───────────────────────────────────────────── # Subcommand: link-issue # ───────────────────────────────────────────── @@ -1291,6 +1465,33 @@ def main() -> None: ) p_create.set_defaults(func=cmd_create_issue) + # --- create-pr --- + p_create_pr = sub.add_parser( + "create-pr", + help="Create a pull request, optionally linking its issue", + ) + p_create_pr.add_argument("--title", required=True, help="Pull request title") + p_create_pr.add_argument( + "--body-file", required=True, + help="Path to the file holding the Markdown body", + ) + p_create_pr.add_argument( + "--base", help="Base branch (default: nearest ancestor branch of HEAD)" + ) + p_create_pr.add_argument( + "--head", help="Head branch (default: current branch)" + ) + p_create_pr.add_argument( + "--issue", type=int, help="Issue number to link to the new PR" + ) + p_create_pr.add_argument( + "--draft", action="store_true", help="Create the PR as a draft" + ) + p_create_pr.add_argument( + "--project", default="Main", help="Project to add the PR to (default: Main)" + ) + p_create_pr.set_defaults(func=cmd_create_pr) + # --- issue (by-number lookup) --- p_issue = sub.add_parser( "issue", help="Fetch details for one or more issues by number (batched)" diff --git a/scripts/test_gh.py b/scripts/test_gh.py index fb15b1a8ce..41f6bd9c4a 100644 --- a/scripts/test_gh.py +++ b/scripts/test_gh.py @@ -179,6 +179,333 @@ class CreateIssueTests(unittest.TestCase): self.assertIn("boom", stderr.getvalue()) +class CreatePrBaseDetectionTests(unittest.TestCase): + @staticmethod + def fake_git(mapping): + def run(*args): + return mapping.get(args, "") + return run + + def test_normalize_branch_ref(self): + cases = [ + ("remotes/origin/staging~2", "staging"), + ("develop^2~1", "develop"), + ("tags/v2.0", "v2.0"), + ("refs/heads/topic~1", "topic"), + ("heads/topic", "topic"), + ] + for raw, expected in cases: + with self.subTest(raw=raw): + self.assertEqual(gh.normalize_branch_ref(raw), expected) + + @patch.object(gh, "run_git") + def test_detects_normalized_base_and_validates_it(self, run_git): + calls = [] + + def fake(*args): + calls.append(args) + if args == ("rev-parse", "--abbrev-ref", "HEAD"): + return "topic" + if args == ("name-rev", "--name-only", "HEAD"): + return "remotes/origin/staging~2" + return "" + run_git.side_effect = fake + + self.assertEqual(gh.detect_target_branch(), "staging") + self.assertIn( + ("show-ref", "--verify", "--quiet", "refs/heads/staging"), calls + ) + + @patch.object(gh, "run_git") + def test_rejects_detected_base_without_local_branch(self, run_git): + def fake(*args): + if args == ("rev-parse", "--abbrev-ref", "HEAD"): + return "topic" + if args == ("name-rev", "--name-only", "HEAD"): + return "tags/v2.0" + if args[:1] == ("show-ref",): + raise gh.GhCommandFailed("not found") + return "" + run_git.side_effect = fake + + with self.assertRaisesRegex(RuntimeError, "pass --base"): + gh.detect_target_branch() + + @patch.object(gh, "run_git") + def test_detects_base_from_name_rev(self, run_git): + run_git.side_effect = self.fake_git({ + ("rev-parse", "--abbrev-ref", "HEAD"): "issue-13202", + ("name-rev", "--name-only", "HEAD"): "staging~3", + }) + + self.assertEqual(gh.detect_target_branch(), "staging") + + @patch.object(gh, "run_git") + def test_falls_back_to_graph_walk(self, run_git): + def fake(*args): + if args == ("rev-parse", "--abbrev-ref", "HEAD"): + return "issue-13202" + if args == ("name-rev", "--name-only", "HEAD"): + return "issue-13202" + if args == ("rev-list", "HEAD"): + return "a\nb\nc\n" + if args[:2] == ("branch", "--points-at"): + return "staging\n" if args[2] == "b" else "" + return "" + run_git.side_effect = fake + + self.assertEqual(gh.detect_target_branch(), "staging") + + @patch.object(gh, "run_git") + def test_tolerates_name_rev_failure(self, run_git): + def fake(*args): + if args == ("name-rev", "--name-only", "HEAD"): + raise gh.GhCommandFailed("boom") + if args == ("rev-parse", "--abbrev-ref", "HEAD"): + return "topic" + if args == ("rev-list", "HEAD"): + return "a\n" + if args[:2] == ("branch", "--points-at"): + return "staging\n" + return "" + run_git.side_effect = fake + + self.assertEqual(gh.detect_target_branch(), "staging") + + @patch.object(gh, "run_git") + def test_raises_when_no_other_branch(self, run_git): + run_git.side_effect = self.fake_git({ + ("rev-parse", "--abbrev-ref", "HEAD"): "topic", + ("name-rev", "--name-only", "HEAD"): "", + ("rev-list", "HEAD"): "a\n", + }) + + with self.assertRaisesRegex(RuntimeError, "unable to determine target branch"): + gh.detect_target_branch() + + +class CreatePrTests(unittest.TestCase): + def setUp(self): + self.url = "https://github.com/penpot/penpot/pull/13204" + self.create_response = self.url + "\n" + + def args(self, **overrides): + values = dict( + title="A title", + body_file="/tmp/pr-body.md", + base=None, + head=None, + issue=None, + project="Main", + draft=False, + ) + values.update(overrides) + return types.SimpleNamespace(**values) + + @patch.object(gh, "link_issue_to_pr") + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git") + @patch.object(gh, "detect_target_branch") + def test_create_pr_detects_base_and_links_issue( + self, detect, run_git, run_command, link_issue + ): + detect.return_value = "staging" + run_git.return_value = "issue-13202" + run_command.return_value = self.create_response + + with contextlib.redirect_stderr(io.StringIO()): + result = gh.create_pr( + "A title", "/tmp/pr-body.md", issue_number=13202 + ) + + self.assertEqual(result, { + "number": 13204, + "url": self.url, + "title": "A title", + "base": "staging", + "head": "issue-13202", + "linked_issue": 13202, + }) + self.assertEqual(run_command.call_args.args[0], [ + "gh", "pr", "create", + "--repo", "penpot/penpot", + "--base", "staging", + "--head", "issue-13202", + "--title", "A title", + "--project", "Main", + "--body-file", "/tmp/pr-body.md", + ]) + link_issue.assert_called_once_with(13202, 13204) + detect.assert_called_once_with() + + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git") + @patch.object(gh, "detect_target_branch") + def test_create_pr_uses_explicit_base(self, detect, run_git, run_command): + run_git.return_value = "topic" + run_command.return_value = self.create_response + + with contextlib.redirect_stderr(io.StringIO()): + result = gh.create_pr("T", "/tmp/pr-body.md", base="release/1.0") + + self.assertEqual(result["base"], "release/1.0") + detect.assert_not_called() + cmd = run_command.call_args.args[0] + self.assertEqual(cmd[cmd.index("--base") + 1], "release/1.0") + + @patch.object(gh, "run_gh_command") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_passes_head_and_draft(self, _detect, run_command): + run_command.return_value = self.create_response + + with contextlib.redirect_stderr(io.StringIO()): + result = gh.create_pr( + "T", "/tmp/pr-body.md", head="custom", draft=True + ) + + cmd = run_command.call_args.args[0] + self.assertEqual(cmd[cmd.index("--head") + 1], "custom") + self.assertIn("--draft", cmd) + self.assertIsNone(result["linked_issue"]) + + @patch.object(gh, "run_gh_command") + @patch.object(gh, "detect_target_branch") + def test_create_pr_rejects_empty_title(self, _detect, run_command): + with self.assertRaisesRegex(ValueError, "title must not be empty"): + gh.create_pr(" ", "/tmp/pr-body.md") + run_command.assert_not_called() + + @patch.object(gh, "run_gh_command", return_value="created") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_fails_when_url_has_no_number( + self, _detect, _run_git, _run_command + ): + with self.assertRaisesRegex(RuntimeError, "could not read PR number"): + gh.create_pr("T", "/tmp/pr-body.md") + + @patch.object(gh, "run_gh_command", side_effect=gh.GhCommandFailed("boom")) + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_propagates_gh_failure( + self, _detect, _run_git, _run_command + ): + with self.assertRaises(gh.GhCommandFailed): + gh.create_pr("T", "/tmp/pr-body.md") + + @patch.object(gh, "link_issue_to_pr") + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_prints_url_once_on_success( + self, _detect, _run_git, run_command, _link_issue + ): + run_command.return_value = self.create_response + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + gh.create_pr("T", "/tmp/pr-body.md", issue_number=13202) + + self.assertEqual(stderr.getvalue().count("Created PR #13204"), 1) + + @patch.object(gh, "link_issue_to_pr", side_effect=RuntimeError("link missing")) + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_cmd_create_pr_keeps_url_when_link_raises_runtime_error( + self, _detect, _run_git, run_command, _link_issue + ): + run_command.return_value = self.create_response + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as error: + gh.cmd_create_pr(self.args(issue=13202)) + + self.assertEqual(error.exception.code, 1) + self.assertIn("Created PR #13204", stderr.getvalue()) + self.assertIn(self.url, stderr.getvalue()) + + @patch.object(gh, "link_issue_to_pr", side_effect=SystemExit(1)) + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_cmd_create_pr_keeps_url_when_link_exits( + self, _detect, _run_git, run_command, _link_issue + ): + run_command.return_value = self.create_response + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as error: + gh.cmd_create_pr(self.args(issue=13202)) + + self.assertEqual(error.exception.code, 1) + self.assertIn("Created PR #13204", stderr.getvalue()) + self.assertIn("issue linking failed", stderr.getvalue()) + self.assertIn(self.url, stderr.getvalue()) + self.assertNotIn("ERROR: 1", stderr.getvalue()) + + @patch.object(gh, "create_pr") + def test_cmd_create_pr_outputs_result(self, create_pr): + expected = { + "number": 13204, + "url": self.url, + "title": "T", + "base": "staging", + "head": "topic", + "linked_issue": None, + } + create_pr.return_value = expected + stdout = io.StringIO() + stderr = io.StringIO() + + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + gh.cmd_create_pr(self.args()) + + self.assertEqual(json.loads(stdout.getvalue()), expected) + self.assertIn("Creating pull request...", stderr.getvalue()) + create_pr.assert_called_once_with( + "A title", "/tmp/pr-body.md", + base=None, head=None, issue_number=None, + project="Main", draft=False, + ) + + @patch.object(gh, "create_pr") + def test_cmd_create_pr_forwards_project(self, create_pr): + create_pr.return_value = {"number": 13204, "url": self.url} + + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr( + io.StringIO() + ): + gh.cmd_create_pr(self.args(project="Other")) + + self.assertEqual(create_pr.call_args.kwargs["project"], "Other") + + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_uses_explicit_project(self, _detect, _run_git, run_command): + run_command.return_value = self.create_response + + with contextlib.redirect_stderr(io.StringIO()): + gh.create_pr("T", "/tmp/pr-body.md", project="Other") + + cmd = run_command.call_args.args[0] + self.assertEqual(cmd[cmd.index("--project") + 1], "Other") + + @patch.object(gh, "create_pr", side_effect=gh.GhCommandFailed("boom")) + def test_cmd_create_pr_exits_on_error(self, _create_pr): + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as error: + gh.cmd_create_pr(self.args()) + + self.assertEqual(error.exception.code, 1) + self.assertIn("boom", stderr.getvalue()) + + class LinkIssueTests(unittest.TestCase): def setUp(self): self.target_response = {