Skip to content

Commit e58dcfc

Browse files
feat(go): fix parsing main module version for go >= 1.24 (#8433)
Signed-off-by: maksim.nabokikh <[email protected]> Co-authored-by: DmitriyLewen <[email protected]>
1 parent 9c609c4 commit e58dcfc

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

pkg/dependency/parser/golang/binary/parse.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package binary
22

33
import (
4-
"cmp"
54
"debug/buildinfo"
65
"fmt"
76
"runtime/debug"
@@ -104,7 +103,13 @@ func (p *Parser) Parse(r xio.ReadSeekerAt) ([]ftypes.Package, []ftypes.Dependenc
104103
// set via `go build -ldflags='-X main.version=<semver>'`, so we fallback to this as.
105104
// as a secondary source.
106105
// See https://github.com/aquasecurity/trivy/issues/1837#issuecomment-1832523477.
107-
version := cmp.Or(p.checkVersion(info.Main.Path, info.Main.Version), p.ParseLDFlags(info.Main.Path, ldflags))
106+
version := p.checkVersion(info.Main.Path, info.Main.Version)
107+
ldflagsVersion := p.ParseLDFlags(info.Main.Path, ldflags)
108+
109+
if version == "" || (strings.HasPrefix(version, "v0.0.0") && ldflagsVersion != "") {
110+
version = ldflagsVersion
111+
}
112+
108113
root := ftypes.Package{
109114
ID: dependency.ID(ftypes.GoBinary, info.Main.Path, version),
110115
Name: info.Main.Path,

pkg/dependency/parser/golang/binary/parse_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,36 @@ func TestParse(t *testing.T) {
168168
},
169169
},
170170
},
171+
/*
172+
Uncomment the test after migrating to autogenerated binaries for tests
173+
See for details: https://github.com/aquasecurity/trivy/pull/8433#discussion_r1967317284
174+
{
175+
name: "with -ldflags=\"-X main.version=v1.0.0\" go v1.24",
176+
inputFile: "testdata/main-version-via-ldflags-go-1-24.elf",
177+
wantPkgs: []ftypes.Package{
178+
{
179+
ID: "github.com/aquasecurity/[email protected]",
180+
Name: "github.com/aquasecurity/test",
181+
Version: "v1.0.0",
182+
Relationship: ftypes.RelationshipRoot,
183+
},
184+
{
185+
186+
Name: "stdlib",
187+
Version: "v1.24.0",
188+
Relationship: ftypes.RelationshipDirect,
189+
},
190+
},
191+
wantDeps: []ftypes.Dependency{
192+
{
193+
ID: "github.com/aquasecurity/[email protected]",
194+
DependsOn: []string{
195+
196+
},
197+
},
198+
},
199+
},
200+
*/
171201
{
172202
name: "goexperiment",
173203
inputFile: "testdata/goexperiment",

0 commit comments

Comments
 (0)