Skip to content

refactor(cli_utils): DRY processArgsAndFlags with table-driven flag parsing, 100% unit test coverage - #2225

Merged
Andriy Knysh (aknysh) merged 14 commits into
mainfrom
copilot/rb-2204-improve-processargsandflags
Mar 20, 2026
Merged

Andriy Knysh (aknysh) merged 14 commits into
mainfrom
copilot/rb-2204-improve-processargsandflags

Conversation

Copilot AI commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor
  • Bug fix: Boolean flags (--dry-run, --skip-init, --affected, --all, --process-templates, --process-functions, -h/--help) were unconditionally stripping args[i+1] from Terraform/Helmfile pass-through args — silently dropping user-intended flags like --refresh=false or --parallelism=10. Fix: added valueTakingCommonFlags set; only value-consuming flags strip args[i+1].
  • Bug fix: strings.Split(arg, "=") rejected flag values containing = (e.g. --query=.tags[?env==prod], --append-user-agent=Key=Val). Fix: strings.SplitN(arg, "=", 2) throughout.
  • Bug fix: strings.HasPrefix(arg+"=", flag) was logically inverted — --terraform-command-extra matched --terraform-command. Fix: strings.HasPrefix(arg, flag+"=") at all call sites.
  • Bug fix: --from-plan and --identity unconditionally consumed args[i+1] even when it was another flag. Fix: both only strip args[i+1] when it does not start with -.
  • Bug fix: --settings-list-merge-strategy was parsed into ArgsAndFlagsInfo but absent from commonFlags, leaking it into Terraform pass-through args. Fix: added to both commonFlags and stringFlagDefs.
  • Refactor: replaced 25+ copy-paste if/else chains (~200 lines) with a table-driven design: stringFlagDefs (26 entries), parseFlagValue helper, parseIdentityFlag helper, parseFromPlanFlag helper, and valueTakingCommonFlags set. Cyclomatic complexity: ~67 → ~15.
  • Tests: added internal/exec/cli_utils_helpers_test.go — 100% coverage on processArgsAndFlags, parseFlagValue, parseIdentityFlag, parseFromPlanFlag, parseQuotedCompoundSubcommand. Regression tests confirm boolean flags no longer drop adjacent pass-through args.
  • Docs: blog post website/blog/2026-03-18-process-args-flags-refactor.mdx, roadmap milestone website/src/data/roadmap.js, code comment clarifying --process-templates/--process-functions are Cobra-only flags.
  • Closes refactor: reduce ExecuteDescribeStacks cyclomatic complexity 247→10 + near-100% unit test coverage  #2204

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@mergify mergify Bot added triage Needs triage wip Work in Progress: Not ready for final review or merge labels Mar 18, 2026
@nitrocode RB (nitrocode) added patch A minor, backward compatible change and removed triage Needs triage labels Mar 18, 2026
Copilot AI and others added 2 commits March 18, 2026 01:13
…it test coverage

- Extract parseFlagValue helper to eliminate 25+ repetitive if/else flag-parsing patterns
- Extract parseIdentityFlag helper for --identity special-case semantics
- Extract parseFromPlanFlag helper for --from-plan optional-value semantics
- Create stringFlagDef table mapping 26 flags to ArgsAndFlagsInfo setters (DRY)
- Consolidate 5 boolean flags into a single switch statement
- Remove dead code branch in parseQuotedCompoundSubcommand
- Fix false-positive prefix matching: strings.HasPrefix(arg+'=',flag) → strings.HasPrefix(arg,flag+'=')
- Add TestParseFlagValue, TestParseIdentityFlag, TestParseFromPlanFlag unit tests
- Add TestProcessArgsAndFlags_AllStringFlagsDefs covering all 26 string flags
- Add TestProcessArgsAndFlags_BooleanFlags for --dry-run, --skip-init, -h, --help, --affected, --all
- Add TestProcessArgsAndFlags_GlobalOptions for both space and equals forms
- Add TestProcessArgsAndFlags_NeedHelp for SubCommand extraction on help flag
- Add TestProcessArgsAndFlags_FromPlan for all --from-plan forms
- Add TestProcessArgsAndFlags_EmptyAfterFlagRemoval edge case
- Add TestProcessArgsAndFlags_IdentityError and TestProcessArgsAndFlags_SingleCommandError

