Only match ldflag version if it matches the main module or targets main.version (#3062)

Signed-off-by: Laurent Goderre <laurent.goderre@docker.com>
This commit is contained in:
Laurent Goderre
2024-07-25 13:56:55 -04:00
committed by GitHub
parent b3848f780f
commit 4882d2e8ce
2 changed files with 44 additions and 14 deletions
+4 -3
View File
@@ -208,7 +208,7 @@ func (c *goBinaryCataloger) findMainModuleVersion(metadata *pkg.GolangBinaryBuil
// version of the package.
ldflags, _ = metadata.BuildSettings.Get("-ldflags")
majorVersion, fullVersion = extractVersionFromLDFlags(ldflags)
majorVersion, fullVersion = extractVersionFromLDFlags(ldflags, metadata.MainModule)
if fullVersion != "" {
return fullVersion
}
@@ -258,13 +258,14 @@ func extractVersionFromContents(reader io.Reader) string {
return ""
}
func extractVersionFromLDFlags(ldflags string) (majorVersion string, fullVersion string) {
func extractVersionFromLDFlags(ldflags string, maimModule string) (majorVersion string, fullVersion string) {
if ldflags == "" {
return "", ""
}
for _, pattern := range knownBuildFlagPatterns {
groups := internal.MatchNamedCaptureGroups(pattern, ldflags)
newPattern := regexp.MustCompile(fmt.Sprintf(`(main|%s\/[^\s]*)%s`, strings.ReplaceAll(maimModule, "/", "\\/"), pattern.String()))
groups := internal.MatchNamedCaptureGroups(newPattern, ldflags)
v, ok := groups["version"]
if !ok {