Skip to content

IAC tool cli building improvements#5448

Merged
denis256 merged 24 commits intomainfrom
iac-cli-improvements
Jan 29, 2026
Merged

IAC tool cli building improvements#5448
denis256 merged 24 commits intomainfrom
iac-cli-improvements

Conversation

@denis256
Copy link
Copy Markdown
Member

@denis256 denis256 commented Jan 28, 2026

Description

  • Improved building of CLI arguments for IAC tool
  • Added error throwing when report extension is not supported
  • Simplified handling of boolean flags
  • Added more test to track parsing of boolean arguments

TODOs

Read the Gruntwork contribution guidelines.

  • I authored this code entirely myself
  • I am submitting code based on open source software (e.g. MIT, MPL-2.0, Apache)]
  • I am adding or upgrading a dependency or adapted code and confirm it has a compatible open source license
  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Added / Removed / Updated [X].

Migration Guide

Summary by CodeRabbit

  • Bug Fixes

    • Added nil-safety to argument handling to avoid panics.
  • Improvements

    • More robust CLI flag and argument parsing (handles -flag, --flag, -flag=value, space-separated values).
    • Smarter merging/normalization of commands, subcommands, flags, and arguments.
    • Lazier initialization for CLI argument builders to support incremental construction.
  • Refactor

    • Internal argument/flag handling reorganized for clarity and safer slice operations.
  • Tests

    • Expanded unit tests covering flag removal, boolean flags, subcommand handling, and nil/edge cases.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link
Copy Markdown

vercel bot commented Jan 28, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
terragrunt-docs Ready Ready Preview, Comment Jan 29, 2026 8:10pm

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jan 28, 2026

📝 Walkthrough

Walkthrough

Refactors CLI argument handling with flag normalization and robust flag/value parsing, adds new IacArgs builder helpers and tests (including boolean flag edge cases), introduces minor nil-guards and capacity-constant tweaks, and updates Terraform CLI args merging behavior with lazy initialization and new subcommand-merge logic.

Changes

Cohort / File(s) Summary
CLI argument parsing & tests
internal/clihelper/args.go, internal/clihelper/args_test.go, internal/clihelper/boolean_args_test.go
Added flag normalization/validation (minFlagLen, normalizeFlag, isFlag), enhanced flag handling (HasFlag, RemoveFlag, MergeFlags, hasFlagWithValue) to support -f value and -f=value forms, introduced argument builder helpers (AppendArgument, InsertArgument(s), AppendSubCommand), exported IsKnownSubCommand, replaced ad-hoc slice ops with utilities, and expanded table-driven tests covering many edge cases.
Run command flags
internal/cli/commands/run/flags.go
Renamed local flags variable to cmdFlags and updated subsequent chained calls to use cmdFlags.Add(...) and cmdFlags.Sort(); no behavioral changes.
Runner nil-safety
internal/runner/runnerpool/runner.go
Added nil-check in isDestroyCommand to avoid nil dereference when args is nil.
Terraform run writers & dependency args
internal/tf/run_cmd.go, pkg/config/dependency.go
Introduced defaultWriterOptionsLen constant for writer-options slice capacity initialization; switched dependency output arg construction to fluent builder pattern (NewIacArgs().SetCommand(...).AppendFlag(...)).
Terraform CLI args merging & tests
pkg/options/options.go, pkg/options/options_test.go
Lazy-initialize TerraformCliArgs, added internal mergeCommandAndSubCommand to merge parsed Command/SubCommand (last-writer-wins for subcommands), adjusted InsertTerraformCliArgs/AppendTerraformCliArgs flows, and added tests for subcommand replacement and nil-guards.

Sequence Diagram(s)

(Skipped — changes are parsing/refactor-focused and do not introduce a new multi-component sequential flow requiring visualization.)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • ThisGuyCodes
  • yhakbar
