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

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

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

    • Generated configuration files are now automatically formatted to meet standardized conventions, ensuring a consistent and readable layout.
  • Tests

    • Added automated tests to validate that the output files adhere to the new formatting guidelines, enhancing reliability and quality assurance.

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 21, 2025 4:53pm

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

This pull request updates the file generation process. In codegen/generate.go, the WriteToFile function now formats content with hclwrite.Format before writing the file using os.WriteFile. Additionally, a new test, TestFmtGeneratedFile, is introduced in codegen/generate_test.go to validate that generated files are correctly formatted. The test creates a temporary file, writes a Terraform variable definition, and verifies the formatted output. There are no changes to the public interfaces.

Changes

File(s) Change Summary
codegen/generate.go Updated WriteToFile to format content using hclwrite.Format before writing with os.WriteFile.
codegen/generate_test.go Added TestFmtGeneratedFile to test that generated files are correctly formatted, including file existence and content verification.

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

  • denis256
  • levkohimins
  • yhakbar

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)

@@ -138,7 +138,7 @@ func WriteToFile(terragruntOptions *options.TerragruntOptions, basePath string,
contentsToWrite := fmt.Sprintf("%s%s", prefix, config.Contents)

const ownerWriteGlobalReadPerms = 0644
if err := os.WriteFile(targetPath, []byte(contentsToWrite), ownerWriteGlobalReadPerms); err != nil {
if err := os.WriteFile(targetPath, hclwrite.Format([]byte(contentsToWrite)), ownerWriteGlobalReadPerms); err != nil {
Copy link
Collaborator

Choose a reason for hiding this comment

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

@wakeful , this needs to be opt-in. The generate block can write arbitrary content, not just HCL content.

We could have a fmt attribute that determines whether to format the file, and users can set that to format the file.

We can also look to leverage the filename extension to have a smarter default for formatting (e.g. if the file has extension hcl, tf or tofu, default to format the file if not defined.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Understood! 💪

I will mark this PR as WiP and come back with extended functionality.

@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
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.

Make hclfmt format generated code
2 participants