Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(terraform_docs): Allow having whitespaces in path to .terraform-docs.yaml config file #796

Merged
merged 6 commits into from
Feb 3, 2025

Conversation

tarfu
Copy link
Contributor

@tarfu tarfu commented Jan 30, 2025

Put an x into the box if that apply:

  • This PR introduces breaking change.
  • This PR fixes a bug.
  • This PR adds new functionality.
  • This PR enhances existing functionality.

Description of your changes

This resolves an issue if the path to the config file for terraform-docs has multiple paths.

How can we test changes

terraform_docs.sh --hook-config="--custom-marker-begin=// BEGIN_TF_DOCS" --hook-config="--custom-marker-end=// END_TF_DOCS" --args=--config="path with spaces/.terraform-docs.yml" ./deployment/main.tf

Summary by CodeRabbit

  • Improvements
    • Enhanced configuration handling for Terraform documentation generation.
    • Improved flexibility in managing Terraform documentation command execution.
    • Refined logic for processing configuration flags and arguments, allowing for whitespace in values.

Copy link

coderabbitai bot commented Jan 30, 2025

Walkthrough

The changes to the terraform_docs.sh script focus on enhancing the handling of the --config flag within the terraform_docs function. A new local variable have_config_flag is introduced to track whether the --config flag is present in the command-line arguments. The logic for processing the args variable is updated to allow for whitespace in the value associated with the --config flag. The command execution for terraform-docs is modified to conditionally include the config_options variable based on the presence of this flag.

Changes

File Change Summary
hooks/terraform_docs.sh - Added local variable have_config_flag to track --config flag presence
- Added local variable config_options
- Modified command execution to conditionally include config_options based on have_config_flag

Sequence Diagram

sequenceDiagram
    participant Script as terraform_docs.sh
    participant Command as terraform-docs
    participant ConfigFile as .terraform-docs.yml

    Script->>Script: Check for --config flag
    alt Config flag present
        Script->>Script: Set have_config_flag = true
        Script->>Command: Execute with config flag
    else No config flag
        Script->>Script: Set have_config_flag = false
        Script->>Command: Execute without config flag
    end
    Command->>ConfigFile: Read configuration (if exists)
    Command-->>Script: Generate documentation
Loading

The sequence diagram illustrates the enhanced logic for handling configuration flags in the terraform_docs.sh script, showing how the presence of the --config flag influences the command execution and potential configuration file usage.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 05339b7 and 8fdfb5b.