Co-authored-by: nitrocode <[email protected]>
…de author

- Add defensive check back in parseQuotedCompoundSubcommand (with direct test for coverage)
- Fix naming inconsistency: expectedPlanFile -> wantPlanFile in TestParseFromPlanFlag
- Add nitrocode (RB, CEO @ Infralicious) to website/blog/authors.yml
- Add blog post: 2026-03-18-process-args-flags-refactor.mdx
- Add roadmap milestone to Code Quality initiative for processArgsAndFlags refactor
- Update roadmap description to reflect 2026 quality work

Co-authored-by: nitrocode <[email protected]>
Copilot AI changed the title [WIP] [PR-2204] Refactor and unit test processArgsAndFlags function refactor(cli_utils): DRY processArgsAndFlags with table-driven flag parsing, 100% unit test coverage Mar 18, 2026
Copilot AI requested a review from RB (nitrocode) March 18, 2026 01:30
@mergify mergify Bot removed the wip Work in Progress: Not ready for final review or merge label Mar 18, 2026
@github-actions github-actions Bot added the size/l Large size PR label Mar 18, 2026
@github-actions

github-actions Bot commented Mar 18, 2026 •

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues found.

Scanned Files

None

@codecov

codecov Bot commented Mar 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.96%. Comparing base (0ef4161) to head (23ff5d8).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2225      +/-   ##
==========================================
+ Coverage   76.88%   76.96%   +0.07%     
==========================================
  Files        1003     1003              
  Lines       95545    95377     -168     
==========================================
- Hits        73461    73404      -57     
+ Misses      17813    17718      -95     
+ Partials     4271     4255      -16     
Flag Coverage Δ
unittests 76.96% <100.00%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
internal/exec/cli_utils.go 96.01% <100.00%> (+14.63%) ⬆️

... and 4 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nitrocode
RB (nitrocode) marked this pull request as ready for review March 18, 2026 12:49
@nitrocode
RB (nitrocode) requested a review from a team as a code owner March 18, 2026 12:49
@osterman

Copy link
Copy Markdown
Member

CodeRabbit (@coderabbitai) please audit this refactor thank you for potential regressions or change of behavior

@coderabbitai

This comment was marked as outdated.

@nitrocode

This comment was marked as outdated.

@coderabbitai

This comment was marked as outdated.

H1/H2: Replace strings.Split with strings.SplitN(arg, "=", 2) in parseFlagValue
- Values containing '=' (JMESPath, key=value pairs, ARN-like strings) now parse correctly
- Before: --query=.tags[?env==prod] would error; after: value is ".tags[?env==prod]"
- parseIdentityFlag simplified to void return (can never error with SplitN)

L1: Add cfg.SettingsListMergeStrategyFlag to commonFlags
- --settings-list-merge-strategy is now stripped from AdditionalArgsAndFlags
- Prevents the flag from leaking through to Terraform/Helmfile as an unknown flag

L2: Fix optional-value flag stripping (--from-plan, --identity)
- --from-plan --refresh=false no longer silently strips --refresh=false from pass-through
- --identity --tf-flag no longer strips the Terraform flag from pass-through
- Only strip i+1 when next arg was actually consumed as the flag's value (not starting with '-')

M1-M4: Add comprehensive tests for all identified coverage gaps
- TestParseFlagValue_EqualsInValue: JMESPath, key=value, multi-equals in values
- TestProcessArgsAndFlags_FlagStripping: all flags strip both name and value
- TestProcessArgsAndFlags_OptionalValueFlagStripping: --from-plan/--identity L2 fix
- TestProcessArgsAndFlags_AllStringFlagsSpaceForm: 8 previously untested flags
- Test_processArgsAndFlags_equalsInValues: all affected flags with '=' values work

