Repository navigation
feature: implement label-based filtering to all list and describe commands - #1323
Matt Calhoun (mcalhoun) wants to merge 21 commits into
Conversation
|
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. |
|
Important Cloud Posse Engineering Team Review RequiredThis pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes. To expedite this process, reach out to us on Slack in the |
| } | ||
|
|
||
| selectorFlag, _ := flags.GetString("selector") | ||
| if selectorFlag != "" { |
Check warning
Code scanning / golangci-lint
`if selectorFlag != ""` has complex nested blocks (complexity: 9)
| return nil, err | ||
| } | ||
|
|
||
| if selectorFlag != "" { |
Check warning
Code scanning / golangci-lint
`if selectorFlag != ""` has complex nested blocks (complexity: 4)
📝 WalkthroughWalkthroughLabel selector filtering is now supported across multiple CLI commands for stacks, components, and related resources. A new Changes
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
Suggested reviewers
📜 Recent review detailsConfiguration used: .coderabbit.yaml 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
🧰 Additional context used🪛 golangci-lint (1.64.8)cmd/list_components.go[warning] 68-68: (nestif) ⏰ Context from checks skipped due to timeout of 90000ms (6)
🔇 Additional comments (3)
✨ Finishing Touches
🧪 Generate Unit Tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
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
Parsefunction 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
matchRequirementfunction 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.yamlbut the environment label is set to "dev". For clarity, consider usingenv: "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-sensitivepkg/selector/labels.go (1)
28-36: Consider optimizing the string conversion function.The
toStringMapfunction 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
📒 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=includeatmos 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
DescribeComponentParamsstruct, 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
MergedLabelsfunction 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 forrequiredarrays
Top-leveloneOfclauses now use inline arrays forrequiredto improve readability. No semantic change.
118-119: Inlinerequiredfor theimportobject
Therequired: ["path"]is now single-line. Formatting only, behavior unchanged.
380-381: Inlineenumvalues formetadata.type
Consolidated["abstract", "real"]onto one line. No functional impact.
432-438: Add optionallabelsproperty tometadata
This introducesmetadata.labelsfor label selector filtering. Ensure this aligns with your merging logic and downstream validation.
533-533: Requireschema_typeandschema_pathinvalidation_manifest
Adding these required fields could break existing manifests. Confirm that allvalidation_manifestusages include both fields.
820-827: Unified inline formatting fordepends_on_manifestrequired arrays
Converted multilinerequiredarrays to inline form. No semantic change.
1001-1008: Inlinerequireddefinitions inworkflow_manifest
Consolidatedrequiredarrays forstepsand its itemcommandonto single lines. Formatting only.examples/demo-localstack/schemas/atmos-manifest.json (7)
41-76: Consistent inline formatting for top-levelrequired
TheoneOfrequirements have been consolidated into single-line arrays. Readability improvement, no behavior change.
118-119: Inlinerequiredforimport.path
Single-linerequired: ["path"]enhances conciseness. No semantic impact.
380-381: Metadatatypeenum values inline
Listing["abstract", "real"]inline is purely formatting.
432-438: Add optionallabelsfield inmetadata
Enables label selector filtering for demo configurations. Good complement to core schema.
533-533: Require fields invalidation_manifest
Introducing requiredschema_typeandschema_path. Verify existing demo manifests comply.
820-827: Inline formatting fordepends_on_manifestoneOf.required
Formatting change only, converting to single-line arrays.
1001-1008: Inlinerequiredforworkflow_manifest
Single-linerequiredforcommandandsteps. No functional difference.tests/fixtures/scenarios/selector/atmos.yaml (4)
1-2: Define projectbase_pathrelative to fixture
Usingbase_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 forrequiredarrays
Top-leveloneOf.requiredarrays are now single-line, improving maintainability without altering semantics.
118-119: Inlinerequiredforimport.path
Changed to single-line required array. No behavior change.
380-381: Compact enum formetadata.type
Inline enum listing is a formatting update only.
432-438: Addlabelstometadataschema
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 invalidation_manifest
Introducing required keys. Confirm that existing docs and examples include bothschema_typeandschema_path.
820-827: Single-linerequiredindepends_on_manifest
Formatting change only.
1001-1008: Inlinerequiredfor 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
labelsproperty 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
labelsproperty 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.
|
|
||
| // 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
| } | ||
|
|
||
| return filtered, nil | ||
| } |
Check failure
Code scanning / golangci-lint
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.
There was a problem hiding this comment.
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 syntaxRepeat 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
📒 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 ninelistanddescribecommands 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
There was a problem hiding this comment.
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
📒 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:
filterComponentsBySelectorhandles the main filtering loopcomponentMatchesSelectorchecks component matches across stackscheckComponentInStackencapsulates component existence and label matchingThis 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
There was a problem hiding this comment.
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 usecritical=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-lalias in examples
All snippets show--selector; it would help users to see the shorthand-las 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
📒 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
| ```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" } | ||
| ``` | ||
|
|
There was a problem hiding this comment.
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.
| ```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
There was a problem hiding this comment.
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 aslugentry alongside the existing fields. For example:slug: /reference/label-selectors
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 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
|
CodeRabbit (@coderabbitai) rescan |
|
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 AssessmentThis 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 ReviewSelector Package (
|
…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.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 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.
| 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) | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| 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
This reverts commit ba7c564.
…be_stacks.go" This reverts commit 0e68cf2.
…ck_processor_utils.go" This reverts commit b509b12.
|
💥 This pull request now has conflicts. Could you fix it Matt Calhoun (@mcalhoun)? 🙏 |
|
💥 This pull request now has conflicts. Could you fix it Matt Calhoun (@mcalhoun)? 🙏 |
Quality Gate
Readiness✅ Fewer than 150 changed files ReviewsMeasuresCurrent commit: Quality Gate details
🤖 Next steps for this PR |
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.labelswith the new--selector(-l) flag.Core Implementation
Label Selector Parser:
key=value)key!=value)key in (a,b))key notin (a,b))key)!key)CLI Integration:
--selector(-l) flag to 9 commands:atmos list stacksatmos list componentsatmos list valuesatmos list varsatmos list settingsatmos list metadataatmos describe componentatmos describe stacksatmos describe affected--stack,--component,--type)Data Model Extensions:
metadata.labelsMergedLabels()function for proper inheritance resolutionError Handling:
Comprehensive Testing
Unit Testing:
Integration Testing:
--selector+ other flags)tests/test-cases/selector-cli.yamlTest Infrastructure:
tests/fixtures/scenarios/selector/Schema Updates
JSON Schema Modifications:
pkg/datafetcher/schema/stacks/stack-config/1.0.jsonpkg/datafetcher/schema/config/global/1.0.jsonpkg/datafetcher/schema/atmos/manifest/1.0.jsonwebsite/static/schemas/atmos/atmos-manifest/1.0/atmos-manifest.jsonComplete Documentation
CLI Command Documentation:
--selectorflag documentation to all 9 affected commandsCore Concepts Documentation:
define-components.mdxwith comprehensivemetadata.labelssectionReference Documentation:
website/docs/reference/label-selectors.mdxwith complete syntax referenceUser Examples:
Task Completion Status
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:
Operational Efficiency:
Scalability Support:
Production Readiness:
References
Key Files Added/Modified
Core Implementation:
pkg/selector/selector.go- Label selector parser and evaluation logicpkg/selector/labels.go- Label inheritance and merging functionspkg/selector/selector_test.go- Comprehensive unit testscmd/selector_flags_test.go- CLI flag integration testsCommand Integration:
cmd/describe.go,cmd/describe_affected.go,cmd/describe_component.go,cmd/describe_stacks.gocmd/list.go,cmd/list_components.go,cmd/list_metadata.go,cmd/list_settings.go,cmd/list_stacks.go,cmd/list_values.gointernal/exec/describe_affected.go,internal/exec/describe_component.go,internal/exec/describe_stacks.gopkg/list/list_values.goSchema Updates:
pkg/datafetcher/schema/atmos/manifest/1.0.jsonpkg/datafetcher/schema/config/global/1.0.jsonpkg/datafetcher/schema/stacks/stack-config/1.0.jsonexamples/demo-helmfile/schemas/atmos-manifest.jsonexamples/demo-localstack/schemas/atmos-manifest.jsonwebsite/static/schemas/atmos/atmos-manifest/1.0/atmos-manifest.jsonTest Infrastructure:
tests/test-cases/selector-cli.yaml- CLI integration teststests/fixtures/scenarios/selector/- Test fixtures with labeled stacksDocumentation:
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.mdxwebsite/docs/reference/label-selectors.mdx(new)website/docs/cheatsheets/common.mdxThis 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
--selector(alias-l) flag to multiple CLI commands, enabling powerful label-based filtering of stacks, components, settings, metadata, and affected resources.labels, with component labels overriding stack labels where applicable.Documentation
Tests
Schema Updates
labelsproperty in stack and component metadata.