Repository navigation
refactor(terraform): reduce ExecuteTerraform complexity 160→9, improve test coverage - #2226
Conversation
…ith unit tests Co-authored-by: nitrocode <7775707+nitrocode@users.noreply.github.com>
…form refactor Co-authored-by: nitrocode <7775707+nitrocode@users.noreply.github.com>
Dependency Review✅ No vulnerabilities or license issues found.Scanned FilesNone |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #2226 +/- ##
==========================================
+ Coverage 76.94% 77.04% +0.10%
==========================================
Files 1004 1007 +3
Lines 95390 95495 +105
==========================================
+ Hits 73394 73573 +179
+ Misses 17740 17680 -60
+ Partials 4256 4242 -14
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.
…erraform helpers Co-authored-by: nitrocode <7775707+nitrocode@users.noreply.github.com>
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
|
CodeRabbit (@coderabbitai) full review please, also check if the "Action Items" have been addressed |
This comment was marked as outdated.
This comment was marked as outdated.
- Add TestPrintAndWriteVarFiles_DebugLogLevel_Success (item 8) - Add TestPrintAndWriteVarFiles_DebugLogLevel_CliVarsSection (item 8) - Add TestPrintAndWriteVarFiles_TraceLogLevel (item 8) - Validate item 5: storeAutoDetectedIdentity already tested in utils_auth_test.go (gomock strict controller implicitly verifies GetChain not called) - Validate item 10: generateConfigFiles comment already added in previous commit - Update fix doc with all audit pass 8 resolutions Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This comment was marked as outdated.
This comment was marked as outdated.
|
CodeRabbit (@coderabbitai) full review please, also check if the "Action Items" and "Remaining Action Items" have been addressed |
This comment was marked as outdated.
This comment was marked as outdated.
…omment - Add TestStoreAutoDetectedIdentity_ExistingIdentity_NotOverwritten with explicit GetChain().Times(0) assertion (item 5) - Add double-invocation comment at generateConfigFiles call site in runPreExecutionSteps (item 10) - Update fix doc with pass 9 resolutions Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
internal/exec/terraform_execute_helpers_coverage_test.go (1)
331-363: These tests don't verify the warning behavior.Every case here only asserts “does not panic”, so a regression where
warnOnConflictingEnvVarsstops warning entirely would still pass. Please capture/assert the warning output, or drop these if log capture is not worth the maintenance cost.As per coding guidelines, "Test behavior, not implementation; never test stub functions; avoid tautological tests; make code testable via DI; no coverage theater; remove always-skipped tests; use errors.Is() for error checking."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/exec/terraform_execute_helpers_coverage_test.go` around lines 331 - 363, These tests only assert that warnOnConflictingEnvVars does not panic and therefore do not verify that a warning is emitted; update each test (TestWarnOnConflictingEnvVars_TFCLIArgs, _TFWorkspace, _TFVarPrefix, _TFCLIArgsPrefix, _MultipleConflicts) to capture and assert the warning output produced by warnOnConflictingEnvVars (e.g., capture logger/stderr or inject a test logger via DI) and assert the expected warning substring is present, or if capturing logs is impractical, remove the redundant tests entirely; ensure you reference and exercise the warnOnConflictingEnvVars function in the updated tests and assert on the warning message content.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/exec/terraform_execute_helpers_exec.go`:
- Around line 182-186: The default stderr redirect currently hardcodes
"/dev/stdout" which breaks on Windows; change it to use the platform-aware
os.Stdout.Name() when info.RedirectStdErr is empty (import "os"), i.e., set
workspaceSelectRedirectStdErr := os.Stdout.Name() and keep using
info.RedirectStdErr when provided so workspaceSelectRedirectStdErr is
platform-neutral; reference workspaceSelectRedirectStdErr and
info.RedirectStdErr in your change.
In `@internal/exec/terraform_execute_helpers_test.go`:
- Around line 393-400: TestResolveExitCode_OsExecExitError relies on the Unix
"false" binary (osexec.Command("false")) which fails on Windows; update the test
to avoid platform-specific binaries by either branching on runtime.GOOS (skip or
use Windows-appropriate command) or implement the helper-process pattern: spawn
the current test binary (exec.Command(os.Args[0], "-test.run=TestHelperProcess",
"--", "exit", "1")) with a distinguishing env var and a TestHelperProcess
function that calls os.Exit(1), then pass the resulting error into
resolveExitCode to assert it returns 1; reference
TestResolveExitCode_OsExecExitError, resolveExitCode, and the osexec.Command
call when making the change.
In `@internal/exec/terraform_execute_helpers.go`:
- Around line 197-199: The code branch that reads the workdir override using
provWorkdir.WorkdirPathKey should treat an empty string as “not set”; change the
check in the block that currently does if workdirPath, ok :=
info.ComponentSection[provWorkdir.WorkdirPathKey].(string); ok { ... } to
additionally verify workdirPath != "" and only then return (workdirPath, true,
nil); otherwise behave like prepareInitExecution and return as if the override
was not present (i.e., do not signal ok when the string is empty).
- Around line 145-156: The current logic conflates provisioning errors from
provisionComponentSource with a "component does not exist" error; change the
branch so that if err != nil you return the original provisioning error wrapped
with context (e.g., fmt.Errorf("provision component source: %w", err)) and only
construct/return ErrInvalidTerraformComponent when componentPathExists is false;
update the block around provisionComponentSource, componentPathExists and the
ErrInvalidTerraformComponent return (and keep the GetComponentBasePath call for
the non-existent-component message) so auth/network/JIT provisioning failures
propagate instead of being masked.
- Around line 47-60: The fast-path in handleVersionSubcommand currently
hard-codes only the single `version` token and drops additional caller options;
update handleVersionSubcommand to preserve and forward all caller args and
options by including `info.SubCommand2`, `info.AdditionalArgsAndFlags`, and the
`info.DryRun` flag when invoking the executor (do not truncate to just
`info.SubCommand`), and thread any variadic `opts...` through to the underlying
call; specifically, call the same execution helper used elsewhere
(ExecuteTerraform) or Ensure ExecuteShellCommand is invoked with the full
constructed args slice and `opts` forwarded so shell-command overrides and flags
like `-json` are preserved.
---
Nitpick comments:
In `@internal/exec/terraform_execute_helpers_coverage_test.go`:
- Around line 331-363: These tests only assert that warnOnConflictingEnvVars
does not panic and therefore do not verify that a warning is emitted; update
each test (TestWarnOnConflictingEnvVars_TFCLIArgs, _TFWorkspace, _TFVarPrefix,
_TFCLIArgsPrefix, _MultipleConflicts) to capture and assert the warning output
produced by warnOnConflictingEnvVars (e.g., capture logger/stderr or inject a
test logger via DI) and assert the expected warning substring is present, or if
capturing logs is impractical, remove the redundant tests entirely; ensure you
reference and exercise the warnOnConflictingEnvVars function in the updated
tests and assert on the warning message content.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 898ff5e4-0119-4984-92e1-c9066238fa93
📒 Files selected for processing (15)
CLAUDE.mddocs/fixes/2026-03-20-executeterraform-refactor.mdinternal/exec/terraform.gointernal/exec/terraform_execute_helpers.gointernal/exec/terraform_execute_helpers_args.gointernal/exec/terraform_execute_helpers_args_test.gointernal/exec/terraform_execute_helpers_auth_test.gointernal/exec/terraform_execute_helpers_coverage_test.gointernal/exec/terraform_execute_helpers_exec.gointernal/exec/terraform_execute_helpers_pipeline_test.gointernal/exec/terraform_execute_helpers_test.gointernal/exec/terraform_execute_helpers_workspace_test.gointernal/exec/utils_auth.gowebsite/blog/2026-03-18-refactoring-executeterraform.mdxwebsite/src/data/roadmap.js
Resolve conflict in terraform.go: keep refactored pipeline, incorporate PR #2216 behavioral changes: - uploadStatusFlag now resolves info.UploadStatus first (Cobra/Viper) - Upload status applies to all subcommands, not just plan - Add mapCIExitCode call for CI exit code remapping - Rename handlePlanStatusUpload to uploadCommandStatus - Update buildPlanSubcommandArgs signature Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…platform test - Separate provisioning errors from "component does not exist" in resolveAndProvisionComponentPath — propagate original error directly - Guard empty _workdir_path in provisionComponentSource to match prepareInitExecution behavior - Replace Unix-only "false" command with cross-platform "go run" in TestResolveExitCode_OsExecExitError - Remove warnOnConflictingEnvVars coverage theater tests (logging-only function, NotPanics assertions add no value) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
These changes were released in v1.211.0-rc.1. |
|
These changes were released in v1.211.0-rc.2. |
what
ExecuteTerraformmonolith (~900 lines, cyclomatic complexity 160), reducing complexity to ~9 across 4 source files all under 600 linestenv != nil,buildTerraformCommandArgsinit branch, andstoreAutoDetectedIdentityguardGenerateFilesForComponentdouble-invocation whenAutoGenerateFiles=true(pre-existing behavior, not a regression)Architecture after refactor
terraform.goExecuteTerraform→prepareComponentExecution→executeCommandPipeline→cleanupTerraformFilesterraform_execute_helpers.goterraform_execute_helpers_args.goterraform_execute_helpers_exec.goKey design decisions
defaultMergedAuthConfigGetter,defaultComponentConfigFetcher,defaultAuthManagerCreator) enable isolated unit testing of auth paths without real infrastructuresubcommandApply,subcommandDeploy,subcommandInit,subcommandWorkspace) replace 16+ magic string literalsexecuteTerraformInitPhaseandbuildInitSubcommandArgsis documented — both callprepareInitExecutionbut are guarded bySubCommand == "init"branchingLint fixes (16 issues → 0)
revive/cyclomatic: extractshouldSkipWorkspaceSetup,runPreExecutionSteps,autoGenerateComponentFiles,provisionComponentSource,logAndWriteComponentVars,logCliVarsOverrides,handlePlanStatusUploadrevive/add-constant:subcommandApply/Deploy/Init/Workspace,dirPermissionsgocritic/hugeParam:handleVersionSubcommandtakes pointer paramsgocritic/unlambda:defaultMergedAuthConfigGetteruses direct function refgocritic/filepathJoin: split path segments in testunparam: remove unusedplanFilefrombuildApplySubcommandArgsforbidigo: nolint forTF_WORKSPACE(Terraform convention)nestif: extracthandlePlanStatusUploadrevive/argument-limit: nolint for variadic optswhy
ExecuteTerraformwas the highest-complexity function in the codebase (cyclomatic 160) — untestable as a unit, any change risked regressions in auth, workspace, plan-file, or cleanup logicreferences
docs/fixes/2026-03-20-executeterraform-refactor.mdwebsite/blog/2026-03-18-refactoring-executeterraform.mdxwebsite/src/data/roadmap.js(Code Quality initiative milestone)Summary by CodeRabbit
Release Notes
Refactor
Tests
Documentation
Chores