-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathroot.go
More file actions
885 lines (797 loc) · 25.1 KB
/
Copy pathroot.go
File metadata and controls
885 lines (797 loc) · 25.1 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
// Package commands implements CLI commands for the Fizzy CLI.
package commands
import (
"bytes"
"encoding/json"
stderrors "errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"github.com/basecamp/cli/credstore"
"github.com/basecamp/cli/output"
"github.com/basecamp/cli/profile"
"github.com/basecamp/fizzy-cli/internal/client"
"github.com/basecamp/fizzy-cli/internal/config"
"github.com/basecamp/fizzy-cli/internal/errors"
"github.com/basecamp/fizzy-cli/internal/render"
"github.com/mattn/go-isatty"
"github.com/spf13/cobra"
)
// Breadcrumb is a type alias for output.Breadcrumb.
type Breadcrumb = output.Breadcrumb
var (
// Global flags
cfgToken string
cfgProfile string
cfgAPIURL string
cfgVerbose bool
cfgJSON bool
cfgQuiet bool
cfgIDsOnly bool
cfgCount bool
cfgAgent bool
cfgStyled bool
cfgMarkdown bool
cfgLimit int
// Loaded config
cfg *config.Config
// Client factory (can be overridden for testing)
clientFactory func() client.API
// Credential store
creds *credstore.Store
// Profile store
profiles *profile.Store
// Output writer
out *output.Writer
outWriter io.Writer // raw writer for styled/markdown rendering
)
// rootCmd represents the base command.
var rootCmd = &cobra.Command{
Use: "fizzy",
Short: "Fizzy CLI - Command-line interface for the Fizzy API",
Long: `A command-line interface for the Fizzy API.
Use fizzy to manage boards, cards, comments, and more from your terminal.`,
Version: "dev",
Run: func(cmd *cobra.Command, args []string) {
printBanner()
_ = cmd.Help()
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Resolve output format from parsed flags (must happen post-parse).
format, err := resolveFormat()
if err != nil {
return &output.Error{Code: output.CodeUsage, Message: err.Error()}
}
if lastResult != nil {
// Test mode — preserve test buffer as writer.
outWriter = &testBuf
out = output.New(output.Options{Format: format, Writer: &testBuf})
} else {
outWriter = os.Stdout
out = output.New(output.Options{Format: format, Writer: os.Stdout})
}
// In test mode, cfg is already set by SetTestConfig - don't overwrite
if cfg == nil {
// Load config from file/env
cfg = config.Load()
}
// Initialize credential store (skip in test mode)
if creds == nil && lastResult == nil {
fallbackDir := ""
if cfgPath, err := config.ConfigPath(); err == nil {
fallbackDir = filepath.Join(filepath.Dir(cfgPath), "credentials")
} else if home, err := os.UserHomeDir(); err == nil {
fallbackDir = filepath.Join(home, ".config", "fizzy", "credentials")
}
creds = credstore.NewStore(credstore.StoreOptions{
ServiceName: "fizzy",
DisableEnvVar: "FIZZY_NO_KEYRING",
FallbackDir: fallbackDir,
})
}
// Initialize profile store (skip in test mode)
if profiles == nil && lastResult == nil {
if cfgPath, err := config.ConfigPath(); err == nil {
profiles = profile.NewStore(filepath.Join(filepath.Dir(cfgPath), "config.json"))
}
}
if err := resolveProfile(); err != nil {
return &output.Error{Code: output.CodeUsage, Message: err.Error()}
}
resolveToken()
// --api-url flag overrides everything (including profile BaseURL)
if cfgAPIURL != "" {
cfg.APIURL = cfgAPIURL
}
// FIZZY_DEBUG enables verbose output
if os.Getenv("FIZZY_DEBUG") != "" {
cfgVerbose = true
}
return nil
},
SilenceUsage: true,
SilenceErrors: true,
}
// SetVersion sets the CLI version used for `--version` and `version`.
func SetVersion(v string) {
if v == "" {
return
}
rootCmd.Version = v
}
// Execute runs the root command.
func Execute() {
// Default to Auto — PersistentPreRunE will re-resolve from parsed flags.
outWriter = os.Stdout
out = output.New(output.Options{Format: output.FormatAuto, Writer: os.Stdout})
if err := rootCmd.Execute(); err != nil {
var e *output.Error
if !stderrors.As(err, &e) {
// Cobra-level errors (arg count, unknown flag) → usage
e = &output.Error{Code: output.CodeUsage, Message: err.Error()}
}
_ = out.Err(e)
os.Exit(e.ExitCode())
}
}
// resolveFormat returns the output format from flags.
// Default is FormatAuto (TTY→Styled, pipe→JSON). At most one format flag may be set.
func resolveFormat() (output.Format, error) {
// Count mutually exclusive format flags
n := 0
if cfgJSON {
n++
}
if cfgQuiet {
n++
}
if cfgIDsOnly {
n++
}
if cfgCount {
n++
}
if cfgStyled {
n++
}
if cfgMarkdown {
n++
}
if n > 1 {
return 0, fmt.Errorf("only one output format flag may be used at a time (--json, --quiet, --ids-only, --count, --styled, --markdown)")
}
// --agent is orthogonal to format flags but --agent --styled is an error
if cfgAgent && cfgStyled {
return 0, fmt.Errorf("--agent and --styled cannot be used together")
}
// Explicit format flag wins
switch {
case cfgQuiet:
return output.FormatQuiet, nil
case cfgIDsOnly:
return output.FormatIDs, nil
case cfgCount:
return output.FormatCount, nil
case cfgJSON:
return output.FormatJSON, nil
case cfgStyled:
return output.FormatStyled, nil
case cfgMarkdown:
return output.FormatMarkdown, nil
}
// --agent alone defaults to FormatQuiet
if cfgAgent {
return output.FormatQuiet, nil
}
return output.FormatAuto, nil
}
// IsMachineOutput returns true when output should be treated as machine-consumable.
// True when any machine format flag is set, --agent is set, or stdout/stdin is not a TTY.
func IsMachineOutput() bool {
if cfgAgent || cfgJSON || cfgQuiet || cfgIDsOnly || cfgCount {
return true
}
if !isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()) {
return true
}
if !isatty.IsTerminal(os.Stdin.Fd()) && !isatty.IsCygwinTerminal(os.Stdin.Fd()) {
return true
}
return false
}
func init() {
rootCmd.PersistentFlags().StringVar(&cfgToken, "token", "", "API access token")
rootCmd.PersistentFlags().StringVar(&cfgProfile, "profile", "", "Named profile to use")
rootCmd.PersistentFlags().StringVar(&cfgAPIURL, "api-url", "", "API base URL")
rootCmd.PersistentFlags().BoolVar(&cfgVerbose, "verbose", false, "Show request/response details")
rootCmd.PersistentFlags().BoolVar(&cfgJSON, "json", false, "JSON envelope output")
rootCmd.PersistentFlags().BoolVar(&cfgQuiet, "quiet", false, "Raw JSON data without envelope")
rootCmd.PersistentFlags().BoolVar(&cfgIDsOnly, "ids-only", false, "Print one ID per line")
rootCmd.PersistentFlags().BoolVar(&cfgCount, "count", false, "Print count of results")
rootCmd.PersistentFlags().BoolVar(&cfgAgent, "agent", false, "Agent mode (default: quiet format, no interactive prompts)")
rootCmd.PersistentFlags().BoolVar(&cfgStyled, "styled", false, "Styled terminal output with colors")
rootCmd.PersistentFlags().BoolVar(&cfgMarkdown, "markdown", false, "Markdown formatted output")
rootCmd.PersistentFlags().IntVar(&cfgLimit, "limit", 0, "Maximum number of results to display")
installAgentHelp()
}
// getClient returns an API client configured from global settings.
func getClient() client.API {
if clientFactory != nil {
return clientFactory()
}
c := client.New(cfg.APIURL, cfg.Token, cfg.Account)
c.Verbose = cfgVerbose
return c
}
// requireAuth checks that we have authentication configured.
func requireAuth() error {
if cfg.Token == "" {
return errors.NewAuthError("No API token configured. Run 'fizzy auth login TOKEN' or set FIZZY_TOKEN")
}
return nil
}
// requireAccount checks that we have an account configured.
func requireAccount() error {
if cfg.Account == "" {
return errors.NewInvalidArgsError("No account configured. Set --profile flag, FIZZY_PROFILE, or run 'fizzy setup'")
}
return nil
}
// requireAuthAndAccount checks both auth and account.
func requireAuthAndAccount() error {
if err := requireAuth(); err != nil {
return err
}
return requireAccount()
}
func effectiveConfig() *config.Config {
if cfg != nil {
return cfg
}
return config.Load()
}
func defaultBoard(board string) string {
if board != "" {
return board
}
return effectiveConfig().Board
}
func requireBoard(board string) (string, error) {
board = defaultBoard(board)
if board == "" {
return "", errors.NewInvalidArgsError("No board configured. Set --board, FIZZY_BOARD, or add 'board' to your config file")
}
return board, nil
}
// CommandResult holds the result of a command execution for testing.
type CommandResult struct {
Response *output.Response
}
// lastResult stores the last command result (for testing)
var lastResult *CommandResult
// testBuf captures output for test mode
var testBuf bytes.Buffer
// lastRawOutput holds the raw output from the last command (before buffer reset).
var lastRawOutput string
// captureResponse parses the writer buffer into lastResult after each shim call.
func captureResponse() {
if lastResult == nil {
return
}
lastRawOutput = testBuf.String()
lastResult.Response = nil
var resp output.Response
if json.Unmarshal(testBuf.Bytes(), &resp) == nil {
lastResult.Response = &resp
}
testBuf.Reset()
}
// printSuccess prints a success response.
func printSuccess(data any) {
_ = out.OK(data)
captureResponse()
}
// printSuccessWithLocation prints a success response with location.
func printSuccessWithLocation(location string) {
_ = out.OK(nil, output.WithContext("location", location))
captureResponse()
}
// breadcrumb creates a single breadcrumb.
func breadcrumb(action, cmd, description string) Breadcrumb {
return Breadcrumb{Action: action, Cmd: cmd, Description: description}
}
// printSuccessWithBreadcrumbs prints a success response with breadcrumbs.
func printSuccessWithBreadcrumbs(data any, summary string, breadcrumbs []Breadcrumb) {
opts := []output.ResponseOption{output.WithBreadcrumbs(breadcrumbs...)}
if summary != "" {
opts = append(opts, output.WithSummary(summary))
}
_ = out.OK(data, opts...)
captureResponse()
}
// printSuccessWithLocationAndBreadcrumbs prints a success response with both location and breadcrumbs.
func printSuccessWithLocationAndBreadcrumbs(data any, location string, breadcrumbs []Breadcrumb) {
_ = out.OK(data,
output.WithBreadcrumbs(breadcrumbs...),
output.WithContext("location", location),
)
captureResponse()
}
// defaultPageSize is the Fizzy API's default page size.
const defaultPageSize = 20
// checkLimitAll validates that --limit and --all are not both set.
func checkLimitAll(all bool) error {
if cfgLimit > 0 && all {
return errors.NewInvalidArgsError("--limit and --all cannot be used together")
}
return nil
}
// truncateData applies --limit client-side truncation to a slice.
// Returns the (possibly truncated) data and the original count.
// Handles both []any and typed slices (e.g. []Attachment).
func truncateData(data any) (any, int) {
if arr, ok := data.([]any); ok {
originalCount := len(arr)
if cfgLimit > 0 && originalCount > cfgLimit {
return arr[:cfgLimit], originalCount
}
return data, originalCount
}
// Handle typed slices via reflect
v := reflect.ValueOf(data)
if v.Kind() == reflect.Slice {
originalCount := v.Len()
if cfgLimit > 0 && originalCount > cfgLimit {
return v.Slice(0, cfgLimit).Interface(), originalCount
}
return data, originalCount
}
return data, 0
}
// dataCount returns the length of data if it's a slice.
func dataCount(data any) int {
if arr, ok := data.([]any); ok {
return len(arr)
}
v := reflect.ValueOf(data)
if v.Kind() == reflect.Slice {
return v.Len()
}
return 0
}
// printList renders list data with format-aware dispatch.
// For non-paginated lists (no --all flag). Applies --limit truncation.
func printList(data any, cols render.Columns, summary string, breadcrumbs []Breadcrumb) {
data, originalCount := truncateData(data)
// For non-paginated lists, generate a simple limit notice (no --all to suggest)
notice := ""
if cfgLimit > 0 && originalCount > cfgLimit {
notice = fmt.Sprintf("Showing %d of %d results", cfgLimit, originalCount)
}
switch out.EffectiveFormat() {
case output.FormatStyled:
fmt.Fprint(outWriter, render.StyledList(toMaps(data), cols, summary))
if notice != "" {
fmt.Fprintf(outWriter, "\n%s\n", notice)
}
captureResponse()
case output.FormatMarkdown:
fmt.Fprint(outWriter, render.MarkdownList(toMaps(data), cols, summary))
if notice != "" {
fmt.Fprintf(outWriter, "\n%s\n", notice)
}
captureResponse()
default:
opts := []output.ResponseOption{output.WithBreadcrumbs(breadcrumbs...)}
if summary != "" {
opts = append(opts, output.WithSummary(summary))
}
if notice != "" {
opts = append(opts, output.WithNotice(notice))
}
_ = out.OK(data, opts...)
captureResponse()
}
}
// printListPaginated renders paginated list data with format-aware dispatch.
// For paginated lists (commands with --all flag). Applies --limit truncation and truncation notices.
func printListPaginated(data any, cols render.Columns, hasNext bool, nextURL string, all bool, summary string, breadcrumbs []Breadcrumb) {
data, _ = truncateData(data)
notice := output.TruncationNotice(dataCount(data), defaultPageSize, all, cfgLimit)
switch out.EffectiveFormat() {
case output.FormatStyled:
fmt.Fprint(outWriter, render.StyledList(toMaps(data), cols, summary))
if notice != "" {
fmt.Fprintf(outWriter, "\n%s\n", notice)
}
captureResponse()
case output.FormatMarkdown:
fmt.Fprint(outWriter, render.MarkdownList(toMaps(data), cols, summary))
if notice != "" {
fmt.Fprintf(outWriter, "\n%s\n", notice)
}
captureResponse()
default:
opts := []output.ResponseOption{output.WithBreadcrumbs(breadcrumbs...)}
if summary != "" {
opts = append(opts, output.WithSummary(summary))
}
if notice != "" {
opts = append(opts, output.WithNotice(notice))
}
if hasNext || nextURL != "" {
opts = append(opts, output.WithContext("pagination", map[string]any{
"has_next": hasNext,
"next_url": nextURL,
}))
}
_ = out.OK(data, opts...)
captureResponse()
}
}
// printDetail renders a single object with format-aware dispatch.
func printDetail(data any, summary string, breadcrumbs []Breadcrumb) {
switch out.EffectiveFormat() {
case output.FormatStyled:
fmt.Fprint(outWriter, render.StyledDetail(toMap(data), summary))
captureResponse()
case output.FormatMarkdown:
fmt.Fprint(outWriter, render.MarkdownDetail(toMap(data), summary))
captureResponse()
default:
printSuccessWithBreadcrumbs(data, summary, breadcrumbs)
}
}
// printMutationWithLocation renders a mutation result that includes a location URL.
func printMutationWithLocation(data any, location string, breadcrumbs []Breadcrumb) {
switch out.EffectiveFormat() {
case output.FormatStyled:
fmt.Fprint(outWriter, render.StyledDetail(toMap(data), ""))
captureResponse()
case output.FormatMarkdown:
fmt.Fprint(outWriter, render.MarkdownDetail(toMap(data), ""))
captureResponse()
default:
printSuccessWithLocationAndBreadcrumbs(data, location, breadcrumbs)
}
}
// printMutation renders a mutation result with format-aware dispatch.
// For styled/markdown, uses summary rendering for simple confirmations.
func printMutation(data any, summary string, breadcrumbs []Breadcrumb) {
switch out.EffectiveFormat() {
case output.FormatStyled:
fmt.Fprint(outWriter, render.StyledSummary(toMap(data), summary))
captureResponse()
case output.FormatMarkdown:
fmt.Fprint(outWriter, render.MarkdownSummary(toMap(data), summary))
captureResponse()
default:
printSuccessWithBreadcrumbs(data, summary, breadcrumbs)
}
}
// toMaps converts any (expected []any of map[string]any) to []map[string]any.
// Falls back to JSON round-trip for typed slices (e.g., []Attachment).
func toMaps(data any) []map[string]any {
if data == nil {
return nil
}
if slice, ok := data.([]any); ok {
result := make([]map[string]any, 0, len(slice))
for _, item := range slice {
if m, ok := item.(map[string]any); ok {
result = append(result, m)
}
}
return result
}
// JSON round-trip for typed structs
b, err := json.Marshal(data)
if err != nil {
return nil
}
var result []map[string]any
if json.Unmarshal(b, &result) == nil {
return result
}
return nil
}
// toMap converts any (expected map[string]any) to map[string]any.
func toMap(data any) map[string]any {
if m, ok := data.(map[string]any); ok {
return m
}
return nil
}
// SetTestMode configures the commands package for testing.
// It sets a mock client factory and captures results instead of exiting.
func SetTestMode(mockClient client.API) *CommandResult {
clientFactory = func() client.API {
return mockClient
}
testBuf.Reset()
outWriter = &testBuf
out = output.New(output.Options{Format: output.FormatJSON, Writer: &testBuf})
lastResult = &CommandResult{}
return lastResult
}
// SetTestFormat reconfigures the output writer with the given format.
// Must be called after SetTestMode.
func SetTestFormat(format output.Format) {
testBuf.Reset()
outWriter = &testBuf
out = output.New(output.Options{Format: format, Writer: &testBuf})
}
// TestOutput returns the raw output from the last command execution.
// Useful for verifying non-JSON format output.
func TestOutput() string {
return lastRawOutput
}
// credsSaveProfileToken JSON-encodes a token and saves it to the credential store
// under a profile-scoped key ("profile:<name>").
func credsSaveProfileToken(profileName, token string) error {
data, err := json.Marshal(token)
if err != nil {
return err
}
return creds.Save(profile.CredentialKey(profileName, ""), data)
}
// credsLoadProfileToken loads and JSON-decodes a token for a profile.
func credsLoadProfileToken(profileName string) (string, error) {
data, err := creds.Load(profile.CredentialKey(profileName, ""))
if err != nil {
return "", err
}
var token string
if json.Unmarshal(data, &token) == nil {
return token, nil
}
return string(data), nil
}
// credsDeleteProfileToken removes the token for a profile.
func credsDeleteProfileToken(profileName string) error {
return creds.Delete(profile.CredentialKey(profileName, ""))
}
// credsLoadLegacyToken loads a token from a legacy credstore entry.
// Checks both the old single "token" key and the account-scoped "token:<account>" key.
func credsLoadLegacyToken(account string) (string, error) {
// Try account-scoped key first (from earlier multi-account PR)
if account != "" {
if data, err := creds.Load("token:" + account); err == nil {
var token string
if json.Unmarshal(data, &token) == nil {
return token, nil
}
return string(data), nil
}
}
// Then try bare "token" key (original single-key format)
data, err := creds.Load("token")
if err != nil {
return "", err
}
var token string
if json.Unmarshal(data, &token) == nil {
return token, nil
}
return string(data), nil
}
// resolveProfile uses profile.Resolve() to determine the active profile,
// then applies its BaseURL and board (from Extra) to cfg.
//
// Profile settings (layer 3) outrank local and global YAML config (layers
// 4–5) but yield to env vars (layer 2) and flags (layer 1). Because
// config.Load() has already run, cfg may contain values from YAML config.
// resolveProfile intentionally overwrites those with profile data:
//
// profile BaseURL → cfg.APIURL (unless FIZZY_API_URL env var is set)
// profile board → cfg.Board (unless FIZZY_BOARD env var is set)
//
// Returns an error when the user explicitly selected a profile (via flag
// or env var) that doesn't exist — that must be a hard failure, not a
// silent fallback to whatever was in the YAML config.
func resolveProfile() error {
if profiles == nil {
// No profile store (test mode or init failure) — fall back to env var
if p := os.Getenv("FIZZY_PROFILE"); p != "" {
cfg.Account = p
}
return nil
}
allProfiles, defaultName, err := profiles.List()
if err != nil || len(allProfiles) == 0 {
// No profiles configured — fall back to env var for account
if p := os.Getenv("FIZZY_PROFILE"); p != "" {
cfg.Account = p
} else if a := os.Getenv("FIZZY_ACCOUNT"); a != "" {
cfg.Account = a
}
return nil
}
envProfile := profileEnvVar()
resolved, err := profile.Resolve(profile.ResolveOptions{
FlagValue: cfgProfile,
EnvVar: envProfile,
DefaultProfile: defaultName,
Profiles: allProfiles,
})
if err != nil {
// If the user explicitly specified a profile (flag or env), that's a
// hard error — don't silently fall back to a different account.
if cfgProfile != "" || envProfile != "" {
return err
}
// Otherwise (ambiguous default, etc.) — not fatal, just skip profile
return nil
}
if resolved == "" {
return nil
}
p := allProfiles[resolved]
if p == nil {
return nil
}
// Apply profile settings to cfg — but only for fields that haven't
// already been set by a higher-precedence source (env var).
cfg.Account = resolved
if p.BaseURL != "" && os.Getenv("FIZZY_API_URL") == "" {
cfg.APIURL = p.BaseURL
}
if boardRaw, ok := p.Extra["board"]; ok {
var board string
if json.Unmarshal(boardRaw, &board) == nil && board != "" && os.Getenv("FIZZY_BOARD") == "" {
cfg.Board = board
}
}
return nil
}
// profileEnvVar returns the FIZZY_PROFILE env var, falling back to FIZZY_ACCOUNT
// for backward compatibility.
func profileEnvVar() string {
if v := os.Getenv("FIZZY_PROFILE"); v != "" {
return v
}
if v := os.Getenv("FIZZY_ACCOUNT"); v != "" {
fmt.Fprintln(os.Stderr, "Warning: FIZZY_ACCOUNT is deprecated, use FIZZY_PROFILE instead")
return v
}
return ""
}
// resolveToken applies token precedence: YAML → credstore (with migration) → env → flag.
func resolveToken() {
// 1. YAML file (global + local, already in cfg.Token from config.Load())
// 2. credstore (overrides YAML — credstore is the "new" storage)
if creds != nil {
profileName := cfg.Account // profile name = account slug
if profileName != "" {
// Try profile-scoped token first
if t, err := credsLoadProfileToken(profileName); err == nil && t != "" {
cfg.Token = t
} else {
// Legacy migration: old keys → profile-scoped key
migrateLegacyToken(profileName)
}
} else {
// No profile — try legacy single key
if t, err := credsLoadLegacyToken(""); err == nil && t != "" {
cfg.Token = t
}
}
}
// 3. env var (overrides credstore)
if t := os.Getenv("FIZZY_TOKEN"); t != "" {
cfg.Token = t
}
// 4. CLI flag (overrides everything)
if cfgToken != "" {
cfg.Token = cfgToken
}
}
// migrateLegacyToken moves a token from legacy storage to profile-scoped storage.
// Handles the old single-key credstore entry, account-scoped keys, and YAML config tokens.
func migrateLegacyToken(profileName string) {
// Check legacy credstore keys — copy to profile-scoped key but keep the
// legacy keys so older CLI versions still work after a downgrade.
if t, err := credsLoadLegacyToken(profileName); err == nil && t != "" {
// Always use the token, even if migration to profile-scoped key fails
cfg.Token = t
if err := credsSaveProfileToken(profileName, t); err == nil {
ensureProfile(profileName, cfg.APIURL, "")
}
return
}
// Check YAML config token (pre-credstore migration)
globalCfg := config.LoadGlobal()
if globalCfg.Token != "" {
// Always use the token, even if migration to profile-scoped key fails
cfg.Token = globalCfg.Token
if err := credsSaveProfileToken(profileName, globalCfg.Token); err == nil {
globalCfg.Token = ""
globalCfg.Account = profileName
_ = globalCfg.Save()
ensureProfile(profileName, cfg.APIURL, "")
}
}
}
// ensureProfile creates or updates a profile in the store.
// If the profile already exists, fields are merged: BaseURL is
// preserved only when the caller passes an empty string (meaning
// "keep whatever is there"), and Extra entries are preserved unless
// explicitly replaced.
func ensureProfile(name, baseURL, board string) {
if profiles == nil {
return
}
existing, _ := profiles.Get(name)
newBaseURL := baseURL
if newBaseURL == "" {
if existing != nil && existing.BaseURL != "" {
newBaseURL = existing.BaseURL
} else {
newBaseURL = config.DefaultAPIURL
}
}
extra := map[string]json.RawMessage{}
if existing != nil {
for k, v := range existing.Extra {
extra[k] = v
}
}
if board != "" {
extra["board"] = func() json.RawMessage { b, _ := json.Marshal(board); return b }()
}
p := &profile.Profile{
Name: name,
BaseURL: newBaseURL,
}
if len(extra) > 0 {
p.Extra = extra
}
if err := profiles.Create(p); err != nil {
_ = profiles.Delete(name)
_ = profiles.Create(p)
}
}
// SetTestCreds sets the credential store for testing.
func SetTestCreds(store *credstore.Store) {
creds = store
}
// SetTestProfiles sets the profile store for testing.
func SetTestProfiles(store *profile.Store) {
profiles = store
}
// SetTestConfig sets the config for testing.
func SetTestConfig(token, account, apiURL string) {
cfg = &config.Config{
Token: token,
Account: account,
APIURL: apiURL,
}
}
// ResetTestMode resets the test mode configuration.
func ResetTestMode() {
clientFactory = nil
lastResult = nil
lastRawOutput = ""
cfg = nil
creds = nil
profiles = nil
cfgJSON = false
cfgQuiet = false
cfgIDsOnly = false
cfgCount = false
cfgAgent = false
cfgStyled = false
cfgMarkdown = false
cfgLimit = 0
cfgProfile = ""
}
// GetRootCmd returns the root command for testing.
func GetRootCmd() *cobra.Command {
return rootCmd
}
// Helper function for required flag errors
func newRequiredFlagError(flag string) error {
return errors.NewInvalidArgsError("required flag --" + flag + " not provided")
}