Skip to content
New issue

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

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

Already on GitHub? # to your account

fix #2072 make sure the generated code is formatted before writing it to a file. #3917

Conversation

wakeful
Copy link
Contributor

@wakeful wakeful commented Feb 21, 2025

Description

Fixes #2072 make sure the generated code is formatted before writing it to a file.

TODOs

Read the Gruntwork contribution guidelines.

  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Ensure any 3rd party code adheres with our license policy or delete this line if its not applicable.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Updated the generated block to format the HCL syntax before writing it to a file, fix for #2072.

Migration Guide

n/a

Summary by CodeRabbit

  • New Features

    • Introduced a new hcl_fmt attribute in the generate block for automatic formatting of .hcl, .tf, and .tofu files before writing.
  • Tests

    • Added automated tests to validate the formatting of generated files, ensuring compliance with the new capabilities.

Copy link

vercel bot commented Feb 21, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
terragrunt-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 24, 2025 4:35pm

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

This pull request introduces a new pointer boolean field HclFmt in the GenerateConfig struct within codegen/generate.go, enabling optional formatting of files according to HCL standards. The WriteToFile function has been updated to format contents based on file extension or the value of HclFmt. A new test function, TestFmtGeneratedFile, has been added in codegen/generate_test.go to verify the correct formatting of generated files. Additionally, documentation has been updated to include the new hcl_fmt attribute in the generate block.

Changes

File(s) Change Summary
codegen/generate.go Added HclFmt field to GenerateConfig and updated WriteToFile to format content using hclwrite.Format based on file extension.
codegen/generate_test.go Introduced TestFmtGeneratedFile to validate file formatting, including checks for file existence and content verification.
docs/_docs/04_reference/04-config-blocks-and-attributes.md Added hcl_fmt attribute to the generate block documentation for Terragrunt configuration.

Sequence Diagram(s)

sequenceDiagram
    participant T as Test
    participant W as WriteToFile
    participant H as hclwrite.Format
    participant OS as os.WriteFile

    T->>W: Call WriteToFile(contents)
    W->>H: Format(contents)
    H-->>W: Return formattedContents
    W->>OS: Write formattedContents
    OS-->>W: Write success/error
    W->>T: Return result
Loading

Suggested reviewers

  • yhakbar
  • denis256
  • levkohimins

Poem

In our repo, a fresh wind does blow,
Formatting magic now takes its show.
Tests run with a merry, keen delight,
Ensuring our code stays neat and bright.
Here’s to robust builds and clarity in sight!
🚀✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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
Contributor

@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 (2)
codegen/generate.go (1)

141-141: Nice improvement! 👍

Good call on using hclwrite.Format to ensure consistent formatting. The placement right before writing to file is perfect.

Consider extracting the formatting into a separate function for better testability and reuse:

