Skip to content

Commit b675b06

Browse files
authored
fix(go): merge nested flags into string for ldflags for Go binaries (#8368)
1 parent f9c5043 commit b675b06

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

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

+10-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"sort"
1010
"strings"
1111

12+
"github.com/mattn/go-shellwords"
1213
"github.com/samber/lo"
1314
"github.com/spf13/pflag"
1415
"golang.org/x/mod/semver"
@@ -145,7 +146,13 @@ func (p *Parser) ldFlags(settings []debug.BuildSetting) []string {
145146
continue
146147
}
147148

148-
return strings.Fields(setting.Value)
149+
flags, err := shellwords.Parse(setting.Value)
150+
if err != nil {
151+
p.logger.Error("Could not parse -ldflags found in build info", log.Err(err))
152+
return nil
153+
}
154+
155+
return flags
149156
}
150157
return nil
151158
}
@@ -163,6 +170,8 @@ func (p *Parser) ParseLDFlags(name string, flags []string) string {
163170
// to handle that edge case.
164171
var x map[string]string
165172
fset.StringToStringVarP(&x, "", "X", nil, "")
173+
// Init `help` flag to avoid error in flags with `h` (e.g. `-lpthread`)
174+
fset.BoolP("help", "h", false, "just to disable the built-in help flag")
166175
if err := fset.Parse(flags); err != nil {
167176
p.logger.Error("Could not parse -ldflags found in build info", log.Err(err))
168177
return ""

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

+15
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,21 @@ func TestParser_ParseLDFlags(t *testing.T) {
390390
},
391391
want: "",
392392
},
393+
{
394+
name: "flag with nested flags",
395+
args: args{
396+
name: "github.com/k3s-io/k3s",
397+
flags: []string{
398+
"-X",
399+
"github.com/k3s-io/k3s/version.Version=v1.28.6+k3s2",
400+
"-w",
401+
"-s",
402+
"-extldflags",
403+
"-static -lm -ldl -lz -lpthread",
404+
},
405+
},
406+
want: "v1.28.6+k3s2",
407+
},
393408
{
394409
name: "with no flags",
395410
args: args{

0 commit comments

Comments
 (0)