-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1815 lines (1629 loc) · 49 KB
/
main.go
File metadata and controls
1815 lines (1629 loc) · 49 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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"embed"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/fs"
"net/url"
"os"
"path/filepath"
"runtime/debug"
"sort"
"strconv"
"strings"
"time"
"github.com/alexeyco/simpletable"
"github.com/mattn/go-runewidth"
"github.com/rest-sh/restish/cli"
"github.com/rest-sh/restish/oauth"
"github.com/rest-sh/restish/openapi"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"golang.org/x/term"
)
var version string = "dev"
const defaultAPIBase = "https://api.doit.com"
// apiBase returns the API base URL, allowing override via DCI_API_BASE_URL.
func apiBase() (string, error) {
v := strings.TrimSpace(os.Getenv("DCI_API_BASE_URL"))
if v == "" {
return defaultAPIBase, nil
}
u, err := url.Parse(v)
if err != nil {
return "", fmt.Errorf("invalid DCI_API_BASE_URL: %w", err)
}
if u.Scheme != "https" {
return "", fmt.Errorf("DCI_API_BASE_URL must use https:// scheme (got %q)", u.Scheme)
}
return strings.TrimRight(v, "/"), nil
}
//go:embed skills/dci-cli
var skillFS embed.FS
// customerContextFlagValue holds the --customer-context / -D flag value when
// set, used to suppress the Doer hint even when no persistent context file exists.
var customerContextFlagValue string
func dciConfigDir() string {
if dir, err := os.UserConfigDir(); err == nil && dir != "" {
cfgDir := filepath.Join(dir, "dci")
// Prefer existing config directories to avoid breaking users on macOS.
if _, err := os.Stat(cfgDir); err == nil {
return cfgDir
}
legacy := filepath.Join(os.Getenv("HOME"), "Library", "Application Support", "dci")
if _, err := os.Stat(legacy); err == nil {
return legacy
}
return cfgDir
}
return filepath.Join(os.Getenv("HOME"), "Library", "Application Support", "dci")
}
func ensureConfig(configDir string) (bool, error) {
configFile := filepath.Join(configDir, "apis.json")
base, err := apiBase()
if err != nil {
return false, err
}
if _, err := os.Stat(configFile); err == nil {
if err := tightenFilePermissions(configFile, 0o600); err != nil {
fmt.Fprintf(os.Stderr, "warning: unable to tighten config permissions for %s: %v\n", configFile, err)
}
// When DCI_API_BASE_URL is set, update the base URL in the existing config.
if os.Getenv("DCI_API_BASE_URL") != "" {
if err := updateConfigBase(configFile, base); err != nil {
return false, err
}
}
return false, nil
} else if !os.IsNotExist(err) {
return false, err
}
if err := os.MkdirAll(configDir, 0o755); err != nil {
return false, err
}
config := map[string]interface{}{
"$schema": "https://rest.sh/schemas/apis.json",
"dci": map[string]interface{}{
"base": base,
"profiles": map[string]interface{}{
"default": map[string]interface{}{
"auth": map[string]interface{}{
"name": "oauth-authorization-code",
"params": map[string]interface{}{
"authorize_url": "https://console.doit.com/sign-in/oauth",
"client_id": "cli",
"token_url": "https://console.doit.com/api/auth/token",
},
},
},
},
"tls": map[string]interface{}{},
},
}
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return false, err
}
if err := os.WriteFile(configFile, data, 0o600); err != nil {
return false, err
}
return true, nil
}
// updateConfigBase reads apis.json, updates the dci.base field, and rewrites the file.
func updateConfigBase(configFile, base string) error {
data, err := os.ReadFile(configFile)
if err != nil {
return err
}
var config map[string]interface{}
if err := json.Unmarshal(data, &config); err != nil {
return err
}
dci, ok := config["dci"].(map[string]interface{})
if !ok {
return nil // unexpected structure, leave as-is
}
if dci["base"] == base {
return nil // already up to date
}
dci["base"] = base
out, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
return os.WriteFile(configFile, out, 0o600)
}
func tightenFilePermissions(path string, desired os.FileMode) error {
info, err := os.Stat(path)
if err != nil {
return err
}
perm := info.Mode().Perm()
if perm&^desired == 0 {
return nil
}
return os.Chmod(path, desired)
}
func printFirstRunOnboarding(configured bool) {
if !configured || !term.IsTerminal(int(os.Stderr.Fd())) {
return
}
fmt.Fprintln(os.Stderr, "DoiT Cloud Intelligence CLI is ready.")
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Next steps:")
fmt.Fprintln(os.Stderr, " dci status")
fmt.Fprintln(os.Stderr, " dci list-budgets")
fmt.Fprintln(os.Stderr, " dci list-reports --output table")
fmt.Fprintln(os.Stderr, "")
}
func main() {
os.Exit(run())
}
func run() (exitCode int) {
// Reset per-invocation state so repeated calls (e.g. in tests) start clean.
customerContextFlagValue = ""
defer func() {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "dci encountered an internal error: %v\n", r)
if os.Getenv("DCI_DEBUG_PANIC") == "1" {
debug.PrintStack()
}
exitCode = 1
}
}()
configDir := dciConfigDir()
configured, err := ensureConfig(configDir)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to initialize config: %v\n", err)
return 1
}
cli.Init("dci", version)
cli.Defaults()
overrideTableOutput()
printFirstRunOnboarding(configured)
cli.AddLoader(openapi.New())
cli.AddAuth("oauth-authorization-code", &oauth.AuthorizationCodeHandler{})
if err := rejectProfileFlags(os.Args); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return 1
}
// Keep profile fixed until we support multi-profile UX.
os.Setenv("RSH_PROFILE", "default")
viper.Set("rsh-profile", "default")
// Hardcode user-agent so the DCI API can identify CLI traffic.
// Restish picks this up via rsh-header and skips its own default.
viper.Set("rsh-header", []string{"user-agent:dci/" + version})
cli.Load("dci", cli.Root)
applyAPIKeyAuth()
brandRootCommand()
brandDCIRootCommand()
registerStatusCommands(configDir)
registerAuthCommands(configDir)
registerCustomerContextCommands(configDir)
registerSkillCommands()
// Unhide the customer-context command for DoiT employees so it appears in help.
if cachedTokenIsDoer() {
for _, c := range cli.Root.Commands() {
if c.Use == "customer-context" {
c.Hidden = false
break
}
}
}
addOutputFlag()
hideGlobalFlags()
customizeDCIUsage()
applyCustomerContext(configDir)
lockToDCI()
setupCompletion()
os.Args = normalizeArgs(os.Args)
if err := cli.Run(); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
maybeHintDoerContext(1, cli.GetLastStatus(), configDir)
return 1
}
code := cli.GetExitCode()
maybeHintDoerContext(code, cli.GetLastStatus(), configDir)
return code
}
func rejectProfileFlags(args []string) error {
flags := cli.Root.PersistentFlags()
for _, arg := range args[1:] {
if arg == "--" {
// Everything after `--` is a positional operand.
return nil
}
if arg == "--profile" || arg == "--rsh-profile" || strings.HasPrefix(arg, "--profile=") || strings.HasPrefix(arg, "--rsh-profile=") {
return fmt.Errorf("profile selection is currently disabled")
}
if !strings.HasPrefix(arg, "-") || strings.HasPrefix(arg, "--") || arg == "-" {
continue
}
shorts := strings.TrimPrefix(arg, "-")
if shorts == "" {
continue
}
if beforeEq, _, ok := strings.Cut(shorts, "="); ok {
shorts = beforeEq
}
for i := 0; i < len(shorts); i++ {
ch := string(shorts[i])
if ch == "p" {
return fmt.Errorf("profile selection is currently disabled")
}
flag := flags.ShorthandLookup(ch)
if flag != nil && !isBoolFlag(flag) {
// Remaining bytes belong to this flag's value.
break
}
}
}
return nil
}
func normalizeArgs(args []string) []string {
if len(args) <= 1 {
return []string{args[0], "--help"}
}
cmd := firstCommandArg(args)
if cmd == "" || cmd == "help" || cmd == "version" || cmd == "completion" || isRootCommand(cmd) {
return args
}
// __complete and __completeNoDesc are hidden cobra commands invoked by
// shell completion scripts. The args after them mirror user input and
// need the same "dci" prefix insertion so cobra resolves completions
// under the API subcommand.
if cmd == "__complete" || cmd == "__completeNoDesc" {
return normalizeCompletionArgs(args, cmd)
}
return append([]string{args[0], "dci"}, args[1:]...)
}
// normalizeCompletionArgs inserts "dci" after __complete/__completeNoDesc when
// the completion target is an API command (not a root command). This mirrors
// normalizeArgs so that tab-completion resolves under the API subcommand.
func normalizeCompletionArgs(args []string, completionCmd string) []string {
// Find the position of __complete/__completeNoDesc.
idx := -1
for i, a := range args {
if a == completionCmd {
idx = i
break
}
}
if idx < 0 || idx+1 >= len(args) {
return args
}
// Check the first arg after the completion command — if it's a root
// command (or empty), let cobra handle it at root level.
tail := args[idx+1:]
first := ""
for _, a := range tail {
if !strings.HasPrefix(a, "-") {
first = a
break
}
}
if first == "" || first == "help" || isRootCommand(first) {
return args
}
// Insert "dci" after the completion command to route into the API subcommand.
result := make([]string, 0, len(args)+1)
result = append(result, args[:idx+1]...)
result = append(result, "dci")
result = append(result, tail...)
return result
}
func firstCommandArg(args []string) string {
flags := cli.Root.PersistentFlags()
for i := 1; i < len(args); i++ {
arg := args[i]
if arg == "--" {
if i+1 < len(args) {
return args[i+1]
}
return ""
}
if !strings.HasPrefix(arg, "-") || arg == "-" {
return arg
}
// Long flag.
if strings.HasPrefix(arg, "--") {
name, hasValue := splitLongFlag(arg)
if name == "" {
continue
}
if hasValue {
continue
}
flag := flags.Lookup(name)
if flag != nil && !isBoolFlag(flag) && i+1 < len(args) {
i++
}
continue
}
// Short flag(s), including compact values (e.g. -pfoo).
shorts := arg[1:]
for j := 0; j < len(shorts); j++ {
flag := flags.ShorthandLookup(string(shorts[j]))
if flag == nil {
continue
}
if isBoolFlag(flag) {
continue
}
if j == len(shorts)-1 && i+1 < len(args) {
i++
}
break
}
}
return ""
}
func splitLongFlag(arg string) (name string, hasValue bool) {
s := strings.TrimPrefix(arg, "--")
if s == "" {
return "", false
}
if n, _, ok := strings.Cut(s, "="); ok {
return n, true
}
return s, false
}
func isBoolFlag(flag *pflag.Flag) bool {
if flag == nil || flag.Value == nil {
return false
}
return flag.Value.Type() == "bool"
}
func isRootCommand(name string) bool {
for _, cmd := range cli.Root.Commands() {
if cmd.Name() == name {
return true
}
for _, alias := range cmd.Aliases {
if alias == name {
return true
}
}
}
return false
}
func hideGlobalFlags() {
// Keep the flags functional but hide them from help output.
cli.Root.PersistentFlags().VisitAll(func(f *pflag.Flag) {
f.Hidden = true
})
}
const dciUsageTemplate = `Usage:{{if .Runnable}}
{{.Use}}{{if .HasAvailableFlags}} [flags]{{end}}{{end}}{{if .HasAvailableSubCommands}}
dci [command]
dci [command] --help{{else}}
{{.Use}} --help{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}
Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}{{if hasVisibleCommandsInGroup $cmds $group.ID}}
{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}
Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if or .HasAvailableLocalFlags .HasAvailableInheritedFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{if .HasAvailableInheritedFlags}}
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}
`
const dciLongDescription = "Command-line interface for the DoiT Cloud Intelligence API."
var rootExamples = []string{
" dci status",
" dci list-budgets",
" dci list-reports --output table",
}
var apiExamples = []string{
" dci list-budgets",
" dci list-reports --output table",
" dci query body.query:\"SELECT * FROM aws_cur_2_0 LIMIT 10\"",
}
func findDCICommand() *cobra.Command {
for _, cmd := range cli.Root.Commands() {
if cmd.Name() == "dci" {
return cmd
}
}
return nil
}
func customizeDCIUsage() {
cobra.AddTemplateFunc("hasVisibleCommandsInGroup", func(cmds []*cobra.Command, groupID string) bool {
for _, cmd := range cmds {
if cmd.GroupID == groupID && (cmd.IsAvailableCommand() || cmd.Name() == "help") {
return true
}
}
return false
})
dciCmd := findDCICommand()
if dciCmd == nil {
return
}
var walk func(c *cobra.Command)
walk = func(c *cobra.Command) {
c.SetUsageTemplate(dciUsageTemplate)
for _, child := range c.Commands() {
walk(child)
}
}
walk(dciCmd)
}
func applyCommandBranding(cmd *cobra.Command, short string, examples []string) {
if cmd == nil {
return
}
cmd.Short = short
cmd.Long = dciLongDescription
cmd.Example = strings.Join(examples, "\n")
}
func brandRootCommand() {
applyCommandBranding(cli.Root, "DoiT Cloud Intelligence CLI", rootExamples)
cli.Root.SetUsageTemplate(dciUsageTemplate)
}
func lockToDCI() {
// Remove API management commands, generic RESTish commands, and any
// additional API entrypoints so users can only call the DCI API.
allowed := map[string]bool{
"completion": true,
"dci": true,
"help": true,
"login": true,
"logout": true,
}
toRemove := make([]*cobra.Command, 0)
for _, cmd := range cli.Root.Commands() {
if allowed[cmd.Name()] {
continue
}
if cmd.Name() == "api" || cmd.GroupID == "generic" || (cmd.GroupID == "api" && cmd.Name() != "dci") {
toRemove = append(toRemove, cmd)
}
}
for _, cmd := range toRemove {
cli.Root.RemoveCommand(cmd)
}
}
// setupCompletion configures shell completion and root help so that API
// commands appear at root level (alongside status, login, etc.).
//
// The "dci" API subcommand is hidden since users access its commands directly
// via normalizeArgs. Its ValidArgsFunction (which returns URL paths from
// restish) is cleared so completions show command names instead.
//
// Restish lazily loads API operations inside cli.Run() by inspecting os.Args
// for the API name. For root-level completion and help, restish skips loading
// because __complete and --help args are filtered out. We work around this by
// triggering the load on demand.
func setupCompletion() {
var dciCmd *cobra.Command
for _, cmd := range cli.Root.Commands() {
if cmd.Name() == "dci" {
dciCmd = cmd
break
}
}
if dciCmd == nil {
return
}
// Hide the "dci" namespace — users interact with API commands at root level.
dciCmd.Hidden = true
// Clear restish's ValidArgsFunction that returns URL paths.
dciCmd.ValidArgsFunction = nil
// loadAPI triggers lazy API loading into the dci subcommand. Restish's
// cli.Run() normally does this by parsing os.Args, but --help and
// __complete are filtered out so we must load explicitly.
//
// To avoid triggering OAuth when no auth is cached, we only call
// cli.Load when restish's API cache file exists. If it doesn't, the
// user hasn't authenticated yet and API commands won't be shown until
// they run "dci login".
var apiLoaded bool
loadAPI := func() {
if apiLoaded {
return
}
apiLoaded = true
cacheDir, _ := os.UserCacheDir()
cacheFile := filepath.Join(cacheDir, "dci", "dci.cbor")
if _, err := os.Stat(cacheFile); err != nil {
return
}
base, err := apiBase()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return
}
cli.Load(base, dciCmd)
}
// Surface API subcommands in root-level completion so "dci <Tab>"
// shows list-budgets, list-reports, etc. alongside status, login, etc.
cli.Root.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
loadAPI()
var completions []string
for _, sub := range dciCmd.Commands() {
if sub.Hidden {
continue
}
if strings.HasPrefix(sub.Name(), toComplete) {
completions = append(completions, sub.Name()+"\t"+sub.Short)
}
}
return completions, cobra.ShellCompDirectiveNoFileComp
}
// Override root help to include API commands. Load the API, move its
// commands to root so the standard usage template renders them, then
// show help normally.
defaultHelp := cli.Root.HelpFunc()
cli.Root.SetHelpFunc(func(cmd *cobra.Command, args []string) {
hasAPICommands := false
if cmd == cli.Root {
loadAPI()
hasAPICommands = len(dciCmd.Commands()) > 0
// Copy command groups from the API subcommand to root so the
// usage template can render grouped commands.
for _, g := range dciCmd.Groups() {
if !cli.Root.ContainsGroup(g.ID) {
cli.Root.AddGroup(g)
}
}
// Collect first — iterating Commands() while removing mutates the slice.
subs := make([]*cobra.Command, len(dciCmd.Commands()))
copy(subs, dciCmd.Commands())
for _, sub := range subs {
dciCmd.RemoveCommand(sub)
cli.Root.AddCommand(sub)
}
}
defaultHelp(cmd, args)
if cmd == cli.Root && !hasAPICommands {
hint := "\n! To get started, authenticate with: dci login (or set DCI_API_KEY)\n\n"
if term.IsTerminal(int(os.Stdout.Fd())) {
hint = "\n\033[1;33m!\033[0m To get started, authenticate with: \033[1mdci login\033[0m (or set \033[1mDCI_API_KEY\033[0m)\n\n"
}
fmt.Fprint(os.Stdout, hint)
}
})
}
func registerCustomerContextCommands(configDir string) {
cmd := &cobra.Command{
Use: "customer-context",
Short: "Manage default customerContext for requests",
Hidden: true,
}
cmd.AddCommand(&cobra.Command{
Use: "set TOKEN",
Short: "Set the default customerContext",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
token := strings.TrimSpace(args[0])
if token == "" {
return fmt.Errorf("customerContext cannot be empty")
}
if err := os.WriteFile(customerContextPath(configDir), []byte(token+"\n"), 0o600); err != nil {
return err
}
fmt.Fprintln(os.Stdout, "customerContext saved")
return nil
},
})
cmd.AddCommand(&cobra.Command{
Use: "clear",
Short: "Clear the default customerContext",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if err := os.Remove(customerContextPath(configDir)); err != nil && !os.IsNotExist(err) {
return err
}
fmt.Fprintln(os.Stdout, "customerContext cleared")
return nil
},
})
cmd.AddCommand(&cobra.Command{
Use: "show",
Short: "Show the current default customerContext",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if ctx := readCustomerContext(configDir); ctx != "" {
fmt.Fprintln(os.Stdout, ctx)
} else {
fmt.Fprintln(os.Stdout, "customerContext not set")
}
return nil
},
})
cli.Root.AddCommand(cmd)
}
// installSkill copies embedded skill files into targetDir/skills/dci-cli/.
func installSkill(targetDir string) error {
const srcRoot = "skills/dci-cli"
destRoot := filepath.Join(targetDir, "skills", "dci-cli")
return fs.WalkDir(skillFS, srcRoot, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(srcRoot, path)
if err != nil {
return err
}
dest := filepath.Join(destRoot, rel)
if d.IsDir() {
return os.MkdirAll(dest, 0o755)
}
data, err := skillFS.ReadFile(path)
if err != nil {
return err
}
return os.WriteFile(dest, data, 0o644)
})
}
func registerSkillCommands() {
agents := []struct {
name string
dir string
}{
{"claude", ".claude"},
{"codex", ".codex"},
{"kiro", ".kiro"},
{"gemini", ".gemini"},
}
cmd := &cobra.Command{
Use: "skill",
Short: "Install the dci skill for an AI agent",
}
for _, a := range agents {
agentName := a.name
agentDir := a.dir
cmd.AddCommand(&cobra.Command{
Use: agentName,
Short: fmt.Sprintf("Install skill into ~/%s/skills/dci-cli/", agentDir),
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("cannot determine home directory: %w", err)
}
targetDir := filepath.Join(home, agentDir)
if err := installSkill(targetDir); err != nil {
return fmt.Errorf("failed to install skill: %w", err)
}
fmt.Fprintf(os.Stdout, "Skill installed to %s\n", filepath.Join(targetDir, "skills", "dci-cli"))
return nil
},
})
}
cli.Root.AddCommand(cmd)
}
func brandDCIRootCommand() {
applyCommandBranding(findDCICommand(), "DoiT Cloud Intelligence API CLI", apiExamples)
}
func registerStatusCommands(configDir string) {
currentOutput := func() string {
output := strings.TrimSpace(viper.GetString("rsh-output-format"))
if output == "" || output == "auto" {
output = "table"
}
return output
}
renderStatus := func(cmd *cobra.Command, args []string) error {
ctx := readCustomerContext(configDir)
base, err := apiBase()
if err != nil {
return err
}
fmt.Fprintln(os.Stdout, "DoiT Cloud Intelligence")
if os.Getenv("DCI_API_BASE_URL") != "" {
fmt.Fprintf(os.Stdout, "API Base: %s (DCI_API_BASE_URL)\n", base)
} else {
fmt.Fprintf(os.Stdout, "API Base: %s\n", base)
}
fmt.Fprintf(os.Stdout, "Auth: %s\n", authSource())
fmt.Fprintf(os.Stdout, "Default Output: %s\n", currentOutput())
fmt.Fprintf(os.Stdout, "Config Dir: %s\n", configDir)
if ctx != "" {
if os.Getenv("DCI_CUSTOMER_CONTEXT") != "" {
fmt.Fprintf(os.Stdout, "Customer context: %s (DCI_CUSTOMER_CONTEXT)\n", ctx)
} else {
fmt.Fprintf(os.Stdout, "Customer context: %s\n", ctx)
}
}
return nil
}
cli.Root.AddCommand(&cobra.Command{
Use: "status",
Short: "Show DoiT CLI configuration and active context",
Args: cobra.NoArgs,
RunE: renderStatus,
})
}
// applyAPIKeyAuth injects DCI_API_KEY into restish's auth cache as a Bearer
// token. Restish's OAuth TokenHandler checks the cache before triggering a
// browser flow, so pre-populating it bypasses interactive login. We use
// cli.Cache (an exported *viper.Viper) because restish does not export its
// config internals (the configs map and apis viper instance are private).
func applyAPIKeyAuth() {
apiKey := os.Getenv("DCI_API_KEY")
if apiKey == "" {
return
}
profile := viper.GetString("rsh-profile")
key := "dci:" + profile
cli.Cache.Set(key+".token", apiKey)
cli.Cache.Set(key+".type", "Bearer")
cli.Cache.Set(key+".expires", "9999-12-31T23:59:59Z")
cli.Cache.Set(key+".refresh", "")
}
func authSource() string {
if os.Getenv("DCI_API_KEY") != "" {
return "API key (DCI_API_KEY)"
}
return "OAuth (DoiT Console)"
}
// maybeHintDoerContext prints a targeted hint when a @doit.com user hits a 403
// without a customer context set — covering both interactive and CI/CD usage.
// status is the HTTP status code from the last request (pass cli.GetLastStatus()).
func maybeHintDoerContext(exitCode int, status int, configDir string) {
if exitCode == 0 || (status != 401 && status != 403) {
return
}
if !cachedTokenIsDoer() {
return
}
if readCustomerContext(configDir) != "" || customerContextFlagValue != "" {
return
}
if term.IsTerminal(int(os.Stderr.Fd())) {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintf(os.Stderr, "\033[1;33m!\033[0m DoiT employees need a customer context for API calls.\n")
fmt.Fprintf(os.Stderr, " Interactive: \033[1mdci customer-context set doit.com\033[0m\n")
fmt.Fprintf(os.Stderr, " CI/scripts: \033[1mexport DCI_CUSTOMER_CONTEXT=doit.com\033[0m\n")
fmt.Fprintln(os.Stderr, "")
} else {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "! DoiT employees need a customer context for API calls.")
fmt.Fprintln(os.Stderr, " Interactive: dci customer-context set doit.com")
fmt.Fprintln(os.Stderr, " CI/scripts: export DCI_CUSTOMER_CONTEXT=doit.com")
fmt.Fprintln(os.Stderr, "")
}
}
// applyDoerContext auto-configures the customer context to "doit.com" for
// @doit.com accounts that haven't set one yet. The validate endpoint requires
// customerContext for DoiT employees; calling this after the OAuth token is
// cached fixes the chicken-and-egg problem on first login. Returns true if the
// context was written so the caller can clear a 403 error from validate.
func applyDoerContext(configDir string) bool {
if !cachedTokenIsDoer() {
return false
}
if readCustomerContext(configDir) != "" {
return false // already configured, don't overwrite
}
err := os.WriteFile(customerContextPath(configDir), []byte("doit.com\n"), 0o600)
if err != nil {
return false
}
fmt.Fprintln(os.Stderr, "Detected DoiT account. Set default customer context to 'doit.com'.")
fmt.Fprintln(os.Stderr, "To use a different context: dci customer-context set <CONTEXT>")
return true
}
// cachedTokenIsDoer reports whether the cached OAuth JWT contains
// DoitEmployee: true. This is more reliable than email-domain matching because
// it is an explicit claim set by the DoiT auth server and is domain-independent.
// Returns false if the cache is empty, the token is absent, or the JWT is malformed.
func cachedTokenIsDoer() bool {
if cli.Cache == nil {
return false
}
token := cli.Cache.GetString("dci:default.token")
if token == "" {
return false
}
parts := strings.Split(token, ".")
if len(parts) != 3 {
return false
}
// JWT payload is base64url-encoded without padding.
b, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return false
}
var claims struct {
DoitEmployee bool `json:"DoitEmployee"`
}
if err := json.Unmarshal(b, &claims); err != nil {
return false
}
return claims.DoitEmployee
}
func registerAuthCommands(configDir string) {
cli.Root.AddCommand(&cobra.Command{
Use: "login",
Aliases: []string{"auth", "init"},
Short: "Authenticate with the DoiT Console",
Long: "Opens a browser window to sign in via the DoiT Console. Credentials are cached locally for subsequent commands.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if os.Getenv("DCI_API_KEY") != "" {
return fmt.Errorf("login is not needed when DCI_API_KEY is set")
}
// Trigger the OAuth flow by calling a lightweight endpoint.
// Suppress the validate response body — login only needs the OAuth
// side effect (token cached), not the API output.
os.Args = []string{os.Args[0], "dci", "validate"}
oldOut := cli.Stdout
cli.Stdout = io.Discard
err := cli.Run()
cli.Stdout = oldOut
// Auto-configure DoiT employees who have no customer context set.
// The validate endpoint requires customerContext for @doit.com accounts,
// causing a 403 on first login before any context is configured. The OAuth
// token exchange succeeds (token is cached) even when validate returns 403,
// so we can inspect the token here and fix the chicken-and-egg problem.
if applyDoerContext(configDir) {
err = nil // the 403 was due to missing context; auth itself succeeded
// Reset the HTTP status so GetExitCode() returns 0 for this process.
viper.Set("rsh-ignore-status-code", true)
}
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, "Authenticated successfully.")
return nil
},
})
cli.Root.AddCommand(&cobra.Command{
Use: "logout",
Short: "Clear stored authentication credentials",
Long: "Removes cached OAuth tokens. You will need to sign in again on the next API call.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if os.Getenv("DCI_API_KEY") != "" {
return fmt.Errorf("logout has no effect when DCI_API_KEY is set; unset the environment variable instead")
}
profile := viper.GetString("rsh-profile")
key := "dci:" + profile