Remove/update tests that tested old buggy behavior:
- Test_processArgsAndFlags_errorPaths: remove all "with multiple equals" cases
- Test_processArgsAndFlags_invalidFlag: --init-pass-vars=invalid=true now succeeds
- TestParseFlagValue: "multiple equals errors" -> "value containing = works"
- TestParseIdentityFlag: "multiple equals errors" -> "ARN-style value works"
- TestProcessArgsAndFlags_IdentityError -> TestProcessArgsAndFlags_IdentityWithEqualsInValue

All target functions maintain 100% coverage:
- parseFlagValue: 100%, parseIdentityFlag: 100%, parseFromPlanFlag: 100%
- processArgsAndFlags: 100%, parseQuotedCompoundSubcommand: 100%

Co-authored-by: nitrocode <[email protected]>

Co-authored-by: nitrocode <[email protected]>
Copilot AI changed the title refactor(cli_utils): DRY processArgsAndFlags with table-driven flag parsing, 100% unit test coverage fix(cli_utils): correct flag parsing bugs, stripping logic, and 100% test coverage Mar 18, 2026
…h args

The stripping loop in processArgsAndFlags unconditionally stripped i+1
for ALL commonFlags entries that weren't --from-plan or --identity.
This silently dropped unrelated Terraform flags (e.g., --refresh=false,
--parallelism=10) when they appeared immediately after a boolean Atmos
flag like --dry-run, --skip-init, --affected, --all, --process-templates,
--process-functions, --heatmap, or --profiler-enabled.

Fix: Introduce valueTakingCommonFlags map derived from stringFlagDefs plus
explicitly enumerated value-taking entries (--stack, -s, --global-options,
--kubeconfig-path, profiler/heatmap/profile string flags, --skip). The
stripping loop now only strips i+1 when the flag is in this set.

Add TestProcessArgsAndFlags_BooleanFlagsDoNotStripNextArg with 6 test
cases covering --dry-run, --skip-init, --affected, --all,
--process-templates, and --process-functions.

Co-authored-by: nitrocode <[email protected]>
Copilot AI changed the title fix(cli_utils): correct flag parsing bugs, stripping logic, and 100% test coverage Fix boolean flags silently dropping adjacent pass-through args Mar 18, 2026
@nitrocode

This comment was marked as outdated.

@coderabbitai

This comment was marked as outdated.

@nitrocode

This comment was marked as outdated.

@coderabbitai

coderabbitai Bot commented Mar 19, 2026

Copy link
Copy Markdown
Contributor

Tip

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

🧩 Analysis chain

Let me pull the latest code state for a fresh audit.


🏁 Script executed:

#!/bin/bash
echo "=== CURRENT cli_utils.go ==="
cat internal/exec/cli_utils.go

echo ""
echo "=== CURRENT TEST FILE ==="
find . -name "cli_utils_helpers_test.go" -exec cat {} \;

echo ""
echo "=== FULL DIFF vs main ==="
git diff origin/main...HEAD -- internal/exec/cli_utils.go

echo ""
echo "=== TEST DIFF vs main ==="
git diff origin/main...HEAD -- $(find . -name "cli_utils_helpers_test.go" 2>/dev/null | head -1)

echo ""
echo "=== CHECK FOR process-templates/process-functions comment ==="
grep -n "process-templates\|process-functions\|ProcessTemplates\|ProcessFunctions\|Cobra-only\|cobra-only" internal/exec/cli_utils.go || echo "NO MATCH"

echo ""
echo "=== valueTakingCommonFlags definition ==="
grep -n -A 30 "valueTakingCommonFlags" internal/exec/cli_utils.go | head -50

echo ""
echo "=== commonFlags definition ==="
grep -n -A 60 "commonFlags\s*=" internal/exec/cli_utils.go | head -80

echo ""
echo "=== CHECK AppendUserAgent/VendorBasePath propagation ==="
grep -n "AppendUserAgent\|VendorBasePath\|appendUserAgent\|vendorBasePath" internal/exec/cli_utils.go

