-
-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathhelp_template.go
More file actions
840 lines (710 loc) · 27.4 KB
/
help_template.go
File metadata and controls
840 lines (710 loc) · 27.4 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
package cmd
import (
"fmt"
"io"
"os"
"runtime"
"sort"
"strings"
"github.com/charmbracelet/colorprofile"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/reflow/wordwrap"
"github.com/muesli/termenv"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/cloudposse/atmos/cmd/internal"
tuiUtils "github.com/cloudposse/atmos/internal/tui/utils"
cfg "github.com/cloudposse/atmos/pkg/config"
"github.com/cloudposse/atmos/pkg/flags/compat"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/schema"
"github.com/cloudposse/atmos/pkg/ui"
markdown "github.com/cloudposse/atmos/pkg/ui/markdown"
"github.com/cloudposse/atmos/pkg/ui/theme"
"github.com/cloudposse/atmos/pkg/version"
)
// Environment variable names for color control.
const (
envAtmosForceColor = "ATMOS_FORCE_COLOR"
envForceColor = "FORCE_COLOR"
envCliColorForce = "CLICOLOR_FORCE"
envNoColor = "NO_COLOR"
envAtmosDebugColor = "ATMOS_DEBUG_COLORS"
envTerm = "TERM"
envColorTerm = "COLORTERM"
)
// Help formatting layout constants.
const (
commandListLeftPad = 6 // Left padding for command list entries.
commandDescriptionSpacing = 2 // Spacing between command name and description.
minDescriptionWidth = 40 // Minimum width for description text.
spaceChar = " " // Space character for padding.
)
// String constants for environment variable values.
const (
valueOne = "1"
valueZero = "0"
)
// colorConfig holds the color detection and environment variable configuration.
type colorConfig struct {
forceColor bool
explicitlyDisabled bool
debugColors bool
}
// writerConfig holds the writer and renderer configuration.
type writerConfig struct {
writer io.Writer
renderer *lipgloss.Renderer
profile colorprofile.Profile
}
// helpStyles holds the styled text renderers for help output.
// Uses theme-aware styles from theme.GetCurrentStyles().
type helpStyles struct {
heading lipgloss.Style // Section headings (USAGE, FLAGS, etc.)
commandName lipgloss.Style // Command names in lists
commandDesc lipgloss.Style // Command descriptions
flagName lipgloss.Style // Flag names
flagDesc lipgloss.Style // Flag descriptions
muted lipgloss.Style // Muted text (footer messages)
}
// helpRenderContext holds the rendering context for help output.
type helpRenderContext struct {
writer io.Writer
renderer *lipgloss.Renderer
atmosConfig *schema.AtmosConfiguration
styles *helpStyles
}
// parseBoolLikeForceColor parses a FORCE_COLOR-style environment variable value.
// Returns (isTruthy, isFalsy) to distinguish between truthy and falsy values.
// Truthy values: "1", "true", "2", "3", "yes", "on", "always".
// Falsy values: "0", "false", "no", "off".
func parseBoolLikeForceColor(val string) (isTruthy bool, isFalsy bool) {
if val == "" {
return false, false
}
v := strings.ToLower(strings.TrimSpace(val))
if v == "" {
return false, false
}
// Check truthy values
truthyValues := []string{"1", "true", "2", "3", "yes", "on", "always"}
for _, truthy := range truthyValues {
if v == truthy {
return true, false
}
}
// Check falsy values
falsyValues := []string{"0", "false", "no", "off"}
for _, falsy := range falsyValues {
if v == falsy {
return false, true
}
}
// Value is set but not recognized - treat as neither truthy nor falsy
return false, false
}
// isTruthy checks if a string represents a truthy value.
func isTruthy(val string) bool {
truthy, _ := parseBoolLikeForceColor(val)
return truthy
}
// isFalsy checks if a string represents a falsy value.
func isFalsy(val string) bool {
_, falsy := parseBoolLikeForceColor(val)
return falsy
}
// setColorEnvVarsForDisabled sets environment variables to disable color.
func setColorEnvVarsForDisabled() {
os.Setenv(envNoColor, valueOne)
os.Setenv(envForceColor, valueZero)
os.Setenv(envCliColorForce, valueZero)
}
// setColorEnvVarsForEnabled sets environment variables to enable color.
func setColorEnvVarsForEnabled() {
os.Unsetenv(envNoColor)
if viper.GetString(envForceColor) == "" {
os.Setenv(envForceColor, valueOne)
}
if viper.GetString(envCliColorForce) == "" {
os.Setenv(envCliColorForce, valueOne)
}
}
// detectColorConfig detects and configures color settings based on environment variables.
func detectColorConfig() colorConfig {
defer perf.Track(nil, "cmd.detectColorConfig")()
// Bind environment variables for color control.
_ = viper.BindEnv(envAtmosForceColor)
_ = viper.BindEnv(envCliColorForce)
_ = viper.BindEnv(envForceColor)
_ = viper.BindEnv(envNoColor)
_ = viper.BindEnv(envAtmosDebugColor)
_ = viper.BindEnv(envTerm)
_ = viper.BindEnv(envColorTerm)
// Check NO_COLOR first - it unconditionally disables color.
noColor := viper.GetString(envNoColor)
if noColor != "" {
setColorEnvVarsForDisabled()
return colorConfig{
forceColor: false,
explicitlyDisabled: true,
debugColors: viper.GetString(envAtmosDebugColor) != "",
}
}
// Check ATMOS_FORCE_COLOR first, then fallback to standard env vars.
atmosForceColor := viper.GetString(envAtmosForceColor)
cliColorForce := viper.GetString(envCliColorForce)
forceColorEnv := viper.GetString(envForceColor)
// Determine final forceColor value.
explicitlyDisabled := isFalsy(atmosForceColor) || isFalsy(cliColorForce) || isFalsy(forceColorEnv)
forceColor := !explicitlyDisabled && (isTruthy(atmosForceColor) || isTruthy(cliColorForce) || isTruthy(forceColorEnv))
// Ensure standard env vars are set for ALL color libraries.
if explicitlyDisabled {
setColorEnvVarsForDisabled()
} else if forceColor {
setColorEnvVarsForEnabled()
}
return colorConfig{
forceColor: forceColor,
explicitlyDisabled: explicitlyDisabled,
debugColors: viper.GetString(envAtmosDebugColor) != "",
}
}
// printColorDebugInfo prints debug information about color detection.
func printColorDebugInfo(profileDetector *colorprofile.Writer, config colorConfig) {
fmt.Fprintf(os.Stderr, "\n[DEBUG] Color Detection:\n")
fmt.Fprintf(os.Stderr, " Detected Profile: %v\n", profileDetector.Profile)
fmt.Fprintf(os.Stderr, " ATMOS_FORCE_COLOR: %s\n", viper.GetString(envAtmosForceColor))
fmt.Fprintf(os.Stderr, " FORCE_COLOR: %s\n", viper.GetString(envForceColor))
fmt.Fprintf(os.Stderr, " CLICOLOR_FORCE: %s\n", viper.GetString(envCliColorForce))
fmt.Fprintf(os.Stderr, " NO_COLOR: %s\n", viper.GetString(envNoColor))
fmt.Fprintf(os.Stderr, " TERM: %s\n", viper.GetString(envTerm))
fmt.Fprintf(os.Stderr, " COLORTERM: %s\n", viper.GetString(envColorTerm))
fmt.Fprintf(os.Stderr, " forceColor: %v\n", config.forceColor)
fmt.Fprintf(os.Stderr, " explicitlyDisabled: %v\n", config.explicitlyDisabled)
}
// configureDisabledColorWriter creates a writer with colors explicitly disabled.
func configureDisabledColorWriter(out io.Writer, debugColors bool) (io.Writer, colorprofile.Profile, *lipgloss.Renderer) {
colorW := colorprofile.NewWriter(out, os.Environ())
colorW.Profile = colorprofile.Ascii
renderer := lipgloss.NewRenderer(colorW)
renderer.SetColorProfile(termenv.Ascii)
if debugColors {
fmt.Fprintf(os.Stderr, " Mode: Explicitly Disabled\n")
fmt.Fprintf(os.Stderr, " Final Profile: Ascii\n")
}
return colorW, colorprofile.Ascii, renderer
}
// configureForcedColorWriter creates a writer with colors forced on.
func configureForcedColorWriter(out io.Writer, debugColors bool) (io.Writer, colorprofile.Profile, *lipgloss.Renderer) {
profile := colorprofile.ANSI256
termOut := termenv.NewOutput(out, termenv.WithProfile(termenv.ANSI256))
termenv.SetDefaultOutput(termOut)
renderer := lipgloss.NewRenderer(termOut, termenv.WithProfile(termenv.ANSI256))
if debugColors {
fmt.Fprintf(os.Stderr, " Mode: Force Color (pipe-safe)\n")
fmt.Fprintf(os.Stderr, " Final Profile: ANSI256 (forced)\n")
fmt.Fprintf(os.Stderr, " Renderer: Created with termenv.Output ANSI256 as writer\n")
fmt.Fprintf(os.Stderr, " Renderer ColorProfile: %v\n", renderer.ColorProfile())
fmt.Fprintf(os.Stderr, " Global termenv DefaultOutput profile: %v\n", termenv.DefaultOutput().ColorProfile())
}
return out, profile, renderer
}
// setRendererProfileForAutoDetect configures the renderer based on the detected color profile.
func setRendererProfileForAutoDetect(renderer *lipgloss.Renderer, profile colorprofile.Profile, debugColors bool) {
switch profile {
case colorprofile.TrueColor:
renderer.SetColorProfile(termenv.TrueColor)
if debugColors {
fmt.Fprintf(os.Stderr, " Renderer: Auto-detect, set to TrueColor\n")
}
case colorprofile.ANSI256:
renderer.SetColorProfile(termenv.ANSI256)
if debugColors {
fmt.Fprintf(os.Stderr, " Renderer: Auto-detect, set to ANSI256\n")
}
case colorprofile.ANSI:
renderer.SetColorProfile(termenv.ANSI)
if debugColors {
fmt.Fprintf(os.Stderr, " Renderer: Auto-detect, set to ANSI\n")
}
case colorprofile.Ascii:
renderer.SetColorProfile(termenv.Ascii)
if debugColors {
fmt.Fprintf(os.Stderr, " Renderer: Auto-detect, set to Ascii\n")
}
}
}
// configureAutoDetectColorWriter creates a writer with auto-detected color support.
func configureAutoDetectColorWriter(out io.Writer, detectedProfile colorprofile.Profile, debugColors bool) (io.Writer, colorprofile.Profile, *lipgloss.Renderer) {
colorW := colorprofile.NewWriter(out, os.Environ())
colorW.Profile = detectedProfile
renderer := lipgloss.NewRenderer(colorW)
setRendererProfileForAutoDetect(renderer, colorW.Profile, debugColors)
if debugColors {
fmt.Fprintf(os.Stderr, " Mode: Auto-detect\n")
fmt.Fprintf(os.Stderr, " Final Profile: %v\n", colorW.Profile)
}
return colorW, colorW.Profile, renderer
}
// configureWriter creates and configures the writer and renderer based on color settings.
func configureWriter(cmd *cobra.Command, config colorConfig) writerConfig {
defer perf.Track(nil, "cmd.configureWriter")()
profileDetector := colorprofile.NewWriter(os.Stdout, os.Environ())
if config.debugColors {
printColorDebugInfo(profileDetector, config)
}
var w io.Writer
var profile colorprofile.Profile
var renderer *lipgloss.Renderer
switch {
case config.explicitlyDisabled:
w, profile, renderer = configureDisabledColorWriter(cmd.OutOrStdout(), config.debugColors)
case config.forceColor:
w, profile, renderer = configureForcedColorWriter(cmd.OutOrStdout(), config.debugColors)
default:
w, profile, renderer = configureAutoDetectColorWriter(cmd.OutOrStdout(), profileDetector.Profile, config.debugColors)
}
if config.debugColors {
fmt.Fprintf(os.Stderr, " Renderer Color Profile: %v\n", renderer.ColorProfile())
fmt.Fprintf(os.Stderr, " Renderer Has Dark Background: %v\n\n", renderer.HasDarkBackground())
}
renderer.SetHasDarkBackground(true)
return writerConfig{
writer: w,
renderer: renderer,
profile: profile,
}
}
// createHelpStyles creates the color styles for help output using theme-aware colors.
func createHelpStyles(renderer *lipgloss.Renderer) helpStyles {
defer perf.Track(nil, "cmd.createHelpStyles")()
// Get theme-aware styles.
themeStyles := theme.GetCurrentStyles()
// Apply renderer to theme styles so they use the correct color profile.
return helpStyles{
heading: renderer.NewStyle().Foreground(themeStyles.Help.Heading.GetForeground()).Bold(true),
commandName: renderer.NewStyle().Foreground(themeStyles.Help.CommandName.GetForeground()).Bold(true),
commandDesc: renderer.NewStyle().Foreground(themeStyles.Help.CommandDesc.GetForeground()),
flagName: renderer.NewStyle().Foreground(themeStyles.Help.FlagName.GetForeground()),
flagDesc: renderer.NewStyle().Foreground(themeStyles.Help.FlagDesc.GetForeground()),
muted: renderer.NewStyle().Foreground(themeStyles.Muted.GetForeground()),
}
}
// printLogoAndVersion prints the Atmos logo and version information.
func printLogoAndVersion(w io.Writer, styles *helpStyles) {
defer perf.Track(nil, "cmd.printLogoAndVersion")()
fmt.Fprintln(w)
_ = tuiUtils.PrintStyledTextToSpecifiedOutput(w, "ATMOS")
versionText := styles.muted.Render(version.Version)
osArchText := styles.muted.Render(fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH))
versionInfo := fmt.Sprintf("👽 %s %s", versionText, osArchText)
fmt.Fprintln(w, versionInfo)
fmt.Fprintln(w)
}
// printDescription prints the command description.
func printDescription(w io.Writer, cmd *cobra.Command, styles *helpStyles) {
defer perf.Track(nil, "cmd.printDescription")()
var desc string
switch {
case cmd.Long != "":
desc = cmd.Long
case cmd.Short != "":
desc = cmd.Short
default:
return
}
// Use markdown rendering to respect terminal width and wrapping settings.
// This ensures long descriptions wrap properly based on screen width.
rendered := renderMarkdownDescription(desc)
styled := styles.commandDesc.Render(rendered)
// Lipgloss pads multi-line strings to uniform width. Trim trailing whitespace from each line.
styled = ui.TrimLinesRight(styled)
fmt.Fprintln(w, styled)
fmt.Fprintln(w)
}
// printUsageSection prints the usage section.
func printUsageSection(w io.Writer, cmd *cobra.Command, renderer *lipgloss.Renderer, styles *helpStyles) {
defer perf.Track(nil, "cmd.printUsageSection")()
fmt.Fprintln(w, styles.heading.Render("USAGE"))
fmt.Fprintln(w)
var usageContent strings.Builder
if cmd.Runnable() {
fmt.Fprintf(&usageContent, "$ %s\n", cmd.UseLine())
}
if cmd.HasAvailableSubCommands() {
fmt.Fprintf(&usageContent, "$ %s", cmd.CommandPath()+" [sub-command] [flags]")
}
if usageContent.Len() > 0 {
usageText := strings.TrimRight(usageContent.String(), "\n")
termWidth := getTerminalWidth()
rendered := markdown.RenderCodeBlock(renderer, usageText, termWidth)
fmt.Fprintln(w, rendered)
}
fmt.Fprintln(w)
}
// printAliases prints command aliases.
func printAliases(w io.Writer, cmd *cobra.Command, styles *helpStyles) {
defer perf.Track(nil, "cmd.printAliases")()
if len(cmd.Aliases) > 0 {
fmt.Fprintln(w, styles.heading.Render("ALIASES"))
fmt.Fprintln(w)
fmt.Fprintf(w, " %s\n", styles.commandDesc.Render(cmd.NameAndAliases()))
fmt.Fprintln(w)
}
}
// renderMarkdownDescription renders a description string as Markdown using the UI formatter.
// Uses the global ui.Format which has theme integration and automatic degradation.
func renderMarkdownDescription(desc string) string {
if ui.Format == nil {
return desc
}
rendered, err := ui.Format.Markdown(desc)
if err != nil {
return desc
}
return strings.TrimSpace(rendered)
}
// printSubcommandAliases prints subcommand aliases.
func printSubcommandAliases(ctx *helpRenderContext, cmd *cobra.Command) {
defer perf.Track(nil, "cmd.printSubcommandAliases")()
hasAliases := false
for _, c := range cmd.Commands() {
if c.IsAvailableCommand() && len(c.Aliases) > 0 {
hasAliases = true
break
}
}
if !hasAliases {
return
}
fmt.Fprintln(ctx.writer, ctx.styles.heading.Render("SUBCOMMAND ALIASES"))
fmt.Fprintln(ctx.writer)
for _, c := range cmd.Commands() {
if !c.IsAvailableCommand() || len(c.Aliases) == 0 {
continue
}
name := ctx.styles.commandName.Render(fmt.Sprintf("%-15s", c.Aliases[0]))
// Render description as Markdown (like command descriptions) with backticks instead of quotes.
desc := fmt.Sprintf("Alias of `%s %s` command", cmd.Name(), c.Name())
desc = renderMarkdownDescription(desc)
fmt.Fprintf(ctx.writer, " %s %s\n", name, desc)
}
fmt.Fprintln(ctx.writer)
}
// printExamples prints command examples.
func printExamples(w io.Writer, cmd *cobra.Command, renderer *lipgloss.Renderer, styles *helpStyles) {
defer perf.Track(nil, "cmd.printExamples")()
if cmd.Example == "" {
return
}
fmt.Fprintln(w, styles.heading.Render("EXAMPLES"))
fmt.Fprintln(w)
exampleText := strings.TrimSpace(cmd.Example)
exampleText = strings.ReplaceAll(exampleText, "```shell", "")
exampleText = strings.ReplaceAll(exampleText, "```", "")
termWidth := getTerminalWidth()
rendered := markdown.RenderCodeBlock(renderer, exampleText, termWidth)
fmt.Fprintln(w, rendered)
fmt.Fprintln(w)
}
// isCommandAvailable checks if a command should be shown in help output.
func isCommandAvailable(cmd *cobra.Command) bool {
return cmd.IsAvailableCommand() || cmd.Name() == "help"
}
// isConfigAlias checks if a command is a CLI config alias.
func isConfigAlias(cmd *cobra.Command) bool {
if cmd.Annotations == nil {
return false
}
_, ok := cmd.Annotations["configAlias"]
return ok
}
// calculateCommandWidth calculates the display width of a command name including type suffix.
func calculateCommandWidth(cmd *cobra.Command) int {
width := len(cmd.Name())
if cmd.HasAvailableSubCommands() {
width += len(" [command]")
}
return width
}
// calculateMaxCommandWidth finds the maximum command name width for alignment.
// Config aliases are excluded from this calculation since they're shown in a separate section.
func calculateMaxCommandWidth(commands []*cobra.Command) int {
maxWidth := 0
for _, c := range commands {
if !isCommandAvailable(c) || isConfigAlias(c) {
continue
}
width := calculateCommandWidth(c)
if width > maxWidth {
maxWidth = width
}
}
return maxWidth
}
// formatCommandLine formats a single command line with proper padding and styling.
func formatCommandLine(ctx *helpRenderContext, cmd *cobra.Command, maxWidth int, mdRenderer *markdown.Renderer) {
cmdName := cmd.Name()
cmdTypePlain := ""
cmdTypeStyled := ""
if cmd.HasAvailableSubCommands() {
cmdTypePlain = " [command]"
cmdTypeStyled = " " + ctx.styles.flagName.Render("[command]")
}
padding := maxWidth - len(cmdName) - len(cmdTypePlain)
// Calculate where the description starts (left pad + command name + padding + spacing)
descColStart := commandListLeftPad + maxWidth + commandDescriptionSpacing
// Get terminal width and calculate available width for description
termWidth := getTerminalWidth()
descWidth := termWidth - descColStart
if descWidth < minDescriptionWidth {
descWidth = minDescriptionWidth
}
fmt.Fprint(ctx.writer, strings.Repeat(spaceChar, commandListLeftPad))
fmt.Fprint(ctx.writer, ctx.styles.commandName.Render(cmdName))
fmt.Fprint(ctx.writer, cmdTypeStyled)
fmt.Fprint(ctx.writer, strings.Repeat(spaceChar, padding))
fmt.Fprint(ctx.writer, strings.Repeat(spaceChar, commandDescriptionSpacing))
// Wrap plain text first, then render markdown without additional wrapping.
// This matches the approach used by flag description rendering.
wrapped := wordwrap.String(cmd.Short, descWidth)
if mdRenderer != nil {
rendered, err := mdRenderer.RenderWithoutWordWrap(wrapped)
if err == nil {
wrapped = strings.TrimSpace(rendered)
}
}
lines := strings.Split(wrapped, "\n")
// Print first line (already positioned)
if len(lines) > 0 {
fmt.Fprintf(ctx.writer, "%s\n", ctx.styles.commandDesc.Render(lines[0]))
}
// Print continuation lines with proper indentation
if len(lines) > 1 {
indentStr := strings.Repeat(spaceChar, descColStart)
for i := 1; i < len(lines); i++ {
fmt.Fprintf(ctx.writer, "%s%s\n", indentStr, ctx.styles.commandDesc.Render(lines[i]))
}
}
}
// printAvailableCommands prints the list of available subcommands.
func printAvailableCommands(ctx *helpRenderContext, cmd *cobra.Command) {
defer perf.Track(nil, "cmd.printAvailableCommands")()
if !cmd.HasAvailableSubCommands() {
return
}
fmt.Fprintln(ctx.writer, ctx.styles.heading.Render("AVAILABLE COMMANDS"))
fmt.Fprintln(ctx.writer)
maxCmdWidth := calculateMaxCommandWidth(cmd.Commands())
// Create markdown renderer for command descriptions (same approach as flag rendering).
var mdRenderer *markdown.Renderer
if ctx.atmosConfig != nil {
mdRenderer, _ = markdown.NewTerminalMarkdownRenderer(*ctx.atmosConfig)
}
for _, c := range cmd.Commands() {
if !isCommandAvailable(c) || isConfigAlias(c) {
continue
}
formatCommandLine(ctx, c, maxCmdWidth, mdRenderer)
}
fmt.Fprintln(ctx.writer)
}
// getConfigAliases returns all available config alias commands.
func getConfigAliases(cmd *cobra.Command) []*cobra.Command {
var aliases []*cobra.Command
for _, c := range cmd.Commands() {
if c.IsAvailableCommand() && isConfigAlias(c) {
aliases = append(aliases, c)
}
}
return aliases
}
// printConfigAliases prints CLI config aliases in a dedicated section.
func printConfigAliases(ctx *helpRenderContext, cmd *cobra.Command) {
defer perf.Track(nil, "cmd.printConfigAliases")()
aliases := getConfigAliases(cmd)
if len(aliases) == 0 {
return
}
fmt.Fprintln(ctx.writer, ctx.styles.heading.Render("ALIASES"))
fmt.Fprintln(ctx.writer)
// Calculate max width for alignment.
maxWidth := 0
for _, c := range aliases {
if len(c.Name()) > maxWidth {
maxWidth = len(c.Name())
}
}
for _, c := range aliases {
name := ctx.styles.commandName.Render(fmt.Sprintf("%-*s", maxWidth, c.Name()))
// c.Short contains "alias for `command`".
desc := renderMarkdownDescription(c.Short)
fmt.Fprintf(ctx.writer, " %s %s\n", name, desc)
}
fmt.Fprintln(ctx.writer)
}
// printFlags prints command flags.
func printFlags(w io.Writer, cmd *cobra.Command, atmosConfig *schema.AtmosConfiguration, styles *helpStyles) {
defer perf.Track(nil, "cmd.printFlags")()
termWidth := getTerminalWidth()
if cmd.HasAvailableLocalFlags() {
fmt.Fprintln(w, styles.heading.Render("FLAGS"))
fmt.Fprintln(w)
renderFlags(w, cmd.LocalFlags(), styles.commandName, styles.flagName, styles.flagDesc, termWidth, atmosConfig)
fmt.Fprintln(w)
}
if cmd.HasAvailableInheritedFlags() {
fmt.Fprintln(w, styles.heading.Render("GLOBAL FLAGS"))
fmt.Fprintln(w)
renderFlags(w, cmd.InheritedFlags(), styles.commandName, styles.flagName, styles.flagDesc, termWidth, atmosConfig)
fmt.Fprintln(w)
}
}
// printCompatibilityFlags prints terraform compatibility flags if applicable.
// These are pass-through flags that are forwarded to the underlying terraform/tofu command.
func printCompatibilityFlags(w io.Writer, cmd *cobra.Command, styles *helpStyles) {
defer perf.Track(nil, "cmd.printCompatibilityFlags")()
// Find the top-level command (e.g., "terraform") to determine if this command has compat flags.
providerName := findProviderName(cmd)
if providerName == "" {
return
}
// Get subcommand-specific compatibility flags.
flags := internal.GetSubcommandCompatFlags(providerName, cmd.Name())
if len(flags) == 0 {
return
}
fmt.Fprintln(w, styles.heading.Render("COMPATIBILITY FLAGS"))
fmt.Fprintln(w)
fmt.Fprintln(w, " These flags are passed through to the underlying terraform/tofu command.")
fmt.Fprintln(w)
renderCompatFlags(w, flags, &styles.flagName, &styles.flagName, &styles.flagDesc)
fmt.Fprintln(w)
}
// findProviderName walks up the command tree to find the top-level command name.
// For example, for "atmos terraform apply", this returns "terraform".
func findProviderName(cmd *cobra.Command) string {
defer perf.Track(nil, "cmd.findProviderName")()
// Walk up to find the first non-root parent.
for c := cmd; c != nil; c = c.Parent() {
parent := c.Parent()
if parent != nil && parent.Parent() == nil {
// c's parent is root, so c is the top-level command.
return c.Name()
}
}
return ""
}
// renderCompatFlags renders compatibility flags with proper styling and alignment.
// FlagStyle is used for the flag name (cyan), argTypeStyle for any type annotations, descStyle for descriptions.
func renderCompatFlags(w io.Writer, flags map[string]compat.CompatibilityFlag, flagStyle, argTypeStyle, descStyle *lipgloss.Style) {
defer perf.Track(nil, "cmd.renderCompatFlags")()
// Collect and sort flag names for consistent output.
type flagEntry struct {
name string
description string
}
entries := make([]flagEntry, 0, len(flags))
for name, flag := range flags {
entries = append(entries, flagEntry{name: name, description: flag.Description})
}
sort.Slice(entries, func(i, j int) bool {
return entries[i].name < entries[j].name
})
// Calculate max flag name length for alignment.
maxLen := 0
for _, entry := range entries {
if len(entry.name) > maxLen {
maxLen = len(entry.name)
}
}
// Calculate available width for description.
termWidth := getTerminalWidth()
// Layout: commandListLeftPad padding + flag name + commandDescriptionSpacing + description
descColStart := commandListLeftPad + maxLen + commandDescriptionSpacing
descWidth := termWidth - descColStart
if descWidth < minDescriptionWidth {
descWidth = minDescriptionWidth
}
// Render each flag.
// Note: argTypeStyle is available but not currently used since compat flags don't have type annotations.
_ = argTypeStyle
for _, entry := range entries {
padding := maxLen - len(entry.name) + 2
// Style the flag name (cyan, like FLAGS section).
styledName := flagStyle.Render(entry.name)
// Wrap and render description.
wrapped := wordwrap.String(entry.description, descWidth)
lines := strings.Split(wrapped, "\n")
// Print first line.
fmt.Fprintf(w, " %s%s%s\n", styledName, strings.Repeat(" ", padding), descStyle.Render(lines[0]))
// Print continuation lines with proper indentation.
if len(lines) > 1 {
indentStr := strings.Repeat(" ", descColStart)
for i := 1; i < len(lines); i++ {
fmt.Fprintf(w, "%s%s\n", indentStr, descStyle.Render(lines[i]))
}
}
}
}
// applyColoredHelpTemplate applies a colored help template to the command.
// This approach ensures colors work in both interactive terminals and redirected output (screengrabs).
// Colors are automatically enabled when ATMOS_FORCE_COLOR, CLICOLOR_FORCE, or FORCE_COLOR is set.
func applyColoredHelpTemplate(cmd *cobra.Command) {
defer perf.Track(nil, "cmd.applyColoredHelpTemplate")()
// Detect and configure color settings.
colorConf := detectColorConfig()
// Configure writer and renderer.
writerConf := configureWriter(cmd, colorConf)
// Create help styles.
styles := createHelpStyles(writerConf.renderer)
// Load Atmos configuration for markdown rendering.
// Reuse existing atmosConfig from root/Execute if available, otherwise load a minimal config.
// Use processStacks=false since help rendering only needs terminal/docs settings.
var helpAtmosConfig *schema.AtmosConfiguration
if atmosConfig.BasePath != "" {
// atmosConfig already loaded by root command.
helpAtmosConfig = &atmosConfig
} else {
// Load minimal config without processing stacks.
config, err := cfg.InitCliConfig(schema.ConfigAndStacksInfo{}, false)
if err != nil {
// If config loading fails, use a minimal zero-value config.
config = schema.AtmosConfiguration{}
}
helpAtmosConfig = &config
}
// Create help render context.
ctx := &helpRenderContext{
writer: writerConf.writer,
renderer: writerConf.renderer,
atmosConfig: helpAtmosConfig,
styles: &styles,
}
// Set custom help function.
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
printLogoAndVersion(ctx.writer, ctx.styles)
printDescription(ctx.writer, c, ctx.styles)
printUsageSection(ctx.writer, c, ctx.renderer, ctx.styles)
printAliases(ctx.writer, c, ctx.styles)
printSubcommandAliases(ctx, c)
printExamples(ctx.writer, c, ctx.renderer, ctx.styles)
printAvailableCommands(ctx, c)
printConfigAliases(ctx, c)
printFlags(ctx.writer, c, ctx.atmosConfig, ctx.styles)
printCompatibilityFlags(ctx.writer, c, ctx.styles)
printFooter(ctx.writer, c, ctx.styles)
})
}
// printFooter prints the help footer message.
func printFooter(w io.Writer, cmd *cobra.Command, styles *helpStyles) {
defer perf.Track(nil, "cmd.printFooter")()
if !cmd.HasAvailableSubCommands() {
return
}
usageMsg := fmt.Sprintf("Use `%s [command] --help` for more information about a command.", cmd.CommandPath())
// Use renderMarkdownDescription to respect terminal width and wrapping settings.
// This ensures the footer wraps properly based on screen width.
usageMsg = renderMarkdownDescription(usageMsg)
fmt.Fprintf(w, "\n%s\n", styles.muted.Render(usageMsg))
}