Skip to content
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

Open
wants to merge 28 commits into
base: main
Choose a base branch
from
Open

Implement: atmos list values #1036

wants to merge 28 commits into from

Conversation

Cerebrovinny
Copy link
Collaborator

@Cerebrovinny Cerebrovinny commented Feb 7, 2025

what

why

Evidence:
Screenshot 2025-02-14 at 10 34 36
Screenshot 2025-02-14 at 10 34 51

references

Summary by CodeRabbit

  • New Features

    • Introduced new CLI commands for listing component values, variables, metadata, and settings, enhancing user capabilities for data retrieval.
    • Expanded output options to support table, JSON, YAML, CSV, and TSV formats with flexible filtering and display customization.
    • Added support for wildcard pattern matching in stack filtering.
  • Documentation

    • Added comprehensive documentation detailing command usage, parameters, and examples for atmos list values, atmos list vars, atmos list metadata, and atmos list settings commands.
  • Tests

    • Enhanced test coverage to validate output formatting, flag handling, and error scenarios across various use cases, including new format validations and wildcard matching.
  • Error Handling

    • Introduced a custom error type for improved error reporting when no values are found for a specified component.

@Cerebrovinny Cerebrovinny marked this pull request as ready for review February 14, 2025 10:44
@Cerebrovinny Cerebrovinny requested a review from a team as a code owner February 14, 2025 10:44
Copy link
Contributor

coderabbitai bot commented Feb 14, 2025

📝 Walkthrough

Walkthrough

This update introduces two new CLI commands—listValuesCmd and listVarsCmd—implemented with the Cobra library to list component values and variables across stacks. It adds core logic in the list package for filtering and formatting outputs in multiple formats, including JSON, YAML, CSV, TSV, and a styled table. Additional tests were introduced for the filtering function, and constants for YAML and TSV formats were added. The changes are also documented in the CLI documentation for clear command usage.

Changes

File(s) Change Summary
cmd/list_values.go Added listValuesCmd and listVarsCmd commands with flag handling and error messaging using the Cobra library.
pkg/list/list_values.go Introduced FilterAndListValues, getMapKeys, and matchStackPattern functions to filter and format component values across stacks.
pkg/list/list_values_test.go Added comprehensive tests for FilterAndListValues covering various formats, queries, and error conditions.
pkg/list/list_workflows.go Added FormatYAML and FormatTSV constants; updated ValidateFormat to handle new formats.
pkg/list/list_workflows_test.go Updated tests to include YAML validation and standardized file permissions (using 0o644).
website/docs/cli/commands/list/list-values.mdx Added documentation for the atmos list values command including usage, flags, and examples.
cmd/markdown/atmos_list_values_usage.md Added usage examples for the atmos list values command.
cmd/markdown/atmos_list_vars_usage.md Documented the atmos list vars command with syntax and options.
pkg/list/errors.go Introduced custom error type ErrNoValuesFound for improved error handling related to missing values.
cmd/list_metadata.go Added listMetadataCmd command for listing metadata across stacks with flag handling.
cmd/list_settings.go Added listSettingsCmd command for listing settings across stacks with flag handling.
pkg/utils/wildcard.go Introduced MatchWildcard function for wildcard pattern matching.
website/docs/cli/commands/list/list-metadata.mdx Added documentation for the atmos list metadata command.
website/docs/cli/commands/list/list-settings.mdx Added documentation for the atmos list settings command.

Possibly related PRs

  • Component and stack completion support #992: The changes in the main PR, which introduce new CLI commands for listing component values and variables, are related to the retrieved PR, as both involve enhancements to command-line interface functionality, specifically through the use of completion features for components and stacks.
  • Add --query (shorthand -q) flag to all atmos describe <subcommand> commands #920: The changes in the main PR, which introduce new commands for listing component values and variables, are related to the retrieved PR as both involve enhancements to command-line functionality, specifically the addition of a --query flag that allows for filtering results.
  • feat: create atmos list command for listing stacks and components #797: The changes in the main PR, which introduce new commands for listing component values and variables, are related to the retrieved PR as both involve enhancements to the atmos list command functionality, specifically in how components and stacks are listed and processed.

Suggested labels

minor

Suggested reviewers

  • aknysh
  • osterman
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or @auto-summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @auto-title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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(), nil
pkg/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 reusing listValuesCmd.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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a55781 and 9060a00.

📒 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 and FormatTSV 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.

pkg/list/list_workflows.go Show resolved Hide resolved
pkg/list/list_workflows_test.go Show resolved Hide resolved
cmd/list_values.go Show resolved Hide resolved
website/docs/cli/commands/list/list-values.mdx Outdated Show resolved Hide resolved
website/docs/cli/commands/list/list-values.mdx Outdated Show resolved Hide resolved
website/docs/cli/commands/list/list-values.mdx Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 15, 2025
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
@mergify mergify bot added triage Needs triage and removed triage Needs triage labels Feb 15, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 making getMapKeys 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d87e2c and befa005.

📒 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 the TableColumnPadding constant instead of magic number.

Replace the magic number 3 with the defined constant TableColumnPadding 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.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 17, 2025
@mergify mergify bot removed the triage Needs triage label Feb 17, 2025
- 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
Copy link

mergify bot commented Feb 17, 2025

Important

Cloud Posse Engineering Team Review Required

This 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 #pr-reviews channel.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 suggestion

Standardize 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 suggestion

Standardize 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 suggestion

Standardize 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 suggestion

Standardize 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 in matchStackPattern.

 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 Header

The 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 Suggestion

The 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 Suggestion

The 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 Suggestion

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between befa005 and f07cb4a.

📒 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 Section

The usage block is clearly presented and easy to follow. Great job on specifying the correct syntax for the command.


8-16: Well-Documented Flags

The flags are thoroughly listed with default values and explanations, making it very clear what options the command supports.


18-40: Comprehensive Examples for Command Usage

The 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 Definition

The 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 Configuration

The front matter is structured properly, ensuring that the document is correctly identified and titled.


6-9: Concise Command Description

The 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 Section

The 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 Description

The 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 Section

The 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 Capabilities

The 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 Outputs

This section clearly outlines how to obtain various output formats, which is very useful for different user needs.


87-97: Practical Example Output

The 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 Documentation

The YAML front matter is correctly configured with title and ID, ensuring the document is well-indexed.


6-9: Clear Overview of the Command

The introduction for the atmos list metadata command is succinct and effectively explains the command’s intent.


10-14: Straightforward Usage Instructions

The usage section is clearly delineated and provides users with a simple command syntax to follow.


16-28: Comprehensive Command Description

The 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 Overview

The 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 Examples

The 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 Guidance

The 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 Display

The example output helps users visualize the expected result, which improves the overall clarity and usability of the documentation.

pkg/list/list_values.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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:

  1. Stack filtering logic (lines 76-148)
  2. Query processing logic (lines 155-223)
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between f07cb4a and 132dfce.

📒 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.

pkg/list/list_values.go Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 17, 2025
@mergify mergify bot removed the triage Needs triage label Feb 17, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 132dfce and ab3bde4.

📒 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.

pkg/list/list_values.go Show resolved Hide resolved

queryFlag, err := flags.GetString("query")
if err != nil {
logger.Error(fmt.Errorf("failed to get query flag: %v", err))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-cloudposse Needs Cloud Posse assistance
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants