Add agentpr and watchpr CLI tools
agentpr manages PRs/comments/whoami as unkin-agent (Vault AppRole -> gitea creds -> Gitea API), fixing tea's post-as-Ben default. watchpr polls PRs and alerts only on merge/close, human comment, CI failure, or lost mergeability. - cobra multi-binary layout mirroring node-lookup (cmd/ + internal/) - Makefile (build, patch|minor|major, completions, rpm), nfpm RPM with both binaries + bash/zsh/fish completions, woodpecker CI publishing to rpm-internal - unit tests for parsing, meaningful-change detection, and the Vault+Gitea client
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
// Command agentpr manages Gitea pull requests and comments as the unkin-agent
|
||||
// user. It obtains a scoped Gitea token from Vault (AppRole login, then reads
|
||||
// gitea/creds/unkin-agent) so actions are attributed to the agent rather than
|
||||
// to whoever runs the tool.
|
||||
//
|
||||
// agentpr pr create --repo owner/repo --base main --head feature --title T --body B
|
||||
// agentpr pr comment --repo owner/repo --pr 12 --body "..."
|
||||
// agentpr whoami
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.unkin.net/unkin/agent-tools/internal/agent"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
root := &cobra.Command{
|
||||
Use: "agentpr",
|
||||
Short: "Manage Gitea PRs and comments as the unkin-agent user.",
|
||||
Long: "agentpr manages Gitea pull requests and comments as unkin-agent, using a\nGitea token minted from Vault (AppRole login + gitea/creds/unkin-agent).",
|
||||
Version: version,
|
||||
SilenceUsage: true,
|
||||
}
|
||||
root.SetVersionTemplate("{{.Version}}\n")
|
||||
|
||||
root.AddCommand(newPRCmd(), newWhoamiCmd(), newVersionCmd())
|
||||
|
||||
if err := root.Execute(); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// client mints a Gitea token via Vault and returns a ready client.
|
||||
func client() (*agent.GiteaClient, error) {
|
||||
token, err := agent.GiteaToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return agent.NewGiteaClient(token), nil
|
||||
}
|
||||
|
||||
func newPRCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "pr",
|
||||
Short: "Create PRs and post PR comments",
|
||||
}
|
||||
cmd.AddCommand(newPRCreateCmd(), newPRCommentCmd())
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newPRCreateCmd() *cobra.Command {
|
||||
var repo, base, head, title, body string
|
||||
cmd := &cobra.Command{
|
||||
Use: "create",
|
||||
Short: "Open a pull request",
|
||||
SilenceUsage: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
owner, name, err := agent.ParseRepo(repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if base == "" || head == "" || title == "" {
|
||||
return fmt.Errorf("--base, --head and --title are required")
|
||||
}
|
||||
c, err := client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pr, err := c.CreatePR(owner+"/"+name, agent.CreatePROptions{
|
||||
Base: base,
|
||||
Head: head,
|
||||
Title: title,
|
||||
Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("#%d %s\n", pr.Number, pr.HTMLURL)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
f := cmd.Flags()
|
||||
f.StringVar(&repo, "repo", "", "Repository as owner/repo (required)")
|
||||
f.StringVar(&base, "base", "", "Base branch (required)")
|
||||
f.StringVar(&head, "head", "", "Head branch (required)")
|
||||
f.StringVar(&title, "title", "", "PR title (required)")
|
||||
f.StringVar(&body, "body", "", "PR body")
|
||||
_ = cmd.MarkFlagRequired("repo")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newPRCommentCmd() *cobra.Command {
|
||||
var repo, body string
|
||||
var pr int
|
||||
cmd := &cobra.Command{
|
||||
Use: "comment",
|
||||
Short: "Post a comment on a pull request",
|
||||
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")
|
||||
}
|
||||
if body == "" {
|
||||
return fmt.Errorf("--body is required")
|
||||
}
|
||||
c, err := client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cm, err := c.CreateComment(owner+"/"+name, pr, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("comment %d posted on %s/%s#%d\n", cm.ID, owner, name, pr)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
f := cmd.Flags()
|
||||
f.StringVar(&repo, "repo", "", "Repository as owner/repo (required)")
|
||||
f.IntVar(&pr, "pr", 0, "PR number (required)")
|
||||
f.StringVar(&body, "body", "", "Comment body (required)")
|
||||
_ = cmd.MarkFlagRequired("repo")
|
||||
_ = cmd.MarkFlagRequired("pr")
|
||||
_ = cmd.MarkFlagRequired("body")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newWhoamiCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "whoami",
|
||||
Short: "Print the authenticated Gitea login (should be unkin-agent)",
|
||||
SilenceUsage: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
c, err := client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u, err := c.Whoami()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(u.Login)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newVersionCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version",
|
||||
Run: func(cmd *cobra.Command, args []string) { fmt.Println(version) },
|
||||
SilenceUsage: true,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// Command watchpr polls one or more Gitea pull requests and exits when a
|
||||
// tracked PR changes in a way worth alerting on: it merges or closes, gets a
|
||||
// new comment from someone other than the agent, its CI fails, or it loses
|
||||
// mergeability. Benign transitions (CI pending→success, the agent's own
|
||||
// comments) are ignored.
|
||||
//
|
||||
// watchpr owner/repo#12 owner/repo:15
|
||||
// watchpr --once --json owner/repo#12
|
||||
// watchpr --interval 30s owner/repo#12
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"git.unkin.net/unkin/agent-tools/internal/agent"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
func main() {
|
||||
var interval time.Duration
|
||||
var once, jsonMode bool
|
||||
|
||||
root := &cobra.Command{
|
||||
Use: "watchpr [flags] owner/repo#N [owner/repo#N ...]",
|
||||
Short: "Poll Gitea PRs and exit when one changes meaningfully.",
|
||||
Long: "watchpr polls each PR every --interval and exits (reporting what changed)\n" +
|
||||
"when a PR merges/closes, gets a new non-agent comment, its CI fails, or it\n" +
|
||||
"loses mergeability. Accepts refs as owner/repo#N or owner/repo:N.",
|
||||
Version: version,
|
||||
Args: cobra.ArbitraryArgs,
|
||||
SilenceUsage: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("no PR references given (e.g. owner/repo#12)")
|
||||
}
|
||||
refs := make([]agent.PRRef, 0, len(args))
|
||||
for _, a := range args {
|
||||
ref, err := agent.ParsePRRef(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
refs = append(refs, ref)
|
||||
}
|
||||
c, err := clientFor()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if once {
|
||||
return runOnce(c, refs, jsonMode)
|
||||
}
|
||||
return runWatch(c, refs, interval, jsonMode)
|
||||
},
|
||||
}
|
||||
root.SetVersionTemplate("{{.Version}}\n")
|
||||
|
||||
f := root.Flags()
|
||||
f.DurationVar(&interval, "interval", 60*time.Second, "Polling interval")
|
||||
f.BoolVar(&once, "once", false, "Check once, print current state, and exit")
|
||||
f.BoolVar(&jsonMode, "json", false, "Emit JSON")
|
||||
|
||||
root.AddCommand(&cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version",
|
||||
Run: func(cmd *cobra.Command, args []string) { fmt.Println(version) },
|
||||
SilenceUsage: true,
|
||||
})
|
||||
|
||||
if err := root.Execute(); err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func clientFor() (*agent.GiteaClient, error) {
|
||||
token, err := agent.GiteaToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return agent.NewGiteaClient(token), nil
|
||||
}
|
||||
|
||||
// runOnce fetches and prints the current state of each PR, then exits 0.
|
||||
func runOnce(c *agent.GiteaClient, refs []agent.PRRef, jsonMode bool) error {
|
||||
login := agent.AgentLogin()
|
||||
states := make([]agent.PRState, 0, len(refs))
|
||||
for _, ref := range refs {
|
||||
st, err := agent.FetchState(c, ref, login)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
states = append(states, st)
|
||||
}
|
||||
if jsonMode {
|
||||
return json.NewEncoder(os.Stdout).Encode(states)
|
||||
}
|
||||
for _, st := range states {
|
||||
printState(st)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// runWatch establishes a baseline then polls until a tracked PR changes
|
||||
// meaningfully, at which point it reports the change and returns.
|
||||
func runWatch(c *agent.GiteaClient, refs []agent.PRRef, interval time.Duration, jsonMode bool) error {
|
||||
login := agent.AgentLogin()
|
||||
|
||||
prev := make(map[string]agent.PRState, len(refs))
|
||||
for _, ref := range refs {
|
||||
st, err := agent.FetchState(c, ref, login)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prev[ref.String()] = st
|
||||
}
|
||||
if !jsonMode {
|
||||
fmt.Fprintf(os.Stderr, "watching %d PR(s) every %s; baseline established\n", len(refs), interval)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
for _, ref := range refs {
|
||||
key := ref.String()
|
||||
cur, err := agent.FetchState(c, ref, login)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "warning: polling %s: %v\n", key, err)
|
||||
continue
|
||||
}
|
||||
changed, reason := agent.MeaningfulChange(prev[key], cur)
|
||||
if changed {
|
||||
report(key, reason, cur, jsonMode)
|
||||
return nil
|
||||
}
|
||||
prev[key] = cur
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// report emits the change that ended the watch.
|
||||
func report(key, reason string, st agent.PRState, jsonMode bool) {
|
||||
if jsonMode {
|
||||
_ = json.NewEncoder(os.Stdout).Encode(struct {
|
||||
Changed bool `json:"changed"`
|
||||
Reason string `json:"reason"`
|
||||
State agent.PRState `json:"state"`
|
||||
}{true, reason, st})
|
||||
return
|
||||
}
|
||||
fmt.Printf("%s changed: %s\n", key, reason)
|
||||
printState(st)
|
||||
}
|
||||
|
||||
func printState(st agent.PRState) {
|
||||
fmt.Printf("%s state=%s merged=%t mergeable=%t ci=%s head=%s comments(non-agent)=%d\n",
|
||||
st.Ref.String(), st.State, st.Merged, st.Mergeable, ciOrNone(st.CIStatus), shortSHA(st.HeadSHA), st.NonAgentComments)
|
||||
}
|
||||
|
||||
func ciOrNone(s string) string {
|
||||
if s == "" {
|
||||
return "none"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func shortSHA(s string) string {
|
||||
if len(s) > 8 {
|
||||
return s[:8]
|
||||
}
|
||||
if s == "" {
|
||||
return "-"
|
||||
}
|
||||
return s
|
||||
}
|
||||
Reference in New Issue
Block a user