Skip to content

Normalize lock file version constraint handling #4541

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

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

Conversation

james03160927
Copy link
Contributor

@james03160927 james03160927 commented Jul 17, 2025

Summary

  • Fixed lockfile handling when modules define constraints
  • Improved dependency constraint normalization for better compatibility
  • Enhanced lockfile version management across different scenarios

Test plan

  • Test lockfile generation with various constraint formats
  • Verify dependency resolution with normalized constraints
  • Test backwards compatibility with existing lockfiles

Summary by CodeRabbit

  • New Features

    • Version constraints in provider lock files are now automatically normalized for consistent formatting.
  • Tests

    • Enhanced test coverage to support dynamic provider constraints, ensuring more flexible and thorough validation of lockfile updates.

Copy link

vercel bot commented Jul 17, 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 Jul 17, 2025 3:29am

Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

📝 Walkthrough

Walkthrough

A new function for normalizing version constraint strings was added and integrated into the lockfile update logic, ensuring consistent formatting of constraints. The test suite was refactored to allow parameterized mocking of provider constraints, enabling more flexible and thorough testing of constraint handling in the lockfile update process.

Changes

File(s) Change Summary
tf/getproviders/lock.go Added normalizeVersionConstraint function; applied it in updateProviderBlock for constraint normalization; imported regexp.
tf/getproviders/lock_test.go Updated mockProviderUpdateLock to accept a constraint parameter; refactored tests to use dynamic provider creation with constraints.

Sequence Diagram(s)

sequenceDiagram
    participant TestCase
    participant MockProvider
    participant UpdateLockfile
    participant normalizeVersionConstraint

    TestCase->>MockProvider: Create mock with address, version, constraint
    TestCase->>UpdateLockfile: Call UpdateLockfile with mocked providers
    UpdateLockfile->>normalizeVersionConstraint: Normalize constraints string
    normalizeVersionConstraint-->>UpdateLockfile: Return normalized constraint
    UpdateLockfile-->>TestCase: Update lockfile with normalized constraint
Loading

Possibly related PRs

  • gruntwork-io/terragrunt#4380: Both PRs change how constraints are handled in updateProviderBlock, but with different approaches to constraint processing.
  • gruntwork-io/terragrunt#4514: Both PRs modify lockfile constraint handling and provider constraint usage, indicating a direct connection in tf/getproviders/lock.go.

Suggested reviewers

  • denis256
  • yhakbar
  • wakeful
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

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: 1

🧹 Nitpick comments (2)
tf/getproviders/lock_test.go (2)

21-21: Fix parameter name spelling.

The parameter name constrain should be constraint to match standard terminology and avoid confusion.

Apply this diff:

