-
-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathroot.go
More file actions
1880 lines (1636 loc) · 66.6 KB
/
root.go
File metadata and controls
1880 lines (1636 loc) · 66.6 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 cmd
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/charmbracelet/lipgloss"
xterm "github.com/charmbracelet/x/term"
"github.com/elewis787/boa"
"github.com/muesli/reflow/wordwrap"
"github.com/muesli/termenv"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
errUtils "github.com/cloudposse/atmos/errors"
e "github.com/cloudposse/atmos/internal/exec"
"github.com/cloudposse/atmos/internal/tui/templates"
"github.com/cloudposse/atmos/internal/tui/templates/term"
atmosansi "github.com/cloudposse/atmos/pkg/ansi"
cfg "github.com/cloudposse/atmos/pkg/config"
// Import adapters to register them with the config package.
_ "github.com/cloudposse/atmos/pkg/config/adapters"
// Import component providers to register them with the component registry.
// The init() function in each package registers the provider.
_ "github.com/cloudposse/atmos/pkg/component/ansible"
_ "github.com/cloudposse/atmos/pkg/component/mock"
"github.com/cloudposse/atmos/pkg/data"
"github.com/cloudposse/atmos/pkg/filesystem"
"github.com/cloudposse/atmos/pkg/flags"
"github.com/cloudposse/atmos/pkg/flags/compat"
iolib "github.com/cloudposse/atmos/pkg/io"
log "github.com/cloudposse/atmos/pkg/logger"
"github.com/cloudposse/atmos/pkg/pager"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/profiler"
"github.com/cloudposse/atmos/pkg/schema"
"github.com/cloudposse/atmos/pkg/telemetry"
"github.com/cloudposse/atmos/pkg/terminal"
"github.com/cloudposse/atmos/pkg/ui"
"github.com/cloudposse/atmos/pkg/ui/heatmap"
"github.com/cloudposse/atmos/pkg/ui/markdown"
"github.com/cloudposse/atmos/pkg/ui/theme"
"github.com/cloudposse/atmos/pkg/utils"
pkgversion "github.com/cloudposse/atmos/pkg/version"
// Import built-in command packages for side-effect registration.
// The init() function in each package registers the command with the registry.
_ "github.com/cloudposse/atmos/cmd/about"
_ "github.com/cloudposse/atmos/cmd/ansible"
_ "github.com/cloudposse/atmos/cmd/aws"
"github.com/cloudposse/atmos/cmd/devcontainer"
_ "github.com/cloudposse/atmos/cmd/env"
_ "github.com/cloudposse/atmos/cmd/helmfile"
"github.com/cloudposse/atmos/cmd/internal"
_ "github.com/cloudposse/atmos/cmd/list"
_ "github.com/cloudposse/atmos/cmd/profile"
_ "github.com/cloudposse/atmos/cmd/terraform"
"github.com/cloudposse/atmos/cmd/terraform/backend"
"github.com/cloudposse/atmos/cmd/terraform/workdir"
themeCmd "github.com/cloudposse/atmos/cmd/theme"
toolchainCmd "github.com/cloudposse/atmos/cmd/toolchain"
_ "github.com/cloudposse/atmos/cmd/vendor"
"github.com/cloudposse/atmos/cmd/version"
_ "github.com/cloudposse/atmos/cmd/workflow"
"github.com/cloudposse/atmos/pkg/toolchain"
)
const (
// LogFileMode is the file mode for log files.
logFileMode = 0o644
// DefaultTopFunctionsMax is the default number of top functions to display in performance summary.
defaultTopFunctionsMax = 50
// VerboseFlagName is the name of the verbose flag.
verboseFlagName = "verbose"
// AnsiEscapePrefix is the ANSI escape sequence prefix.
ansiEscapePrefix = "\x1b["
)
// atmosConfig This is initialized before everything in the Execute function. So we can directly use this.
var atmosConfig schema.AtmosConfiguration
// profilerServer holds the global profiler server instance.
var profilerServer *profiler.Server
// logFileHandle holds the opened log file for the lifetime of the program.
var logFileHandle *os.File
// chdirProcessed tracks whether chdir has already been processed to avoid double-processing.
var chdirProcessed bool
// parseChdirFromArgs manually parses --chdir or -C flag from os.Args.
// This is needed for commands with DisableFlagParsing=true (terraform, helmfile, packer)
// parseChdirFromArgs scans the process arguments for a chdir flag and returns the specified path if present.
// It recognizes `--chdir=value`, `--chdir value`, `-C=value`, `-Cvalue`, and `-C value` forms.
// If no chdir flag is found, it returns an empty string.
func parseChdirFromArgs() string {
return parseChdirFromArgsInternal(os.Args)
}
// parseUseVersionFromArgs manually parses --use-version flag from os.Args.
// This is needed for commands with DisableFlagParsing=true (terraform, helmfile, packer)
// where Cobra doesn't parse flags automatically.
// It recognizes `--use-version=value` and `--use-version value` forms.
// If no --use-version flag is found, it returns an empty string.
func parseUseVersionFromArgs() string {
return parseUseVersionFromArgsInternal(os.Args)
}
// parseUseVersionFromArgsInternal manually parses --use-version flag from the provided args.
// This internal version accepts args as a parameter for testability.
func parseUseVersionFromArgsInternal(args []string) string {
for i := 0; i < len(args); i++ {
arg := args[i]
// Stop scanning after bare "--" (end-of-flags delimiter).
if arg == "--" {
break
}
// Check for --use-version=value format.
if strings.HasPrefix(arg, "--use-version=") {
return strings.TrimPrefix(arg, "--use-version=")
}
// Check for --use-version value format (next arg is the value).
if arg == "--use-version" {
if i+1 < len(args) {
return args[i+1]
}
}
}
return ""
}
// parseChdirFromArgsInternal manually parses --chdir or -C flag from the provided args.
// This internal version accepts args as a parameter for testability.
func parseChdirFromArgsInternal(args []string) string {
for i := 0; i < len(args); i++ {
arg := args[i]
// Stop scanning after bare "--" (end-of-flags delimiter).
if arg == "--" {
break
}
// Check for --chdir=value format.
if strings.HasPrefix(arg, "--chdir=") {
return strings.TrimPrefix(arg, "--chdir=")
}
// Check for -C=value format.
if strings.HasPrefix(arg, "-C=") {
return strings.TrimPrefix(arg, "-C=")
}
// Check for -C<value> format (concatenated, e.g., -C../foo).
if strings.HasPrefix(arg, "-C") && len(arg) > 2 {
return arg[2:]
}
// Check for --chdir value or -C value format (next arg is the value).
if arg == "--chdir" || arg == "-C" {
if i+1 < len(args) {
return args[i+1]
}
}
}
return ""
}
// processEarlyChdirFlag processes --chdir flag before RootCmd is fully initialized.
// This is called in Execute() before loading atmos.yaml to ensure the config is loaded
// processEarlyChdirFlag changes the current working directory based on the first
// occurrence of the `--chdir`/`-C` flag (parsed from os.Args) or the ATMOS_CHDIR
// environment variable, expanding `~`, resolving to an absolute path, and
// validating that the target exists and is a directory.
// It returns nil on success or an error describing why the directory could not
// be resolved or changed.
func processEarlyChdirFlag() error {
// If chdir already processed, skip (avoid double-processing).
if chdirProcessed {
return nil
}
// Parse --chdir from os.Args since we can't use Cobra flags yet.
chdir := parseChdirFromArgs()
// If flag is not set, check environment variable.
if chdir == "" {
//nolint:forbidigo // Must use os.Getenv: chdir is processed before Viper configuration loads.
chdir = os.Getenv("ATMOS_CHDIR")
}
if chdir == "" {
return nil // No chdir specified.
}
// Expand tilde to home directory using filesystem package.
homeDirProvider := filesystem.NewOSHomeDirProvider()
expandedPath, err := homeDirProvider.Expand(chdir)
if err != nil {
return fmt.Errorf("%w: %w", errUtils.ErrPathResolution, err)
}
// Clean and make absolute to handle both relative and absolute paths.
absPath, err := filepath.Abs(expandedPath)
if err != nil {
return fmt.Errorf("%w: invalid chdir path: %s", errUtils.ErrPathResolution, chdir)
}
// Verify the directory exists before attempting to change to it.
stat, err := os.Stat(absPath)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("%w: directory does not exist: %s", errUtils.ErrWorkdirNotExist, absPath)
}
return fmt.Errorf("%w: failed to access directory: %s", errUtils.ErrStatFile, absPath)
}
if !stat.IsDir() {
return fmt.Errorf("%w: not a directory: %s", errUtils.ErrWorkdirNotExist, absPath)
}
// Change to the specified directory.
if err := os.Chdir(absPath); err != nil {
return fmt.Errorf("%w: failed to change directory to %s", errUtils.ErrPathResolution, absPath)
}
// Mark as processed to avoid double-processing in PersistentPreRun.
chdirProcessed = true
return nil
}
// syncGlobalFlagsToViper synchronizes global flags from Cobra's FlagSet to Viper.
// This is necessary because Viper's BindPFlag doesn't immediately sync values when flags are parsed.
// Call this after Cobra parses flags but before accessing flag values via Viper.
//
// Background: When using viper.BindPFlag(), the binding happens at initialization time,
// but the actual flag value isn't synced to Viper until you call viper.Get*().
// For some code paths (especially in InitCliConfig), we need the flag values
// available in Viper before config loading completes.
//
// This function explicitly syncs changed flags to Viper, making their values
// immediately available via viper.Get*() calls.
func syncGlobalFlagsToViper(cmd *cobra.Command) {
v := viper.GetViper()
// Sync profile flag if explicitly set.
if cmd.Flags().Changed("profile") {
if profiles, err := cmd.Flags().GetStringSlice("profile"); err == nil {
v.Set("profile", profiles)
}
}
// Sync identity flag if explicitly set.
if cmd.Flags().Changed("identity") {
if identity, err := cmd.Flags().GetString("identity"); err == nil {
v.Set("identity", identity)
}
}
}
// processChdirFlag processes the --chdir flag and ATMOS_CHDIR environment variable,
// changing the working directory before any other operations.
// Precedence: --chdir flag > ATMOS_CHDIR environment variable.
// Note: This is also called from PersistentPreRun, but will be a no-op if
// processChdirFlag changes the current working directory when a chdir target is provided
// via the --chdir flag (or by parsing os.Args when flag parsing is disabled) or the
// ATMOS_CHDIR environment variable, and marks the change as processed to avoid
// double-processing.
//
// It expands a leading tilde, resolves the path to an absolute location, verifies the
// path exists and is a directory, then calls os.Chdir. If the chdir has already been
// handled, the function returns immediately. It returns an error when the path cannot
// be resolved, does not exist, is not a directory, or when changing directories fails.
func processChdirFlag(cmd *cobra.Command) error {
// If chdir already processed in Execute(), skip to avoid double-processing.
if chdirProcessed {
return nil
}
// Try to get chdir from parsed flags first (works when DisableFlagParsing=false).
chdir, _ := cmd.Flags().GetString("chdir")
// If flag parsing is disabled (terraform/helmfile/packer commands), manually parse os.Args.
// This is necessary because Cobra doesn't parse flags when DisableFlagParsing=true,
// but PersistentPreRun runs before the command's Run function where flags would be manually parsed.
if chdir == "" {
chdir = parseChdirFromArgs()
}
// If flag is not set, check environment variable.
// Note: chdir is not supported in atmos.yaml since it must be processed before atmos.yaml is loaded.
if chdir == "" {
//nolint:forbidigo // Must use os.Getenv: chdir is processed before Viper configuration loads.
chdir = os.Getenv("ATMOS_CHDIR")
}
if chdir == "" {
return nil // No chdir specified.
}
// Expand tilde to home directory using filesystem package.
homeDirProvider := filesystem.NewOSHomeDirProvider()
expandedPath, err := homeDirProvider.Expand(chdir)
if err != nil {
return fmt.Errorf("%w: %w", errUtils.ErrPathResolution, err)
}
// Clean and make absolute to handle both relative and absolute paths.
absPath, err := filepath.Abs(expandedPath)
if err != nil {
return fmt.Errorf("%w: invalid chdir path: %s", errUtils.ErrPathResolution, chdir)
}
// Verify the directory exists before attempting to change to it.
stat, err := os.Stat(absPath)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("%w: directory does not exist: %s", errUtils.ErrWorkdirNotExist, absPath)
}
return fmt.Errorf("%w: failed to access directory: %s", errUtils.ErrStatFile, absPath)
}
if !stat.IsDir() {
return fmt.Errorf("%w: not a directory: %s", errUtils.ErrWorkdirNotExist, absPath)
}
// Change to the specified directory.
if err := os.Chdir(absPath); err != nil {
return fmt.Errorf("%w: failed to change directory to %s", errUtils.ErrPathResolution, absPath)
}
// Mark as processed to avoid double-processing.
chdirProcessed = true
return nil
}
// RootCmd represents the base command when called without any subcommands.
var RootCmd = &cobra.Command{
Use: "atmos",
Short: "Framework for Infrastructure Orchestration",
Long: `Atmos is a framework for orchestrating and operating infrastructure workflows across multiple cloud and DevOps toolchains.`,
// Note: FParseErrWhitelist is NOT set on RootCmd to allow proper flag validation.
// Individual commands that need to pass through flags (terraform, helmfile, packer)
// set FParseErrWhitelist{UnknownFlags: true} explicitly.
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// Set verbose flag for error formatting before any command execution or fatal exits.
if cmd.Flags().Changed(verboseFlagName) {
// CLI flag explicitly set - use it.
verbose, flagErr := cmd.Flags().GetBool(verboseFlagName)
if flagErr != nil {
errUtils.CheckErrorPrintAndExit(flagErr, "", "")
}
errUtils.SetVerboseFlag(verbose)
} else if viper.IsSet(verboseFlagName) {
// CLI flag not set - check environment variable via Viper.
verbose := viper.GetBool(verboseFlagName)
errUtils.SetVerboseFlag(verbose)
}
// Check for conflicting flags: --version and --use-version cannot be used together.
if cmd.Flags().Changed("version") && cmd.Flags().Changed("use-version") {
conflictErr := errUtils.Build(errUtils.ErrInvalidFlag).
WithExplanation("--version and --use-version cannot be used together").
WithHint("Use --version to display the current Atmos version").
WithHint("Use --use-version to run a command with a specific Atmos version").
Err()
errUtils.CheckErrorPrintAndExit(conflictErr, "", "")
}
// Determine if the command is a help command or if the help flag is set.
isHelpCommand := cmd.Name() == "help"
helpFlag := cmd.Flags().Changed("help")
isHelpRequested := isHelpCommand || helpFlag
if isHelpRequested {
// Do not silence usage or errors when help is invoked.
cmd.SilenceUsage = false
cmd.SilenceErrors = false
} else {
cmd.SilenceUsage = true
cmd.SilenceErrors = true
}
// Process --chdir flag before any other operations (including config loading).
if err := processChdirFlag(cmd); err != nil {
errUtils.CheckErrorPrintAndExit(err, "", "")
}
// Configure lipgloss color profile early, before config loading.
// This is critical because stack processing during config load may trigger
// validation that uses theme styles. We need to set the color profile BEFORE
// those styles are accessed to ensure NO_COLOR and other settings are respected.
configureEarlyColorProfile(cmd)
// Sync global flags from Cobra to Viper before InitCliConfig.
// This ensures flag values are immediately available in Viper for config loading.
syncGlobalFlagsToViper(cmd)
configAndStacksInfo := schema.ConfigAndStacksInfo{}
// Honor CLI overrides for resolving atmos.yaml and its imports.
if bp, _ := cmd.Flags().GetString("base-path"); bp != "" {
configAndStacksInfo.AtmosBasePath = bp
}
if cfgFiles, _ := cmd.Flags().GetStringSlice("config"); len(cfgFiles) > 0 {
configAndStacksInfo.AtmosConfigFilesFromArg = cfgFiles
}
if cfgDirs, _ := cmd.Flags().GetStringSlice("config-path"); len(cfgDirs) > 0 {
configAndStacksInfo.AtmosConfigDirsFromArg = cfgDirs
}
// Load the config (includes env var bindings); don't store globally yet.
tmpConfig, err := cfg.InitCliConfig(configAndStacksInfo, false)
if err != nil {
if errors.Is(err, cfg.NotFound) {
// For help commands or when help flag is set, we don't want to show the error.
if !isHelpRequested {
log.Warn(err.Error())
}
} else if isVersionCommand() {
// Version command should always work, even with invalid config.
// Log config error but allow version command to proceed.
log.Debug("CLI configuration error (continuing for version command)", "error", err)
} else {
// Enrich config errors with helpful context.
enrichedErr := errUtils.Build(err).
WithHint("Verify your atmos.yaml syntax and configuration").
WithHint("Run 'atmos version' to check if Atmos is working").
WithExitCode(2). // Config/usage error
Err()
errUtils.CheckErrorPrintAndExit(enrichedErr, "", "")
}
}
// Check for version.use configuration and re-exec with specified version if needed.
// This runs after profiles are loaded, so version.use can be set via profiles.
if !isHelpRequested && err == nil {
// Check if explicit --use-version flag was provided.
var explicitVersionRequested bool
var explicitVersion string
// First try Cobra's parsed flag (works when DisableFlagParsing=false).
if cmd.Flags().Changed("use-version") {
if useVersion, flagErr := cmd.Flags().GetString("use-version"); flagErr == nil && useVersion != "" {
explicitVersion = useVersion
explicitVersionRequested = true
}
}
// For commands with DisableFlagParsing=true (terraform, helmfile, packer),
// manually parse --use-version from os.Args.
if !explicitVersionRequested {
if useVersion := parseUseVersionFromArgs(); useVersion != "" {
explicitVersion = useVersion
explicitVersionRequested = true
}
}
// Set ATMOS_VERSION_USE env var if explicit flag was provided.
if explicitVersionRequested {
_ = os.Setenv(pkgversion.VersionUseEnvVar, explicitVersion)
}
// Skip re-exec for version management commands (to avoid loops),
// unless an explicit --use-version flag was provided.
shouldReexec := explicitVersionRequested || !isVersionManagementCommand(cmd)
if shouldReexec {
// CheckAndReexec returns true only on successful syscall.Exec, which replaces
// the current process entirely. This means true is never returned in practice
// since exec doesn't return. We call it for its side effects.
_ = pkgversion.CheckAndReexec(&tmpConfig)
}
}
// Setup profiler before command execution (but skip for help commands).
if !isHelpRequested {
if setupErr := setupProfiler(cmd, &tmpConfig); setupErr != nil {
errUtils.CheckErrorPrintAndExit(setupErr, "Failed to setup profiler", "")
}
}
// Note: --version flag is now handled in main.go before Execute() for production use.
// For tests that use RootCmd.SetArgs(["--version"]), we don't need special handling here
// since tests expect normal command flow without os.Exit.
// Enable performance tracking if heatmap flag is set.
// P95 latency tracking via HDR histogram is automatically enabled.
if showHeatmap, _ := cmd.Flags().GetBool("heatmap"); showHeatmap {
perf.EnableTracking(true)
}
// Print telemetry disclosure if needed (skip for completion commands and when CLI config not found).
if !isCompletionCommand(cmd) && err == nil {
telemetry.PrintTelemetryDisclosure()
}
// Initialize I/O context and global formatter after flag parsing.
// This ensures flags like --no-color, --redirect-stderr, --mask are respected.
// Initialize() sets the global iolib.Data and iolib.UI writers with masking enabled.
if ioErr := iolib.Initialize(); ioErr != nil {
errUtils.CheckErrorPrintAndExit(fmt.Errorf("failed to initialize I/O context: %w", ioErr), "", "")
}
ioCtx := iolib.GetContext()
ui.InitFormatter(ioCtx)
data.InitWriter(ioCtx)
data.SetMarkdownRenderer(ui.Format) // Connect markdown rendering to data channel
// Check if running an experimental command.
// This happens after I/O init so ui.Experimental() can output properly.
// Walk up the command tree to find if any parent is experimental.
// For example, "atmos devcontainer list" should trigger the devcontainer warning.
experimentalCmd := findExperimentalParent(cmd)
if experimentalCmd != "" {
experimentalMode := tmpConfig.Settings.Experimental
if experimentalMode == "" {
experimentalMode = "warn" // Default
}
switch experimentalMode {
case "silence":
// Do nothing - completely silent.
case "disable":
// Command is registered but disabled at runtime.
errUtils.CheckErrorPrintAndExit(
errUtils.Build(errUtils.ErrExperimentalDisabled).
WithContext("command", experimentalCmd).
WithHint("Enable with settings.experimental: warn").
Err(),
"", "",
)
case "warn":
ui.Experimental(experimentalCmd)
case "error":
ui.Experimental(experimentalCmd)
errUtils.CheckErrorPrintAndExit(
errUtils.Build(errUtils.ErrExperimentalRequiresIn).
WithContext("command", experimentalCmd).
WithHint("Enable with settings.experimental: warn").
Err(),
"", "",
)
}
}
// Check for experimental settings (non-command features gated by config values).
// This extends the experimental check above to cover settings like key_delimiter.
checkExperimentalSettings(&tmpConfig)
// Configure lipgloss color profile based on terminal capabilities.
// This ensures tables and styled output degrade gracefully when piped or in non-TTY environments.
term := terminal.New()
lipgloss.SetColorProfile(convertToTermenvProfile(term.ColorProfile()))
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
// Stop profiler after command execution.
if profilerServer != nil {
if stopErr := profilerServer.Stop(); stopErr != nil {
log.Error("Failed to stop profiler", "error", stopErr)
}
}
// Show performance heatmap if enabled.
showHeatmap, _ := cmd.Flags().GetBool("heatmap")
if showHeatmap {
heatmapMode, _ := cmd.Flags().GetString("heatmap-mode")
if err := displayPerformanceHeatmap(cmd, heatmapMode); err != nil {
log.Error("Failed to display performance heatmap", "error", err)
}
}
},
RunE: func(cmd *cobra.Command, args []string) error {
// Check Atmos configuration.
checkAtmosConfig()
err := e.ExecuteAtmosCmd()
return err
},
}
// SetupLogger configures the global logger based on the provided Atmos configuration.
//
//nolint:revive,cyclop // Function complexity is acceptable for logger configuration.
func SetupLogger(atmosConfig *schema.AtmosConfiguration) {
switch atmosConfig.Logs.Level {
case "Trace":
log.SetLevel(log.TraceLevel)
case "Debug":
log.SetLevel(log.DebugLevel)
case "Info":
log.SetLevel(log.InfoLevel)
case "Warning":
log.SetLevel(log.WarnLevel)
case "Off":
log.SetLevel(math.MaxInt32)
default:
log.SetLevel(log.WarnLevel)
}
// Get theme-aware log styles.
var styles *log.Styles
if atmosConfig.Settings.Terminal.IsColorEnabled(term.IsTTYSupportForStderr()) {
// Get color scheme for the configured theme.
scheme, err := theme.GetColorSchemeForTheme(atmosConfig.Settings.Terminal.Theme)
if err == nil && scheme != nil {
// Use themed styles.
styles = theme.GetLogStyles(scheme)
} else {
// Fallback to default styles if theme loading fails.
styles = log.DefaultStyles()
}
} else {
// Use no-color styles.
styles = theme.GetLogStylesNoColor()
}
// Add TRCE level for trace logging (using same style as DEBU).
if debugStyle, ok := styles.Levels[log.DebugLevel]; ok {
styles.Levels[log.TraceLevel] = debugStyle.SetString("TRCE")
} else {
styles.Levels[log.TraceLevel] = lipgloss.NewStyle().SetString("TRCE")
}
log.SetStyles(styles)
// Only set output if a log file is configured.
if atmosConfig.Logs.File != "" {
var output io.Writer
switch atmosConfig.Logs.File {
case "/dev/stderr":
output = iolib.MaskWriter(os.Stderr)
case "/dev/stdout":
output = iolib.MaskWriter(os.Stdout)
case "/dev/null":
output = io.Discard // More efficient than opening os.DevNull
default:
logFile, err := os.OpenFile(atmosConfig.Logs.File, os.O_CREATE|os.O_WRONLY|os.O_APPEND, logFileMode)
errUtils.CheckErrorPrintAndExit(err, "Failed to open log file", "")
// Store the file handle for later cleanup instead of deferring close.
logFileHandle = logFile
output = iolib.MaskWriter(logFile)
}
log.SetOutput(output)
}
if _, err := log.ParseLogLevel(atmosConfig.Logs.Level); err != nil {
// Enrich the error with proper formatting for user-facing output.
// The error from ParseLogLevel has format: "sentinel\nexplanation"
// Extract the explanation text (everything after the first newline).
errMsg := err.Error()
parts := strings.SplitN(errMsg, "\n", 2)
explanation := ""
if len(parts) > 1 {
explanation = parts[1]
}
// Build enriched error from the wrapped error, adding the explanation as a detail.
// This ensures the formatter can extract both the sentinel message and the explanation.
enrichedErr := errUtils.Build(log.ErrInvalidLogLevel).
WithExplanation(explanation).
Err()
errUtils.CheckErrorPrintAndExit(enrichedErr, "", "")
}
log.Debug("Set", "logs-level", log.GetLevelString(), "logs-file", atmosConfig.Logs.File)
}
// configureEarlyColorProfile sets the lipgloss color profile based on environment variables.
// This is called early in PersistentPreRun, before config loading, to ensure that any
// theme styles accessed during stack processing respect NO_COLOR and other settings.
func configureEarlyColorProfile(cmd *cobra.Command) {
// Check NO_COLOR environment variable (standard terminal env var).
//nolint:forbidigo // Standard terminal env var, must use os.Getenv before config loads.
if os.Getenv("NO_COLOR") != "" {
// NO_COLOR is set - disable all colors
lipgloss.SetColorProfile(termenv.Ascii)
theme.InvalidateStyleCache() // Regenerate theme styles without colors
return
}
// Check --no-color flag (already parsed by cobra at this point)
if noColor, _ := cmd.Flags().GetBool("no-color"); noColor {
lipgloss.SetColorProfile(termenv.Ascii)
theme.InvalidateStyleCache()
return
}
// Check --force-color flag
if forceColor, _ := cmd.Flags().GetBool("force-color"); forceColor {
lipgloss.SetColorProfile(termenv.TrueColor)
theme.InvalidateStyleCache()
return
}
// Note: Full color profile detection happens later in InitFormatter().
// This early configuration just handles the most critical cases (NO_COLOR).
}
// setupColorProfile configures the global lipgloss color profile based on Atmos configuration.
func setupColorProfile(atmosConfig *schema.AtmosConfiguration) {
defer perf.Track(atmosConfig, "root.setupColorProfile")()
// Force TrueColor profile when ATMOS_FORCE_COLOR is enabled.
// This bypasses terminal detection and always outputs ANSI color codes.
if atmosConfig.Settings.Terminal.ForceColor {
lipgloss.SetColorProfile(termenv.TrueColor)
log.SetColorProfile(termenv.TrueColor)
log.Debug("Forced TrueColor profile", "force_color", true)
}
}
// setupColorProfileFromEnv checks ATMOS_FORCE_COLOR environment variable and --force-color flag early.
// This is called during init() before Boa styles are created, ensuring Cobra help
// text rendering respects the forced color profile.
func setupColorProfileFromEnv() {
defer perf.Track(nil, "cmd.setupColorProfileFromEnv")()
// Check environment variable first using global viper.
// Note: ATMOS env prefix and AutomaticEnv are configured in init().
forceColor := viper.GetBool("FORCE_COLOR")
// Also check --force-color CLI flag by manually parsing os.Args.
// This is needed because Cobra hasn't parsed flags yet during init().
if !forceColor {
for _, arg := range os.Args {
if arg == "--force-color" {
forceColor = true
break
}
}
}
if forceColor {
// Set both lipgloss profile AND CLICOLOR_FORCE environment variable.
// Lipgloss respects SetColorProfile(), but Boa (help renderer) checks CLICOLOR_FORCE.
lipgloss.SetColorProfile(termenv.TrueColor)
_ = os.Setenv("CLICOLOR_FORCE", "1")
}
}
// cleanupLogFile closes the log file handle if it was opened.
func cleanupLogFile() {
if logFileHandle != nil {
// Flush any remaining log data before closing.
_ = logFileHandle.Sync()
_ = logFileHandle.Close()
logFileHandle = nil
}
}
// Cleanup performs cleanup operations before the program exits.
// This should be called by main when the program is terminating.
func Cleanup() {
cleanupLogFile()
}
// RenderFlags renders a flag set with colors and proper text wrapping.
// Flag names are colored green, flag types are dimmed, descriptions are wrapped to terminal width.
// Markdown in descriptions is rendered to terminal output.
// flagRenderLayout holds layout constants and dimensions for flag rendering.
type flagRenderLayout struct {
leftPad int
spaceBetween int
rightMargin int
minDescWidth int
maxFlagWidth int
descColStart int
descWidth int
}
// newFlagRenderLayout creates a new layout configuration for flag rendering.
func newFlagRenderLayout(termWidth int, maxFlagWidth int) flagRenderLayout {
const (
leftPad = 2
spaceBetween = 2
rightMargin = 2
minDescWidth = 40
)
descColStart := leftPad + maxFlagWidth + spaceBetween
descWidth := termWidth - descColStart - rightMargin
if descWidth < minDescWidth {
descWidth = minDescWidth
}
return flagRenderLayout{
leftPad: leftPad,
spaceBetween: spaceBetween,
rightMargin: rightMargin,
minDescWidth: minDescWidth,
maxFlagWidth: maxFlagWidth,
descColStart: descColStart,
descWidth: descWidth,
}
}
// calculateMaxFlagWidth finds the maximum flag name width for alignment.
func calculateMaxFlagWidth(flags *pflag.FlagSet) int {
maxWidth := 0
flags.VisitAll(func(f *pflag.Flag) {
if f.Hidden {
return
}
flagName := formatFlagName(f)
if len(flagName) > maxWidth {
maxWidth = len(flagName)
}
})
return maxWidth
}
// buildFlagDescription creates the flag description with default value if applicable.
func buildFlagDescription(f *pflag.Flag) string {
usage := f.Usage
if f.DefValue != "" && f.DefValue != "false" && f.DefValue != "0" && f.DefValue != "[]" && f.Name != "" && f.Name != "help" {
usage += fmt.Sprintf(" (default `%s`)", f.DefValue)
}
return usage
}
// renderWrappedLines renders wrapped description lines with proper indentation.
func renderWrappedLines(w io.Writer, lines []string, indent int, descStyle *lipgloss.Style) {
if len(lines) == 0 {
return
}
// Print first line (already positioned on same line as flag name)
fmt.Fprintf(w, "%s\n", descStyle.Render(lines[0]))
// Print continuation lines with proper indentation
indentStr := strings.Repeat(" ", indent)
for i := 1; i < len(lines); i++ {
fmt.Fprintf(w, "%s%s\n", indentStr, descStyle.Render(lines[i]))
}
}
func isCompletionCommand(cmd *cobra.Command) bool {
if cmd == nil {
return false
}
// Check the command name directly from the Cobra command
// This works for both os.Args and SetArgs() invocations
cmdName := cmd.Name()
if cmdName == "completion" || cmdName == "__complete" || cmdName == "__completeNoDesc" {
return true
}
// Also check for shell completion environment variables
// Cobra sets these when generating completions
//nolint:forbidigo // These are external shell variables, not Atmos config
if os.Getenv("COMP_LINE") != "" || os.Getenv("_ARGCOMPLETE") != "" {
return true
}
return false
}
// findExperimentalParent walks up the command tree to find if any command in the
// chain is experimental. Returns the name of the experimental command, or empty
// string if none found. This allows subcommands to inherit experimental status
// from their parent (e.g., "atmos devcontainer list" triggers the devcontainer warning).
//
// The function uses a two-pass approach:
// 1. First, check for registry-based experimental commands (top-level like devcontainer, toolchain).
// These are the "original" experimental commands and should be preferred.
// 2. Second, check for annotation-based experimental subcommands (like terraform backend).
// This handles explicit subcommand-level experimental status.
//
// This ordering ensures that "devcontainer list" returns "devcontainer" (the registered
// experimental parent) rather than "list" (which inherited the annotation).
func findExperimentalParent(cmd *cobra.Command) string {
// First pass: Look for registry-based experimental commands.
// These are top-level commands like devcontainer, toolchain.
for c := cmd; c != nil; c = c.Parent() {
if internal.IsCommandExperimental(c.Name()) {
return c.Name()
}
}
// Second pass: Look for annotation-based experimental subcommands.
// These are subcommands explicitly marked experimental like "terraform backend".
for c := cmd; c != nil; c = c.Parent() {
if c.Annotations != nil && c.Annotations["experimental"] == "true" {
return c.Name()
}
}
return ""
}
// checkExperimentalSettings checks if any experimental settings are enabled in the config
// and applies the same experimental mode handling (silence/warn/error/disable) as commands.
// This extends the experimental system to cover non-command features gated by config values.
func checkExperimentalSettings(atmosConfig *schema.AtmosConfiguration) {
if atmosConfig == nil {
return
}
// Collect experimental settings that are enabled.
var features []string
if atmosConfig.Settings.YAML.KeyDelimiter != "" {
features = append(features, "settings.yaml.key_delimiter")
}
if len(features) == 0 {
return
}
experimentalMode := atmosConfig.Settings.Experimental
if experimentalMode == "" {
experimentalMode = "warn"
}
for _, feature := range features {
switch experimentalMode {
case "silence":
// Do nothing.
case "disable":
errUtils.CheckErrorPrintAndExit(
errUtils.Build(errUtils.ErrExperimentalDisabled).
WithContext("setting", feature).
WithHint("Enable with settings.experimental: warn").
Err(),
"", "",
)
case "warn":
ui.Experimental(feature)
case "error":
ui.Experimental(feature)
errUtils.CheckErrorPrintAndExit(
errUtils.Build(errUtils.ErrExperimentalRequiresIn).
WithContext("setting", feature).
WithHint("Enable with settings.experimental: warn").
Err(),
"", "",
)
}
}
}
// flagStyles holds the lipgloss styles for flag rendering.
type flagStyles struct {
flagStyle lipgloss.Style
argTypeStyle lipgloss.Style
descStyle lipgloss.Style
}
// renderSingleFlag renders one flag with its description.
func renderSingleFlag(w io.Writer, f *pflag.Flag, layout flagRenderLayout, styles *flagStyles, renderer *markdown.Renderer) {
// Get flag name parts and calculate padding
flagNamePlain, flagTypePlain := formatFlagNameParts(f)
fullPlainLength := len(flagNamePlain)
if flagTypePlain != "" {
fullPlainLength += 1 + len(flagTypePlain)
}
padding := layout.maxFlagWidth - fullPlainLength
const space = " "
// Render flag name with colors
fmt.Fprint(w, strings.Repeat(space, layout.leftPad))
fmt.Fprint(w, styles.flagStyle.Render(flagNamePlain))
if flagTypePlain != "" {
fmt.Fprint(w, space)
fmt.Fprint(w, styles.argTypeStyle.Render(flagTypePlain))
}
fmt.Fprint(w, strings.Repeat(space, padding+layout.spaceBetween))
// Build and process description
usage := buildFlagDescription(f)
wrapped := wordwrap.String(usage, layout.descWidth)
if renderer != nil {
rendered, err := renderer.RenderWithoutWordWrap(wrapped)
if err == nil {
wrapped = atmosansi.TrimLinesRight(rendered)
}
}
lines := strings.Split(wrapped, "\n")
renderWrappedLines(w, lines, layout.descColStart, &styles.descStyle)
fmt.Fprintln(w)
}
// renderFlags renders all flags with formatting and styling.