Skip to content

Commit

Permalink
Properly lookup for ldflags inside GOFLAGS.
Browse files Browse the repository at this point in the history
  • Loading branch information
Cedric BAIL committed Jan 16, 2023
1 parent fcc15f4 commit 5af625a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 13 deletions.
43 changes: 30 additions & 13 deletions cmd/fyne/internal/commands/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,22 +229,27 @@ func (b *Builder) build() error {
env = append(env, "CGO_ENABLED=1") // in case someone is trying to cross-compile...

if b.release {
appendEnv(&env, "GOFLAGS", "-s -w")
b.ldFlags += " -s -w"
args = append(args, "-trimpath")
}

if goos == "windows" {
appendEnv(&env, "GOFLAGS", "-H=windowsgui")
b.ldFlags += " -H=windowsgui"
}
}

if b.ldFlags != "" {
appendEnv(&env, "GOFLAGS", b.ldFlags)
goFlags := os.Getenv("GOFLAGS")
goLdFlags, goFlags := extractLdFlags(goFlags)
if goLdFlags != "" {
b.ldFlags += " " + goLdFlags
}
if goFlags != "" {
os.Setenv("GOFLAGS", goFlags)
}

ldFlags := getEnv(env, "GOFLAGS")
if len(ldFlags) > 0 {
args = append(args, "-ldflags", ldFlags)
if len(b.ldFlags) > 0 {
b.ldFlags = strings.TrimSpace(b.ldFlags)
args = append(args, "-ldflags", b.ldFlags)
}

if b.target != "" {
Expand Down Expand Up @@ -372,13 +377,25 @@ func appendEnv(env *[]string, varName, value string) {
*env = append(*env, varName+"="+value)
}

func getEnv(env []string, varName string) string {
for _, e := range env {
keyValue := strings.SplitN(e, "=", 2)
func extractLdFlags(goFlags string) (string, string) {
if goFlags == "" {
return "", ""
}

flags := strings.Fields(goFlags)
ldflags := ""
newGoFlags := ""

if keyValue[0] == "GOFLAGS" {
return keyValue[1]
for _, flag := range flags {
if strings.HasPrefix(flag, "-ldflags=") {
ldflags += strings.TrimPrefix(flag, "-ldflags=") + " "
} else {
newGoFlags += flag + " "
}
}
return ""

ldflags = strings.TrimSpace(ldflags)
newGoFlags = strings.TrimSpace(newGoFlags)

return ldflags, newGoFlags
}
21 changes: 21 additions & 0 deletions cmd/fyne/internal/commands/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,24 @@ func Test_AppendEnv(t *testing.T) {
assert.Equal(t, "foo2=baz2", env[3])
}
}

type extractTest struct {
value string
wantLdFlags string
wantGoFlags string
}

func Test_ExtractLdFlags(t *testing.T) {
goFlagsTests := []extractTest{
{"-ldflags=-w", "-w", ""},
{"-ldflags=-s", "-s", ""},
{"-ldflags=-w -ldflags=-s", "-w -s", ""},
{"-mod=vendor", "", "-mod=vendor"},
}

for _, test := range goFlagsTests {
ldFlags, goFlags := extractLdFlags(test.value)
assert.Equal(t, test.wantLdFlags, ldFlags)
assert.Equal(t, test.wantGoFlags, goFlags)
}
}

0 comments on commit 5af625a

Please sign in to comment.