🚥 Pre-merge checks | ❌ 3
❌ Failed checks (1 warning, 2 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.37% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is partially related to the changeset but lacks specificity. While 'IAC tool cli building improvements' refers to real changes in the CLI argument handling code, it is overly broad and generic, not highlighting the main focus such as flag normalization, argument refactoring, or boolean flag handling. Consider a more specific title such as 'Refactor IacArgs API and flag handling utilities' or 'Improve CLI argument parsing with normalized flags' to better convey the primary technical changes.
Description check ❓ Inconclusive The description covers the main improvements but lacks detail and specificity. It mentions bullet points about CLI argument building, error throwing for report extensions, boolean flag handling, and tests, but does not provide sufficient context about what aspects were improved or why. Enhance the description with more details about the specific improvements: explain the refactoring of IacArgs API (new methods, flag normalization), what the report extension error addresses, and how boolean flag handling was simplified. Add the issue number to the 'Fixes #000' line.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

- prevent false positives in flag matching by checking for dash prefix
- reintroduce nil guards for TerraformCliArgs in options
- improve subcommand replacement logic in InsertTerraformCliArgs
- restore fixture counter cleanup in run-cmd tests
Comment thread internal/cli/commands/run/flags.go Outdated

if ext != ".csv" && ext != ".json" {
return nil
return fmt.Errorf("unsupported report file extension: %s (supported: .csv, .json)", ext)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why is this an error now? Users should be able to use whatever extension they want, we just won't auto-detect the right report format automatically if they don't use .csv or .json.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

In the old version it is just returning out, so silently, no report format will be set

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The docs say the default is CSV if it can't work it out based on extension or flag:
https://terragrunt.gruntwork.io/docs/features/run-report/#run-report

It must have been working at some point.

newFlags := make([]string, 0, len(a.Flags))
target := normalizeFlag(name)

for i := 0; i < len(a.Flags); i++ {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

NIT: You can use the modern range syntax here.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Ah, maybe you run into issues if you're manually manipulating the iterator on line 318?

"-write-out",
// valueTakingFlags contains flags that require space-separated values.
// Only flags that commonly use a space-separated format need to be listed here.
var valueTakingFlags = []string{
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Are we keeping this because there's no way around having knowledge of OpenTofu/Terraform CLI arguments?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, we need wha to take as "next parameter"

@@ -991,7 +991,7 @@ func (r *Runner) SetReport(rpt *report.Report) {
// isDestroyCommand checks if the current command is a destroy operation
func isDestroyCommand(cmd string, args *clihelper.IacArgs) bool {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If we move IaCArgs out of clihelper (which is pretty bloated right now), we can put stuff like this as methods on IaCArgs.

Comment thread pkg/config/dependency.go
targetOptions.CheckDependentUnits = false
targetOptions.TerraformCommand = "output"
targetOptions.TerraformCliArgs = clihelper.NewIacArgs("output", "-json")
targetOptions.TerraformCliArgs = clihelper.NewIacArgs().SetCommand("output").AppendFlag("-json")
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice

Comment thread pkg/options/options.go Outdated

// Subcommands: replace or append
if len(parsed.SubCommand) > 0 {
// For "providers lock", if we insert "providers mirror", we want "providers mirror".
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I don't really understand what this means. Why are we overwriting this?

Comment thread pkg/options/options.go Outdated
// - If parsed.Command matches opts command, do nothing (idempotent)
// - If parsed.Command is a known subcommand, add to SubCommand
// - Otherwise treat parsed.Command as positional argument
func (opts *TerragruntOptions) mergeCommand(parsed *clihelper.IacArgs) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I'm nervous about adding another method to TerragruntOptions. I feel like we're giving more responsibility to something we should be slimming down.

@denis256 denis256 merged commit b6da3f0 into main Jan 29, 2026
51 of 52 checks passed
@denis256 denis256 deleted the iac-cli-improvements branch January 29, 2026 20:53
@coderabbitai coderabbitai bot mentioned this pull request Jan 30, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants