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

Added handler for OCI Artifacts not supporting the plus sign (+) #23

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

Conversation

EStork09
Copy link
Contributor

@EStork09 EStork09 commented Oct 27, 2024

This is to fix #19, helm will automatically switch between the + to an _ because OCI Artifacts don't support the +.

To get around this I have added the logic, if the passed in version contains an _, to for do a lookup for + by replacing all the underscores then if that fails bomb out entirely.

This could be a problem if a tag contains both the + and _, but it will be impossible to tell since helm automatically changes the chart to a _ in all places so this might require more changes at the upstream helm handling.

Summary by CodeRabbit

  • New Features
    • Enhanced handling of chart references and manifest targets to support alternative formats.
    • Introduced a new function to replace underscores with plus signs in version strings.
  • Bug Fixes
    • Improved error handling for cases where manifests are not found, ensuring consistent error messages.
  • Documentation
    • Minor adjustments made to comments for clarity.

Copy link

coderabbitai bot commented Oct 27, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces changes to the prepareChart, Handle, and HandleTags methods within the Manifests struct in the internal/manifest/charts.go and internal/manifest/manifest.go files. Modifications include adding logic to replace underscores with plus signs in the reference and target strings, respectively. This adjustment allows for alternative formats to be processed. Error handling is updated to ensure consistent messaging, and redundant checks in the HandleTags method are removed for simplification. Overall, the control flow remains intact.

Changes

File Change Summary
internal/manifest/charts.go Modified prepareChart method to replace _ with + in reference for chart version retrieval. Updated error handling for broader reference formats.
internal/manifest/manifest.go Updated Handle method to replace _ with + in target. Simplified error handling in HandleTags method. Minor comments and formatting adjustments.

Assessment against linked issues

