-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathsetup.go
More file actions
390 lines (332 loc) · 9.16 KB
/
Copy pathsetup.go
File metadata and controls
390 lines (332 loc) · 9.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package commands
import (
"fmt"
"strings"
"github.com/basecamp/cli/output"
"github.com/basecamp/fizzy-cli/internal/client"
"github.com/basecamp/fizzy-cli/internal/config"
"github.com/basecamp/fizzy-cli/internal/errors"
"github.com/charmbracelet/huh"
"github.com/spf13/cobra"
)
// Account represents an account from the identity response.
type Account struct {
ID string
Name string
Slug string
}
// Board represents a board from the boards response.
type Board struct {
ID string
Name string
}
var setupCmd = &cobra.Command{
Use: "setup",
Short: "Interactive setup wizard",
Long: "Configure Fizzy CLI with your API token, account, and default board.",
RunE: runSetup,
}
func init() {
rootCmd.AddCommand(setupCmd)
}
func runSetup(cmd *cobra.Command, args []string) error {
if IsMachineOutput() {
return output.ErrUsageHint("setup requires an interactive terminal", "Run without --agent/--json/--quiet or in a TTY")
}
printBanner()
fmt.Println()
fmt.Println("Welcome to Fizzy CLI setup!")
fmt.Println()
// Check for existing config
globalExists := config.Exists()
localPath := config.LocalConfigPath()
if globalExists || localPath != "" {
var reconfigure bool
configLocation := "global config"
if localPath != "" {
configLocation = "local config (" + localPath + ")"
}
err := huh.NewConfirm().
Title(fmt.Sprintf("Existing %s found. Reconfigure?", configLocation)).
Value(&reconfigure).
Run()
if err != nil {
fmt.Println("Setup cancelled.")
return nil //nolint:nilerr // user cancelled prompt
}
if !reconfigure {
fmt.Println("Setup cancelled. Existing configuration unchanged.")
return nil
}
}
// Ask hosted vs self-hosted
var hostingType string
err := huh.NewSelect[string]().
Title("Are you using the hosted or self-hosted version?").
Options(
huh.NewOption("Hosted (app.fizzy.do)", "hosted"),
huh.NewOption("Self-hosted", "selfhosted"),
).
Value(&hostingType).
Run()
if err != nil {
fmt.Println("Setup cancelled.")
return nil //nolint:nilerr // user cancelled prompt
}
apiURL := config.DefaultAPIURL
if hostingType == "selfhosted" {
err = huh.NewInput().
Title("Enter your Fizzy URL").
Placeholder("https://fizzy.example.com").
Value(&apiURL).
Validate(func(s string) error {
if s == "" {
return fmt.Errorf("URL is required")
}
if !strings.HasPrefix(s, "http://") && !strings.HasPrefix(s, "https://") {
return fmt.Errorf("URL must start with http:// or https://")
}
return nil
}).
Run()
if err != nil {
fmt.Println("Setup cancelled.")
return nil //nolint:nilerr // user cancelled prompt
}
}
// Token input loop with retry
var token string
var accounts []Account
for {
err = huh.NewInput().
Title("Enter your API token").
Description("Visit My Profile → Personal Access Tokens").
Placeholder("fizzy_...").
Value(&token).
EchoMode(huh.EchoModePassword).
Validate(func(s string) error {
if s == "" {
return fmt.Errorf("token is required")
}
return nil
}).
Run()
if err != nil {
fmt.Println("Setup cancelled.")
return nil //nolint:nilerr // user cancelled prompt
}
// Validate token
fmt.Print("Validating token... ")
accounts, err = validateToken(apiURL, token)
if err != nil {
fmt.Println("✗")
var retry bool
_ = huh.NewConfirm().
Title("Invalid token. Would you like to try again?").
Value(&retry).
Run()
if !retry {
fmt.Println("Setup cancelled.")
return nil
}
continue
}
fmt.Println("✓")
break
}
if len(accounts) == 0 {
return errors.NewError("No accounts found for this token")
}
// Account selection
var selectedAccountSlug string
if len(accounts) == 1 {
selectedAccountSlug = accounts[0].Slug
fmt.Printf("Using account: %s (%s)\n", accounts[0].Name, accounts[0].Slug)
} else {
accountOptions := make([]huh.Option[string], len(accounts))
for i, acc := range accounts {
accountOptions[i] = huh.NewOption(fmt.Sprintf("%s (%s)", acc.Name, acc.Slug), acc.Slug)
}
err = huh.NewSelect[string]().
Title("Select your account").
Options(accountOptions...).
Value(&selectedAccountSlug).
Run()
if err != nil {
fmt.Println("Setup cancelled.")
return nil //nolint:nilerr // user cancelled prompt
}
}
// Fetch boards for selected account
fmt.Print("Fetching boards... ")
boards, err := fetchBoards(apiURL, token, selectedAccountSlug)
if err != nil {
fmt.Println("✗")
// Non-fatal, just skip board selection
fmt.Println("Could not fetch boards. Skipping board selection.")
boards = nil
} else {
fmt.Println("✓")
}
// Board selection (optional)
var selectedBoardID string
if len(boards) > 0 {
boardOptions := make([]huh.Option[string], len(boards)+1)
boardOptions[0] = huh.NewOption("None (skip)", "")
for i, board := range boards {
boardOptions[i+1] = huh.NewOption(board.Name, board.ID)
}
err = huh.NewSelect[string]().
Title("Select default board (optional)").
Options(boardOptions...).
Value(&selectedBoardID).
Run()
if err != nil {
fmt.Println("Setup cancelled.")
return nil //nolint:nilerr // user cancelled prompt
}
}
// Ask where to save
var saveGlobal bool
err = huh.NewSelect[bool]().
Title("Where should we save the configuration?").
Options(
huh.NewOption("Global (~/.config/fizzy/config.yaml)", true),
huh.NewOption("Local (.fizzy.yaml in current directory)", false),
).
Value(&saveGlobal).
Run()
if err != nil {
fmt.Println("Setup cancelled.")
return nil //nolint:nilerr // user cancelled prompt
}
// Build and save config
newConfig := &config.Config{
Token: token,
Account: selectedAccountSlug,
Board: selectedBoardID,
APIURL: apiURL,
}
if saveGlobal {
// Save token to credstore when available
credstoreSaved := false
if creds != nil {
if err := credsSaveProfileToken(selectedAccountSlug, token); err != nil {
fmt.Printf("Warning: could not save token to credential store: %v\n", err)
} else {
credstoreSaved = true
}
}
// Create/update profile
ensureProfile(selectedAccountSlug, apiURL, selectedBoardID)
if profiles != nil {
_ = profiles.SetDefault(selectedAccountSlug)
}
// Load existing global config to preserve any other settings
existingConfig := config.LoadGlobal()
// Only clear YAML token when credstore save actually succeeded
if credstoreSaved {
existingConfig.Token = ""
} else {
existingConfig.Token = newConfig.Token
}
existingConfig.Account = newConfig.Account
existingConfig.Board = newConfig.Board
if newConfig.APIURL != "" {
existingConfig.APIURL = newConfig.APIURL
}
if err := existingConfig.Save(); err != nil {
return err
}
fmt.Println()
fmt.Println("✓ Configuration saved to ~/.config/fizzy/config.yaml")
} else {
if err := newConfig.SaveLocal(); err != nil {
return err
}
fmt.Println()
fmt.Println("✓ Configuration saved to .fizzy.yaml")
fmt.Println()
fmt.Println("⚠ Remember to add .fizzy.yaml to your .gitignore to avoid committing your token!")
}
fmt.Println()
fmt.Println("You're all set! Try: fizzy board list")
return nil
}
// validateToken validates the token by calling the identity endpoint.
// Returns the list of accounts on success.
func validateToken(apiURL, token string) ([]Account, error) {
c := client.New(apiURL, token, "")
resp, err := c.Get(apiURL + "/my/identity.json")
if err != nil {
return nil, err
}
return parseAccounts(resp.Data)
}
// parseAccounts extracts account information from the identity response.
func parseAccounts(data any) ([]Account, error) {
dataMap, ok := data.(map[string]any)
if !ok {
return nil, fmt.Errorf("unexpected response format")
}
accountsRaw, ok := dataMap["accounts"]
if !ok {
return nil, fmt.Errorf("no accounts in response")
}
accountsList, ok := accountsRaw.([]any)
if !ok {
return nil, fmt.Errorf("unexpected accounts format")
}
accounts := make([]Account, 0, len(accountsList))
for _, acc := range accountsList {
accMap, ok := acc.(map[string]any)
if !ok {
continue
}
id, _ := accMap["id"].(string)
name, _ := accMap["name"].(string)
slug, _ := accMap["slug"].(string)
// Remove leading slash from slug if present
slug = strings.TrimPrefix(slug, "/")
if slug != "" {
accounts = append(accounts, Account{
ID: id,
Name: name,
Slug: slug,
})
}
}
return accounts, nil
}
// fetchBoards fetches the list of boards for the given account.
func fetchBoards(apiURL, token, accountSlug string) ([]Board, error) {
c := client.New(apiURL, token, accountSlug)
resp, err := c.GetWithPagination("/boards.json", true)
if err != nil {
return nil, err
}
return parseBoards(resp.Data)
}
// parseBoards extracts board information from the boards response.
func parseBoards(data any) ([]Board, error) {
boardsList, ok := data.([]any)
if !ok {
return nil, fmt.Errorf("unexpected boards format")
}
boards := make([]Board, 0, len(boardsList))
for _, b := range boardsList {
boardMap, ok := b.(map[string]any)
if !ok {
continue
}
id, _ := boardMap["id"].(string)
name, _ := boardMap["name"].(string)
if id != "" && name != "" {
boards = append(boards, Board{
ID: id,
Name: name,
})
}
}
return boards, nil
}