Repository navigation
refactor(cli_utils): DRY processArgsAndFlags with table-driven flag parsing, 100% unit test coverage - #2225
Conversation
…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]>
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ 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
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
|
CodeRabbit (@coderabbitai) please audit this refactor thank you for potential regressions or change of behavior |
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
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]>
…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]>
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
Co-authored-by: nitrocode <[email protected]>
This comment was marked as outdated.
This comment was marked as outdated.
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chainLet me pull the latest code state for a fresh audit. 🏁 Script executed: Length of output: 136669
✅ All Previously Raised Issues — Fully Resolved
Remaining Items (All Pre-existing, Not Introduced by This PR)🟡 Low —
|
…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]>
|
These changes were released in v1.211.0-rc.1. |
…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]>
--dry-run,--skip-init,--affected,--all,--process-templates,--process-functions,-h/--help) were unconditionally strippingargs[i+1]from Terraform/Helmfile pass-through args — silently dropping user-intended flags like--refresh=falseor--parallelism=10. Fix: addedvalueTakingCommonFlagsset; only value-consuming flags stripargs[i+1].strings.Split(arg, "=")rejected flag values containing=(e.g.--query=.tags[?env==prod],--append-user-agent=Key=Val). Fix:strings.SplitN(arg, "=", 2)throughout.strings.HasPrefix(arg+"=", flag)was logically inverted —--terraform-command-extramatched--terraform-command. Fix:strings.HasPrefix(arg, flag+"=")at all call sites.--from-planand--identityunconditionally consumedargs[i+1]even when it was another flag. Fix: both only stripargs[i+1]when it does not start with-.--settings-list-merge-strategywas parsed intoArgsAndFlagsInfobut absent fromcommonFlags, leaking it into Terraform pass-through args. Fix: added to bothcommonFlagsandstringFlagDefs.if/elsechains (~200 lines) with a table-driven design:stringFlagDefs(26 entries),parseFlagValuehelper,parseIdentityFlaghelper,parseFromPlanFlaghelper, andvalueTakingCommonFlagsset. Cyclomatic complexity: ~67 → ~15.internal/exec/cli_utils_helpers_test.go— 100% coverage onprocessArgsAndFlags,parseFlagValue,parseIdentityFlag,parseFromPlanFlag,parseQuotedCompoundSubcommand. Regression tests confirm boolean flags no longer drop adjacent pass-through args.website/blog/2026-03-18-process-args-flags-refactor.mdx, roadmap milestonewebsite/src/data/roadmap.js, code comment clarifying--process-templates/--process-functionsare Cobra-only flags.✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.