gunk-dev/the-valley

project.go

sourcec14b0e68e9c3main's published tip history
11.5 KiB
1package cmd
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10
11 "the-valley/flow/internal/git"
12 "the-valley/flow/internal/project"
13 "github.com/spf13/cobra"
14)
15
16var projectCmd = &cobra.Command{
17 Use: "project",
18 Short: "Manage the project registry",
19 Long: `Register, list, and remove projects from the flow project registry.
20
21The registry maps project names to local paths and is stored in ~/.klaus/projects.json.
22
23 valley flow project add owner/repo Clone and register a project
24 valley flow project add owner/repo --path . Register with explicit local path
25 valley flow project add owner/repo -d "what it does" Register with a description
26 valley flow project list Show registered projects
27 valley flow project remove <name> Unregister a project
28 valley flow project describe <name> <desc> Set a one-line description (empty to clear)
29 valley flow project set-dir ~/hack Set the default projects directory`,
30}
31
32var projectAddCmd = &cobra.Command{
33 Use: "add <owner/repo | name>",
34 Short: "Clone and register a project",
35 Long: `Register a project in the flow project registry.
36
37With owner/repo format, clones the repo into the projects directory and registers it.
38With just a name, searches your GitHub repos for a match.
39
40If --path is provided, registers the project at that path (must be an existing git repo).
41If the repo is already cloned at the expected path, it is registered without re-cloning.
42
43If --description is provided, it is stored as the project's one-line description.
44When --description is omitted, flow tries 'gh repo view --json description' to fetch
45the GitHub description automatically; if that fails or returns empty, no description
46is stored (you can set one later with 'valley flow project describe').`,
47 Args: cobra.ExactArgs(1),
48 RunE: runProjectAdd,
49}
50
51var projectListCmd = &cobra.Command{
52 Use: "list",
53 Short: "Show registered projects",
54 Args: cobra.NoArgs,
55 RunE: runProjectList,
56}
57
58var projectRemoveCmd = &cobra.Command{
59 Use: "remove <name>",
60 Short: "Unregister a project (does not delete the local clone)",
61 Args: cobra.ExactArgs(1),
62 RunE: runProjectRemove,
63}
64
65var projectSetDirCmd = &cobra.Command{
66 Use: "set-dir <path>",
67 Short: "Set the default projects directory",
68 Args: cobra.ExactArgs(1),
69 RunE: runProjectSetDir,
70}
71
72var projectDescribeCmd = &cobra.Command{
73 Use: "describe <name> <description>",
74 Short: "Set a one-line description for a registered project (empty string clears it)",
75 Long: `Set a freeform one-line description for a registered project.
76
77The description is shown in 'valley flow project list' and included in the session
78coordinator's system prompt so the coordinator knows what each project is for.
79
80Pass an empty string to clear an existing description:
81
82 valley flow project describe my-tool "CLI for managing X"
83 valley flow project describe my-tool ""`,
84 Args: cobra.ExactArgs(2),
85 RunE: runProjectDescribe,
86}
87
88func runProjectAdd(cmd *cobra.Command, args []string) error {
89 ref := args[0]
90 explicitPath, _ := cmd.Flags().GetString("path")
91 description, _ := cmd.Flags().GetString("description")
92
93 reg, err := project.Load()
94 if err != nil {
95 return err
96 }
97
98 deps := getProjectDeps()
99 var owner, repoName, cloneURL string
100
101 if strings.Contains(ref, "/") {
102 // owner/repo format
103 parts := strings.SplitN(ref, "/", 2)
104 owner = parts[0]
105 repoName = parts[1]
106 cloneURL = git.CloneURL(owner, repoName)
107 } else {
108 // Bare name — search GitHub repos
109 repoName = ref
110 ghOwner, ghURL, err := deps.ResolveGitHubRepo(ref)
111 if err != nil {
112 return err
113 }
114 owner = ghOwner
115 cloneURL = ghURL
116 }
117
118 // If the user didn't supply --description, try to pull one from GitHub.
119 // Best-effort: any error or empty result leaves description blank.
120 if description == "" && owner != "" && repoName != "" {
121 description = deps.FetchDescription(owner + "/" + repoName)
122 }
123
124 if explicitPath != "" {
125 // Register with explicit path
126 expanded, err := project.ExpandHome(explicitPath)
127 if err != nil {
128 return err
129 }
130 absPath, err := filepath.Abs(expanded)
131 if err != nil {
132 return fmt.Errorf("resolving path: %w", err)
133 }
134
135 if !isGitRepo(absPath) {
136 return fmt.Errorf("%s is not a git repository", absPath)
137 }
138
139 if err := reg.Add(repoName, absPath); err != nil {
140 return err
141 }
142 if description != "" {
143 if err := reg.Describe(repoName, description); err != nil {
144 return err
145 }
146 }
147 if err := reg.Save(); err != nil {
148 return err
149 }
150 printRegistered(cmd, repoName, absPath, description)
151 return nil
152 }
153
154 // Clone to projects_dir/<repo-name>
155 projDir, err := reg.ExpandedProjectsDir()
156 if err != nil {
157 return err
158 }
159 targetDir := filepath.Join(projDir, repoName)
160
161 if isGitRepo(targetDir) {
162 fmt.Fprintf(cmd.OutOrStdout(), "Already cloned at %s\n", targetDir)
163 } else {
164 fmt.Fprintf(cmd.OutOrStdout(), "Cloning %s/%s into %s...\n", owner, repoName, targetDir)
165 if err := deps.GitClone(cloneURL, targetDir); err != nil {
166 return fmt.Errorf("cloning: %w", err)
167 }
168 }
169
170 if err := reg.Add(repoName, targetDir); err != nil {
171 return err
172 }
173 if description != "" {
174 if err := reg.Describe(repoName, description); err != nil {
175 return err
176 }
177 }
178 if err := reg.Save(); err != nil {
179 return err
180 }
181 printRegistered(cmd, repoName, targetDir, description)
182 return nil
183}
184
185func printRegistered(cmd *cobra.Command, name, path, description string) {
186 if description != "" {
187 fmt.Fprintf(cmd.OutOrStdout(), "Registered %s → %s — %s\n", name, path, description)
188 return
189 }
190 fmt.Fprintf(cmd.OutOrStdout(), "Registered %s → %s\n", name, path)
191}
192
193func runProjectList(cmd *cobra.Command, _ []string) error {
194 reg, err := project.Load()
195 if err != nil {
196 return err
197 }
198
199 projects := reg.List()
200 if len(projects) == 0 {
201 fmt.Fprintln(cmd.OutOrStdout(), "No projects registered. Use 'valley flow project add' to register one.")
202 return nil
203 }
204
205 for name, localPath := range projects {
206 remote := gitRemoteURL(localPath)
207 desc := reg.Description(name)
208 line := fmt.Sprintf("%-20s %s", name, localPath)
209 if remote != "" {
210 line += fmt.Sprintf(" (%s)", remote)
211 }
212 if desc != "" {
213 line += " — " + desc
214 }
215 fmt.Fprintln(cmd.OutOrStdout(), line)
216 }
217 return nil
218}
219
220func runProjectDescribe(cmd *cobra.Command, args []string) error {
221 name := args[0]
222 description := args[1]
223
224 reg, err := project.Load()
225 if err != nil {
226 return err
227 }
228
229 if err := reg.Describe(name, description); err != nil {
230 return err
231 }
232 if err := reg.Save(); err != nil {
233 return err
234 }
235
236 if description == "" {
237 fmt.Fprintf(cmd.OutOrStdout(), "Cleared description for %s\n", name)
238 } else {
239 fmt.Fprintf(cmd.OutOrStdout(), "Set description for %s: %s\n", name, description)
240 }
241 return nil
242}
243
244func runProjectRemove(cmd *cobra.Command, args []string) error {
245 name := args[0]
246
247 reg, err := project.Load()
248 if err != nil {
249 return err
250 }
251
252 if err := reg.Remove(name); err != nil {
253 return err
254 }
255 if err := reg.Save(); err != nil {
256 return err
257 }
258 fmt.Fprintf(cmd.OutOrStdout(), "Removed %s from registry (local clone was not deleted)\n", name)
259 return nil
260}
261
262func runProjectSetDir(cmd *cobra.Command, args []string) error {
263 dir := args[0]
264
265 expanded, err := project.ExpandHome(dir)
266 if err != nil {
267 return err
268 }
269 absDir, err := filepath.Abs(expanded)
270 if err != nil {
271 return fmt.Errorf("resolving path: %w", err)
272 }
273
274 reg, err := project.Load()
275 if err != nil {
276 return err
277 }
278
279 reg.SetProjectsDir(absDir)
280 if err := reg.Save(); err != nil {
281 return err
282 }
283 fmt.Fprintf(cmd.OutOrStdout(), "Projects directory set to %s\n", absDir)
284 return nil
285}
286
287// ghRepoEntry represents a repo from gh repo list JSON output.
288type ghRepoEntry struct {
289 Name string `json:"name"`
290 NameWithOwner string `json:"nameWithOwner"`
291 URL string `json:"url"`
292}
293
294// ProjectDeps holds dependencies for project commands.
295type ProjectDeps struct {
296 ResolveGitHubRepo func(name string) (string, string, error)
297 GitClone func(url, targetDir string) error
298 // FetchDescription returns the GitHub description for owner/repo, or "" on
299 // any failure (missing binary, auth issue, no description set). It must
300 // never return an error — a missing description is not an error condition.
301 FetchDescription func(repoSlug string) string
302}
303
304// DefaultProjectDeps returns ProjectDeps wired to real implementations.
305func DefaultProjectDeps() ProjectDeps {
306 return ProjectDeps{
307 ResolveGitHubRepo: defaultResolveGitHubRepo,
308 GitClone: defaultGitClone,
309 FetchDescription: defaultFetchDescription,
310 }
311}
312
313// getProjectDeps lets tests swap in stub dependencies without touching cobra.
314var getProjectDeps = DefaultProjectDeps
315
316// defaultFetchDescription shells out to `gh repo view <slug> --json description -q .description`.
317// Returns "" if gh is unavailable, unauthenticated, the repo doesn't exist, or
318// the repo has no description set. All failure modes collapse to empty so that
319// `klaus project add` does not fail just because a description couldn't be fetched.
320func defaultFetchDescription(repoSlug string) string {
321 out, err := exec.Command("gh", "repo", "view", repoSlug, "--json", "description", "-q", ".description").Output()
322 if err != nil {
323 return ""
324 }
325 return strings.TrimSpace(string(out))
326}
327
328// defaultResolveGitHubRepo searches the user's GitHub repos for a name match.
329// Returns (owner, cloneURL, error).
330func defaultResolveGitHubRepo(name string) (string, string, error) {
331 out, err := exec.Command("gh", "repo", "list", "--json", "name,nameWithOwner,url", "--limit", "200").Output()
332 if err != nil {
333 return "", "", fmt.Errorf("running gh repo list: %w", err)
334 }
335
336 var repos []ghRepoEntry
337 if err := json.Unmarshal(out, &repos); err != nil {
338 return "", "", fmt.Errorf("parsing gh output: %w", err)
339 }
340
341 var matches []ghRepoEntry
342 for _, r := range repos {
343 if r.Name == name {
344 matches = append(matches, r)
345 }
346 }
347
348 switch len(matches) {
349 case 0:
350 return "", "", fmt.Errorf("no GitHub repo found matching %q. Use owner/repo format to be explicit", name)
351 case 1:
352 parts := strings.SplitN(matches[0].NameWithOwner, "/", 2)
353 return parts[0], matches[0].URL + ".git", nil
354 default:
355 var names []string
356 for _, m := range matches {
357 names = append(names, m.NameWithOwner)
358 }
359 return "", "", fmt.Errorf("multiple repos match %q: %s. Use owner/repo format to be specific", name, strings.Join(names, ", "))
360 }
361}
362
363// isGitRepo checks whether the given directory exists and contains a .git directory.
364func isGitRepo(dir string) bool {
365 info, err := os.Stat(filepath.Join(dir, ".git"))
366 if err != nil {
367 return false
368 }
369 return info.IsDir()
370}
371
372// defaultGitClone clones a repository to the target directory.
373func defaultGitClone(url, targetDir string) error {
374 c := exec.Command("git", "clone", url, targetDir)
375 c.Stdout = os.Stdout
376 c.Stderr = os.Stderr
377 return c.Run()
378}
379
380// gitRemoteURL returns the origin remote URL for a repo, or empty string on error.
381func gitRemoteURL(repoDir string) string {
382 c := exec.Command("git", "-C", repoDir, "remote", "get-url", "origin")
383 out, err := c.Output()
384 if err != nil {
385 return ""
386 }
387 return strings.TrimSpace(string(out))
388}
389
390func init() {
391 projectAddCmd.Flags().String("path", "", "Register with an explicit local path instead of cloning")
392 projectAddCmd.Flags().StringP("description", "d", "", "One-line description for the project (falls back to 'gh repo view' if unset)")
393 projectCmd.AddCommand(projectAddCmd)
394 projectCmd.AddCommand(projectListCmd)
395 projectCmd.AddCommand(projectRemoveCmd)
396 projectCmd.AddCommand(projectSetDirCmd)
397 projectCmd.AddCommand(projectDescribeCmd)
398 rootCmd.AddCommand(projectCmd)
399}