-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathcomponents.go
More file actions
377 lines (313 loc) · 12 KB
/
components.go
File metadata and controls
377 lines (313 loc) · 12 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
package list
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
errUtils "github.com/cloudposse/atmos/errors"
e "github.com/cloudposse/atmos/internal/exec"
"github.com/cloudposse/atmos/pkg/config"
"github.com/cloudposse/atmos/pkg/flags"
"github.com/cloudposse/atmos/pkg/flags/global"
"github.com/cloudposse/atmos/pkg/list/column"
"github.com/cloudposse/atmos/pkg/list/extract"
"github.com/cloudposse/atmos/pkg/list/filter"
"github.com/cloudposse/atmos/pkg/list/format"
"github.com/cloudposse/atmos/pkg/list/renderer"
listSort "github.com/cloudposse/atmos/pkg/list/sort"
perf "github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/schema"
"github.com/cloudposse/atmos/pkg/ui"
)
var componentsParser *flags.StandardParser
// ComponentsOptions contains parsed flags for the components command.
type ComponentsOptions struct {
global.Flags
Stack string
Type string
Enabled *bool
Locked *bool
Format string
Columns []string
Sort string
Abstract bool
}
// componentsCmd lists atmos components.
var componentsCmd = &cobra.Command{
Use: "components",
Short: "List all Atmos components with filtering, sorting, and formatting options",
Long: `List Atmos components with support for filtering by stack, type, enabled/locked status, custom column selection, sorting, and multiple output formats.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
// Get Viper instance for flag/env precedence.
v := viper.GetViper()
// Check Atmos configuration (honors --base-path, --config, --config-path, --profile).
if err := checkAtmosConfig(cmd, v); err != nil {
return err
}
// Parse flags using StandardParser with Viper precedence.
if err := componentsParser.BindFlagsToViper(cmd, v); err != nil {
return err
}
// Parse enabled/locked flags as tri-state (*bool).
// nil = unset (show all), true = filter for true, false = filter for false.
// Use cmd.Flags().Changed() instead of v.IsSet() because IsSet returns true
// when a default value is registered, but we only want to filter when
// the user explicitly provided the flag.
var enabledPtr *bool
if cmd.Flags().Changed("enabled") {
val := v.GetBool("enabled")
enabledPtr = &val
}
var lockedPtr *bool
if cmd.Flags().Changed("locked") {
val := v.GetBool("locked")
lockedPtr = &val
}
opts := &ComponentsOptions{
Flags: flags.ParseGlobalFlags(cmd, v),
Stack: v.GetString("stack"),
Type: v.GetString("type"),
Enabled: enabledPtr,
Locked: lockedPtr,
Format: v.GetString("format"),
Columns: v.GetStringSlice("columns"),
Sort: v.GetString("sort"),
Abstract: v.GetBool("abstract"),
}
return listComponentsWithOptions(cmd, args, opts)
},
}
// columnsCompletionForComponents provides dynamic tab completion for --columns flag.
// Returns column names from atmos.yaml components.list.columns configuration.
func columnsCompletionForComponents(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
defer perf.Track(nil, "list.components.columnsCompletionForComponents")()
// Load atmos configuration with CLI flags.
configAndStacksInfo, err := e.ProcessCommandLineArgs("list", cmd, args, nil)
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
atmosConfig, err := config.InitCliConfig(configAndStacksInfo, false)
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
// Extract column names from atmos.yaml configuration.
if len(atmosConfig.Components.List.Columns) > 0 {
var columnNames []string
for _, col := range atmosConfig.Components.List.Columns {
columnNames = append(columnNames, col.Name)
}
return columnNames, cobra.ShellCompDirectiveNoFileComp
}
// If no custom columns configured, return empty list.
return nil, cobra.ShellCompDirectiveNoFileComp
}
func init() {
// Create parser with components-specific flags using flag wrappers.
componentsParser = NewListParser(
WithFormatFlag,
WithComponentsColumnsFlag,
WithSortFlag,
WithStackFlag,
WithTypeFlag,
WithEnabledFlag,
WithLockedFlag,
WithAbstractFlag,
)
// Register flags.
componentsParser.RegisterFlags(componentsCmd)
// Register dynamic tab completion for --columns flag.
if err := componentsCmd.RegisterFlagCompletionFunc("columns", columnsCompletionForComponents); err != nil {
panic(err)
}
// Bind flags to Viper for environment variable support.
if err := componentsParser.BindToViper(viper.GetViper()); err != nil {
panic(err)
}
}
func listComponentsWithOptions(cmd *cobra.Command, args []string, opts *ComponentsOptions) error {
defer perf.Track(nil, "list.components.listComponentsWithOptions")()
// Initialize configuration and extract components.
atmosConfig, components, err := initAndExtractComponents(cmd, args, opts)
if err != nil {
return err
}
if len(components) == 0 {
ui.Info("No components found")
return nil
}
// Build and execute render pipeline.
return renderComponents(atmosConfig, opts, components)
}
// initAndExtractComponents initializes config and extracts components from stacks.
func initAndExtractComponents(cmd *cobra.Command, args []string, opts *ComponentsOptions) (*schema.AtmosConfiguration, []map[string]any, error) {
defer perf.Track(nil, "list.components.initAndExtractComponents")()
// Process command line args to get ConfigAndStacksInfo with CLI flags.
configAndStacksInfo, err := e.ProcessCommandLineArgs("list", cmd, args, nil)
if err != nil {
return nil, nil, err
}
atmosConfig, err := config.InitCliConfig(configAndStacksInfo, true)
if err != nil {
return nil, nil, fmt.Errorf("%w: %w", errUtils.ErrInitializingCLIConfig, err)
}
// If format is empty, check command-specific config.
if opts.Format == "" && atmosConfig.Components.List.Format != "" {
opts.Format = atmosConfig.Components.List.Format
}
// Create AuthManager for authentication support.
authManager, err := createAuthManagerForList(cmd, &atmosConfig)
if err != nil {
return nil, nil, err
}
stacksMap, err := e.ExecuteDescribeStacks(&atmosConfig, "", nil, nil, nil, false, false, false, false, nil, authManager)
if err != nil {
return nil, nil, fmt.Errorf("%w: %w", errUtils.ErrExecuteDescribeStacks, err)
}
// Extract unique components (deduplicated across all stacks).
// This is the original "list components" behavior - showing unique component definitions.
// Pass the stack pattern to filter which stacks to consider when deduplicating.
components, err := extract.UniqueComponents(stacksMap, opts.Stack)
if err != nil {
return nil, nil, err
}
return &atmosConfig, components, nil
}
// renderComponents builds the render pipeline and renders components.
func renderComponents(atmosConfig *schema.AtmosConfiguration, opts *ComponentsOptions, components []map[string]any) error {
defer perf.Track(nil, "list.components.renderComponents")()
// Build filters.
filters := buildComponentFilters(opts)
// Get column configuration.
columns := getComponentColumns(atmosConfig, opts.Columns)
// Build column selector.
selector, err := column.NewSelector(columns, column.BuildColumnFuncMap())
if err != nil {
return fmt.Errorf("error creating column selector: %w", err)
}
// Build sorters.
sorters, err := buildComponentSorters(opts.Sort)
if err != nil {
return fmt.Errorf("error parsing sort specification: %w", err)
}
// Create renderer and execute pipeline.
outputFormat := format.Format(opts.Format)
r := renderer.New(filters, selector, sorters, outputFormat, "")
return r.Render(components)
}
// buildComponentFilters creates filters based on command options.
// Note: --stack filter is not applicable to unique components (use "list instances" for per-stack filtering).
func buildComponentFilters(opts *ComponentsOptions) []filter.Filter {
defer perf.Track(nil, "list.components.buildComponentFilters")()
var filters []filter.Filter
// Note: Stack filter is intentionally not applied here.
// "list components" shows unique component definitions, not per-stack instances.
// Use "atmos list instances --stack=xxx" for per-stack filtering.
// Type filter (authoritative when provided, targets component_type field).
if opts.Type != "" && opts.Type != "all" {
filters = append(filters, filter.NewColumnFilter("component_type", opts.Type))
} else if opts.Type == "" && !opts.Abstract {
// Only apply default abstract filter when Type is not set.
filters = append(filters, filter.NewColumnFilter("component_type", "real"))
}
// Enabled filter (tri-state: nil = all, true = enabled only, false = disabled only).
if opts.Enabled != nil {
filters = append(filters, filter.NewBoolFilter("enabled", opts.Enabled))
}
// Locked filter (tri-state: nil = all, true = locked only, false = unlocked only).
if opts.Locked != nil {
filters = append(filters, filter.NewBoolFilter("locked", opts.Locked))
}
return filters
}
// getComponentColumns returns column configuration for unique components listing.
func getComponentColumns(atmosConfig *schema.AtmosConfiguration, columnsFlag []string) []column.Config {
defer perf.Track(nil, "list.components.getComponentColumns")()
// If --columns flag is provided, parse it and return.
if len(columnsFlag) > 0 {
return parseColumnsFlag(columnsFlag)
}
// Check new config path: list.components.columns.
if len(atmosConfig.List.Components.Columns) > 0 {
var configs []column.Config
for _, col := range atmosConfig.List.Components.Columns {
configs = append(configs, column.Config{
Name: col.Name,
Value: col.Value,
Width: col.Width,
})
}
return configs
}
// Default columns: show unique component information.
// Note: Stack is not included because this lists unique components, not instances.
// Note: We intentionally do NOT fall back to components.list.columns here because
// that configuration is designed for instances (per-stack data), not unique components.
return []column.Config{
{Name: "Component", Value: "{{ .component }}"},
{Name: "Type", Value: "{{ .type }}"},
{Name: "Stacks", Value: "{{ .stack_count }}"},
}
}
// buildComponentSorters creates sorters from sort specification.
func buildComponentSorters(sortSpec string) ([]*listSort.Sorter, error) {
defer perf.Track(nil, "list.components.buildComponentSorters")()
if sortSpec == "" {
// Default sort: by component name ascending for deterministic output.
return []*listSort.Sorter{
listSort.NewSorter("Component", listSort.Ascending),
}, nil
}
return listSort.ParseSortSpec(sortSpec)
}
// parseColumnsFlag parses column specifications from CLI flag.
// Supports two formats:
// - Simple field name: "component" → Name: "component", Value: "{{ .component }}"
// - Named column with template: "Name=template" → Name: "Name", Value: "template"
//
// Examples:
//
// --columns component,stack,type
// --columns "Component={{ .component }},Stack={{ .stack }}"
// --columns component --columns stack
func parseColumnsFlag(columnsFlag []string) []column.Config {
defer perf.Track(nil, "list.components.parseColumnsFlag")()
var configs []column.Config
for _, spec := range columnsFlag {
cfg := parseColumnSpec(spec)
if cfg.Name != "" {
configs = append(configs, cfg)
}
}
return configs
}
// parseColumnSpec parses a single column specification.
// Format: "name" or "Name=template".
func parseColumnSpec(spec string) column.Config {
defer perf.Track(nil, "list.components.parseColumnSpec")()
spec = strings.TrimSpace(spec)
if spec == "" {
return column.Config{}
}
// Check for Name=template format.
if idx := strings.Index(spec, "="); idx > 0 {
name := strings.TrimSpace(spec[:idx])
value := strings.TrimSpace(spec[idx+1:])
// If value doesn't contain template syntax, wrap it.
if !strings.Contains(value, "{{") {
value = "{{ ." + value + " }}"
}
return column.Config{
Name: name,
Value: value,
}
}
// Simple field name: auto-generate template.
// Use title case for display name.
name := strings.Title(spec) //nolint:staticcheck // strings.Title is deprecated but works for simple ASCII column names
value := "{{ ." + spec + " }}"
return column.Config{
Name: name,
Value: value,
}
}