echo ""
echo "=== CHECK stripping loop for boolean flags ==="
grep -n -A 20 "indexesToRemove" internal/exec/cli_utils.go | head -80

Length of output: 136669


@nitrocode — full fourth-pass audit complete. Good news: the one remaining 🟠 Medium item from the previous audit is now fixed. Here is the complete current state.


✅ All Previously Raised Issues — Fully Resolved

ID Description Status
H1 strings.Split → SplitN(arg, "=", 2) in parseFlagValue ✅ Fixed
H2 strings.Split → SplitN(arg, "=", 2) in parseIdentityFlag ✅ Fixed
L1 SettingsListMergeStrategyFlag missing from commonFlags ✅ Fixed
L2-extended Boolean flags unconditionally stripping i+1 ✅ Fixed via valueTakingCommonFlags
GlobalOptionsFlag prefix bug HasPrefix(arg+"=", flag) → HasPrefix(arg, flag+"=") ✅ Fixed
M1–M4 Missing stripping/space-form test coverage ✅ Added
🟠 Cobra-only comment --process-templates/--process-functions lack comment explaining Cobra-only usage ✅ Fixed — comment added at Line 597

Remaining Items (All Pre-existing, Not Introduced by This PR)

🟡 Low — AppendUserAgent and VendorBasePath parsed but not propagated

Both are populated in ArgsAndFlagsInfo via stringFlagDefs (Lines 400 and 406), but ProcessCommandLineArgs never copies them to configAndStacksInfo. Scanning the propagation block, there is no configAndStacksInfo.AppendUserAgent = argsAndFlagsInfo.AppendUserAgent line. This is identical to the old code — the refactor faithfully preserved this gap.

Action item (follow-up PR): Either add the two propagation lines, or document that these are expected to be consumed elsewhere (e.g., via Viper).

🟡 Low — Space-form value flags accept adjacent flags as values

parseFlagValue returns args[index+1] with no - prefix check. So --terraform-command --refresh=false silently sets TerraformCommand = "--refresh=false" and strips --refresh=false from pass-through args. Pre-existing, user error, low blast radius.


Verdict

This refactor is correct and safe to merge. All audit-surfaced bugs are fixed, all test gaps are covered, and the valueTakingCommonFlags design cleanly solves the boolean-flag stripping problem. The two remaining items are pre-existing and appropriate for a separate follow-up PR.


✏️ Learnings added
Learnt from: nitrocode
URL: https://github.com/cloudposse/atmos/pull/2225

