| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 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 | |
| 17 | var 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 flow dashboard and |
| 21 | valley flow status for monitoring. |
| 22 | |
| 23 | A PR is named by its number, its full GitHub PR URL, or owner/repo#number. |
| 24 | Use --repo to specify the repository when using bare PR numbers. |
| 25 | |
| 26 | A valley change is named by its handle (vpkz), its full change ID, or |
| 27 | <project>:<handle>. flow asks the valley about the project's local checkout |
| 28 | (valley changes --json, run there) and records the change; the dashboard |
| 29 | then shows it as a change row and valley flow status as a run, both standing where |
| 30 | the valley's listing says its active version does, as for a change an agent |
| 31 | pushed. The project is the one before the colon, else --repo, else the |
| 32 | session target, else the repo of the current directory: a registered project |
| 33 | name, owner/repo or URL with a checkout on this machine. A change already on |
| 34 | the dashboard, tracked or pushed by a run, isn't added again. |
| 35 | |
| 36 | Examples: |
| 37 | valley flow track 405 # uses session target repo |
| 38 | valley flow track 405 --repo site # explicit repo |
| 39 | valley flow track https://github.com/org/repo/pull/405 |
| 40 | valley flow track 405 406 407 # multiple PRs |
| 41 | valley flow track --repo the-valley vpkz # a valley change, by handle |
| 42 | valley flow track the-valley:vpkz # the same change |
| 43 | valley flow 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. |
| 95 | var 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") |
| 102 | func 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. |
| 133 | func 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. |
| 149 | func 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, err := registryUnlessConflict() |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | normalizedRepo := project.NormalizeRepoName(repo, reg) |
| 188 | |
| 189 | id, err := run.GenID() |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | |
| 194 | st := &run.State{ |
| 195 | ID: id, |
| 196 | Prompt: title, |
| 197 | Branch: headBranch, |
| 198 | PRURL: &prURL, |
| 199 | Type: "track", |
| 200 | TargetRepo: &normalizedRepo, |
| 201 | CreatedAt: time.Now().Format(time.RFC3339), |
| 202 | } |
| 203 | |
| 204 | if err := store.Save(st); err != nil { |
| 205 | return fmt.Errorf("saving state: %w", err) |
| 206 | } |
| 207 | |
| 208 | fmt.Printf("Tracking PR #%s (%s) — %s\n", prNumber, normalizedRepo, title) |
| 209 | return nil |
| 210 | } |
| 211 | |
| 212 | // fetchPRMetadata fetches PR URL, title, head branch, and state from GitHub via the Client interface. |
| 213 | func fetchPRMetadata(prNumber, repo string) (prURL, title, headBranch, state string, err error) { |
| 214 | client := github.NewGHCLIClient("") |
| 215 | return client.FetchPRMetadata(context.TODO(), prNumber, repo) |
| 216 | } |
| 217 | |
| 218 | func init() { |
| 219 | trackCmd.Flags().String("repo", "", "Repo of a bare PR number, or project of a valley change: registered project name, owner/repo, or full URL") |
| 220 | rootCmd.AddCommand(trackCmd) |
| 221 | } |