Add agentpr pr edit subcommand #15

Merged
benvin merged 3 commits from benvin/agentpr-pr-edit into main 2026-09-19 13:48:44 +10:00
6 changed files with 194 additions and 8 deletions
+5 -5
View File
@@ -8,9 +8,9 @@ from Vault, so actions are attributed to the agent rather than to whoever runs
the tool. Setting `AGENT_LOGIN` selects a different agent identity, so a service
like repospawner can run these tools as itself.
- **`agentpr`** — create pull requests and post PR comments as `unkin-agent`
(fixes the "tea posts as Ben" attribution problem). Subcommands:
`pr create`, `pr comment`, `whoami`.
- **`agentpr`** — create and edit pull requests, and post PR comments, as
`unkin-agent` (fixes the "tea posts as Ben" attribution problem).
Subcommands: `pr create`, `pr comment`, `pr edit`, `whoami`.
- **`watchpr`** — poll one or more PRs and exit when a tracked PR changes
meaningfully: it merges/closes, gets a new non-agent comment, its CI fails,
or it loses mergeability. Benign transitions (CI pending→success, the agent's
@@ -28,7 +28,7 @@ parsing, watch-state comparison, git worktree helpers).
## Structure
```
cmd/agentpr/main.go # agentpr CLI (pr create / pr comment / whoami)
cmd/agentpr/main.go # agentpr CLI (pr create / pr comment / pr edit / whoami)
cmd/watchpr/main.go # watchpr CLI (poll + meaningful-change exit)
cmd/agentws/main.go # agentws CLI (new / list / rm / clean / token / credential)
cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe ones)
@@ -36,7 +36,7 @@ cmd/agentvault/main.go # agentvault CLI (seed-outpost / seed-oauth)
internal/agent/ # shared plumbing:
token.go # env config + in-process Gitea-token cache
vault.go # AppRole login + read the gitea creds path
gitea.go # Gitea REST client (PR create/get, comments, status, whoami)
gitea.go # Gitea REST client (PR create/edit/get, comments, status, whoami)
parse.go # owner/repo#N and owner/repo parsing
watch.go # PRState snapshot + MeaningfulChange comparison
git.go # git worktree/clone/fetch helpers (os/exec, no go-git)
+7 -1
View File
@@ -6,7 +6,8 @@ token from Vault, so automated PRs, comments and pushes are attributed to the
agent — not to whoever happens to run the command. Set `AGENT_LOGIN` to act as a
different agent identity.
- **`agentpr`** — create pull requests and post PR comments as the agent user.
- **`agentpr`** — create and edit pull requests, and post PR comments as the
agent user.
- **`watchpr`** — poll one or more PRs and exit when one changes in a way worth
acting on.
- **`agentws`** — manage per-branch git worktrees for `unkin-agent`, cloning
@@ -50,6 +51,11 @@ agentpr pr create --repo unkin/argocd-apps \
# Comment on a PR
agentpr pr comment --repo unkin/argocd-apps --pr 42 --body "Rebased, CI green."
# Edit a PR's title and/or body; an omitted flag is left unchanged
agentpr pr edit --repo unkin/argocd-apps --pr 42 --body "Adds the ServiceAccount ..."
agentpr pr edit --repo unkin/argocd-apps --pr 42 --title "Add woodpecker SA"
# prints: #<number> <html_url>
agentpr --version
agentpr --help
```
+57 -2
View File
@@ -5,6 +5,7 @@
//
// agentpr pr create --repo owner/repo --base main --head feature --title T --body B
// agentpr pr comment --repo owner/repo --pr 12 --body "..."
// agentpr pr edit --repo owner/repo --pr 12 --title T --body B
// agentpr whoami
package main
@@ -56,9 +57,9 @@ func client() (*agent.GiteaClient, error) {
func newPRCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "pr",
Short: "Create PRs and post PR comments",
Short: "Create and edit PRs, and post PR comments",
}
cmd.AddCommand(newPRCreateCmd(), newPRCommentCmd())
cmd.AddCommand(newPRCreateCmd(), newPRCommentCmd(), newPREditCmd())
return cmd
}
@@ -143,6 +144,60 @@ func newPRCommentCmd() *cobra.Command {
return cmd
}
func newPREditCmd() *cobra.Command {
var repo, title, body string
var pr int
cmd := &cobra.Command{
Use: "edit",
Short: "Edit a pull request's title and/or body",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
owner, name, err := agent.ParseRepo(repo)
if err != nil {
return err
}
if pr <= 0 {
return fmt.Errorf("--pr must be a positive PR number")
}
// Only the flags actually given are sent: omitting --title must
// leave the title as it is, not blank it.
var opts agent.EditPROptions
if cmd.Flags().Changed("title") {
// Gitea ignores an empty title, so sending one would report
// success while changing nothing.
if title == "" {
return fmt.Errorf("--title cannot be empty: a title can be set but not cleared")
}
opts.Title = &title
}
if cmd.Flags().Changed("body") {
opts.Body = &body
}
if opts.Title == nil && opts.Body == nil {
return fmt.Errorf("at least one of --title or --body is required")
}
c, err := client()
if err != nil {
return err
}
updated, err := c.EditPR(owner+"/"+name, pr, opts)
if err != nil {
return err
}
fmt.Printf("#%d %s\n", updated.Number, updated.HTMLURL)
return nil
},
}
f := cmd.Flags()
f.StringVar(&repo, "repo", "", "Repository as owner/repo (required)")
f.IntVar(&pr, "pr", 0, "PR number (required)")
f.StringVar(&title, "title", "", "New PR title (unchanged when omitted)")
f.StringVar(&body, "body", "", "New PR body (unchanged when omitted)")
_ = cmd.MarkFlagRequired("repo")
_ = cmd.MarkFlagRequired("pr")
return cmd
}
func newWhoamiCmd() *cobra.Command {
return &cobra.Command{
Use: "whoami",
+33
View File
@@ -2,6 +2,7 @@ package main
import (
"io"
"strings"
"testing"
)
@@ -16,3 +17,35 @@ func TestExecuteBadRepoErrors(t *testing.T) {
t.Fatal("Execute() = nil, want error for a malformed --repo")
}
}
// `pr edit` with neither --title nor --body has nothing to send; it must fail
// with a usage error before any Vault/Gitea call, so this stays hermetic.
func TestPREditRequiresTitleOrBody(t *testing.T) {
cmd := newRootCmd()
cmd.SetArgs([]string{"pr", "edit", "--repo", "unkin/repo", "--pr", "7"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
if err == nil {
t.Fatal("Execute() = nil, want an error when neither --title nor --body is given")
}
if !strings.Contains(err.Error(), "--title or --body") {
t.Errorf("error = %q, want it to name the missing flags", err)
}
}
// Gitea silently ignores an empty title, so `pr edit --title ""` would report
// success while changing nothing; it must fail before any Vault/Gitea call.
func TestPREditRejectsEmptyTitle(t *testing.T) {
cmd := newRootCmd()
cmd.SetArgs([]string{"pr", "edit", "--repo", "unkin/repo", "--pr", "7", "--title", ""})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
err := cmd.Execute()
if err == nil {
t.Fatal("Execute() = nil, want an error for an empty --title")
}
if !strings.Contains(err.Error(), "--title cannot be empty") {
t.Errorf("error = %q, want it to reject the empty title", err)
}
}
+74
View File
@@ -98,6 +98,80 @@ func TestCreatePRRequestBody(t *testing.T) {
}
}
// An edit must send only the fields it was given: Gitea overwrites whatever
// key it receives, so an omitted --title arriving as "" would blank the title.
func TestEditPRSendsOnlySuppliedFields(t *testing.T) {
title, body, empty := "new title", "new body", ""
tests := []struct {
name string
opts EditPROptions
want map[string]any
}{
{"body only", EditPROptions{Body: &body}, map[string]any{"body": "new body"}},
{"title only", EditPROptions{Title: &title}, map[string]any{"title": "new title"}},
{"both", EditPROptions{Title: &title, Body: &body}, map[string]any{"title": "new title", "body": "new body"}},
{"explicit empty body is sent", EditPROptions{Body: &empty}, map[string]any{"body": ""}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var gotBody map[string]any
var gotMethod, gotPath string
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls/7", func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
_ = json.NewDecoder(r.Body).Decode(&gotBody)
_, _ = io.WriteString(w, `{"number":7,"title":"new title","html_url":"https://git.unkin.net/unkin/repo/pulls/7"}`)
})
srv := httptest.NewServer(mux)
defer srv.Close()
c := &GiteaClient{BaseURL: srv.URL, Token: "gitea-abc", HTTP: srv.Client()}
pr, err := c.EditPR("unkin/repo", 7, tt.opts)
if err != nil {
t.Fatalf("EditPR: %v", err)
}
if gotMethod != http.MethodPatch {
t.Errorf("method = %s, want PATCH", gotMethod)
}
if gotPath != "/api/v1/repos/unkin/repo/pulls/7" {
t.Errorf("path = %q", gotPath)
}
if len(gotBody) != len(tt.want) {
t.Errorf("payload = %v, want exactly the supplied fields %v", gotBody, tt.want)
}
for k, v := range tt.want {
if gotBody[k] != v {
t.Errorf("payload[%q] = %v, want %v", k, gotBody[k], v)
}
}
if pr.Number != 7 || pr.HTMLURL == "" {
t.Errorf("parsed PR = %+v", pr)
}
})
}
}
// A non-2xx must surface the API's own message rather than a bare status.
func TestEditPRAPIError(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/repos/unkin/repo/pulls/7", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = io.WriteString(w, `{"message":"not found","url":"https://git.unkin.net/api/swagger","errors":null}`)
})
srv := httptest.NewServer(mux)
defer srv.Close()
title := "new title"
c := &GiteaClient{BaseURL: srv.URL, Token: "t", HTTP: srv.Client()}
_, err := c.EditPR("unkin/repo", 7, EditPROptions{Title: &title})
if err == nil {
t.Fatal("expected error on 404")
}
if !strings.Contains(err.Error(), `"message":"not found"`) {
t.Errorf("error %q should carry the API message", err)
}
}
func TestCreateComment(t *testing.T) {
var gotBody map[string]string
mux := http.NewServeMux()
+18
View File
@@ -214,6 +214,24 @@ func (c *GiteaClient) CreatePR(repoPath string, opts CreatePROptions) (PullReque
return pr, err
}
// EditPROptions are the fields an edit may change. Pointers so an unset field
// is omitted from the payload entirely, leaving that field as it is. The two
// fields are not symmetric: Gitea only applies a title when it is non-empty,
// so Title can be set but never cleared and a "" title is a silent no-op,
// while a pointer to "" Body really does blank the body.
type EditPROptions struct {
Title *string `json:"title,omitempty"`
Body *string `json:"body,omitempty"`
}
// EditPR updates a pull request's title and/or body
// (PATCH /api/v1/repos/{owner}/{repo}/pulls/{index}).
func (c *GiteaClient) EditPR(repoPath string, number int, opts EditPROptions) (PullRequest, error) {
var pr PullRequest
err := c.do(http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/pulls/%d", repoPath, number), opts, &pr)
return pr, err
}
// GetPR fetches a single pull request.
func (c *GiteaClient) GetPR(repoPath string, number int) (PullRequest, error) {
var pr PullRequest