gunk-dev/the-valley

track.go

source60ad80d5a5a5main's published tip history
6.6 KiB
1package cmd
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "regexp"
8 "strings"
9 "time"
10
11 "the-valley/flow/internal/github"
12 "the-valley/flow/internal/project"
13 "the-valley/flow/internal/run"
14 "github.com/spf13/cobra"
15)
16
17var trackCmd = &cobra.Command{
18 Use: "track <ref> [<ref>...]",
19 Short: "Track existing PRs or valley changes on the dashboard",
20 Long: `Adds existing GitHub PRs or valley changes to the klaus dashboard and
21klaus status for monitoring.
22
23A PR is named by its number, its full GitHub PR URL, or owner/repo#number.
24Use --repo to specify the repository when using bare PR numbers.
25
26A valley change is named by its handle (vpkz), its full change ID, or
27<project>:<handle>. klaus asks the valley about the project's local checkout
28(valley changes --json, run there) and records the change; the dashboard
29then shows it as a change row and klaus status as a run, both standing where
30the valley's listing says its active version does, as for a change an agent
31pushed. The project is the one before the colon, else --repo, else the
32session target, else the repo of the current directory: a registered project
33name, owner/repo or URL with a checkout on this machine. A change already on
34the dashboard, tracked or pushed by a run, isn't added again.
35
36Examples:
37 klaus track 405 # uses session target repo
38 klaus track 405 --repo site # explicit repo
39 klaus track https://github.com/org/repo/pull/405
40 klaus track 405 406 407 # multiple PRs
41 klaus track --repo the-valley vpkz # a valley change, by handle
42 klaus track the-valley:vpkz # the same change
43 klaus track --repo the-valley vpkzrpxvokultrxwoomvtwqvqqxuxvyw # by change ID`,
44 Args: cobra.MinimumNArgs(1),
45 RunE: func(cmd *cobra.Command, args []string) error {
46 repoFlag, _ := cmd.Flags().GetString("repo")
47
48 store, err := sessionStore()
49 if err != nil {
50 return err
51 }
52 if err := store.EnsureDirs(); err != nil {
53 return err
54 }
55
56 // Load existing states to check for duplicates
57 existingStates, err := store.List()
58 if err != nil {
59 return err
60 }
61
62 // Resolve repo context for bare PR numbers and change handles
63 resolvedRepo := resolveTrackRepo(repoFlag)
64
65 listings := make(valleyListings)
66 for _, ref := range args {
67 if _, _, err := parsePRRef(ref); err == nil {
68 err = trackPR(ref, resolvedRepo, store, existingStates)
69 if err != nil {
70 fmt.Fprintf(os.Stderr, "warning: %s: %v\n", ref, err)
71 }
72 continue
73 }
74 project, id, ok := parseChangeRef(ref)
75 if !ok {
76 fmt.Fprintf(os.Stderr, "warning: %s: not a PR (number, URL or owner/repo#number) or a valley change (handle, change ID or <project>:<handle>)\n", ref)
77 continue
78 }
79 if project == "" {
80 project = resolvedRepo
81 }
82 st, err := trackChange(cmd.Context(), project, id, store, existingStates, listings)
83 if err != nil {
84 fmt.Fprintf(os.Stderr, "warning: %s: %v\n", ref, err)
85 }
86 if st != nil {
87 existingStates = append(existingStates, st)
88 }
89 }
90 return nil
91 },
92}
93
94// ownerRepoPRPattern matches owner/repo#number references.
95var ownerRepoPRPattern = regexp.MustCompile(`^([^/]+/[^#]+)#(\d+)$`)
96
97// parsePRRef parses a PR reference into (repo, prNumber) where repo may be empty.
98// Supported formats:
99// - "405" → ("", "405")
100// - "https://github.com/org/repo/pull/405" → ("org/repo", "405")
101// - "owner/repo#405" → ("owner/repo", "405")
102func parsePRRef(ref string) (repo, prNumber string, err error) {
103 // Full GitHub URL
104 if strings.HasPrefix(ref, "https://github.com/") {
105 // https://github.com/owner/repo/pull/123
106 trimmed := strings.TrimPrefix(ref, "https://github.com/")
107 parts := strings.Split(trimmed, "/")
108 if len(parts) >= 4 && parts[2] == "pull" {
109 return parts[0] + "/" + parts[1], parts[3], nil
110 }
111 return "", "", fmt.Errorf("invalid GitHub PR URL: %s", ref)
112 }
113
114 // owner/repo#number
115 if m := ownerRepoPRPattern.FindStringSubmatch(ref); m != nil {
116 return m[1], m[2], nil
117 }
118
119 // Bare number
120 for _, c := range ref {
121 if c < '0' || c > '9' {
122 return "", "", fmt.Errorf("invalid PR reference: %s", ref)
123 }
124 }
125 if ref == "" {
126 return "", "", fmt.Errorf("empty PR reference")
127 }
128 return "", ref, nil
129}
130
131// resolveTrackRepo determines which repo to use for bare PR numbers and
132// change handles. Priority: --repo flag > session target.
133func resolveTrackRepo(repoFlag string) string {
134 if repoFlag != "" {
135 return repoFlag
136 }
137 // Try session target
138 if s, storeErr := sessionStore(); storeErr == nil {
139 if hds, ok := s.(*run.HomeDirStore); ok {
140 if target, loadErr := run.LoadTarget(hds.BaseDir()); loadErr == nil && target != "" {
141 return target
142 }
143 }
144 }
145 return ""
146}
147
148// trackPR tracks a single PR reference.
149func trackPR(ref, defaultRepo string, store run.StateStore, existingStates []*run.State) error {
150 repo, prNumber, err := parsePRRef(ref)
151 if err != nil {
152 return err
153 }
154
155 // If no repo from the reference, use the default
156 if repo == "" {
157 repo = defaultRepo
158 }
159 if repo == "" {
160 return fmt.Errorf("no repo specified for PR #%s — use --repo or set a session target", prNumber)
161 }
162
163 // Fetch PR metadata from GitHub
164 prURL, title, headBranch, state, err := fetchPRMetadata(prNumber, repo)
165 if err != nil {
166 return fmt.Errorf("fetching PR #%s metadata: %w", prNumber, err)
167 }
168
169 // Check for duplicates
170 for _, s := range existingStates {
171 if s.PRURL != nil && *s.PRURL == prURL {
172 fmt.Printf("Already tracking PR #%s (%s)\n", prNumber, repo)
173 return nil
174 }
175 }
176
177 // Warn if PR is closed/merged
178 if strings.EqualFold(state, "MERGED") || strings.EqualFold(state, "CLOSED") {
179 fmt.Fprintf(os.Stderr, "warning: PR #%s is %s\n", prNumber, strings.ToLower(state))
180 }
181
182 // Normalize repo name
183 reg, _ := project.Load()
184 normalizedRepo := project.NormalizeRepoName(repo, reg)
185
186 id, err := run.GenID()
187 if err != nil {
188 return err
189 }
190
191 st := &run.State{
192 ID: id,
193 Prompt: title,
194 Branch: headBranch,
195 PRURL: &prURL,
196 Type: "track",
197 TargetRepo: &normalizedRepo,
198 CreatedAt: time.Now().Format(time.RFC3339),
199 }
200
201 if err := store.Save(st); err != nil {
202 return fmt.Errorf("saving state: %w", err)
203 }
204
205 fmt.Printf("Tracking PR #%s (%s) — %s\n", prNumber, normalizedRepo, title)
206 return nil
207}
208
209// fetchPRMetadata fetches PR URL, title, head branch, and state from GitHub via the Client interface.
210func fetchPRMetadata(prNumber, repo string) (prURL, title, headBranch, state string, err error) {
211 client := github.NewGHCLIClient("")
212 return client.FetchPRMetadata(context.TODO(), prNumber, repo)
213}
214
215func init() {
216 trackCmd.Flags().String("repo", "", "Repo of a bare PR number, or project of a valley change: registered project name, owner/repo, or full URL")
217 rootCmd.AddCommand(trackCmd)
218}