Add agentpr issue create/comment/edit #16
@@ -8,9 +8,10 @@ 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
|
the tool. Setting `AGENT_LOGIN` selects a different agent identity, so a service
|
||||||
like repospawner can run these tools as itself.
|
like repospawner can run these tools as itself.
|
||||||
|
|
||||||
- **`agentpr`** — create and edit pull requests, and post PR comments, as
|
- **`agentpr`** — create and edit pull requests and issues, and post comments on
|
||||||
`unkin-agent` (fixes the "tea posts as Ben" attribution problem).
|
either, as `unkin-agent` (fixes the "tea posts as Ben" attribution problem).
|
||||||
Subcommands: `pr create`, `pr comment`, `pr edit`, `whoami`.
|
Subcommands: `pr create`, `pr comment`, `pr edit`, `issue create`,
|
||||||
|
`issue comment`, `issue edit`, `whoami`.
|
||||||
- **`watchpr`** — poll one or more PRs and exit when a tracked PR changes
|
- **`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,
|
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
|
or it loses mergeability. Benign transitions (CI pending→success, the agent's
|
||||||
@@ -28,7 +29,7 @@ parsing, watch-state comparison, git worktree helpers).
|
|||||||
## Structure
|
## Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
cmd/agentpr/main.go # agentpr CLI (pr create / pr comment / pr edit / whoami)
|
cmd/agentpr/main.go # agentpr CLI (pr + issue create/comment/edit, whoami)
|
||||||
cmd/watchpr/main.go # watchpr CLI (poll + meaningful-change exit)
|
cmd/watchpr/main.go # watchpr CLI (poll + meaningful-change exit)
|
||||||
cmd/agentws/main.go # agentws CLI (new / list / rm / clean / token / credential)
|
cmd/agentws/main.go # agentws CLI (new / list / rm / clean / token / credential)
|
||||||
cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe ones)
|
cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe ones)
|
||||||
@@ -36,7 +37,7 @@ cmd/agentvault/main.go # agentvault CLI (seed-outpost / seed-oauth)
|
|||||||
internal/agent/ # shared plumbing:
|
internal/agent/ # shared plumbing:
|
||||||
token.go # env config + in-process Gitea-token cache
|
token.go # env config + in-process Gitea-token cache
|
||||||
vault.go # AppRole login + read the gitea creds path
|
vault.go # AppRole login + read the gitea creds path
|
||||||
gitea.go # Gitea REST client (PR create/edit/get, comments, status, whoami)
|
gitea.go # Gitea REST client (PR/issue create/edit/get, comments, status, whoami)
|
||||||
parse.go # owner/repo#N and owner/repo parsing
|
parse.go # owner/repo#N and owner/repo parsing
|
||||||
watch.go # PRState snapshot + MeaningfulChange comparison
|
watch.go # PRState snapshot + MeaningfulChange comparison
|
||||||
git.go # git worktree/clone/fetch helpers (os/exec, no go-git)
|
git.go # git worktree/clone/fetch helpers (os/exec, no go-git)
|
||||||
@@ -129,8 +130,8 @@ make test # go test -v -race ./...
|
|||||||
|
|
||||||
`internal/agent` covers PR-ref parsing, the `MeaningfulChange` table (benign vs
|
`internal/agent` covers PR-ref parsing, the `MeaningfulChange` table (benign vs
|
||||||
alerting transitions), request-body construction, and the Vault+Gitea client
|
alerting transitions), request-body construction, and the Vault+Gitea client
|
||||||
against `httptest` servers (fake AppRole login + gitea creds + PR create /
|
against `httptest` servers (fake AppRole login + gitea creds + PR/issue create
|
||||||
comment / whoami / status). No live Vault/Gitea access is required for tests.
|
+ edit / comment / whoami / status). No live Vault/Gitea access is required for tests.
|
||||||
|
|
||||||
## agentvault seed-outpost
|
## agentvault seed-outpost
|
||||||
|
|
||||||
@@ -208,3 +209,6 @@ wrapped per stage (login / read denied / write denied) via `ErrVaultDenied`.
|
|||||||
worktree root.
|
worktree root.
|
||||||
- CI "combined status" comes from `/commits/{sha}/status`; an empty head SHA
|
- CI "combined status" comes from `/commits/{sha}/status`; an empty head SHA
|
||||||
yields an empty state without an API call.
|
yields an empty state without an API call.
|
||||||
|
- Gitea backs every PR with an issue of the same number and serves comments from
|
||||||
|
`/issues/{n}/comments`, so `agentpr pr comment` and `agentpr issue comment`
|
||||||
|
are one implementation under two flag names (`--pr` / `--issue`).
|
||||||
|
|||||||
@@ -6,8 +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
|
agent — not to whoever happens to run the command. Set `AGENT_LOGIN` to act as a
|
||||||
different agent identity.
|
different agent identity.
|
||||||
|
|
||||||
- **`agentpr`** — create and edit pull requests, and post PR comments as the
|
- **`agentpr`** — create and edit pull requests and issues, and post comments on
|
||||||
agent user.
|
either, as the agent user.
|
||||||
- **`watchpr`** — poll one or more PRs and exit when one changes in a way worth
|
- **`watchpr`** — poll one or more PRs and exit when one changes in a way worth
|
||||||
acting on.
|
acting on.
|
||||||
- **`agentws`** — manage per-branch git worktrees for `unkin-agent`, cloning
|
- **`agentws`** — manage per-branch git worktrees for `unkin-agent`, cloning
|
||||||
@@ -56,6 +56,18 @@ 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"
|
agentpr pr edit --repo unkin/argocd-apps --pr 42 --title "Add woodpecker SA"
|
||||||
# prints: #<number> <html_url>
|
# prints: #<number> <html_url>
|
||||||
|
|
||||||
|
# File an issue (--body optional)
|
||||||
|
agentpr issue create --repo unkin/argocd-apps \
|
||||||
|
--title "Woodpecker SA missing" --body "The pipeline fails with ..."
|
||||||
|
# prints: #<number> <html_url>
|
||||||
|
|
||||||
|
# Comment on an issue (the same Gitea endpoint `pr comment` posts to)
|
||||||
|
agentpr issue comment --repo unkin/argocd-apps --issue 43 --body "Fixed in #44."
|
||||||
|
|
||||||
|
# Edit an issue's title and/or body; an omitted flag is left unchanged
|
||||||
|
agentpr issue edit --repo unkin/argocd-apps --issue 43 --body "The pipeline fails with ..."
|
||||||
|
# prints: #<number> <html_url>
|
||||||
|
|
||||||
agentpr --version
|
agentpr --version
|
||||||
agentpr --help
|
agentpr --help
|
||||||
```
|
```
|
||||||
|
|||||||
+132
-29
@@ -6,6 +6,9 @@
|
|||||||
// agentpr pr create --repo owner/repo --base main --head feature --title T --body B
|
// 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 comment --repo owner/repo --pr 12 --body "..."
|
||||||
// agentpr pr edit --repo owner/repo --pr 12 --title T --body B
|
// agentpr pr edit --repo owner/repo --pr 12 --title T --body B
|
||||||
|
// agentpr issue create --repo owner/repo --title T --body B
|
||||||
|
// agentpr issue comment --repo owner/repo --issue 12 --body "..."
|
||||||
|
// agentpr issue edit --repo owner/repo --issue 12 --title T --body B
|
||||||
// agentpr whoami
|
// agentpr whoami
|
||||||
package main
|
package main
|
||||||
|
|
||||||
@@ -34,14 +37,14 @@ func main() {
|
|||||||
func newRootCmd() *cobra.Command {
|
func newRootCmd() *cobra.Command {
|
||||||
root := &cobra.Command{
|
root := &cobra.Command{
|
||||||
Use: "agentpr",
|
Use: "agentpr",
|
||||||
Short: "Manage Gitea PRs and comments as an agent user.",
|
Short: "Manage Gitea PRs, issues and comments as an agent user.",
|
||||||
Long: "agentpr manages Gitea pull requests and comments as an agent user, using a\nGitea token minted from Vault (AppRole login + gitea/creds/<AGENT_LOGIN>).\nSet AGENT_LOGIN to act as another agent identity, or GITEA_CREDS_PATH to name\nthe Vault creds path outright.",
|
Long: "agentpr manages Gitea pull requests, issues and comments as an agent user,\nusing a Gitea token minted from Vault (AppRole login + gitea/creds/<AGENT_LOGIN>).\nSet AGENT_LOGIN to act as another agent identity, or GITEA_CREDS_PATH to name\nthe Vault creds path outright.",
|
||||||
Version: version,
|
Version: version,
|
||||||
SilenceUsage: true,
|
SilenceUsage: true,
|
||||||
}
|
}
|
||||||
root.SetVersionTemplate("{{.Version}}\n")
|
root.SetVersionTemplate("{{.Version}}\n")
|
||||||
|
|
||||||
root.AddCommand(newPRCmd(), newWhoamiCmd(), newVersionCmd())
|
root.AddCommand(newPRCmd(), newIssueCmd(), newWhoamiCmd(), newVersionCmd())
|
||||||
return root
|
return root
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,7 +62,16 @@ func newPRCmd() *cobra.Command {
|
|||||||
Use: "pr",
|
Use: "pr",
|
||||||
Short: "Create and edit PRs, and post PR comments",
|
Short: "Create and edit PRs, and post PR comments",
|
||||||
}
|
}
|
||||||
cmd.AddCommand(newPRCreateCmd(), newPRCommentCmd(), newPREditCmd())
|
cmd.AddCommand(newPRCreateCmd(), newCommentCmd("pr", "PR", "Post a comment on a pull request"), newPREditCmd())
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func newIssueCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "issue",
|
||||||
|
Short: "File and edit issues, and post issue comments",
|
||||||
|
}
|
||||||
|
cmd.AddCommand(newIssueCreateCmd(), newCommentCmd("issue", "issue", "Post a comment on an issue"), newIssueEditCmd())
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,20 +116,24 @@ func newPRCreateCmd() *cobra.Command {
|
|||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPRCommentCmd() *cobra.Command {
|
// newCommentCmd builds a comment command whose number flag is named numFlag.
|
||||||
|
// Gitea backs every PR with an issue of the same number and serves comments
|
||||||
|
// from the issue endpoint, so `pr comment` and `issue comment` are one command
|
||||||
|
// under two flag names rather than two implementations that could drift.
|
||||||
|
func newCommentCmd(numFlag, noun, short string) *cobra.Command {
|
||||||
var repo, body string
|
var repo, body string
|
||||||
var pr int
|
var number int
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "comment",
|
Use: "comment",
|
||||||
Short: "Post a comment on a pull request",
|
Short: short,
|
||||||
SilenceUsage: true,
|
SilenceUsage: true,
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
owner, name, err := agent.ParseRepo(repo)
|
owner, name, err := agent.ParseRepo(repo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if pr <= 0 {
|
if number <= 0 {
|
||||||
return fmt.Errorf("--pr must be a positive PR number")
|
return fmt.Errorf("--%s must be a positive %s number", numFlag, noun)
|
||||||
}
|
}
|
||||||
if body == "" {
|
if body == "" {
|
||||||
return fmt.Errorf("--body is required")
|
return fmt.Errorf("--body is required")
|
||||||
@@ -126,20 +142,20 @@ func newPRCommentCmd() *cobra.Command {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
cm, err := c.CreateComment(owner+"/"+name, pr, body)
|
cm, err := c.CreateComment(owner+"/"+name, number, body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Printf("comment %d posted on %s/%s#%d\n", cm.ID, owner, name, pr)
|
fmt.Printf("comment %d posted on %s/%s#%d\n", cm.ID, owner, name, number)
|
||||||
return nil
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
f := cmd.Flags()
|
f := cmd.Flags()
|
||||||
f.StringVar(&repo, "repo", "", "Repository as owner/repo (required)")
|
f.StringVar(&repo, "repo", "", "Repository as owner/repo (required)")
|
||||||
f.IntVar(&pr, "pr", 0, "PR number (required)")
|
f.IntVar(&number, numFlag, 0, noun+" number (required)")
|
||||||
f.StringVar(&body, "body", "", "Comment body (required)")
|
f.StringVar(&body, "body", "", "Comment body (required)")
|
||||||
_ = cmd.MarkFlagRequired("repo")
|
_ = cmd.MarkFlagRequired("repo")
|
||||||
_ = cmd.MarkFlagRequired("pr")
|
_ = cmd.MarkFlagRequired(numFlag)
|
||||||
_ = cmd.MarkFlagRequired("body")
|
_ = cmd.MarkFlagRequired("body")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
@@ -159,22 +175,9 @@ func newPREditCmd() *cobra.Command {
|
|||||||
if pr <= 0 {
|
if pr <= 0 {
|
||||||
return fmt.Errorf("--pr must be a positive PR number")
|
return fmt.Errorf("--pr must be a positive PR number")
|
||||||
}
|
}
|
||||||
// Only the flags actually given are sent: omitting --title must
|
opts, err := editOptions(cmd, title, body)
|
||||||
// leave the title as it is, not blank it.
|
if err != nil {
|
||||||
var opts agent.EditPROptions
|
return err
|
||||||
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()
|
c, err := client()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -198,6 +201,106 @@ func newPREditCmd() *cobra.Command {
|
|||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// editOptions turns the --title/--body flags actually given into an edit
|
||||||
|
// payload. Only the flags present are sent: omitting --title must leave the
|
||||||
|
// title as it is, not blank it.
|
||||||
|
func editOptions(cmd *cobra.Command, title, body string) (agent.EditOptions, error) {
|
||||||
|
var opts agent.EditOptions
|
||||||
|
if cmd.Flags().Changed("title") {
|
||||||
|
// Gitea ignores an empty title, so sending one would report success
|
||||||
|
// while changing nothing.
|
||||||
|
if title == "" {
|
||||||
|
return opts, 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 opts, fmt.Errorf("at least one of --title or --body is required")
|
||||||
|
}
|
||||||
|
return opts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newIssueCreateCmd() *cobra.Command {
|
||||||
|
var repo, title, body string
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "create",
|
||||||
|
Short: "File an issue",
|
||||||
|
SilenceUsage: true,
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
owner, name, err := agent.ParseRepo(repo)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if title == "" {
|
||||||
|
return fmt.Errorf("--title is required")
|
||||||
|
}
|
||||||
|
c, err := client()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
issue, err := c.CreateIssue(owner+"/"+name, agent.CreateIssueOptions{
|
||||||
|
Title: title,
|
||||||
|
Body: body,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Printf("#%d %s\n", issue.Number, issue.HTMLURL)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
f := cmd.Flags()
|
||||||
|
f.StringVar(&repo, "repo", "", "Repository as owner/repo (required)")
|
||||||
|
f.StringVar(&title, "title", "", "Issue title (required)")
|
||||||
|
f.StringVar(&body, "body", "", "Issue body")
|
||||||
|
_ = cmd.MarkFlagRequired("repo")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func newIssueEditCmd() *cobra.Command {
|
||||||
|
var repo, title, body string
|
||||||
|
var issue int
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "edit",
|
||||||
|
Short: "Edit an issue'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 issue <= 0 {
|
||||||
|
return fmt.Errorf("--issue must be a positive issue number")
|
||||||
|
}
|
||||||
|
opts, err := editOptions(cmd, title, body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c, err := client()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
updated, err := c.EditIssue(owner+"/"+name, issue, 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(&issue, "issue", 0, "Issue number (required)")
|
||||||
|
f.StringVar(&title, "title", "", "New issue title (unchanged when omitted)")
|
||||||
|
f.StringVar(&body, "body", "", "New issue body (unchanged when omitted)")
|
||||||
|
_ = cmd.MarkFlagRequired("repo")
|
||||||
|
_ = cmd.MarkFlagRequired("issue")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
func newWhoamiCmd() *cobra.Command {
|
func newWhoamiCmd() *cobra.Command {
|
||||||
return &cobra.Command{
|
return &cobra.Command{
|
||||||
Use: "whoami",
|
Use: "whoami",
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A malformed --repo must fail the command (so main exits non-zero). ParseRepo
|
// A malformed --repo must fail the command (so main exits non-zero). ParseRepo
|
||||||
@@ -49,3 +51,101 @@ func TestPREditRejectsEmptyTitle(t *testing.T) {
|
|||||||
t.Errorf("error = %q, want it to reject the empty title", err)
|
t.Errorf("error = %q, want it to reject the empty title", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// execute runs the command tree with args, discarding output, so tests assert
|
||||||
|
// on the error alone. Every case here fails before any Vault/Gitea call.
|
||||||
|
func execute(args ...string) error {
|
||||||
|
cmd := newRootCmd()
|
||||||
|
cmd.SetArgs(args)
|
||||||
|
cmd.SetOut(io.Discard)
|
||||||
|
cmd.SetErr(io.Discard)
|
||||||
|
return cmd.Execute()
|
||||||
|
}
|
||||||
|
|
||||||
|
// An issue needs a title; Gitea rejects an empty one, so the command must too.
|
||||||
|
func TestIssueCreateRequiresTitle(t *testing.T) {
|
||||||
|
err := execute("issue", "create", "--repo", "unkin/repo", "--body", "b")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Execute() = nil, want an error when --title is missing")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "--title is required") {
|
||||||
|
t.Errorf("error = %q, want it to name the missing flag", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --repo is required, and cobra must reject its absence before anything reaches
|
||||||
|
// for a token.
|
||||||
|
func TestIssueCreateRequiresRepo(t *testing.T) {
|
||||||
|
err := execute("issue", "create", "--title", "t")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Execute() = nil, want an error when --repo is missing")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "repo") {
|
||||||
|
t.Errorf("error = %q, want it to name the missing flag", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIssueCreateBadRepoErrors(t *testing.T) {
|
||||||
|
if err := execute("issue", "create", "--repo", "not-a-repo", "--title", "t"); err == nil {
|
||||||
|
t.Fatal("Execute() = nil, want error for a malformed --repo")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// `issue comment` addresses the issue by --issue, not --pr, and needs it.
|
||||||
|
func TestIssueCommentRequiresIssueNumber(t *testing.T) {
|
||||||
|
err := execute("issue", "comment", "--repo", "unkin/repo", "--body", "hi")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Execute() = nil, want an error when --issue is missing")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "issue") {
|
||||||
|
t.Errorf("error = %q, want it to name the missing --issue flag", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIssueEditRequiresTitleOrBody(t *testing.T) {
|
||||||
|
err := execute("issue", "edit", "--repo", "unkin/repo", "--issue", "12")
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIssueEditRejectsEmptyTitle(t *testing.T) {
|
||||||
|
err := execute("issue", "edit", "--repo", "unkin/repo", "--issue", "12", "--title", "")
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PRs and issues share Gitea's comment endpoint, so both comment commands are
|
||||||
|
// built from one constructor: they must stay identical apart from the flag
|
||||||
|
// naming the number.
|
||||||
|
func TestCommentCommandsStayInStep(t *testing.T) {
|
||||||
|
find := func(group string) *cobra.Command {
|
||||||
|
t.Helper()
|
||||||
|
cmd, _, err := newRootCmd().Find([]string{group, "comment"})
|
||||||
|
if err != nil || cmd.Name() != "comment" {
|
||||||
|
t.Fatalf("%s comment not found: %v", group, err)
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
has := func(cmd *cobra.Command, name string) bool { return cmd.Flags().Lookup(name) != nil }
|
||||||
|
|
||||||
|
prCmd, issueCmd := find("pr"), find("issue")
|
||||||
|
for _, name := range []string{"repo", "body"} {
|
||||||
|
if !has(prCmd, name) || !has(issueCmd, name) {
|
||||||
|
t.Errorf("--%s missing: pr=%t issue=%t", name, has(prCmd, name), has(issueCmd, name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !has(prCmd, "pr") || has(prCmd, "issue") {
|
||||||
|
t.Error("pr comment must take --pr and only --pr")
|
||||||
|
}
|
||||||
|
if !has(issueCmd, "issue") || has(issueCmd, "pr") {
|
||||||
|
t.Error("issue comment must take --issue and only --issue")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -104,13 +104,13 @@ func TestEditPRSendsOnlySuppliedFields(t *testing.T) {
|
|||||||
title, body, empty := "new title", "new body", ""
|
title, body, empty := "new title", "new body", ""
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
opts EditPROptions
|
opts EditOptions
|
||||||
want map[string]any
|
want map[string]any
|
||||||
}{
|
}{
|
||||||
{"body only", EditPROptions{Body: &body}, map[string]any{"body": "new body"}},
|
{"body only", EditOptions{Body: &body}, map[string]any{"body": "new body"}},
|
||||||
{"title only", EditPROptions{Title: &title}, map[string]any{"title": "new title"}},
|
{"title only", EditOptions{Title: &title}, map[string]any{"title": "new title"}},
|
||||||
{"both", EditPROptions{Title: &title, Body: &body}, map[string]any{"title": "new title", "body": "new body"}},
|
{"both", EditOptions{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": ""}},
|
{"explicit empty body is sent", EditOptions{Body: &empty}, map[string]any{"body": ""}},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
@@ -163,7 +163,7 @@ func TestEditPRAPIError(t *testing.T) {
|
|||||||
|
|
||||||
title := "new title"
|
title := "new title"
|
||||||
c := &GiteaClient{BaseURL: srv.URL, Token: "t", HTTP: srv.Client()}
|
c := &GiteaClient{BaseURL: srv.URL, Token: "t", HTTP: srv.Client()}
|
||||||
_, err := c.EditPR("unkin/repo", 7, EditPROptions{Title: &title})
|
_, err := c.EditPR("unkin/repo", 7, EditOptions{Title: &title})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("expected error on 404")
|
t.Fatal("expected error on 404")
|
||||||
}
|
}
|
||||||
@@ -618,3 +618,139 @@ func TestAnonymousPollingNeverMints(t *testing.T) {
|
|||||||
t.Errorf("sent %d Authorization headers, want none", authHeaders)
|
t.Errorf("sent %d Authorization headers, want none", authHeaders)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCreateIssueRequestBody(t *testing.T) {
|
||||||
|
var gotPath, gotMethod, gotAuth string
|
||||||
|
var gotBody CreateIssueOptions
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/api/v1/repos/unkin/repo/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotPath, gotMethod = r.URL.Path, r.Method
|
||||||
|
gotAuth = r.Header.Get("Authorization")
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&gotBody)
|
||||||
|
_, _ = io.WriteString(w, `{"number":12,"state":"open","title":"T","html_url":"https://git.unkin.net/unkin/repo/issues/12"}`)
|
||||||
|
})
|
||||||
|
srv := httptest.NewServer(mux)
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := &GiteaClient{BaseURL: srv.URL, Token: "gitea-abc", HTTP: srv.Client()}
|
||||||
|
issue, err := c.CreateIssue("unkin/repo", CreateIssueOptions{Title: "T", Body: "B"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateIssue: %v", err)
|
||||||
|
}
|
||||||
|
if gotMethod != http.MethodPost || gotPath != "/api/v1/repos/unkin/repo/issues" {
|
||||||
|
t.Errorf("request = %s %s, want POST /api/v1/repos/unkin/repo/issues", gotMethod, gotPath)
|
||||||
|
}
|
||||||
|
if gotAuth != "token gitea-abc" {
|
||||||
|
t.Errorf("auth header = %q, want 'token gitea-abc'", gotAuth)
|
||||||
|
}
|
||||||
|
if gotBody.Title != "T" || gotBody.Body != "B" {
|
||||||
|
t.Errorf("request body = %+v", gotBody)
|
||||||
|
}
|
||||||
|
if issue.Number != 12 || issue.HTMLURL != "https://git.unkin.net/unkin/repo/issues/12" {
|
||||||
|
t.Errorf("parsed issue = %+v", issue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filing against a repo that does not exist (or that the token may not see)
|
||||||
|
// gets Gitea's 404, which must surface as a not-found error carrying the API's
|
||||||
|
// own message rather than a bare status.
|
||||||
|
func TestCreateIssueRepoNotFound(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
_, _ = io.WriteString(w, `{"errors":null,"message":"user redirect does not exist [name: ghost]","url":"https://git.unkin.net/api/swagger"}`)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := &GiteaClient{BaseURL: srv.URL, Token: "t", HTTP: srv.Client()}
|
||||||
|
_, err := c.CreateIssue("ghost/repo", CreateIssueOptions{Title: "T"})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for a repo that does not exist")
|
||||||
|
}
|
||||||
|
if !IsNotFound(err) {
|
||||||
|
t.Errorf("IsNotFound(%v) = false, want true", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "user redirect does not exist") {
|
||||||
|
t.Errorf("error %q should carry the API message", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Any other non-2xx is a plain API failure: reported, not retried, and not
|
||||||
|
// mistaken for a missing repo.
|
||||||
|
func TestCreateIssueAPIError(t *testing.T) {
|
||||||
|
requests := 0
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/api/v1/repos/unkin/repo/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requests++
|
||||||
|
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||||
|
_, _ = io.WriteString(w, `{"errors":null,"message":"Validation Error: title is empty","url":"https://git.unkin.net/api/swagger"}`)
|
||||||
|
})
|
||||||
|
srv := httptest.NewServer(mux)
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := &GiteaClient{BaseURL: srv.URL, Token: "t", HTTP: srv.Client()}
|
||||||
|
_, err := c.CreateIssue("unkin/repo", CreateIssueOptions{Title: "T"})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error on 422")
|
||||||
|
}
|
||||||
|
if IsNotFound(err) {
|
||||||
|
t.Errorf("a 422 must not read as not-found: %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "Validation Error") {
|
||||||
|
t.Errorf("error %q should carry the API message", err)
|
||||||
|
}
|
||||||
|
if requests != 1 {
|
||||||
|
t.Errorf("requests = %d, want 1 (a 422 is not retried)", requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// An issue edit sends only the fields it was given, for the same reason a PR
|
||||||
|
// edit does: Gitea overwrites whatever key it receives.
|
||||||
|
func TestEditIssueSendsOnlySuppliedFields(t *testing.T) {
|
||||||
|
title, body := "new title", "new body"
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
opts EditOptions
|
||||||
|
want map[string]any
|
||||||
|
}{
|
||||||
|
{"body only", EditOptions{Body: &body}, map[string]any{"body": "new body"}},
|
||||||
|
{"title only", EditOptions{Title: &title}, map[string]any{"title": "new title"}},
|
||||||
|
{"both", EditOptions{Title: &title, Body: &body}, map[string]any{"title": "new title", "body": "new 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/issues/12", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotMethod, gotPath = r.Method, r.URL.Path
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&gotBody)
|
||||||
|
_, _ = io.WriteString(w, `{"number":12,"title":"new title","html_url":"https://git.unkin.net/unkin/repo/issues/12"}`)
|
||||||
|
})
|
||||||
|
srv := httptest.NewServer(mux)
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := &GiteaClient{BaseURL: srv.URL, Token: "t", HTTP: srv.Client()}
|
||||||
|
issue, err := c.EditIssue("unkin/repo", 12, tt.opts)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("EditIssue: %v", err)
|
||||||
|
}
|
||||||
|
if gotMethod != http.MethodPatch {
|
||||||
|
t.Errorf("method = %s, want PATCH", gotMethod)
|
||||||
|
}
|
||||||
|
if gotPath != "/api/v1/repos/unkin/repo/issues/12" {
|
||||||
|
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 issue.Number != 12 || issue.HTMLURL == "" {
|
||||||
|
t.Errorf("parsed issue = %+v", issue)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+42
-9
@@ -214,19 +214,20 @@ func (c *GiteaClient) CreatePR(repoPath string, opts CreatePROptions) (PullReque
|
|||||||
return pr, err
|
return pr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// EditPROptions are the fields an edit may change. Pointers so an unset field
|
// EditOptions are the fields an edit may change, for a pull request or an
|
||||||
// is omitted from the payload entirely, leaving that field as it is. The two
|
// issue alike. Pointers so an unset field is omitted from the payload
|
||||||
// fields are not symmetric: Gitea only applies a title when it is non-empty,
|
// entirely, leaving that field as it is. The two fields are not symmetric:
|
||||||
// so Title can be set but never cleared and a "" title is a silent no-op,
|
// Gitea only applies a title when it is non-empty, so Title can be set but
|
||||||
// while a pointer to "" Body really does blank the body.
|
// never cleared and a "" title is a silent no-op, while a pointer to "" Body
|
||||||
type EditPROptions struct {
|
// really does blank the body.
|
||||||
|
type EditOptions struct {
|
||||||
Title *string `json:"title,omitempty"`
|
Title *string `json:"title,omitempty"`
|
||||||
Body *string `json:"body,omitempty"`
|
Body *string `json:"body,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// EditPR updates a pull request's title and/or body
|
// EditPR updates a pull request's title and/or body
|
||||||
// (PATCH /api/v1/repos/{owner}/{repo}/pulls/{index}).
|
// (PATCH /api/v1/repos/{owner}/{repo}/pulls/{index}).
|
||||||
func (c *GiteaClient) EditPR(repoPath string, number int, opts EditPROptions) (PullRequest, error) {
|
func (c *GiteaClient) EditPR(repoPath string, number int, opts EditOptions) (PullRequest, error) {
|
||||||
var pr PullRequest
|
var pr PullRequest
|
||||||
err := c.do(http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/pulls/%d", repoPath, number), opts, &pr)
|
err := c.do(http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/pulls/%d", repoPath, number), opts, &pr)
|
||||||
return pr, err
|
return pr, err
|
||||||
@@ -239,6 +240,36 @@ func (c *GiteaClient) GetPR(repoPath string, number int) (PullRequest, error) {
|
|||||||
return pr, err
|
return pr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Issue is the subset of Gitea's issue object we track. Gitea numbers issues
|
||||||
|
// and pull requests in one sequence, so Number is comparable to a PR number.
|
||||||
|
type Issue struct {
|
||||||
|
Number int `json:"number"`
|
||||||
|
State string `json:"state"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
HTMLURL string `json:"html_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateIssueOptions are the fields for filing an issue.
|
||||||
|
type CreateIssueOptions struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateIssue files an issue (POST /api/v1/repos/{owner}/{repo}/issues).
|
||||||
|
func (c *GiteaClient) CreateIssue(repoPath string, opts CreateIssueOptions) (Issue, error) {
|
||||||
|
var issue Issue
|
||||||
|
err := c.do(http.MethodPost, "/api/v1/repos/"+repoPath+"/issues", opts, &issue)
|
||||||
|
return issue, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// EditIssue updates an issue's title and/or body
|
||||||
|
// (PATCH /api/v1/repos/{owner}/{repo}/issues/{index}).
|
||||||
|
func (c *GiteaClient) EditIssue(repoPath string, number int, opts EditOptions) (Issue, error) {
|
||||||
|
var issue Issue
|
||||||
|
err := c.do(http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/issues/%d", repoPath, number), opts, &issue)
|
||||||
|
return issue, err
|
||||||
|
}
|
||||||
|
|
||||||
// Comment is the subset of an issue comment we track.
|
// Comment is the subset of an issue comment we track.
|
||||||
type Comment struct {
|
type Comment struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
@@ -246,8 +277,10 @@ type Comment struct {
|
|||||||
Body string `json:"body"`
|
Body string `json:"body"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateComment posts a comment on the PR's issue thread
|
// CreateComment posts a comment on an issue thread
|
||||||
// (POST /api/v1/repos/{owner}/{repo}/issues/{n}/comments).
|
// (POST /api/v1/repos/{owner}/{repo}/issues/{n}/comments). Gitea backs a pull
|
||||||
|
// request with an issue of the same number, so this is the single path for
|
||||||
|
// both.
|
||||||
func (c *GiteaClient) CreateComment(repoPath string, number int, body string) (Comment, error) {
|
func (c *GiteaClient) CreateComment(repoPath string, number int, body string) (Comment, error) {
|
||||||
var cm Comment
|
var cm Comment
|
||||||
payload := map[string]string{"body": body}
|
payload := map[string]string{"body": body}
|
||||||
|
|||||||
Reference in New Issue
Block a user