Timestamp: 2026-03-19T02:41:57.374Z
Learning: In cloudposse/atmos internal/exec/cli_utils.go: cfg.ProcessTemplatesFlag and cfg.ProcessFunctionsFlag are intentionally absent from the boolean switch in processArgsAndFlags. They are Cobra-only flags consumed via viper.GetBool in the cmd/terraform/* layer, not via processArgsAndFlags. They are listed in commonFlags solely to be stripped from pass-through args to the underlying tool. No ArgsAndFlagsInfo field exists for them.

Learnt from: nitrocode
URL: https://github.com/cloudposse/atmos/pull/2225

Timestamp: 2026-03-19T02:41:57.374Z
Learning: In cloudposse/atmos internal/exec/cli_utils.go ProcessCommandLineArgs: AppendUserAgent and VendorBasePath are parsed into ArgsAndFlagsInfo via stringFlagDefs but are NOT propagated to configAndStacksInfo in ProcessCommandLineArgs. This is a known pre-existing gap to be addressed in a separate PR.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: aknysh
Repo: cloudposse/atmos PR: 825
File: internal/exec/terraform.go:30-30
Timestamp: 2024-12-07T16:19:01.683Z
Learning: In `internal/exec/terraform.go`, skipping stack validation when help flags are present is not necessary.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1599
File: internal/exec/terraform.go:394-402
Timestamp: 2025-10-10T23:51:36.597Z
Learning: In Atmos (internal/exec/terraform.go), when adding OpenTofu-specific flags like `--var-file` for `init`, do not gate them based on command name (e.g., checking if `info.Command == "tofu"` or `info.Command == "opentofu"`) because command names don't reliably indicate the actual binary being executed (symlinks, aliases). Instead, document the OpenTofu requirement in code comments and documentation, trusting users who enable the feature (e.g., `PassVars`) to ensure their terraform command points to an OpenTofu binary.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 1327
File: cmd/terraform.go:111-117
Timestamp: 2025-06-23T02:14:30.937Z
Learning: In cmd/terraform.go, flags for the DescribeAffected function are added dynamically at runtime when info.Affected is true. This is intentional to avoid exposing internal flags like "file", "format", "verbose", "include-spacelift-admin-stacks", "include-settings", and "upload" in the terraform command interface, while still providing them for the shared DescribeAffected function used by both `atmos describe affected` and `atmos terraform apply --affected`.

Learnt from: Cerebrovinny
Repo: cloudposse/atmos PR: 1560
File: pkg/utils/string_utils.go:43-64
Timestamp: 2025-09-30T19:03:50.738Z
Learning: In the Atmos codebase, YAML tags like !terraform.output rely on positional arguments, so the SplitStringByDelimiter function in pkg/utils/string_utils.go must preserve empty strings (even after trimming quotes) to maintain the correct number of positional arguments. Filtering out empty values after trimming would collapse the array and break these function calls.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1813
File: cmd/terraform/shell.go:28-73
Timestamp: 2025-12-13T03:21:35.786Z
Learning: In Atmos, when calling cfg.InitCliConfig, you must first populate the schema.ConfigAndStacksInfo struct with global flag values using flags.ParseGlobalFlags(cmd, v) rather than passing an empty struct. The LoadConfig function (pkg/config/load.go) reads config selection fields (AtmosConfigFilesFromArg, AtmosConfigDirsFromArg, BasePath, ProfilesFromArg) directly from the ConfigAndStacksInfo struct, NOT from Viper. Passing an empty struct causes config selection flags (--base-path, --config, --config-path, --profile) to be silently ignored. Correct pattern: parse flags → populate struct → call InitCliConfig. See cmd/terraform/plan_diff.go for reference implementation.

Learnt from: samtholiya
Repo: cloudposse/atmos PR: 914
File: cmd/terraform_commands.go:260-265
Timestamp: 2025-01-09T22:37:01.004Z
Learning: In the terraform commands implementation (cmd/terraform_commands.go), the direct use of `os.Args[2:]` for argument handling is intentionally preserved to avoid extensive refactoring. While it could be improved to use cobra's argument parsing, such changes should be handled in a dedicated PR to maintain focus and minimize risk.

Learnt from: aknysh
Repo: cloudposse/atmos PR: 1185
File: internal/exec/yaml_func_store.go:26-26
Timestamp: 2025-04-04T02:03:23.676Z
Learning: The Atmos codebase currently uses `log.Fatal` for error handling in multiple places. The maintainers are aware this isn't an ideal pattern (should only be used in main() or init() functions) and plan to address it comprehensively in a separate PR. CodeRabbit should not flag these issues or push for immediate changes until that refactoring is complete.

Learnt from: osterman
Repo: cloudposse/atmos PR: 740
File: cmd/cmd_utils.go:340-359
Timestamp: 2024-10-23T21:36:40.262Z
Learning: In the Go codebase for Atmos, when reviewing functions like `checkAtmosConfig` in `cmd/cmd_utils.go`, avoid suggesting refactoring to return errors instead of calling `os.Exit` if such changes would significantly increase the scope due to the need to update multiple call sites.

Learnt from: osterman
Repo: cloudposse/atmos PR: 1686
File: errors/errors.go:184-203
Timestamp: 2025-12-13T06:10:13.688Z
Learning: cloudposse/atmos: For toolchain work, duplicate/unused error sentinels in errors/errors.go should be cleaned up in a separate refactor PR and not block feature PRs; canonical toolchain sentinels live under toolchain/registry with re-exports in toolchain/errors.go.

Learnt from: osterman
Repo: cloudposse/atmos PR: 727
File: internal/exec/terraform_clean.go:233-235
Timestamp: 2024-10-31T19:25:41.298Z
Learning: When specifying color values in functions like `confirmDeleteTerraformLocal` in `internal/exec/terraform_clean.go`, avoid hardcoding color values. Instead, use predefined color constants or allow customization through configuration settings to improve accessibility and user experience across different terminals and themes.

Learnt from: CR
Repo: cloudposse/atmos PR: 0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-11-24T17:35:37.209Z
Learning: Applies to cmd/**/*.go : Provide comprehensive help text for all commands and flags, include examples in command help, and follow Go's documentation conventions in Cobra command definitions

