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

Copy lock file only when needed #2823

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

ben-z
Copy link

@ben-z ben-z commented Dec 3, 2023

Description

Terragrunt copies lock files into the working directory every time Terraform is initialized. This is inconsistent with the Terraform behaviour where the lock file is only written to when changed.

This is important when the working directory is on a readonly filesystem. I work with an organization that does this to prevent unintentional code changes during provisioning.

This PR makes it so that copying the lock file is avoided when the file has no changes.

TODOs

Read the Gruntwork contribution guidelines.

  • 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].

Updated the lock file copy mechanism to avoid copying when the lock file is unchanged. Useful for using a readonly working directory.

Summary by CodeRabbit

  • Refactor

    • Enhanced file handling operations with improved error management and validation to avoid unnecessary actions and ensure greater overall reliability.
  • Tests

    • Added comprehensive test cases to verify the updated file operations under multiple scenarios, ensuring consistent behavior and stability.

@ben-z ben-z requested a review from denis256 as a code owner December 3, 2023 05:47
@denis256
Copy link
Member

[INFO] Initializing environment for https://github.com/gruntwork-io/pre-commit.
Terraform fmt............................................................Passed
goimports................................................................Failed
- hook id: goimports
- files were modified by this hook

util/file.go
util/file.go

@ben-z
Copy link
Author

ben-z commented Jan 6, 2024

@denis256 I had some trailing whitespaces. Fixed in the latest commit by running pre-commit run --all-files:

pre-commit run --all-files

util/file.go Outdated
return errors.WithStackTrace(destReadErr)
}