Objective Addressed Explanation
Remove special characters for image tags (#19)

Possibly related PRs

  • Added removal of "v" on handler #21: The changes in this PR also modify the Handle method within the Manifests struct in internal/manifest/manifest.go, specifically addressing string formatting for the target variable, which is related to the changes made to handle underscores in the prepareChart method of the main PR.

Suggested reviewers

  • Vad1mo
  • tpoxa

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a4ecef6 and ed60295.

📒 Files selected for processing (3)
  • internal/helper/helper.go (1 hunks)
  • internal/manifest/charts.go (2 hunks)
  • internal/manifest/manifest.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/manifest/charts.go
  • internal/manifest/manifest.go
🔇 Additional comments (1)
internal/helper/helper.go (1)

75-80: Add documentation and consider validation improvements

The function serves a specific purpose in handling OCI Artifacts' limitation with plus signs, but this context isn't clear from the code alone. Consider these improvements:

  1. Add documentation explaining:
    • The purpose of the function
    • When to use it
    • The transformation it performs
  2. Consider adding basic semver validation
  3. Handle potential edge cases with multiple underscores

Here's a suggested implementation:

+// SemVerReplace handles the conversion of semantic version strings for OCI Artifact compatibility.
+// It replaces underscores with plus signs to work around OCI Artifacts' limitation
+// of not supporting the plus sign in version tags.
+//
+// Example: "1.0.0_beta.1" -> "1.0.0+beta.1"
 func SemVerReplace(semver string) string {
-	if semver != "" && strings.Contains(semver, "_") {
-		semver = strings.ReplaceAll(semver, "_", "+")
+	if semver == "" {
+		return semver
 	}
-	return semver
+	
+	// Optional: Add basic semver validation here
+	// if !isValidSemver(semver) {
+	//     return semver
+	// }
+	
+	return strings.ReplaceAll(semver, "_", "+")
 }

Let's verify the usage context of this function:


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

🧹 Outside diff range and nitpick comments (3)
internal/manifest/charts.go (1)

50-56: Consider adding debug logging and improving error messages.

To improve maintainability and user experience:

  1. Add debug logging when performing underscore-to-plus conversion
  2. Enhance error messages to be more specific about version format issues

Consider these improvements:

 if strings.Contains(reference, "_") {
+    if m.config.Debug {
+        m.log.Printf("attempting lookup with underscore converted to plus sign for reference: %s\n", reference)
+    }
     reference = strings.ReplaceAll(reference, "_", "+")
 }
 chartVer, err = index.Get(chart, reference)
 if err != nil {
     return &errors.RegError{
         Status:  http.StatusNotFound,
         Code:    "NOT FOUND",
-        Message: fmt.Sprintf("Chart: %s version: %s not found: %v", chart, reference, err),
+        Message: fmt.Sprintf("Chart: %s version: %s not found (tried with both underscore and plus sign formats): %v", chart, reference, err),
     }
 }
internal/manifest/manifest.go (2)

201-204: Improve comment clarity for OCI compatibility.

The comment should explicitly mention this is for OCI compatibility. Consider updating it to be more descriptive.

-// check if chart was just remapped to an _ before failing
+// Handle OCI artifact compatibility by converting underscore back to plus sign
+// OCI artifacts don't support plus signs in tags, so they get converted to underscores

201-212: Add debug logging for underscore conversion attempts.

Consider adding debug logging to help troubleshoot when conversions are attempted.

 				if target != "" && strings.Contains(target, "_") {
+					if m.config.Debug {
+						m.log.Printf("attempting underscore to plus conversion for tag: %s", target)
+					}
 					target = strings.ReplaceAll(target, "_", "+")
 				}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0fee3db and a4ecef6.

📒 Files selected for processing (2)
  • internal/manifest/charts.go (1 hunks)
  • internal/manifest/manifest.go (1 hunks)
🔇 Additional comments (2)
internal/manifest/charts.go (1)

50-56: Implementation looks good, but consider edge cases.

The solution effectively handles the OCI Artifacts limitation with plus signs by attempting a fallback lookup with underscore-to-plus conversion. However, there are some edge cases to consider:

  1. The current implementation might incorrectly convert legitimate underscores to plus signs
  2. As noted in the PR description, there could be ambiguity when a tag contains both underscore and plus sign (converted to underscore by Helm)

Let's verify the potential impact of these edge cases:

Consider adding a more specific validation:

 if strings.Contains(reference, "_") {
+    // Only replace underscores that are likely to be plus sign replacements
+    // e.g., in version patterns like "1.2.3_4" or "v1.2.3_beta.4"
+    if strings.Contains(reference, ".") && strings.Count(reference, "_") == 1 {
         reference = strings.ReplaceAll(reference, "_", "+")
+    }
 }
✅ Verification successful

The underscore-to-plus conversion is consistent with existing codebase patterns

The search results reveal that this conversion pattern is already established in the codebase:

  • In internal/manifest/manifest.go, there's a similar conversion: target = strings.ReplaceAll(target, "_", "+")
  • No instances of version strings containing underscores were found in the yaml files
  • The implementation follows the same error-handling pattern as other index.Get calls

The original review's concerns about edge cases are less critical given:

  1. The conversion is consistent with existing codebase behavior
  2. The conversion only happens after an initial lookup fails, preserving any legitimate underscore usage
  3. No conflicting version patterns were found in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing chart versions containing underscores or plus signs
# to identify potential conflicts

# Look for version patterns in yaml files
rg -g '*.yaml' '(?:version|tag):\s*["\']?[^"'\s]*[_+][^"'\s]*["\']?' -A 2

# Look for direct version string assignments in go files
rg 'Version\s*=\s*["\']?[^"'\s]*[_+][^"'\s]*["\']?' -A 2

Length of output: 93


Script:

#!/bin/bash
# Let's try a different approach to search for version patterns

# Search for version patterns in yaml files
rg -g '*.yaml' '(?:version|tag):\s*["\']?[^"'\s]*[_+][^"'\s]*["\']?'

# Search for direct version string assignments in go files
rg 'Version\s*=\s*["\']?[^"'\s]*[_+][^"'\s]*["\']?'

# Look for chart version handling in the codebase
ast-grep --pattern 'chartVer, err = index.Get($_, $_)'

# Search for other underscore to plus conversions
rg 'ReplaceAll.*"_".*"+"'

Length of output: 94


Script:

#!/bin/bash

# Look for version patterns in yaml files
rg -g "*.yaml" "version:|tag:" -A 1

# Look for chart version handling in the codebase
rg "index\.Get\(" -A 2

# Search for underscore to plus conversions
rg "ReplaceAll.*_.*\+" -A 2

# Look for version-related error handling
rg "chartVer.*err.*index\.Get" -A 3

Length of output: 1825

internal/manifest/manifest.go (1)

201-212: Verify the impact on existing underscore usage.

We should verify that this change doesn't affect charts that legitimately use underscores in their version tags.

Let's check for any existing usage of underscores in chart versions:

✅ Verification successful

The underscore replacement is a safe fallback mechanism

The code changes are safe because:

  1. The underscore replacement only occurs as a fallback mechanism when the initial chart lookup fails
  2. The codebase shows no existing usage of underscores in version tags
  3. The replacement is specifically designed to handle cases where + was encoded as _ in URLs, which is a common URL encoding scenario

The search results confirm there are no legitimate uses of underscores in chart versions that could be affected by this change. The only underscore handling in the codebase is this specific fallback mechanism in internal/manifest/charts.go and internal/manifest/manifest.go.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for chart versions containing underscores to assess impact
# Expected: Should find any legitimate uses of underscores in version tags

# Look for version fields in Chart.yaml files
echo "Searching for Chart.yaml version fields with underscores..."
fd Chart.yaml --exec rg -l 'version:\s+[^#\n]*_'

# Look for version references in values.yaml files
echo "Searching for version references with underscores in values.yaml..."
fd values.yaml --exec rg -l 'version:\s+[^#\n]*_'

Length of output: 376


Script:

#!/bin/bash
# Let's try a different approach to find version patterns with underscores
# Search for any version-like patterns with underscores in all files

# Look for version patterns like v1_2, 1_2_3, etc.
echo "Searching for version-like patterns with underscores..."
rg -l '[vV]?\d+_\d+(?:_\d+)?'

# Look specifically for chart references with underscores
echo "Searching for chart references with underscores..."
rg -l 'chart:.*_'

# Look for any version field followed by underscore pattern
echo "Searching for version fields with underscores..."
rg -l 'version:.*_'

# Check the manifest code for any other underscore handling
echo "Checking manifest code for underscore handling..."
rg -A 5 -B 5 '_' internal/manifest/

Length of output: 11994

Comment on lines 201 to 212
// check if chart was just remapped to an _ before failing
if target != "" && strings.Contains(target, "_") {
target = strings.ReplaceAll(target, "_", "+")
}
ma, ok = m.manifests[repo][target]
// we failed
return &errors.RegError{
Status: http.StatusNotFound,
Code: "NOT FOUND",
Message: "Chart prepare error",
if !ok {
return &errors.RegError{
Status: http.StatusNotFound,
Code: "NOT FOUND",
Message: "Chart prepare error",
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure consistent handling between GET and HEAD methods.

The underscore to plus sign conversion is only implemented in the HEAD method. Consider applying the same logic to the GET method for consistency.

Would you like me to provide the implementation for the GET method as well?

Comment on lines +208 to +212
return &errors.RegError{
Status: http.StatusNotFound,
Code: "NOT FOUND",
Message: "Chart prepare error",
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance error message for better debugging.

The current error message "Chart prepare error" is not descriptive enough. It should indicate the attempted conversion and actual values.

-						Message: "Chart prepare error",
+						Message: fmt.Sprintf("Chart not found for repository %q with tag %q (attempted underscore to plus conversion)", repo, target),

Committable suggestion was skipped due to low confidence.

@tpoxa
Copy link
Collaborator

tpoxa commented Oct 27, 2024

thanks for your contribution @EStork09

I wonder if could have this in a single place, in some kind of normalise re-usable function?

if strings.Contains(reference, "_") {
	reference = strings.ReplaceAll(reference, "_", "+")
}

@EStork09
Copy link
Contributor Author

EStork09 commented Dec 3, 2024

thanks for your contribution @EStork09

I wonder if could have this in a single place, in some kind of normalise re-usable function?

if strings.Contains(reference, "_") {
	reference = strings.ReplaceAll(reference, "_", "+")
}

Sorry for the delay, I have been out of the country for a long while.

I don't fully know how much this makes sense, I feel it is a little more complicated to read but if there are more changes required for semver that helm deviates from with OCI artifacts then this could more easily be updated.

Either way it is updated, let me know if it makes sense or if I should adjust something else!

@EStork09
Copy link
Contributor Author

Hey @tpoxa could this possibly get reviewed again with the recent changes?

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.

Improvement request: Remove special characters for image tags
2 participants