Learnt from: RoseSecurity
Repo: cloudposse/atmos PR: 1448
File: cmd/ansible.go:26-28
Timestamp: 2025-09-05T14:57:37.360Z
Learning: The Atmos codebase uses a consistent pattern for commands that delegate to external tools: `PersistentFlags().Bool("", false, doubleDashHint)` where doubleDashHint provides help text about using double dashes to separate Atmos options from native command arguments. This pattern is used across terraform, packer, helmfile, atlantis, aws, and ansible commands.

Learnt from: CR
Repo: cloudposse/atmos PR: 0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-11-24T17:35:37.209Z
Learning: Ensure all tests pass, verify code coverage meets targets, run golangci-lint and fix any issues, and update documentation before submitting pull requests

Learnt from: Listener430
Repo: cloudposse/atmos PR: 825
File: internal/exec/helmfile_generate_varfile.go:28-31
Timestamp: 2024-12-07T16:16:13.038Z
Learning: In `internal/exec/helmfile_generate_varfile.go`, the `--help` command (`./atmos helmfile generate varfile --help`) works correctly without requiring stack configurations, and the only change needed was to make `ProcessCommandLineArgs` exportable by capitalizing its name.

Learnt from: CR
Repo: cloudposse/atmos PR: 0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-11-24T17:35:37.209Z
Learning: Applies to **/*.go : Follow standard Go coding style: use `gofmt` and `goimports` to format code, prefer short descriptive variable names, use kebab-case for command-line flags, and snake_case for environment variables

Learnt from: CR
Repo: cloudposse/atmos PR: 0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-11-24T17:35:37.209Z
Learning: Applies to **/*_test.go : Include integration tests for command flows and test CLI end-to-end when possible with test fixtures