if string(sourceContents) == string(destinationContents) {
Copy link
Member

Choose a reason for hiding this comment

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

util/file.go:613:5: stringXbytes: suggestion: bytes.Equal(sourceContents, destinationContents) (gocritic)
        if string(sourceContents) == string(destinationContents) {

Copy link
Author

Choose a reason for hiding this comment

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

Resolved in b3b9287

@denis256
Copy link
Member

denis256 commented Jan 8, 2024

Failed integration tests:

TestRenderJSONConfig
TestLocalDownload
TestLocalDownloadWithHiddenFolder
TestLocalDownloadWithRelativePath
TestLocalWithBackend
TestRemoteDownload
TestRemoteDownloadWithRelativePath
TestRemoteDownloadOverride
TestRemoteWithBackend
TestExcludeDirs
TestIncludeDirs
TestIncludeDirsDependencyConsistencyRegression
TestTerraformRegistryFetchingRootModule
TestTerraformRegistryFetchingRootShorthandModule
TestTerraformRegistryFetchingSubdirModule
TestTerraformRegistryFetchingSubdirWithReferenceModule
TestTerragruntInitHookWithSourceNoBackend
TestTerragruntInitHookWithSourceWithBackend
TestTerragruntCatchErrorsInTerraformExecution
TestTerragruntStdOut

@denis256
Copy link
Member

denis256 commented Jan 8, 2024

Will be also helpful to add an integration test which will track that the lock copy works as expected.

@ben-z ben-z force-pushed the support-readonly-fs branch from 9fa1844 to 889aca5 Compare February 17, 2024 01:07
@ben-z
Copy link
Author

ben-z commented Feb 17, 2024

Will be also helpful to add an integration test which will track that the lock copy works as expected.

I added some unit tests. Integration tests seem a lot more involved and I'm not super familiar with Go. Are unit tests sufficient?

Copy link

github-actions bot commented Dec 3, 2024

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for submitting this pull request.

@github-actions github-actions bot added the stale Stale label Dec 3, 2024
@ben-z
Copy link
Author

ben-z commented Dec 3, 2024

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for submitting this pull request.

cc @denis256

@github-actions github-actions bot removed the stale Stale label Dec 4, 2024
Copy link

github-actions bot commented Mar 5, 2025

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for submitting this pull request.

@github-actions github-actions bot added the stale Stale label Mar 5, 2025
Copy link
Contributor

coderabbitai bot commented Mar 5, 2025

Walkthrough

This pull request refines the CopyLockFile function by computing absolute file paths for the source and destination, checking for identical paths, verifying the existence of the source file, and comparing contents before copying the file with preserved permissions. Additionally, a comprehensive test suite has been added to ensure the function behaves correctly under various scenarios including missing files and content mismatches.

Changes

File(s) Change Summary
util/file.go Updated CopyLockFile to compute absolute paths, check if source and destination are identical, verify file existence, compare file contents, and copy only when needed while preserving permissions.
util/file_test.go Added TestCopyLockFile to cover scenarios such as identical paths, absent source file, creation of destination file, identical content, and differing content; utilizes subtests with assertions and silenced logging.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant CopyLockFile
    participant FileSystem
    participant Logger

    Caller->>CopyLockFile: Call CopyLockFile(src, dest)
    CopyLockFile->>FileSystem: Compute absolute paths for src & dest
    alt Paths are identical
        CopyLockFile->>Logger: Log identical path message
        CopyLockFile-->>Caller: Return early
    else
        CopyLockFile->>FileSystem: Check source file existence
        alt Source file not found
            CopyLockFile->>Logger: Log missing source
            CopyLockFile-->>Caller: Return early
        else
            CopyLockFile->>FileSystem: Read source file
            CopyLockFile->>FileSystem: Check destination file existence
            alt Destination file not found
                CopyLockFile->>Logger: Log action to copy file
                CopyLockFile->>FileSystem: Copy file preserving permissions
            else
                CopyLockFile->>FileSystem: Read destination file
                alt Contents are identical
                    CopyLockFile->>Logger: Log no copy needed
                    CopyLockFile-->>Caller: Return early
                else
                    CopyLockFile->>FileSystem: Copy file preserving permissions
                end
            end
        end
    end
Loading

Poem

In code we trust, improvements shine bright,
Paths become clear with absolute light.
Checks ensure each file is in the right space,
Logs and tests bring a smile to its face.
A little tweak, a thoughtful trace, all in good dev pace!

✨ 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
🪧 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.
  • @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)
util/file_test.go (1)

5-6: Consider using os package instead of ioutil.
Although ioutil still works, it’s encouraged in modern Go to use os.ReadFile and os.WriteFile directly for new code. This helps ensure consistency and avoids reliance on soon-to-be fully deprecated APIs.

Here’s a sample diff showing how you might replace ioutil calls:

-import (
-    "io/ioutil"
-    ...
-)
+import (
+    "os"
+    ...
+)

-err := ioutil.WriteFile(sourceLockFilePath, []byte("lock file contents"), 0644)
+err := os.WriteFile(sourceLockFilePath, []byte("lock file contents"), 0644)

-contents, err := ioutil.ReadFile(destinationLockFilePath)
+contents, err := os.ReadFile(destinationLockFilePath)
util/file.go (1)

588-629: Consider concurrency safety if multiple processes run at the same time.
If there’s a chance of parallel execution, we could add locking or concurrency checks. That might prevent partial overwrites or race conditions.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b47b57a and 889aca5.

📒 Files selected for processing (2)
  • util/file.go (2 hunks)
  • util/file_test.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Pull Request has non-contributor approval
🔇 Additional comments (3)
util/file_test.go (1)

344-454: Great coverage of lock file copying scenarios.
All your sub-tests nicely verify key conditions like missing files, unchanged contents, etc. This thorough approach helps ensure reliability.

util/file.go (2)

4-4: Thanks for switching to bytes.Equal.
Comparing byte slices directly is more idiomatic and efficient than converting to strings.


588-629: Solid implementation aligned with the PR objective.
The CopyLockFile function checks path equality, file existence, and content differences before copying. This avoids unnecessary writes, which matches Terraform’s approach and resolves read-only filesystem concerns.

@github-actions github-actions bot removed the stale Stale label Mar 6, 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.

2 participants