1package cli
2
3import (
4 "fmt"
5 "io"
6 "sort"
7 "strings"
8
9 "github.com/bnema/gordon/internal/adapters/in/cli/remote"
10 "github.com/bnema/gordon/internal/adapters/in/cli/ui/components"
11 "github.com/bnema/gordon/internal/adapters/in/cli/ui/styles"
12
13 "github.com/spf13/cobra"
14)
15
16// newRemotesCmd creates the remotes command group.
17func newRemotesCmd() *cobra.Command {
18 cmd := &cobra.Command{
19 Use: "remotes",
20 Short: "Manage saved remote Gordon instances",
21 Long: `Manage saved remote Gordon instances.
22
23Remotes allow you to save frequently used remote Gordon instances
24and quickly switch between them.
25
26Configuration is stored in ~/.config/gordon/remotes.toml`,
27 }
28
29 cmd.AddCommand(newRemotesListCmd())
30 cmd.AddCommand(newRemotesAddCmd())
31 cmd.AddCommand(newRemotesRemoveCmd())
32 cmd.AddCommand(newRemotesUseCmd())
33 cmd.AddCommand(newRemotesSetTokenCmd())
34
35 return cmd
36}
37
38// newRemotesListCmd creates the remotes list command.
39func newRemotesListCmd() *cobra.Command {
40 var jsonOut bool
41
42 cmd := &cobra.Command{
43 Use: "list",
44 Short: "List saved remotes",
45 RunE: func(cmd *cobra.Command, args []string) error {
46 return runRemotesList(cmd.OutOrStdout(), jsonOut)
47 },
48 }
49
50 cmd.Flags().BoolVar(&jsonOut, "json", false, "Output as JSON")
51
52 return cmd
53}
54
55func runRemotesList(out io.Writer, jsonOut bool) error {
56 remotes, active, err := remote.ListRemotes()
57 if err != nil {
58 return fmt.Errorf("failed to list remotes: %w", err)
59 }
60
61 if len(remotes) == 0 {
62 return remotesListEmpty(out, jsonOut)
63 }
64
65 names := sortedRemoteNames(remotes)
66
67 if jsonOut {
68 return remotesListJSON(out, remotes, names, active)
69 }
70
71 if err := cliWriteLine(out, cliRenderTitle("Saved Remotes")); err != nil {
72 return err
73 }
74 if err := cliWriteLine(out, ""); err != nil {
75 return err
76 }
77
78 rows := make([][]string, 0, len(names))
79 for _, name := range names {
80 r := remotes[name]
81 status := ""
82 if name == active {
83 status = styles.Theme.Success.Render("active")
84 }
85
86 tokenStatus := styles.Theme.Muted.Render("none")
87 if token := remote.ResolveTokenForRemote(name, r); token != "" {
88 tokenStatus = styles.Theme.Success.Render("set")
89 } else if r.TokenEnv != "" {
90 tokenStatus = fmt.Sprintf("$%s", r.TokenEnv)
91 }
92
93 tlsStatus := ""
94 if r.InsecureTLS {
95 tlsStatus = styles.Theme.Warning.Render("insecure")
96 }
97
98 rows = append(rows, []string{name, r.URL, tokenStatus, tlsStatus, status})
99 }
100
101 table := components.NewTable(
102 components.WithColumns([]components.TableColumn{
103 {Title: "Name", Width: 15},
104 {Title: "URL", Width: 35},
105 {Title: "Token", Width: 15},
106 {Title: "TLS", Width: 10},
107 {Title: "Status", Width: 10},
108 }),
109 components.WithRows(rows),
110 )
111
112 _, err = fmt.Fprintln(out, table.View())
113 return err
114}
115
116func remotesListEmpty(out io.Writer, jsonOut bool) error {
117 if jsonOut {
118 return writeJSON(out, []map[string]any{})
119 }
120 if err := cliWriteLine(out, cliRenderMuted("No remotes configured")); err != nil {
121 return err
122 }
123 if err := cliWriteLine(out, ""); err != nil {
124 return err
125 }
126 if err := cliWriteLine(out, "Add a remote with:"); err != nil {
127 return err
128 }
129 return cliWriteLine(out, styles.Theme.Bold.Render(" gordon remotes add <name> <url>"))
130}
131
132func sortedRemoteNames(remotes map[string]remote.RemoteEntry) []string {
133 names := make([]string, 0, len(remotes))
134 for name := range remotes {
135 names = append(names, name)
136 }
137 sort.Strings(names)
138 return names
139}
140
141func remotesListJSON(out io.Writer, remotes map[string]remote.RemoteEntry, names []string, active string) error {
142 payload := make([]map[string]any, 0, len(names))
143 for _, name := range names {
144 r := remotes[name]
145 payload = append(payload, map[string]any{
146 "name": name,
147 "url": r.URL,
148 "active": name == active,
149 "insecure_tls": r.InsecureTLS,
150 })
151 }
152 return writeJSON(out, payload)
153}
154
155// newRemotesAddCmd creates the remotes add command.
156func newRemotesAddCmd() *cobra.Command {
157 var token string
158 var tokenEnv string
159 var insecureTLS bool
160
161 cmd := &cobra.Command{
162 Use: "add <name> <url>",
163 Short: "Add a new remote",
164 Long: `Add a new saved remote.
165
166Examples:
167 gordon remotes add prod https://gordon.mydomain.com
168 gordon remotes add prod https://gordon.mydomain.com --token eyJ...
169 gordon remotes add staging https://staging.mydomain.com --token-env STAGING_TOKEN
170 gordon remotes add dev https://dev.internal --insecure`,
171 Args: cobra.ExactArgs(2),
172 RunE: func(cmd *cobra.Command, args []string) error {
173 name := args[0]
174 url := normalizeURL(args[1])
175
176 // If token-env is provided, use that instead of token
177 finalToken := token
178 if tokenEnv != "" {
179 // Store token_env reference instead of actual token
180 if err := addRemoteWithEnv(name, url, tokenEnv, insecureTLS); err != nil {
181 return fmt.Errorf("failed to add remote: %w", err)
182 }
183 } else {
184 if err := remote.AddRemote(name, url, finalToken, insecureTLS); err != nil {
185 return fmt.Errorf("failed to add remote: %w", err)
186 }
187 }
188
189 fmt.Println(styles.RenderSuccess(fmt.Sprintf("Remote added: %s -> %s", name, url)))
190
191 if token == "" && tokenEnv == "" {
192 fmt.Println(styles.Theme.Muted.Render("Tip: Add a token with --token or --token-env for authenticated access"))
193 }
194
195 return nil
196 },
197 }
198
199 cmd.Flags().StringVar(&token, "token", "", "Authentication token")
200 cmd.Flags().StringVar(&tokenEnv, "token-env", "", "Environment variable containing token")
201 cmd.Flags().BoolVar(&insecureTLS, "insecure", false, "Skip TLS certificate verification")
202
203 return cmd
204}
205
206// addRemoteWithEnv adds a remote with a token environment variable reference.
207func addRemoteWithEnv(name, url, tokenEnv string, insecureTLS bool) error {
208 config, err := remote.LoadRemotes("")
209 if err != nil {
210 return err
211 }
212
213 config.Remotes[name] = remote.RemoteEntry{
214 URL: url,
215 TokenEnv: tokenEnv,
216 InsecureTLS: insecureTLS,
217 }
218
219 return remote.SaveRemotes("", config)
220}
221
222// newRemotesRemoveCmd creates the remotes remove command.
223func newRemotesRemoveCmd() *cobra.Command {
224 var force bool
225
226 cmd := &cobra.Command{
227 Use: "remove <name>",
228 Aliases: []string{"rm"},
229 Short: "Remove a remote",
230 Args: cobra.ExactArgs(1),
231 RunE: func(cmd *cobra.Command, args []string) error {
232 name := args[0]
233
234 // Check if remote exists
235 remotes, active, err := remote.ListRemotes()
236 if err != nil {
237 return fmt.Errorf("failed to list remotes: %w", err)
238 }
239
240 if _, exists := remotes[name]; !exists {
241 fmt.Println(styles.RenderError(fmt.Sprintf("Remote '%s' not found", name)))
242 return nil
243 }
244
245 // Confirm unless --force
246 if !force {
247 message := fmt.Sprintf("Remove remote '%s'?", name)
248 if name == active {
249 message = fmt.Sprintf("Remove remote '%s'? (currently active)", name)
250 }
251
252 confirmed, err := components.RunConfirm(message)
253 if err != nil {
254 return err
255 }
256 if !confirmed {
257 fmt.Println(styles.Theme.Muted.Render("Cancelled"))
258 return nil
259 }
260 }
261
262 if err := remote.RemoveRemote(name); err != nil {
263 return fmt.Errorf("failed to remove remote: %w", err)
264 }
265
266 fmt.Println(styles.RenderSuccess(fmt.Sprintf("Remote removed: %s", name)))
267 return nil
268 },
269 }
270
271 cmd.Flags().BoolVarP(&force, "force", "f", false, "Skip confirmation")
272
273 return cmd
274}
275
276// newRemotesUseCmd creates the remotes use command.
277func newRemotesUseCmd() *cobra.Command {
278 return &cobra.Command{
279 Use: "use <name>",
280 Short: "Set the active remote",
281 Long: `Set a remote as the active default.
282
283When a remote is active, it will be used automatically for remote commands
284without needing to specify --remote.
285
286Examples:
287 gordon remotes use prod
288 gordon routes list # Uses prod remote automatically`,
289 Args: cobra.ExactArgs(1),
290 RunE: func(cmd *cobra.Command, args []string) error {
291 name := args[0]
292
293 if err := remote.SetActiveRemote(name); err != nil {
294 if err.Error() == fmt.Sprintf("remote '%s' not found", name) {
295 fmt.Println(styles.RenderError(fmt.Sprintf("Remote '%s' not found", name)))
296 fmt.Println()
297 fmt.Println("Available remotes:")
298
299 remotes, _, _ := remote.ListRemotes()
300 for remoteName := range remotes {
301 fmt.Printf(" %s\n", remoteName)
302 }
303 return nil
304 }
305 return fmt.Errorf("failed to set active remote: %w", err)
306 }
307
308 fmt.Println(styles.RenderSuccess(fmt.Sprintf("Active remote set to '%s'", name)))
309 return nil
310 },
311 }
312}
313
314// newRemotesSetTokenCmd creates the remotes set-token command.
315func newRemotesSetTokenCmd() *cobra.Command {
316 return &cobra.Command{
317 Use: "set-token <name> <token>",
318 Short: "Set the token for a remote",
319 Long: `Set or update the authentication token for a saved remote.
320
321This is useful when:
322- The server uses token-based authentication (not password auth)
323- You have a pre-generated token from 'gordon auth token generate'
324- You want to update an expired token
325
326For servers with password authentication, use 'gordon auth login' instead.
327
328Examples:
329 gordon remotes set-token prod eyJhbGciOiJIUzI1NiIs...
330 gordon remotes set-token staging $(cat token.txt)`,
331 Args: cobra.ExactArgs(2),
332 RunE: func(cmd *cobra.Command, args []string) error {
333 name := args[0]
334 token := args[1]
335
336 // Verify remote exists
337 remotes, _, err := remote.ListRemotes()
338 if err != nil {
339 return fmt.Errorf("failed to list remotes: %w", err)
340 }
341
342 if _, exists := remotes[name]; !exists {
343 fmt.Println(styles.RenderError(fmt.Sprintf("Remote '%s' not found", name)))
344 return nil
345 }
346
347 if err := remote.UpdateRemoteToken(name, token); err != nil {
348 return fmt.Errorf("failed to update token: %w", err)
349 }
350
351 fmt.Println(styles.RenderSuccess(fmt.Sprintf("Token updated for remote '%s'", name)))
352 return nil
353 },
354 }
355}
356
357// normalizeURL ensures the URL has a protocol scheme, defaulting to https.
358func normalizeURL(url string) string {
359 if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
360 return url
361 }
362 return "https://" + url
363}