Learnt from: CR
Repo: cloudposse/atmos PR: 0
File: .cursor/rules/atmos-rules.mdc:0-0
Timestamp: 2025-11-24T17:35:37.209Z
Learning: Applies to **/*.go : Use Viper for managing configuration, environment variables, and flags in CLI commands

@nitrocode RB (nitrocode) changed the title Fix boolean flags silently dropping adjacent pass-through args refactor(cli_utils): DRY processArgsAndFlags with table-driven flag parsing, 100% unit test coverage Mar 19, 2026
Andriy Knysh (aknysh) and others added 2 commits March 20, 2026 12:21
…x doc

- Add bounds check to valueTakingCommonFlags stripping (i+1 OOB guard)
- Fix gosec G602 slice index warning in optional-value flag stripping
- Fix godot linter warnings in pre-existing comments
- Add TestFlagListConsistency to validate three parallel flag lists stay in sync
- Add TestProcessArgsAndFlags_PrefixCollisionSafety for --skip/--heatmap/--profile
- Add TestProcessArgsAndFlags_BooleanFlagEqualsFormStripping for equals-form booleans
- Add TestProcessArgsAndFlags_GlobalOptionsStripping for pass-through arg verification
- Add fix doc documenting all 8 audit findings

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@aknysh
Andriy Knysh (aknysh) merged commit 990b763 into main Mar 20, 2026
58 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the copilot/rb-2204-improve-processargsandflags branch March 20, 2026 17:24
@github-actions

Copy link
Copy Markdown

These changes were released in v1.211.0-rc.1.

kapats pushed a commit to kapats/atmos that referenced this pull request May 18, 2026
…dposse#2412)

* fix(auth): normalize --identity=false to disable authentication

`--identity=false` (and `=0`, `=no`, `=off`, case-insensitive) was reaching
auth hooks as the literal string "false" instead of the disabled sentinel,
so authentication was not skipped. The env-var path (`ATMOS_IDENTITY=false`)
already normalized correctly; the flag path regressed when
`internal/exec/cli_utils.go::parseIdentityFlag` was extracted in cloudposse#2225 and
the new helper omitted the call to `cfg.NormalizeIdentityValue`.

Apply normalization to both value branches (`--identity=value` and
`--identity value`) so every `ProcessCommandLineArgs` consumer
(terraform / helmfile / packer / list / describe / workflow / …) receives
the disabled sentinel and short-circuits auth. Add parser-level and
end-to-end unit tests covering all boolean-false spellings.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(list): honor disabled identity for instances

* style(exec): satisfy ci gofumpt

* test(exec,list): cover the auth-disabled stacks-processor seam

Coverage report showed 30 missing lines on the PR; 26 of them were in the
auth-disabled wiring added for `--identity=false`. Pure pass-through and
test-seam code that wasn't reachable from existing test fixtures.

* internal/exec/stacks_processor_test.go:
  TestDefaultStacksProcessor_ExecuteDescribeStacksWithAuthDisabled — table
  drives authDisabled=true and authDisabled=false through the new
  pass-through method, mirroring the existing
  TestDefaultStacksProcessor_ExecuteDescribeStacks empty-fixture pattern.
  Lifts the function from 0% to 100% (15 missing lines recovered).

* pkg/list/list_instances_authdisabled_test.go (new):
  Hand-written fakes for the unexported authDisabledStacksProcessor
  interface (the gomock MockStacksProcessor only models the public
  interface; the auth-disabled method is an optional capability
  type-asserted at runtime).

  - TestExecuteDescribeStacksForInstances_AuthDisabledDispatchesToAuthDisabledMethod
    pins authDisabled=true + capable processor → auth-disabled method.
  - TestExecuteDescribeStacksForInstances_AuthDisabledFalseUsesRegularPath
    pins authDisabled=false → regular ExecuteDescribeStacks even when
    the optional interface is implemented.
  - TestExecuteDescribeStacksForInstances_FallsBackWhenInterfaceNotImplemented
    safety-net: authDisabled=true with a non-capable processor must
    fall back to ExecuteDescribeStacks rather than panic on a failed
    type assertion.
  - TestProcessInstancesWithDepsAuthDisabled_PropagatesAuthDisabledFlag
    end-to-end through the helper with a realistic stacks map.
  - TestProcessInstancesWithAuthDisabled_ConstructsDefaultProcessor
    smoke test for the production wrapper.

  Lifts processInstancesWithDepsAuthDisabled, executeDescribeStacksForInstances,
  and processInstancesWithAuthDisabled from <80% to 100% each.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(list): anchor processInstancesWithAuthDisabled smoke test to TempDir

CodeRabbit flagged the smoke test as ambient-state-dependent: with an
empty AtmosConfiguration the underlying FindStacksMap resolves CWD-relative
empty BasePath/Stacks.BasePath, so the assertion that the collector returns
zero instances depends on whatever happens to exist in the test runner's
CWD.

The fix matches the existing convention in
TestDefaultStacksProcessor_ExecuteDescribeStacks
(internal/exec/stacks_processor_test.go:14-27) and the CLAUDE.md guidance
to anchor file-discovery tests to an absolute path: set BasePath to
t.TempDir() and give the relative Stacks/Components paths explicit values.
The temp dir is empty, so the empty-instances assertion is now guaranteed
regardless of CWD or filesystem state.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
Co-authored-by: aknysh <[email protected]>

This branch was successfully deployed

1 active deployment
preview — 23ff5d87 Deployed Mar 20, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch A minor, backward compatible change size/l Large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants