Skip to content
This repository has been archived by the owner on Mar 23, 2021. It is now read-only.

Commit

Permalink
main: fix precedence logic between GOFLAGS and -tags (#76)
Browse files Browse the repository at this point in the history
Thanks to Roger Peppe for picking this up in the last review.
  • Loading branch information
myitcv authored May 13, 2019
1 parent f43ef5b commit 082f55c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 19 deletions.
38 changes: 19 additions & 19 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ var (
fNoNet = flag.Bool("nonet", false, "prevent network access")
fDebug = flag.Bool("debug", false, "print debug information")
fTags = flag.String("tags", "", "build tags to apply; go help build for more information")

// envGOFLAGS is the value of GOENV passed to gobin with -tags= values stripped out
envGOFLAGS string
)

func main() {
Expand All @@ -66,6 +69,21 @@ func main1() int {
}

func mainerr() error {
// Set the default value of the -tags value to be the last -tags= value in
// GOFLAGS. Also, strip any -tags= values from GOFLAGS to ensure a "clean"
// value that can then be used for any cmd/go calls.
if gf := os.Getenv("GOFLAGS"); gf != "" {
var goenvVals []string
for _, v := range strings.Fields(gf) {
if strings.HasPrefix(v, "-tags=") {
*fTags = strings.TrimPrefix(v, "-tags=")
continue
}
goenvVals = append(goenvVals, v)
}
envGOFLAGS = strings.Join(goenvVals, " ")
}

flag.Usage = func() {
mainUsage(os.Stderr)
}
Expand All @@ -92,24 +110,6 @@ func mainerr() error {
}

*fTags = strings.TrimSpace(*fTags)
if gf := os.Getenv("GOFLAGS"); gf != "" {
// take the last value of -tags, if there is one
fvs := strings.Fields(gf)
for i := len(fvs) - 1; i >= 0; i-- {
v := fvs[i]
if !strings.HasPrefix(v, "-tags=") {
continue
}
v = strings.TrimPrefix(v, "-tags=")
if v != "" {
if *fTags != "" {
v += " " + *fTags
}
*fTags = v
}
break
}
}

if *fMod != "" {
switch *fMod {
Expand Down Expand Up @@ -628,7 +628,7 @@ func buildEnv(proxy string) []string {
if proxy != "" {
env = append(env, proxy)
}
goflags := os.Getenv("GOFLAGS")
goflags := envGOFLAGS
if *fMainMod && *fMod != "" {
goflags += " -mod=" + *fMod
}
Expand Down
34 changes: 34 additions & 0 deletions testdata/goflags-tags-precedence.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Test that we have correct precedence handling of GOFLAGS and -tags
gobin -m -run .
stdout '^Not blah$'
gobin -m -run -tags blah .
stdout '^Blah$'
env GOFLAGS=-tags=blah
gobin -m -run .
stdout '^Blah$'
gobin -m -run -tags '' .
stdout '^Not blah$'

-- go.mod --
module mod.com

-- not_blah.go --
// +build !blah

package main

import "fmt"

func main() {
fmt.Println("Not blah")
}
-- blah.go --
// +build blah

package main

import "fmt"

func main() {
fmt.Println("Blah")
}

0 comments on commit 082f55c

Please sign in to comment.