📒 Files selected for processing (1)
  • hooks/terraform_docs.sh (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@macos-13
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@macos-13
  • GitHub Check: 🧪 Tests / pytest@🐍3.12@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.12@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.11@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.10@windows-2025
🔇 Additional comments (3)
hooks/terraform_docs.sh (3)

91-91: Initialization of have_config_flag
The variable is correctly initialized to false. This clear initialization makes the later conditional assignment unambiguous.


146-157: Config Extraction Logic with Extended Globbing
In the block where the script detects the presence of the --config flag, the code uses advanced parameter expansion with extglob to extract the config file path and remove the --config argument from the remainder of args. This approach is clever and addresses whitespace issues; however, its complexity may hurt readability and maintainability. Please verify that the following edge cases are handled correctly:

  • Paths that include multiple internal spaces or special characters (such as dashes)
  • Cases where trailing arguments start immediately after the config path

It may be beneficial to add more inline comments or refactor this segment into a helper function to clarify each step of the extraction and trimming process.


243-247: 🛠️ Refactor suggestion

Conditional Construction of the terraform-docs Invocation
The code conditionally sets a local variable config_options based on have_config_flag and then calls terraform-docs with the concatenation of $tf_docs_formatter, $config_options, and $args. One potential area for concern is that the variable tf_docs_formatter is only explicitly set to "md" when --config is not present (line 143). If arguments contain --config, then no default formatter value is assigned, which means $tf_docs_formatter may be empty.

Please verify whether this behavior is intentional. If a default formatter is desired regardless of the flag’s presence, consider initializing tf_docs_formatter in the else branch as well. For example, you might update the command line as follows to set a default if it’s unset:

-    terraform-docs --output-mode="$output_mode" --output-file="$output_file" $tf_docs_formatter "$config_options" $args ./ > /dev/null
+    terraform-docs --output-mode="$output_mode" --output-file="$output_file" ${tf_docs_formatter:="md"} "$config_options" $args ./ > /dev/null
✅ Verification successful

Review of terraform-docs Default Formatter Handling
The configuration assigns a default formatter value "md" only when the arguments do not contain --config (lines 140–143). When --config is present, the local variable tf_docs_formatter is not set, which appears to be an intentional behavior rather than an oversight. However, if you intended to always have a default formatter, you might consider initializing tf_docs_formatter in both branches.

  • Verified that tf_docs_formatter is only set when no --config flag is present.
  • The behavior is consistent with the current design, so it appears intentional.
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Display the section of hooks/terraform_docs.sh around the assignment of tf_docs_formatter (around line 140)
sed -n '130,160p' hooks/terraform_docs.sh

Length of output: 1332


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b0ad90 and 611b708.

📒 Files selected for processing (1)
  • hooks/terraform_docs.sh (3 hunks)
🧰 Additional context used
🪛 Shellcheck (0.10.0)
hooks/terraform_docs.sh

[warning] 241-241: config_arg is referenced but not assigned.

(SC2154)

⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.12@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.12@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.12@macos-13
  • GitHub Check: 🧪 Tests / pytest@🐍3.11@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.10@macos-14
  • GitHub Check: 🧹 Linters / pre-commit@🐍3.13@ubuntu-latest
  • GitHub Check: pre-commit
🔇 Additional comments (1)
hooks/terraform_docs.sh (1)

Line range hint 20-23: Verify path handling compatibility.

The initial config path handling using pwd might interfere with the new whitespace handling logic. Please verify that both mechanisms work together correctly, especially with paths containing spaces.

Run this script to test various path scenarios:

hooks/terraform_docs.sh Outdated Show resolved Hide resolved
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
@tarfu tarfu changed the title fix(terraform_docs): fix config path having multiple whitespaces fix(terraform_docs): fFix config path having multiple whitespaces Jan 31, 2025
@tarfu tarfu changed the title fix(terraform_docs): fFix config path having multiple whitespaces fix(terraform_docs): Fix config path having multiple whitespaces Jan 31, 2025
@MaxymVlasov MaxymVlasov changed the title fix(terraform_docs): Fix config path having multiple whitespaces fix(terraform_docs): Allow having whitespaces in path to .terraform-docs.yaml config file Jan 31, 2025
@MaxymVlasov MaxymVlasov added hook/terraform_docs Bash hook bug_with_workaround Something isn't working but there is a workaround labels Jan 31, 2025
Copy link
Collaborator

@MaxymVlasov MaxymVlasov left a comment

Choose a reason for hiding this comment

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

Thank you for catch and fixing this bug.
Simplest workaround - do not use spaces in path, as it's never ending good in many cases

More comprehensive bash review will be preformed by @yermulnik

Sidenote: there will be no such problems in Python hooks, but they are not ready yet.

hooks/terraform_docs.sh Outdated Show resolved Hide resolved
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
@MaxymVlasov MaxymVlasov self-requested a review January 31, 2025 21:29
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
hooks/terraform_docs.sh Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
hooks/terraform_docs.sh (1)

242-245: Handling and passing the config option cleanly.

Here you declare a local variable config_options and, if the flag is set, assign it the value --config=$config_file. Then it is passed as a separate argument in the terraform-docs command call. This approach cleanly separates the config flag from the rest of the arguments.

  • Suggestion:
    • For added clarity and to prevent any unintended behavior, you might explicitly initialize config_options to an empty string (e.g. local config_options="") before conditionally reassigning it.
    • Verify that the quoting (using "$config_options") behaves as expected when config_options is empty.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a6bf17a and 2d7203b.

📒 Files selected for processing (1)
  • hooks/terraform_docs.sh (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@macos-13
  • GitHub Check: 🧪 Tests / pytest@🐍3.12@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.12@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.10@windows-2025
🔇 Additional comments (2)
hooks/terraform_docs.sh (2)

90-90: Initialize the config flag variable appropriately.

The newly introduced variable have_config_flag=false at line 90 is correctly defined to track the presence of the --config flag. This initialization is consistent with our overall design.


145-156: Complex extraction logic for the --config flag value.

This block sets have_config_flag to true and then uses extended globbing to extract the config file path from the args string. While the use of shopt -s extglob and the parameter expansions help support both the = and whitespace-based separators, the logic is fairly complex and could be brittle in certain edge cases (e.g., paths with multiple spaces or dashes near a -- token).

  • Recommendation:
    • Consider adding clarifying inline comments or refactoring this block into a helper function to improve readability and maintainability.
    • Ensure extensive test coverage for various config path formats (paths with leading/trailing spaces, multiple internal spaces, and even cases where the path might include sequences like --).

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d7203b and 05339b7.

📒 Files selected for processing (1)
  • hooks/terraform_docs.sh (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.9@macos-13
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@windows-2025
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.13@macos-13
  • GitHub Check: 🧪 Tests / pytest@🐍3.12@macos-14
  • GitHub Check: 🧪 Tests / pytest@🐍3.10@windows-2025
🔇 Additional comments (2)
hooks/terraform_docs.sh (2)

91-92: Initialization of config flag variable
The addition of local have_config_flag=false correctly initializes a flag to track whether the --config flag is present. This is in line with the objective of handling config paths with spaces.


241-244: Conditional Insertion of Config Options
Introducing a dedicated local variable config_options and conditionally assigning it with

ensures that the --config flag (with its cleaned-up value) is passed to the terraform-docs command only when it is detected.

A minor note: please verify that the variable tf_docs_formatter is defined in all cases before its use in the command invocation, as it is used unconditionally on line 244.

✅ Verification successful

I'll perform an additional search in the codebase to confirm whether tf_docs_formatter is defined before its use. One useful approach is to search for assignments to this variable across the codebase, and particularly in hooks/terraform_docs.sh before line 244.

Please run the following script:


tf_docs_formatter is defined before its use.

  • The variable is locally set to "md" on line 143 in hooks/terraform_docs.sh.
  • The command on line 244 uses it after its assignment, ensuring it is always defined before use.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

[[ $have_config_flag == true ]] && config_options="--config=$config_file"

Length of output: 18


Script:

#!/bin/bash
echo "Searching for assignments to tf_docs_formatter across the repository:"
rg -n "tf_docs_formatter=" .

echo ""
echo "Searching for usage and assignment in hooks/terraform_docs.sh (lines 1-244):"
awk 'NR<=244' hooks/terraform_docs.sh | grep "tf_docs_formatter" || echo "No assignment found in the first 244 lines"

Length of output: 647

hooks/terraform_docs.sh Outdated Show resolved Hide resolved
# Enable extended pattern matching operators
shopt -qp extglob || EXTGLOB_IS_NOT_SET=true && shopt -s extglob
# Trim any args before the `--config` arg value
local config_file=${args##*--config(+([[:space:]])|=)}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
local config_file=${args##*--config(+([[:space:]])|=)}
local config_file=${args##*--config@(+([[:space:]])|=)}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks, added it and added back the blank line.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Thanks.
Did you have a chance to verify the final changeset?

Copy link
Collaborator

Choose a reason for hiding this comment

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

If it works as expected and w/o issues, then please merge the latest changes from master and we should be good to merge this PR 👍🏻
image

@tarfu
Copy link
Contributor Author

tarfu commented Feb 3, 2025

Thanks for merging master :)

@MaxymVlasov MaxymVlasov changed the title fix(terraform_docs): Allow having whitespaces in path to .terraform-docs.yaml config file fix(terraform_docs): Allow having whitespaces in path to .terraform-docs.yaml config file Feb 3, 2025
@MaxymVlasov MaxymVlasov merged commit 7d83911 into antonbabenko:master Feb 3, 2025
42 checks passed
antonbabenko pushed a commit that referenced this pull request Feb 3, 2025
## [1.97.2](v1.97.1...v1.97.2) (2025-02-03)

### Bug Fixes

* **`terraform_docs`:** Allow having whitespaces in path to `.terraform-docs.yaml` config file ([#796](#796)) ([7d83911](7d83911))
@antonbabenko
Copy link
Owner

This PR is included in version 1.97.2 🎉

@emoshaya
Copy link

emoshaya commented Feb 3, 2025

this change broke our pre-commit hook for terraform_docs.. Getting the following error:

Terraform docs...........................................................Failed
- hook id: terraform_docs
- duration: 0.36s
- exit code: 1

Error: accepts 1 arg(s), received 2
- repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.97.2
    hooks:
      - id: terraform_docs
        args: ["--args=--sort-by required --show all"]

v1.97.1 is working fine for us with the above config.

yermulnik added a commit that referenced this pull request Feb 3, 2025
* Fix bug introduced via #796 by passing config file only when it is
  defined
* While here make array declarations in `common::parse_cmdline` in
  `hooks/_common.sh` compliant with Bash v3
* While here suppress error outputs from `grep` for non-existing config
  file in `hooks/terraform_docs.sh` where error output makes no sense
@yermulnik
Copy link
Collaborator

yermulnik commented Feb 3, 2025

@emoshaya Thanks for reporting this bug.
Please see if #801 fixes this for you (it's 3ec780cc7b667b2bb2dddbc8e71ec55c025500b7 commit hash)

MaxymVlasov pushed a commit that referenced this pull request Feb 4, 2025
* Fix bug introduced via #796 by passing config file only when it is
  defined
* While here make array declarations in `common::parse_cmdline` in
  `hooks/_common.sh` compliant with Bash v3
* While here suppress error outputs from `grep` for non-existing config
  file in `hooks/terraform_docs.sh` where error output makes no sense
antonbabenko pushed a commit that referenced this pull request Feb 4, 2025
## [1.97.3](v1.97.2...v1.97.3) (2025-02-04)

### Bug Fixes

* **`terraform_docs`:** Fix bug introduced in `v1.97.2` ([#801](#801)) ([64b81f4](64b81f4)), closes [#796](#796)
@antonbabenko
Copy link
Owner

This issue has been resolved in version 1.97.3 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug_with_workaround Something isn't working but there is a workaround hook/terraform_docs Bash hook
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants