From dca200c2e91121426fec7e21d6ee091419eb9200 Mon Sep 17 00:00:00 2001 From: Alexander Neumann Date: Tue, 25 Aug 2015 22:07:52 +0200 Subject: [PATCH] build.go: Make `-ldflags` compatible to Go 1.5 This change uses the old syntax (-ldflags "-X foo bar") for Go <= 1.4 and the new syntax for (-ldflags "-X foo=bar") for Go 1.5 (without a warning). --- build.go | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/build.go b/build.go index 05c930ae3..d14566fc2 100644 --- a/build.go +++ b/build.go @@ -229,6 +229,27 @@ func gitVersion() string { return version } +// Constants represents a set constants set in the final binary to the given +// value. +type Constants map[string]string + +// LDFlags returns the string that can be passed to go build's `-ldflags`. +func (cs Constants) LDFlags() string { + l := make([]string, 0, len(cs)) + + if strings.HasPrefix(runtime.Version(), "go1.5") { + for k, v := range cs { + l = append(l, fmt.Sprintf(`-X "%s=%s"`, k, v)) + } + } else { + for k, v := range cs { + l = append(l, fmt.Sprintf(`-X %q %q`, k, v)) + } + } + + return strings.Join(l, " ") +} + func main() { buildTags := []string{} @@ -307,10 +328,13 @@ func main() { } version := getVersion() compileTime := time.Now().Format(timeFormat) - ldflags := fmt.Sprintf("-s -X main.compiledAt %q", compileTime) + constants := Constants{`main.compiledAt`: compileTime} if version != "" { - ldflags = fmt.Sprintf("%s -X main.version %q", ldflags, version) + constants["main.version"] = version } + ldflags := "-s " + constants.LDFlags() + fmt.Printf("ldflags: %s\n", ldflags) + args := []string{ "-tags", strings.Join(buildTags, " "), "-ldflags", ldflags,