-if err := os.WriteFile(targetPath, hclwrite.Format([]byte(contentsToWrite)), ownerWriteGlobalReadPerms); err != nil {
+formattedContent := hclwrite.Format([]byte(contentsToWrite))
+if err := os.WriteFile(targetPath, formattedContent, ownerWriteGlobalReadPerms); err != nil {
codegen/generate_test.go (1)

148-201: Great test structure! Let's add more test cases.

The table-driven test pattern is perfect for this, and the first test case is a good start. However, we could strengthen the test coverage with more cases.

Consider adding these test cases:

 tc := []struct {
   name     string
   disabled bool
   path     string
   contents string
   expected string
   ifExists codegen.GenerateConfigExists
 }{
   {
     "generate-simple-example",
     false,
     fmt.Sprintf("%s/%s", testDir, "simple_example"),
     "variable \"msg\"{\ntype=string\n  default=\"hello\"\n}\n",
     "variable \"msg\" {\n  type    = string\n  default = \"hello\"\n}\n",
     codegen.ExistsError,
   },
+  {
+    "generate-block-with-nested-blocks",
+    false,
+    fmt.Sprintf("%s/%s", testDir, "nested_blocks"),
+    "resource\"aws_instance\"\"example\"{\nami=\"ami-123\"\ntags={\nName=\"test\"\n}\n}\n",
+    "resource \"aws_instance\" \"example\" {\n  ami = \"ami-123\"\n  tags = {\n    Name = \"test\"\n  }\n}\n",
+    codegen.ExistsError,
+  },
+  {
+    "generate-with-comments",
+    false,
+    fmt.Sprintf("%s/%s", testDir, "with_comments"),
+    "#test comment\nvariable\"foo\"{#another comment\ntype=string}\n",
+    "# test comment\nvariable \"foo\" { # another comment\n  type = string\n}\n",
+    codegen.ExistsError,
+  },
 },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fb4b493 and 60d607e.

📒 Files selected for processing (2)
  • codegen/generate.go (1 hunks)
  • codegen/generate_test.go (2 hunks)

@wakeful wakeful marked this pull request as draft February 21, 2025 17:25
@wakeful wakeful changed the title fix #2072 make sure the generated code is formatted before writing it to a file. [WiP] fix #2072 make sure the generated code is formatted before writing it to a file. Feb 21, 2025
@wakeful wakeful force-pushed the fix-2072-fmt-generated-code-before-writing-to-disk branch from 60d607e to db053bd Compare February 24, 2025 08:06
@wakeful wakeful marked this pull request as ready for review February 24, 2025 08:07
@wakeful
Copy link
Contributor Author

wakeful commented Feb 24, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@wakeful wakeful changed the title [WiP] fix #2072 make sure the generated code is formatted before writing it to a file. fix #2072 make sure the generated code is formatted before writing it to a file. Feb 24, 2025
@wakeful
Copy link
Contributor Author

wakeful commented Feb 24, 2025

hey @yhakbar,

I added an hcl_fmt attribute to the generate block and limited the formatting to specific file extensions.
Am I on the right track now?

@wakeful wakeful requested a review from yhakbar February 24, 2025 08:18
@yhakbar
Copy link
Collaborator

yhakbar commented Feb 24, 2025

hey @yhakbar,

I added an hcl_fmt attribute to the generate block and limited the formatting to specific file extensions. Am I on the right track now?

@wakeful

We're very close now. What I thought would be done is to define the value of HclFmt as a pointer of bool, and immediately look at the value of Path after parsing the config, and default the value to true if the extension is in the list of .hcl, .tf or .tofu, and default the value to false otherwise. If a user explicitly sets the value to something, we should blindly accept what they've requested (in-case some other extension we haven't thought of uses HCL and we should format it anyways, or they would very intentionally like to avoid formatting a file, even though it's an HCL file).

@wakeful wakeful force-pushed the fix-2072-fmt-generated-code-before-writing-to-disk branch from db053bd to 7c9f0d6 Compare February 24, 2025 16:34
Copy link
Contributor

@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)
codegen/generate_test.go (1)

148-221: Great test coverage! Consider adding one more case.

The test cases thoroughly cover the formatting scenarios. Nice job using table-driven tests and temporary directories! 🎯

Would you consider adding one more test case for a non-HCL file extension (e.g., .txt) to verify it's not formatted by default?

Here's a suggested test case to add:

 tc := []struct {
     // ... existing fields ...
 }{
+    {
+        name:     "ignore-non-hcl-by-default",
+        path:     fmt.Sprintf("%s/%s", testDir, "unformatted.txt"),
+        contents: "variable \"msg\"{\ntype=string\n  default=\"hello\"\n}\n",
+        expected: "variable \"msg\"{\ntype=string\n  default=\"hello\"\n}\n",
+        ifExists: codegen.ExistsError,
+    },
     // ... existing test cases ...
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db053bd and 7c9f0d6.

📒 Files selected for processing (3)
  • codegen/generate.go (2 hunks)
  • codegen/generate_test.go (2 hunks)
  • docs/_docs/04_reference/04-config-blocks-and-attributes.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/_docs/04_reference/04-config-blocks-and-attributes.md
🔇 Additional comments (3)
codegen/generate.go (3)

89-89: LGTM! Smart use of pointer boolean for the formatting flag.

The HclFmt field is well-designed, using a pointer boolean to support three states: nil (auto), true (force format), and false (no format).


138-153: Nice implementation of the formatting logic! 👍

The code elegantly handles both automatic and explicit formatting:

  • Automatically formats known HCL extensions (.hcl, .tf, .tofu)
  • Respects user's explicit preference when set
  • Uses a map for efficient extension lookup

156-158: LGTM! Clean formatting implementation.

Good use of hclwrite.Format to ensure consistent HCL formatting.

@wakeful
Copy link
Contributor Author

wakeful commented Feb 24, 2025

@yhakbar I modified the code based on your suggestions.

@yhakbar yhakbar merged commit 4a36f3f into gruntwork-io:main Feb 24, 2025
7 checks passed
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Make hclfmt format generated code
2 participants