gunk-dev/the-valley

target.go

source6a7605f70901main's published tip history
2.8 KiB
1package cmd
2
3import (
4 "fmt"
5 "strings"
6
7 "the-valley/flow/internal/git"
8 "the-valley/flow/internal/project"
9 "the-valley/flow/internal/run"
10 "github.com/spf13/cobra"
11)
12
13var targetCmd = &cobra.Command{
14 Use: "target [name | owner/repo]",
15 Short: "Set or show the session-level default target repo",
16 Long: `Sets a session-level default repo so that 'valley flow launch' without --repo
17uses this target. Useful when the coordinator session is not inside a git repo.
18
19 valley flow target owner/repo Set the default target repo
20 valley flow target my-project Set target using a registered project name
21 valley flow target Show the current target repo
22 valley flow target --clear Remove the default target repo`,
23 Args: cobra.MaximumNArgs(1),
24 RunE: func(cmd *cobra.Command, args []string) error {
25 store, err := sessionStore()
26 if err != nil {
27 return err
28 }
29 hds, ok := store.(*run.HomeDirStore)
30 if !ok {
31 return fmt.Errorf("target command requires a home-dir session store")
32 }
33 baseDir := hds.BaseDir()
34
35 clear, _ := cmd.Flags().GetBool("clear")
36
37 if clear {
38 if err := run.ClearTarget(baseDir); err != nil {
39 return err
40 }
41 fmt.Fprintln(cmd.OutOrStdout(), "Target cleared.")
42 return nil
43 }
44
45 if len(args) == 0 {
46 // Show current target
47 repo, err := run.LoadTarget(baseDir)
48 if err != nil {
49 return err
50 }
51 if repo == "" {
52 fmt.Fprintln(cmd.OutOrStdout(), "No target repo set.")
53 fmt.Fprintln(cmd.OutOrStdout(), "Usage: valley flow target owner/repo")
54 } else {
55 fmt.Fprintln(cmd.OutOrStdout(), repo)
56 }
57 return nil
58 }
59
60 repoRef := args[0]
61
62 // If no "/" in the reference, try resolving as a registered project name
63 if !strings.Contains(repoRef, "/") {
64 reg, err := registryUnlessConflict()
65 if err != nil {
66 return err
67 }
68 if reg != nil {
69 if _, ok := reg.Get(repoRef); ok {
70 // It's a known project name — use it as the canonical name
71 if err := run.SaveTarget(baseDir, repoRef); err != nil {
72 return err
73 }
74 fmt.Fprintf(cmd.OutOrStdout(), "Target set to %s\n", repoRef)
75 return nil
76 }
77 }
78 }
79
80 // Validate the repo reference as owner/repo or URL
81 owner, repo, _, err := git.ParseRepoRef(repoRef)
82 if err != nil {
83 return fmt.Errorf("invalid repo reference: %w", err)
84 }
85
86 // Normalize: if the repo portion matches a registered project, use the short name
87 reg, err := registryUnlessConflict()
88 if err != nil {
89 return err
90 }
91 normalized := project.NormalizeRepoName(owner+"/"+repo, reg)
92
93 if err := run.SaveTarget(baseDir, normalized); err != nil {
94 return err
95 }
96 fmt.Fprintf(cmd.OutOrStdout(), "Target set to %s\n", normalized)
97 return nil
98 },
99}
100
101func init() {
102 targetCmd.Flags().Bool("clear", false, "Remove the default target repo")
103 rootCmd.AddCommand(targetCmd)
104}