Skip to content

feat(terraform): add flag auto-completion for subcommand aliases#769

Open
senderic wants to merge 2 commits into
ohmybash:masterfrom
senderic:feature/terraform-auto-complete
Open

feat(terraform): add flag auto-completion for subcommand aliases#769
senderic wants to merge 2 commits into
ohmybash:masterfrom
senderic:feature/terraform-auto-complete

Conversation

@senderic

Copy link
Copy Markdown

Implement auto-completion support for terraform aliases (t, tapply, tplan, tinit, tfmt).

  • Since the terraform CLI binary (complete -C) does not support flag completion out of the box, intercept completions starting with - to provide static suggestions for common flags of the relevant subcommand.
  • Fallback to delegating completions to the registered terraform specification, carefully translating context arguments (shifting cur/prev), parsing quoted complete paths, and properly restoring shell completion environments.

Implement auto-completion support for terraform aliases (`t`, `tapply`,
`tplan`, `tinit`, `tfmt`).

- Since the terraform CLI binary (`complete -C`) does not support flag
  completion out of the box, intercept completions starting with `-` to
  provide static suggestions for common flags of the relevant subcommand.
- Fallback to delegating completions to the registered terraform specification,
  carefully translating context arguments (shifting `cur`/`prev`), parsing
  quoted complete paths, and properly restoring shell completion environments.
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Add flag completion for terraform alias subcommands

✨ Enhancement 🕐 20-40 Minutes

Grey Divider

AI Description

• Add bash completion entrypoints for terraform aliases (t, tapply, tplan, tinit, tfmt).
• Provide static flag suggestions when completing options for common subcommands.
• Delegate non-flag completions to the underlying terraform completion handler with shifted context.
Diagram

graph TD
  A([Alias invocation]) --> B["Expand to terraform ..."] --> C{cur starts with "-"?}
  C -->|Yes| D["Static flags by subcommand"] --> H["Set COMPREPLY & return"]
  C -->|No| E{Completion type?}
  E -->|"-C" binary| F["Run real_cmd with shifted context"] --> H
  E -->|"-F" function| G["Temporarily rewrite COMP_* and call function"] --> I["Restore COMP_* env"] --> H

  subgraph Legend
    direction LR
    _start([Entry]) ~~~ _proc["Process"] ~~~ _dec{Decision}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Generate flags dynamically via `terraform -help` parsing
  • ➕ Avoids maintaining static flag lists as Terraform evolves
  • ➕ Potentially covers more subcommands/flags automatically
  • ➖ Help output is not a stable machine interface; parsing is brittle across versions/locales
  • ➖ Slower completion and more subprocess calls during interactive typing
2. Rely solely on upstream terraform completion delegation (no flag interception)
  • ➕ Simpler implementation and less maintenance
  • ➕ Leverages whatever completion behavior the Terraform install provides
  • ➖ Does not solve the core issue: complete -C lacks flag completion, so alias UX remains poor
3. Ship a dedicated Terraform completion spec for aliases (separate from terraform’s registered completion)
  • ➕ Full control over flags, args, and file/path completions
  • ➕ Can be made consistent across environments
  • ➖ Significant effort to replicate Terraform’s rich completion behavior
  • ➖ High maintenance burden to keep parity with Terraform releases

Recommendation: The PR’s approach (static flag suggestions for the high-value cases, then delegate everything else to Terraform’s registered completion) is the best trade-off. It materially improves UX for common alias workflows without attempting to reimplement Terraform’s full completion semantics, while preserving compatibility with both complete -C and complete -F setups.

Files changed (1) +155 / -0

Enhancement (1) +155 / -0
terraform.completion.shAdd alias-aware Terraform completion with static flag suggestions +155/-0

Add alias-aware Terraform completion with static flag suggestions

• Introduces '_omb_terraform_alias_complete' to support completions for 't', 'tapply', 'tplan', 'tinit', and 'tfmt'. The function expands aliases into their terraform equivalents, intercepts option completion to suggest common flags per subcommand, and otherwise delegates to Terraform’s registered 'complete -C' or 'complete -F' handler while safely translating and restoring COMP_* state.

completions/terraform.completion.sh

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 16, 2026

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Command-token completion mis-shift ✓ Resolved 🐞 Bug ≡ Correctness
Description
When completion runs on the alias token itself (i.e., COMP_CWORD==0), new_cword is shifted to
point at a different word in the expanded command (e.g., apply), so the delegated completion
generates COMPREPLY for the wrong word and can yield incorrect suggestions for the original
command token.
Code

completions/terraform.completion.sh[R46-48]

