-
Notifications
You must be signed in to change notification settings - Fork 3
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
SKIP-1159 - A better labeler #557
base: main
Are you sure you want to change the base?
Conversation
- Fixed most cases
…e robust - All tests pass now
WalkthroughThe changes involve modifications to the Changes
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Co-authored-by: Martin Haram Nygård <[email protected]>
There was a problem hiding this 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 (4)
pkg/resourcegenerator/resourceutils/helpers_test.go (1)
9-39
: Consider adding negative test cases.While the current test cases are comprehensive for valid inputs, consider adding negative test cases to verify proper handling of:
- Invalid image strings
- Malformed version strings
- Empty strings
- Very long version strings that exceed LabelValueMaxLength
This would further improve the robustness of the labeler.
pkg/resourcegenerator/resourceutils/helpers.go (3)
24-28
: Handle errors explicitly inMatchesRegex
functionCurrently, the function checks
err == nil
in the return statement. For better clarity and error handling, consider checking iferr
is notnil
before returning the result. This helps in debugging and maintaining the code.Apply this diff to handle errors explicitly:
func MatchesRegex(s string, pattern string) bool { obj, err := regexp.Match(pattern, []byte(s)) - return obj && err == nil + if err != nil { + // Handle or log the error as needed + return false + } + return obj }
33-36
: Ensure consistent handling of image digestsWhen an image string contains an
"@"
, the code replaces everything after it with":unknown"
. This could lead to confusion or mislabeling. Consider using a more descriptive tag or handling the digest appropriately.For example, you might retain the digest information or use a more meaningful placeholder:
if strings.Contains(imageVersionString, "@") { imageVersionString = strings.Split(imageVersionString, "@")[0] - imageVersionString = imageVersionString + ":unknown" + imageVersionString = imageVersionString + ":digest" }
57-58
: Prevent potential issues in version string sanitization loopThe loop that removes leading characters not matching
[a-zA-Z0-9]
may result in an emptyversionPart
, which could cause issues downstream if an empty string is not an acceptable version label. Consider adding a check to handle this scenario.For example:
for len(versionPart) > 0 && !MatchesRegex(versionPart[:1], "[a-zA-Z0-9]") { versionPart = versionPart[1:] } + if len(versionPart) == 0 { + versionPart = "unknown" + }This ensures that
versionPart
will have a valid value even if all leading characters were removed.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
pkg/resourcegenerator/resourceutils/helpers.go
(2 hunks)pkg/resourcegenerator/resourceutils/helpers_test.go
(1 hunks)
🔇 Additional comments (8)
pkg/resourcegenerator/resourceutils/helpers_test.go (3)
1-7
: LGTM! Clean import section.
The import section is well-organized with only the necessary testing dependency.
9-13
: Excellent use of table-driven tests!
The test structure follows Go best practices, making it easy to maintain and extend with new test cases.
34-39
: Well-structured test execution!
The use of subtests with descriptive names and clear assertions will make test failures easy to diagnose.
pkg/resourcegenerator/resourceutils/helpers.go (5)
6-6
: Approved: Necessary imports added
The addition of "regexp"
and "strings"
imports is appropriate and necessary for the functions introduced later in the code.
10-11
: Approved: Define LabelValueMaxLength
constant
Defining LabelValueMaxLength
as 63
correctly sets the maximum length for Kubernetes label values, adhering to Kubernetes specifications.
39-41
: Approved: Default to "latest" when no version is specified
The logic correctly assumes "latest" when no version tag is present in the image string.
49-49
: Approved: Replace "+" with "-" in version strings
Replacing "+"
with "-"
in the version string helps maintain compatibility with label value requirements.
52-53
: Approved: Enforce maximum label value length
Truncating the versionPart
to LabelValueMaxLength
characters ensures compliance with Kubernetes label length constraints.
{"image", "latest"}, | ||
{"image:latest", "latest"}, | ||
{"image:1.2.3-dev-123abc", "1.2.3-dev-123abc"}, | ||
{"image:1.2.3", "1.2.3"}, | ||
{"ghcr.io/org/repo@sha256:54d7ea8b48d0e7569766e0e10b9e38da778a5f65d764168dd7db76a37d6b8", "unknown"}, | ||
{"ghcr.io/org/one-app:sha-b15dc91c27ad2387bea81294593d5ce5a686bcc4@sha256:3cda54f1d25458f25fdde0398130da57a4ebb4a4cd759bc49035b7ebf9d83619", "sha-b15dc91c27ad2387bea81294593d5ce5a686bcc4"}, | ||
{"ghcr.io/org/another-app:3fb7048", "3fb7048"}, | ||
{"ghcr.io/org/some-team/third-app:v1.2.54", "v1.2.54"}, | ||
{"ghcr.io/org/another-team/fourth-app:4.0.0.rc-36", "4.0.0.rc-36"}, | ||
{"ghcr.io/org/another-team/fifth-app:4.0.0.rc-36-master-latest", "4.0.0.rc-36-master-latest"}, | ||
{"ghcr.io/kartverket/vulnerability-disclosure-program@sha256:ab85022d117168585bdedc71cf9c67c3ca327533dc7cd2c5bcc42a83f308ea5d", "unknown"}, | ||
{"ghcr.io/kartverket/vulnerability-disclosure-program:4.0.1@sha256:ab85022d117168585bdedc71cf9c67c3ca327533dc7cd2c5bcc42a83f308ea5d", "4.0.1"}, | ||
{"nginxinc/nginx-unprivileged:1.20.0-alpine", "1.20.0-alpine"}, | ||
{"foo/bar:1.2.3+build.4", "1.2.3-build.4"}, | ||
{"foo/bar:1.2.3+somethingLongXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "1.2.3-somethingLongXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}, | ||
{"foo/bar:-1.2.3", "1.2.3"}, | ||
{"foo/bar:__1.2.3", "1.2.3"}, | ||
{"foo/bar:.1.2.3", "1.2.3"}, | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Documentation needs improvement for version string transformations
The implementation in GetImageVersion
includes several important transformations that should be better documented in the function's header comment:
- Handling of SHA digests (returns "unknown")
- Replacing "+" with "-" in version strings
- Truncating version strings longer than
LabelValueMaxLength
- Stripping non-alphanumeric leading characters
- Default "latest" tag handling
The current comment // GetImageVersion returns the version part of an image string
is too brief given the complexity of the transformations.
🔗 Analysis chain
Comprehensive test coverage with clear test cases!
The test cases cover a wide range of scenarios including:
- Basic image tags
- Semantic versions
- SHA digests
- Special character handling
- Version string transformations
Let's verify if these transformations are documented in the implementation:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the version string transformation rules are documented
# Expected: Comments or documentation explaining the transformation rules
# Look for documentation about version transformations
rg -A 5 "GetImageVersion" pkg/resourcegenerator/resourceutils/helpers.go
Length of output: 429
Script:
#!/bin/bash
# Let's see the complete implementation of GetImageVersion to understand all transformations
rg -A 20 "GetImageVersion" pkg/resourcegenerator/resourceutils/helpers.go
# Also check for any related tests that might document the behavior
rg -A 10 "TestGetImageVersion" pkg/resourcegenerator/resourceutils/helpers_test.go
Length of output: 901
Script:
#!/bin/bash
# Let's try with ast-grep to get the complete function implementation
ast-grep --pattern 'func GetImageVersion($_) string {
$$$
}'
# And get the test function as well
ast-grep --pattern 'func TestGetImageVersion($_) $_ {
$$$
}'
Length of output: 2719
parts := strings.Split(imageVersionString, ":") | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handle image strings with multiple colons
Splitting imageVersionString
by ":"
and accessing parts[1]
can lead to errors if the image string contains multiple colons, such as when specifying a registry with a port number (e.g., "registry:5000/repo/image:tag"
). This could cause versionPart
to be incorrect.
Apply this diff to correctly extract the version tag using the last occurrence of ":"
:
- parts := strings.Split(imageVersionString, ":")
- versionPart := parts[1]
+ lastColon := strings.LastIndex(imageVersionString, ":")
+ if lastColon == -1 || lastColon == len(imageVersionString)-1 {
+ versionPart := "latest"
+ } else {
+ versionPart := imageVersionString[lastColon+1:]
+ imageVersionString = imageVersionString[:lastColon]
+ }
This approach ensures that the version tag is accurately extracted, even when the image string includes a registry port or multiple colons.
Committable suggestion skipped: line range outside the PR's diff.
if !strings.Contains(imageVersionString, ":") { | ||
return "latest" | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we return the image digest if no version is specified instead of latest?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't necessarily have the digest and for a human readable version I prefer latest
.
There was a problem hiding this 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 (1)
pkg/resourcegenerator/resourceutils/helpers.go (1)
30-30
: Add comprehensive function documentationThe function should document its behavior for different input formats and edge cases:
- Image strings with digests (@sha256:...)
- Images without tags
- Version sanitization rules
Add this documentation:
-// GetImageVersion returns the version part of an image string +// GetImageVersion extracts and sanitizes the version tag from an image string. +// It handles various formats: +// - Images with digests (e.g., image@sha256:123) -> returns "unknown" +// - Images without tags (e.g., nginx) -> returns "latest" +// - Images with tags (e.g., nginx:1.19) -> returns sanitized tag +// The returned tag is sanitized to be valid as a Kubernetes label value: +// - Maximum length of 63 characters +// - Must start with alphanumeric character +// - '+' characters replaced with '-'
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
pkg/resourcegenerator/resourceutils/helpers.go
(2 hunks)
🧰 Additional context used
🪛 GitHub Check: Build and run tests
pkg/resourcegenerator/resourceutils/helpers.go
[failure] 57-57:
undefined: MatchesRegex
🔇 Additional comments (3)
pkg/resourcegenerator/resourceutils/helpers.go (3)
6-6
: LGTM! Follows Kubernetes conventions
The LabelValueMaxLength
constant of 63 correctly adheres to Kubernetes label value length limitations.
Also applies to: 10-10
30-61
: Verify usage and test coverage
Let's ensure all callers handle the new edge cases (empty string -> "unknown") and that test coverage is adequate.
✅ Verification successful
The previous output showed that GetImageVersion is used in deployment, service, and job generators to set the version label. We need to see the test coverage to ensure edge cases are handled properly, especially for the "@" handling and empty string cases.
Test coverage is comprehensive and implementation is correct
The test coverage is thorough with test cases covering all edge cases including:
- Images with SHA digests (both with and without tags)
- Empty versions defaulting to "latest"
- Version strings with "+" being converted to "-"
- Long version strings being truncated
- Version strings with invalid starting characters
- Various real-world version formats
The implementation correctly handles all these cases and is being used consistently across deployment, service, and job generators to set the version label. No issues found.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Find all usages of GetImageVersion
echo "=== GetImageVersion usage ==="
rg "GetImageVersion\(" -A 2
# Check test coverage for edge cases
echo -e "\n=== Test coverage ==="
rg "TestVersion" -A 10 ".*_test\.go$"
Length of output: 1873
Script:
#!/bin/bash
# Let's check the test file content specifically
echo "=== Test content ==="
cat pkg/resourcegenerator/resourceutils/helpers_test.go
# Let's also check the actual implementation to compare with tests
echo -e "\n=== Implementation ==="
cat pkg/resourcegenerator/resourceutils/helpers.go
Length of output: 3786
🧰 Tools
🪛 GitHub Check: Build and run tests
[failure] 57-57:
undefined: MatchesRegex
43-45
:
Fix handling of image strings with multiple colons
The current implementation can break with registry URLs containing ports (e.g., "registry:5000/image:tag").
Apply this diff:
- // Split image string into parts
- parts := strings.Split(imageVersionString, ":")
-
- versionPart := parts[1]
+ // Extract version using last colon
+ lastColon := strings.LastIndex(imageVersionString, ":")
+ if lastColon == -1 || lastColon == len(imageVersionString)-1 {
+ return "latest"
+ }
+ versionPart := imageVersionString[lastColon+1:]
Likely invalid or redundant comment.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The more special cases I think of the more I think that the return type should be (string, error)
. What do you think @martinhny @omaen @BardOve?
if !strings.Contains(imageVersionString, ":") { | ||
return "latest" | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't necessarily have the digest and for a human readable version I prefer latest
.
if strings.Contains(versionPart, "@") { | ||
versionPart = strings.Split(versionPart, "@")[0] | ||
// Replace "+" with "-" in version text if version includes one | ||
versionPart = strings.ReplaceAll(versionPart, "+", "-") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should match any special character really 🤔
Redid logic to make it more robust
Summary by CodeRabbit
New Features
Bug Fixes
Tests