-func mockProviderUpdateLock(t *testing.T, ctrl *gomock.Controller, address, version, constrain string) getproviders.Provider {
+func mockProviderUpdateLock(t *testing.T, ctrl *gomock.Controller, address, version, constraint string) getproviders.Provider {

46-46: Update parameter usage to match corrected name.

The parameter usage should be updated to match the corrected parameter name.

Apply this diff:

-	provider.EXPECT().Constraints().Return(constrain).AnyTimes()
+	provider.EXPECT().Constraints().Return(constraint).AnyTimes()
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 497e2b2 and d2b04f5.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (2)
  • tf/getproviders/lock.go (3 hunks)
  • tf/getproviders/lock_test.go (7 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🧠 Learnings (1)
tf/getproviders/lock.go (1)
Learnt from: wakeful
PR: gruntwork-io/terragrunt#4491
File: test/integration_test.go:4265-4265
Timestamp: 2025-07-03T22:05:07.356Z
Learning: Constants defined in one Go file are accessible from other files in the same package without explicit imports. When reviewing Go code, consider the package-level scope rather than just the individual file scope.
🧬 Code Graph Analysis (1)
tf/getproviders/lock_test.go (2)
tf/getproviders/provider.go (1)
  • Provider (12-30)
tf/getproviders/lock.go (1)
  • UpdateLockfile (28-58)
🪛 GitHub Actions: Codespell
tf/getproviders/lock.go

[error] 303-303: codespell: 'contrains' is a misspelling; suggested corrections are 'constrains', 'contains', 'constraints'.


[error] 304-304: codespell: 'contrains' is a misspelling; suggested corrections are 'constrains', 'contains', 'constraints'.


[error] 306-306: codespell: 'contrains' is a misspelling; suggested corrections are 'constrains', 'contains', 'constraints'.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
  • GitHub Check: Test (Mock)
  • GitHub Check: Test (Deprecated)
  • GitHub Check: Test (Race)
  • GitHub Check: Test (AWS Tofu)
  • GitHub Check: Test (CAS)
  • GitHub Check: Build (windows/386)
  • GitHub Check: Test (Windows)
  • GitHub Check: Test (AWS with Latest Terraform)
  • GitHub Check: Test (AWSGCP)
  • GitHub Check: Test (SOPS)
  • GitHub Check: Test (AWS with Latest OSS Terraform)
  • GitHub Check: Test (Tflint)
  • GitHub Check: Build (windows/amd64)
  • GitHub Check: Build (windows/386)
  • GitHub Check: Build (darwin/amd64)
  • GitHub Check: Build (linux/amd64)
  • GitHub Check: Build (linux/arm64)
  • GitHub Check: Build (darwin/arm64)
  • GitHub Check: Build (linux/386)
  • GitHub Check: lint
  • GitHub Check: lint
🔇 Additional comments (6)
tf/getproviders/lock.go (3)

11-11: LGTM!

The addition of the regexp package import is appropriate for the new version constraint normalization functionality.


132-132: LGTM!

The integration of the normalizeVersionConstraint function into the constraint setting logic ensures consistent formatting of version constraints in lockfiles.


300-300: LGTM!

The regex variable correctly uses version.VersionRegexpRaw from the HashiCorp go-version library to match version strings, ensuring consistency with Terraform's version parsing.

tf/getproviders/lock_test.go (3)

60-60: LGTM!

The refactoring to use a providersFunc function enables dynamic provider creation with different constraints for each test case, improving test flexibility and coverage.


82-99: LGTM!

The new test case effectively verifies the constraint normalization functionality by testing that ">= 5.37, < 6 " gets normalized to ">= 5.37.0, < 6.0.0 ". This validates the core functionality of the PR.


219-219: LGTM!

The test execution correctly uses the new providersFunc pattern to dynamically generate providers and pass them to UpdateLockfile, enabling parameterized testing of constraint handling.

Also applies to: 233-233

Comment on lines +302 to +323
func normalizeVersionConstraint(raw string) string {
contrains := strings.Split(raw, ",")
result := make([]string, len(contrains))

for i, constrain := range contrains {
pos := versionRegex.FindStringIndex(constrain)
if pos == nil {
result[i] = constrain
continue
}
constrainClean := strings.TrimSpace(constrain[pos[0]:pos[1]])
v, err := version.NewVersion(constrainClean)
if err != nil {
result[i] = constrain
continue
}

result[i] = constrain[0:pos[0]] + v.String() + constrain[pos[0]+len(constrainClean):]
}

return strings.Join(result, ",")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix spelling errors and improve variable naming.

The function has several spelling errors flagged by the pipeline:

Apply this diff to fix the spelling errors:

 func normalizeVersionConstraint(raw string) string {
-	contrains := strings.Split(raw, ",")
-	result := make([]string, len(contrains))
+	constraints := strings.Split(raw, ",")
+	result := make([]string, len(constraints))
 
-	for i, constrain := range contrains {
+	for i, constraint := range constraints {
-		pos := versionRegex.FindStringIndex(constrain)
+		pos := versionRegex.FindStringIndex(constraint)
 		if pos == nil {
-			result[i] = constrain
+			result[i] = constraint
 			continue
 		}
-		constrainClean := strings.TrimSpace(constrain[pos[0]:pos[1]])
+		constraintClean := strings.TrimSpace(constraint[pos[0]:pos[1]])
-		v, err := version.NewVersion(constrainClean)
+		v, err := version.NewVersion(constraintClean)
 		if err != nil {
-			result[i] = constrain
+			result[i] = constraint
 			continue
 		}
 
-		result[i] = constrain[0:pos[0]] + v.String() + constrain[pos[0]+len(constrainClean):]
+		result[i] = constraint[0:pos[0]] + v.String() + constraint[pos[0]+len(constraintClean):]
 	}
 
 	return strings.Join(result, ",")
 }

Additional observations about the function logic:

The normalization logic is sound - it preserves operators and whitespace while normalizing only the version numbers themselves. The error handling appropriately falls back to the original constraint segment if parsing fails.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func normalizeVersionConstraint(raw string) string {
contrains := strings.Split(raw, ",")
result := make([]string, len(contrains))
for i, constrain := range contrains {
pos := versionRegex.FindStringIndex(constrain)
if pos == nil {
result[i] = constrain
continue
}
constrainClean := strings.TrimSpace(constrain[pos[0]:pos[1]])
v, err := version.NewVersion(constrainClean)
if err != nil {
result[i] = constrain
continue
}
result[i] = constrain[0:pos[0]] + v.String() + constrain[pos[0]+len(constrainClean):]
}
return strings.Join(result, ",")
}
func normalizeVersionConstraint(raw string) string {
constraints := strings.Split(raw, ",")
result := make([]string, len(constraints))
for i, constraint := range constraints {
pos := versionRegex.FindStringIndex(constraint)
if pos == nil {
result[i] = constraint
continue
}
constraintClean := strings.TrimSpace(constraint[pos[0]:pos[1]])
v, err := version.NewVersion(constraintClean)
if err != nil {
result[i] = constraint
continue
}
result[i] = constraint[0:pos[0]] + v.String() + constraint[pos[0]+len(constraintClean):]
}
return strings.Join(result, ",")
}
🧰 Tools
🪛 GitHub Actions: Codespell

[error] 303-303: codespell: 'contrains' is a misspelling; suggested corrections are 'constrains', 'contains', 'constraints'.


[error] 304-304: codespell: 'contrains' is a misspelling; suggested corrections are 'constrains', 'contains', 'constraints'.


[error] 306-306: codespell: 'contrains' is a misspelling; suggested corrections are 'constrains', 'contains', 'constraints'.

🤖 Prompt for AI Agents
In tf/getproviders/lock.go around lines 302 to 323, fix the spelling errors by
renaming the variable "contrains" to "constraints" and "constrain" to
"constraint" throughout the function. This improves code readability and
correctness without changing the existing logic.

@grimm26
Copy link
Contributor

grimm26 commented Jul 17, 2025

will this fix #4542 ? @james03160927 can you add a test case for my issue?

@james03160927
Copy link
Contributor Author

Hi @grimm26, I don't think this would entirely fix the issue you posted but I believe it's the first step toward it.

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