+  local -a expansion_words=($expansion)
+  local -a new_words=("${expansion_words[@]}" "${COMP_WORDS[@]:1}")
+  local new_cword=$((COMP_CWORD + ${#expansion_words[@]} - 1))
Evidence
The alias expansion increases the word count and shifts new_cword; later delegation overwrites
COMP_CWORD to that shifted index. For multi-word aliases, this changes what word the delegated
completion thinks it is completing.

completions/terraform.completion.sh[28-49]
completions/terraform.completion.sh[145-150]
aliases/terraform.aliases.sh[5-10]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`_omb_terraform_alias_complete` rewrites the completion context by expanding aliases into multiple words and shifting `COMP_CWORD`. When the user is completing the command token itself (`COMP_CWORD==0`), this shift points completion at a different word (e.g., `apply`), so delegated completion results are for the wrong token.
### Issue Context
This happens for multi-word expansions such as `tapply -> "terraform apply"`, where `new_cword` becomes 1 when `COMP_CWORD` is 0.
### Fix Focus Areas
- completions/terraform.completion.sh[28-49]
### Suggested fix
Add an early guard before computing `new_words/new_cword`, e.g.:
- If `((COMP_CWORD==0))`, do not delegate/shift; either `COMPREPLY=(); return 0` (do nothing) or `return 1` (allow default completion behavior if configured).
Then proceed with the existing shifting logic only for argument completion (`COMP_CWORD>0`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Missing function existence check ✓ Resolved 🐞 Bug ☼ Reliability
Description
In the -F delegation path, the code executes "$real_func" without verifying the function exists,
which can produce command not found errors on every TAB if complete -p terraform references an
undefined/stale function.
Code

completions/terraform.completion.sh[R129-151]

+  if [[ $completion_info == *"-F "* ]]; then
+    local real_func=""
+    if [[ $completion_info =~ -F[[:space:]]+(\'[^\']+\'|\"[^\"]+\"|[^[:space:]]+) ]]; then
+      real_func="${BASH_REMATCH[1]}"
+      real_func="${real_func#\'}"
+      real_func="${real_func%\'}"
+      real_func="${real_func#\"}"
+      real_func="${real_func%\"}"
+    fi
+
+    if [[ $real_func ]]; then
+      local -a COMP_WORDS_saved=("${COMP_WORDS[@]}")
+      local COMP_CWORD_saved=$COMP_CWORD
+      local COMP_LINE_saved="$COMP_LINE"
+      local COMP_POINT_saved=$COMP_POINT
+
+      COMP_WORDS=("${new_words[@]}")
+      COMP_CWORD=$new_cword
+      COMP_LINE="$new_line"
+      COMP_POINT=$new_point
+
+      "$real_func"
+
Evidence
Terraform alias completion dynamically extracts a -F function name and calls it unconditionally.
The repository has a standard helper for checking function existence and other completion code uses
it before dynamic invocation.

completions/terraform.completion.sh[129-151]
lib/utils.sh[119-121]
completions/docker-machine.completion.sh[245-248]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The completion function extracted from `complete -p terraform` is invoked directly without a function-existence check.
### Issue Context
The repo already provides `_omb_util_function_exists` and uses it elsewhere before dynamically calling completion functions.
### Fix Focus Areas
- completions/terraform.completion.sh[129-151]
### Suggested fix
Before calling `"$real_func"`, add a guard:

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

3. Unused prev variable ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
prev is computed in _omb_terraform_alias_complete but never used, which is dead code and can
mislead future edits.
Code

completions/terraform.completion.sh[R29-33]

+  local cur=${COMP_WORDS[COMP_CWORD]}
+  local prev=""
+  if ((COMP_CWORD > 0)); then
+    prev=${COMP_WORDS[COMP_CWORD - 1]}
+  fi
Evidence
The function assigns prev, but there are no subsequent references to prev within
_omb_terraform_alias_complete.

completions/terraform.completion.sh[29-34]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`prev` is assigned but never referenced in `_omb_terraform_alias_complete`.
### Issue Context
This variable appears to be leftover from an earlier version of the logic.
### Fix Focus Areas
- completions/terraform.completion.sh[29-33]
### Suggested fix
Delete the `prev` local variable block, or use it if intended (otherwise it is dead code).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread completions/terraform.completion.sh
Comment thread completions/terraform.completion.sh
Comment thread completions/terraform.completion.sh Outdated
Address review feedback for the terraform alias completion function:
- Add an early guard to return 1 when COMP_CWORD is 0, preventing pointing
  at the wrong expanded word during command token completion.
- Verify the existence of the delegated completion function (real_func)
  using [_omb_util_function_exists](cci:1://file:///home/g56147/.oh-my-bash/lib/utils.sh:118:0-120:1) before executing it.
- Remove the unused local variable `prev` to clean up dead code.
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.

1 participant