-
-
Notifications
You must be signed in to change notification settings - Fork 111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement: atmos list values #1036
base: main
Are you sure you want to change the base?
Conversation
📝 WalkthroughWalkthroughThis update introduces two new CLI commands— Changes
Possibly related PRs
Suggested labels
Suggested reviewers
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (11)
pkg/list/list_workflows.go (1)
202-230
: Simplify the default case logic.The default case handles both empty format and "table" format with duplicated string joining logic. This can be simplified to reduce code duplication.
Consider this refactor:
default: + var output strings.Builder + output.WriteString(strings.Join(header, delimiter) + utils.GetLineEnding()) + for _, row := range rows { + output.WriteString(strings.Join(row, delimiter) + utils.GetLineEnding()) + } + // If format is empty or "table", use table format if format == "" && term.IsTTYSupportForStdout() { // Create a styled table for TTY t := table.New(). // ... existing table configuration ... Headers(header...). Rows(rows...) return t.String() + utils.GetLineEnding(), nil } - // Default to simple tabular format for non-TTY or when format is explicitly "table" - var output strings.Builder - output.WriteString(strings.Join(header, delimiter) + utils.GetLineEnding()) - for _, row := range rows { - output.WriteString(strings.Join(row, delimiter) + utils.GetLineEnding()) - } return output.String(), nilpkg/list/list_values.go (3)
23-31
: Consider removing the unused function.The static analysis tool confirms that
getMapKeys
is unused. If there's no future usage planned, removing it will reduce clutter.-// getMapKeys returns a sorted slice of map keys -func getMapKeys(m map[string]interface{}) []string { - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - return keys -}🧰 Tools
🪛 golangci-lint (1.62.2)
24-24: func
getMapKeys
is unused(unused)
34-324
: Refactor the large function.
FilterAndListValues
handles multiple steps: filtering stacks, applying queries, formatting output, etc. Splitting it into smaller helper functions would improve readability and maintainability.
265-272
: Handle CSV field quoting.Concatenating fields with a plain delimiter can corrupt CSV data if the field itself contains the delimiter or newline. Consider quoting fields for robust CSV output.
pkg/list/list_values_test.go (1)
56-148
: Expand test coverage.You might test nested or array-based query paths to confirm filtering works for complex data structures. It would further validate the code’s resilience.
cmd/list_values.go (2)
35-63
: Avoid repeated flag error-handling.Error-handling for each flag is repeated. Consolidating this into a small helper would reduce duplication and simplify reading.
95-116
: Evaluate independent command structure.
listVarsCmd
sets a single flag before reusinglistValuesCmd.Run
. This works but might complicate future expansions. Consider a dedicated or unified approach for better clarity.website/docs/cli/commands/list/list-values.mdx (4)
31-42
: Consider enhancing flag documentation with example values.While the flag descriptions are clear, adding example values would make them more user-friendly.
<dt><code>--query string</code></dt> - <dd>JMESPath query to filter values (e.g., ".vars" to show only variables)</dd> + <dd>JMESPath query to filter values (e.g., ".vars" to show only variables, ".config.vpc" to show VPC configuration)</dd> <dt><code>--format string</code></dt> - <dd>Output format: `table`, `json`, `csv`, `tsv` (default "`table`")</dd> + <dd>Output format: `table`, `json`, `csv`, `tsv` (default "`table`"). Example: --format=json</dd>
58-58
: Replace TODO placeholder with actual JMESPath query examples.The placeholder needs to be replaced with practical JMESPath query examples to help users understand how to filter values effectively.
Would you like me to help generate some practical JMESPath query examples? Here's a suggestion:
-TODO: define more outputs +# Show only networking configuration +atmos list values vpc --query ".config.networking" + +# Filter for specific environment variables +atmos list values vpc --query ".vars | [?contains(name, 'ENV')]" + +# Show components with specific tags +atmos list values vpc --query ".metadata.tags"
86-86
: Add example command output to enhance documentation.Replace the TODO with actual command output to help users understand what to expect.
Would you like me to help generate an example output? Here's a suggestion:
-TODO: define example output +Component: vpc + +┌─────────────┬──────────────┬──────────────┬──────────────┐ +│ Key │ dev-ue1 │ staging-ue1 │ prod-ue1 │ +├─────────────┼──────────────┼──────────────┼──────────────┤ +│ cidr_block │ 10.0.0.0/16 │ 10.1.0.0/16 │ 10.2.0.0/16 │ +│ enable_flow │ true │ true │ true │ +│ max_azs │ 3 │ 3 │ 3 │ +└─────────────┴──────────────┴──────────────┴──────────────┘
91-92
: Enhance typography in related commands section.Replace hyphens with em dashes for better readability.
-[atmos list components](/cli/commands/list/component) - List available components -[atmos describe component](/cli/commands/describe/component) - Show detailed information about a component +[atmos list components](/cli/commands/list/component) — List available components +[atmos describe component](/cli/commands/describe/component) — Show detailed information about a component🧰 Tools
🪛 LanguageTool
[typographical] ~91-~91: To join two clauses or introduce examples, consider using an em dash.
Context: ...omponents](/cli/commands/list/component) - List available components - [atmos descr...(DASH_RULE)
[typographical] ~92-~92: To join two clauses or introduce examples, consider using an em dash.
Context: ...onent](/cli/commands/describe/component) - Show detailed information about a compon...(DASH_RULE)
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
cmd/list_values.go
(1 hunks)pkg/list/list_values.go
(1 hunks)pkg/list/list_values_test.go
(1 hunks)pkg/list/list_workflows.go
(1 hunks)pkg/list/list_workflows_test.go
(7 hunks)website/docs/cli/commands/list/list-values.mdx
(1 hunks)
🧰 Additional context used
🪛 LanguageTool
website/docs/cli/commands/list/list-values.mdx
[typographical] ~91-~91: To join two clauses or introduce examples, consider using an em dash.
Context: ...omponents](/cli/commands/list/component) - List available components - [atmos descr...
(DASH_RULE)
[typographical] ~92-~92: To join two clauses or introduce examples, consider using an em dash.
Context: ...onent](/cli/commands/describe/component) - Show detailed information about a compon...
(DASH_RULE)
🪛 golangci-lint (1.62.2)
pkg/list/list_values.go
24-24: func getMapKeys
is unused
(unused)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Summary
🔇 Additional comments (3)
pkg/list/list_workflows.go (1)
25-25
: LGTM! New format constants follow the established pattern.The addition of
FormatYAML
andFormatTSV
constants maintains consistency with the existing format naming convention.Also applies to: 27-27
pkg/list/list_workflows_test.go (1)
76-76
: LGTM! File permission notation updated to modern format.The change to use the
0o
prefix for octal file permissions is more explicit and follows modern Go conventions.Also applies to: 89-89, 100-100, 118-118, 136-136, 310-310
website/docs/cli/commands/list/list-values.mdx (1)
1-28
: Strong work on the command description!The command description effectively communicates the purpose and value proposition of the
atmos list values
command. The tabular view explanation is particularly clear and helpful.
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (2)
pkg/list/list_values.go (2)
23-31
: Consider makinggetMapKeys
an unexported function.The function is only used internally within this package and is currently marked as unused. Following Go conventions, internal helper functions should be unexported.
-func getMapKeys(m map[string]interface{}) []string { +func getMapKeys(m map[string]interface{}) []string {🧰 Tools
🪛 golangci-lint (1.62.2)
24-24: func
getMapKeys
is unused(unused)
48-86
: Consider extracting type assertions into helper functions.The stack filtering logic contains multiple nested type assertions that could be refactored into helper functions for better readability and maintainability.
Example helper function:
func getComponentVars(stackData interface{}, componentName string, includeAbstract bool) (map[string]interface{}, bool) { stack, ok := stackData.(map[string]interface{}) if !ok { return nil, false } components, ok := stack["components"].(map[string]interface{}) if !ok { return nil, false } terraform, ok := components["terraform"].(map[string]interface{}) if !ok { return nil, false } componentConfig, exists := terraform[componentName] if !exists { return nil, false } config, ok := componentConfig.(map[string]interface{}) if !ok { return nil, false } if !includeAbstract { if isAbstract, ok := config["abstract"].(bool); ok && isAbstract { return nil, false } } vars, ok := config["vars"].(map[string]interface{}) if !ok { return nil, false } return vars, true }
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
cmd/list_values.go
(1 hunks)pkg/list/list_values.go
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- cmd/list_values.go
🧰 Additional context used
🪛 golangci-lint (1.62.2)
pkg/list/list_values.go
24-24: func getMapKeys
is unused
(unused)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Summary
🔇 Additional comments (3)
pkg/list/list_values.go (3)
1-21
: Well-structured package with clear organization!The package follows Go best practices with logically grouped imports and well-defined constants.
287-287
: Use theTableColumnPadding
constant instead of magic number.Replace the magic number
3
with the defined constantTableColumnPadding
for consistency.- totalWidth += maxWidth + 3 + totalWidth += maxWidth + TableColumnPadding
296-296
: Use centralized TTY support check.As mentioned in previous reviews, we should use a centralized function for TTY support checks to maintain consistent behavior across the codebase.
- Renamed `list_values` to `list_metadata` and `list_settings` - Added stack pattern filtering for all commands - Updated usage docs with new command examples - Introduced wildcard matching utility function
Important Cloud Posse Engineering Team Review RequiredThis pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes. To expedite this process, reach out to us on Slack in the |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (4)
cmd/list_metadata.go (1)
34-36
: 🛠️ Refactor suggestionStandardize error handling with semantic logging.
Based on previous feedback, error handling should use semantic logging consistently.
- fmt.Fprintf(os.Stderr, "Error initializing CLI config: %v\n", err) + logger.Error("failed to initialize CLI config", "error", err) return - logger.Error(fmt.Errorf("failed to get stack pattern flag: %v", err)) + logger.Error("failed to get stack pattern flag", "error", err) return - logger.Error(fmt.Errorf("failed to describe stacks: %v", err)) + logger.Error("failed to describe stacks", "error", err)Also applies to: 48-50, 96-102
cmd/list_settings.go (1)
34-36
: 🛠️ Refactor suggestionStandardize error handling with semantic logging.
The same error handling improvements are needed here for consistency.
Also applies to: 48-50, 96-102
cmd/list_values.go (2)
133-136
: 🛠️ Refactor suggestionStandardize error handling in listVarsCmd.
For consistency with the rest of the codebase, use the logger instead of PrintMessageInColor.
- u.PrintMessageInColor(fmt.Sprintf("Error setting query flag: %v", err), theme.Colors.Error) + logger.Error("failed to set query flag", "error", err)
41-49
: 🛠️ Refactor suggestionStandardize error handling with semantic logging.
Apply consistent error handling pattern here as well.
- fmt.Fprintf(os.Stderr, "Error initializing CLI config: %v\n", err) + logger.Error("failed to initialize CLI config", "error", err) return - fmt.Fprintf(os.Stderr, "Error initializing logger: %v\n", err) + logger.Error("failed to initialize logger", "error", err)
🧹 Nitpick comments (10)
pkg/utils/wildcard.go (1)
8-14
: Enhance documentation with path separator details.The documentation is good but could be more explicit about path separator normalization. Consider adding a note about backslash/forward-slash handling.
// MatchWildcard checks if a string matches a wildcard pattern. // The pattern can include simple file-style glob patterns: // - '*' matches any sequence of non-separator characters // - '?' matches any single non-separator character // - '[abc]' matches any character within the brackets // - '[a-z]' matches any character in the range +// Note: Path separators (backslashes and forward slashes) are normalized +// to forward slashes before matching.pkg/list/list_values.go (4)
23-45
: Consider enhancing error handling in helper functions.While the functions are well-implemented, consider adding capacity validation in
getMapKeys
and input validation inmatchStackPattern
.func getMapKeys(m map[string]interface{}) []string { + if m == nil { + return []string{} + } keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } sort.Strings(keys) return keys } func matchStackPattern(stackName, pattern string) (bool, error) { + if stackName == "" { + return false, fmt.Errorf("stack name cannot be empty") + } if pattern == "" { return true, nil // No pattern means match all }
47-74
: Consider caching terminal width.The terminal width is retrieved directly from
templates.GetTerminalWidth()
. Consider caching this value to avoid multiple calls in case of repeated invocations.+ // Cache terminal width to avoid multiple calls + var termWidth int + if format == "" || format == FormatTable { + termWidth = templates.GetTerminalWidth() + }
75-148
: Consider extracting filtering logic into separate functions.The stack filtering logic is complex and handles multiple concerns. Consider breaking it down into smaller, focused functions for better maintainability.
For example:
+func filterStackByPattern(stackName string, stackPattern string) (bool, error) { + matched, err := matchStackPattern(stackName, stackPattern) + if err != nil { + return false, err + } + return matched, nil +} + +func processSpecialComponents(component string, stack map[string]interface{}) (map[string]interface{}, bool) { + if component == "settings" || component == "metadata" { + return stack, true + } + return nil, false +}
297-398
: Optimize output formatting for large datasets.The current implementation loads all data into memory before formatting. Consider implementing streaming for large datasets.
+func streamTableOutput(header []string, rows [][]string, delimiter string) (string, error) { + var output strings.Builder + output.WriteString(strings.Join(header, delimiter) + utils.GetLineEnding()) + + // Stream rows in chunks + const chunkSize = 1000 + for i := 0; i < len(rows); i += chunkSize { + end := i + chunkSize + if end > len(rows) { + end = len(rows) + } + for _, row := range rows[i:end] { + output.WriteString(strings.Join(row, delimiter) + utils.GetLineEnding()) + } + } + return output.String(), nil +}cmd/markdown/atmos_list_metadata_usage.md (1)
1-1
: Use an em dash for better readability.Replace the en dash with an em dash for better typography.
-– List metadata across stacks +— List metadata across stacks🧰 Tools
🪛 LanguageTool
[typographical] ~1-~1: Consider using an em dash in dialogues and enumerations.
Context: – List metadata across stacks Usage: ```...(DASH_RULE)
cmd/markdown/atmos_list_values_usage.md (2)
1-2
: Typographical Consistency in HeaderThe header “– List component values across stacks” looks good, but consider verifying that the dash used is the preferred em dash for documentation consistency (per LanguageTool hints).
🧰 Tools
🪛 LanguageTool
[typographical] ~1-~1: Consider using an em dash in dialogues and enumerations.
Context: – List component values across stacks Us...(DASH_RULE)
49-53
: Useful Notes with a Minor SuggestionThe note section gives practical advice for handling wide tables and filtering. As a minor point, you might consider rephrasing the bullet on stack patterns to read, for example, “Stack patterns support glob matching (e.g., use '-dev-' or 'prod-*')” for enhanced clarity.
website/docs/cli/commands/list/list-settings.mdx (1)
99-103
: Practical Notes with a Minor Rewording SuggestionThe notes nicely summarize key considerations. For the bullet on stack patterns, consider adding a preposition (e.g., “Stack patterns support glob matching such as '-dev-', 'prod-*'”) to enhance clarity.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~102-~102: Possible missing preposition found.
Context: ...e the number of stacks - Stack patterns support glob matching (e.g., '-dev-', 'prod-*...(AI_HYDRA_LEO_MISSING_TO)
website/docs/cli/commands/list/list-metadata.mdx (1)
99-104
: Informative Notes with a Minor SuggestionThe notes section provides useful tips for handling wide tables and explains that stack patterns support glob matching. For enhanced clarity, consider rephrasing the bullet to “Stack patterns support glob matching (e.g., '-dev-' or 'prod-*')”.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
cmd/list_metadata.go
(1 hunks)cmd/list_settings.go
(1 hunks)cmd/list_values.go
(1 hunks)cmd/markdown/atmos_list_metadata_usage.md
(1 hunks)cmd/markdown/atmos_list_settings_usage.md
(1 hunks)cmd/markdown/atmos_list_values_usage.md
(1 hunks)cmd/markdown/atmos_list_vars_usage.md
(1 hunks)pkg/list/list_values.go
(1 hunks)pkg/utils/wildcard.go
(1 hunks)website/docs/cli/commands/list/list-metadata.mdx
(1 hunks)website/docs/cli/commands/list/list-settings.mdx
(1 hunks)
🧰 Additional context used
🪛 LanguageTool
cmd/markdown/atmos_list_values_usage.md
[typographical] ~1-~1: Consider using an em dash in dialogues and enumerations.
Context: – List component values across stacks Us...
(DASH_RULE)
cmd/markdown/atmos_list_settings_usage.md
[typographical] ~1-~1: Consider using an em dash in dialogues and enumerations.
Context: – List settings across stacks Usage: ```...
(DASH_RULE)
[uncategorized] ~48-~48: Possible missing preposition found.
Context: ...e the number of stacks - Stack patterns support glob matching (e.g., '-dev-', 'prod-*...
(AI_HYDRA_LEO_MISSING_TO)
cmd/markdown/atmos_list_metadata_usage.md
[typographical] ~1-~1: Consider using an em dash in dialogues and enumerations.
Context: – List metadata across stacks Usage: ```...
(DASH_RULE)
website/docs/cli/commands/list/list-settings.mdx
[uncategorized] ~102-~102: Possible missing preposition found.
Context: ...e the number of stacks - Stack patterns support glob matching (e.g., '-dev-', 'prod-*...
(AI_HYDRA_LEO_MISSING_TO)
website/docs/cli/commands/list/list-metadata.mdx
[uncategorized] ~51-~51: Possible missing preposition found.
Context: ... shell atmos list metadata
List metadata for specific stacks: ```shell # List me...
(AI_HYDRA_LEO_MISSING_OF)
cmd/markdown/atmos_list_vars_usage.md
[typographical] ~1-~1: Consider using an em dash in dialogues and enumerations.
Context: – List component variables across stacks ...
(DASH_RULE)
[duplication] ~50-~50: Possible typo: you repeated a word.
Context: ...arated values Note: - This is an alias for atmos list values <component> --query .vars
- For wide tables, try using more specific qu...
(ENGLISH_WORD_REPEAT_RULE)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Summary
🔇 Additional comments (23)
pkg/list/list_values.go (1)
3-21
: Well-organized imports and constants!The imports are logically grouped, and the constants are clearly defined with meaningful names.
cmd/markdown/atmos_list_settings_usage.md (1)
1-1
: Use an em dash for better readability.Replace the en dash with an em dash for better typography.
🧰 Tools
🪛 LanguageTool
[typographical] ~1-~1: Consider using an em dash in dialogues and enumerations.
Context: – List settings across stacks Usage: ```...(DASH_RULE)
cmd/markdown/atmos_list_vars_usage.md (1)
1-1
: Use an em dash for better readability.Replace the en dash with an em dash for better typography.
🧰 Tools
🪛 LanguageTool
[typographical] ~1-~1: Consider using an em dash in dialogues and enumerations.
Context: – List component variables across stacks ...(DASH_RULE)
cmd/markdown/atmos_list_values_usage.md (4)
3-6
: Clear and Concise Usage SectionThe usage block is clearly presented and easy to follow. Great job on specifying the correct syntax for the command.
8-16
: Well-Documented FlagsThe flags are thoroughly listed with default values and explanations, making it very clear what options the command supports.
18-40
: Comprehensive Examples for Command UsageThe examples effectively demonstrate various command options and outputs. They cover multiple scenarios—from filtering by query to different output formats—which is very helpful to users.
42-48
: Clear Output Formats DefinitionThe description of the available output formats is succinct and informative. This helps users know what to expect when switching formats.
website/docs/cli/commands/list/list-settings.mdx (8)
1-4
: Solid Front Matter ConfigurationThe front matter is structured properly, ensuring that the document is correctly identified and titled.
6-9
: Concise Command DescriptionThe brief description of the
atmos list settings
command is clear and to the point. It effectively informs the user about the command’s purpose.
10-14
: Straightforward Usage SectionThe usage block is simple and uses a code block, which makes it easy for users to copy and execute the command.
16-28
: Detailed and Informative DescriptionThe description and bullet-point list explain how the command works in a very user-friendly manner. The clarity in outlining what each column and row represents is commendable.
29-42
: Well-Structured Flags SectionThe flags are neatly documented using a definition list, which improves legibility. Every flag has an explanation and its default value, ensuring no ambiguity for the users.
44-70
: Effective Examples Demonstrating Command CapabilitiesThe examples are practical and illustrate a variety of use cases (from listing all settings to filtering with JMESPath queries). This level of detail greatly enhances the documentation.
72-85
: Clear Instructions for Format OutputsThis section clearly outlines how to obtain various output formats, which is very useful for different user needs.
87-97
: Practical Example OutputThe provided example output gives users a good visual understanding of what to expect when running the command. The tabular display is neatly rendered.
website/docs/cli/commands/list/list-metadata.mdx (8)
1-4
: Correct Front Matter in DocumentationThe YAML front matter is correctly configured with title and ID, ensuring the document is well-indexed.
6-9
: Clear Overview of the CommandThe introduction for the
atmos list metadata
command is succinct and effectively explains the command’s intent.
10-14
: Straightforward Usage InstructionsThe usage section is clearly delineated and provides users with a simple command syntax to follow.
16-28
: Comprehensive Command DescriptionThe description outlines the tabular representation in a detailed yet clear manner, making it easy for users to understand the command’s function.
29-42
: Detailed Flags OverviewThe flags section is well-structured using a definition list. Each flag is clearly explained with defaults provided, contributing to overall clarity.
44-70
: Well-Illustrated ExamplesThe examples effectively demonstrate how to use the command in various scenarios, including filtering via JMESPath queries and selecting output formats. This adds significant practical value to the documentation.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~51-~51: Possible missing preposition found.
Context: ...shell atmos list metadata
List metadata for specific stacks: ```shell # List me...(AI_HYDRA_LEO_MISSING_OF)
72-85
: Clear Output Format GuidanceThe instructions for output in different formats are clearly presented and easy to follow, ensuring users know how to tailor output to their needs.
87-97
: Useful Example Output DisplayThe example output helps users visualize the expected result, which improves the overall clarity and usability of the documentation.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (2)
pkg/list/list_values.go (2)
17-21
: Add documentation for constants.Consider adding descriptive comments for each constant to improve code maintainability.
const ( + // DefaultCSVDelimiter is the default delimiter used for CSV output format DefaultCSVDelimiter = "," + // DefaultTSVDelimiter is the default delimiter used for TSV output format DefaultTSVDelimiter = "\t" + // TableColumnPadding defines the number of spaces used for padding table columns TableColumnPadding = 3 )
47-424
: Consider breaking down the FilterAndListValues function for better maintainability.The function is quite long and handles multiple responsibilities. Consider extracting the following into separate functions:
- Stack filtering logic (lines 76-148)
- Query processing logic (lines 155-223)
- Output formatting logic (lines 316-423)
This would improve readability and make the code easier to test.
Example refactor for the stack filtering logic:
+func filterStacksByPattern(stacksMap map[string]interface{}, stackPattern string, component string, includeAbstract bool) (map[string]interface{}, error) { + filteredStacks := make(map[string]interface{}) + for stackName, stackData := range stacksMap { + matched, err := matchStackPattern(stackName, stackPattern) + if err != nil { + return nil, err + } + if !matched { + continue + } + // ... rest of the filtering logic ... + } + return filteredStacks, nil +} func FilterAndListValues(stacksMap map[string]interface{}, component, query string, includeAbstract bool, maxColumns int, format, delimiter string, stackPattern string) (string, error) { // ... initial setup ... - filteredStacks := make(map[string]interface{}) - for stackName, stackData := range stacksMap { - // ... filtering logic ... - } + filteredStacks, err := filterStacksByPattern(stacksMap, stackPattern, component, includeAbstract) + if err != nil { + return "", err + } // ... rest of the function ... }
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
pkg/list/list_values.go
(1 hunks)pkg/list/list_values_test.go
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/list/list_values_test.go
🧰 Additional context used
🪛 golangci-lint (1.62.2)
pkg/list/list_values.go
24-24: func getMapKeys
is unused
(unused)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Summary
🔇 Additional comments (2)
pkg/list/list_values.go (2)
33-45
: LGTM! Well-structured pattern matching implementation.The function has good error handling and uses the utility function for wildcard matching.
397-397
: Use centralized TTY support function.As mentioned in previous reviews, we should use the centralized function for TTY support to maintain consistent behavior across the codebase.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
pkg/list/list_values.go (3)
58-58
: Consider handling terminal width retrieval errors.The terminal width retrieval could fail in certain environments.
-termWidth := templates.GetTerminalWidth() +termWidth, err := templates.GetTerminalWidth() +if err != nil { + return "", fmt.Errorf("failed to get terminal width: %w", err) +}
78-81
: Enhance error handling for invalid stack data.Instead of silently continuing on invalid stack data, consider logging or providing more context.
stack, ok := stackData.(map[string]interface{}) if !ok { + // Log warning or return error with context + return "", fmt.Errorf("invalid stack data structure for stack: expected map[string]interface{}, got %T", stackData) continue }
387-404
: Consider extracting table styling to a separate function.The table styling logic is complex and could be moved to a dedicated function for better maintainability.
+func createStyledTable(header []string, rows [][]string) *table.Table { + return table.New(). + Border(lipgloss.ThickBorder()). + BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color(theme.ColorBorder))). + StyleFunc(func(row, col int) lipgloss.Style { + style := lipgloss.NewStyle().PaddingLeft(1).PaddingRight(1) + if row == -1 { + return style.Inherit(theme.Styles.CommandName).Align(lipgloss.Center) + } + return style.Inherit(theme.Styles.Description) + }). + Headers(header...). + Rows(rows...) +}Then use it in the main function:
-t := table.New(). - Border(lipgloss.ThickBorder()). - BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color(theme.ColorBorder))). - StyleFunc(func(row, col int) lipgloss.Style { - style := lipgloss.NewStyle().PaddingLeft(1).PaddingRight(1) - if row == -1 { - return style.Inherit(theme.Styles.CommandName).Align(lipgloss.Center) - } - return style.Inherit(theme.Styles.Description) - }). - Headers(header...). - Rows(rows...) +t := createStyledTable(header, rows)
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
pkg/list/list_values.go
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Build (windows-latest, windows)
- GitHub Check: Summary
🔇 Additional comments (3)
pkg/list/list_values.go (3)
17-21
: LGTM! Well-defined constants.The constants are clearly defined and appropriately named, making the code more maintainable.
23-35
: LGTM! Clean pattern matching implementation.The
matchStackPattern
function is well-implemented with proper error handling and clear documentation.
382-384
: LGTM! Excellent user experience.The error message provides clear guidance when the table is too wide, suggesting specific solutions.
|
||
queryFlag, err := flags.GetString("query") | ||
if err != nil { | ||
logger.Error(fmt.Errorf("failed to get query flag: %v", err)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
logger.Error(fmt.Errorf("failed to get query flag: %v", err)) | |
logger.Error("failed to get query flag", "error", err) |
Use semantic logging, not wrapping.
Update all log statements in this PR
what
why
Evidence:


references
Summary by CodeRabbit
New Features
Documentation
atmos list values
,atmos list vars
,atmos list metadata
, andatmos list settings
commands.Tests
Error Handling