Skip to content

Commit f281fe0

Browse files
author
Antonio Salinas
authored
fix: Added flags to define buildtime for version command (#344)
* Added flags to define buildtime for version command * Cleaned ldflag creation * Added SOURCE DATE EPOCH support for reproducibility * Removed unneccessary closure and consolidated formatting. * Minor code formatting changes for builddate * Simplifying dattime env var logic
1 parent 2586e97 commit f281fe0

1 file changed

Lines changed: 31 additions & 2 deletions

File tree

magefiles/magebuild/magebuild.go

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ import (
1111
"os/exec"
1212
"path"
1313
"regexp"
14+
"strconv"
1415
"strings"
16+
"time"
1517

1618
"github.com/magefile/mage/mg"
1719
"github.com/magefile/mage/sh"
@@ -34,13 +36,35 @@ var (
3436
// and folders with test-only code from code coverage calculations.
3537
var gocovExcludesRegexp = regexp.MustCompile(`(/magefiles/|_test(/|$))`)
3638

39+
// getBuildLdflags returns the ldflags string with build information.
40+
func getBuildLdflags() (string, error) {
41+
buildTime := time.Now().UTC()
42+
43+
// Check for SOURCE_DATE_EPOCH environment variable for reproducible builds.
44+
if epoch := os.Getenv("SOURCE_DATE_EPOCH"); epoch != "" {
45+
epochTime, err := strconv.ParseInt(epoch, 10, 64)
46+
if err != nil {
47+
return "", fmt.Errorf("%#q is an invalid value of the 'SOURCE_DATE_EPOCH' env variable", epoch)
48+
}
49+
50+
buildTime = time.Unix(epochTime, 0).UTC()
51+
}
52+
53+
return fmt.Sprintf(`-X 'go.szostok.io/version.buildDate=%s'`, buildTime.Format(time.RFC3339)), nil
54+
}
55+
3756
// Build all the go code.
3857
func Build() error {
3958
mg.SerialDeps(checkForBuildErrors, mageutil.CreateBinDir, magesrc.Generate)
4059

4160
mageutil.MagePrintln(mageutil.MsgStart, "Building...")
4261

43-
err := sh.Run(mg.GoCmd(), "build", "-o", mageutil.BinDir(), "./...")
62+
ldflags, err := getBuildLdflags()
63+
if err != nil {
64+
return mageutil.PrintAndReturnError("Failed to get build ldflags.", ErrBuild, err)
65+
}
66+
67+
err = sh.Run(mg.GoCmd(), "build", "-ldflags", ldflags, "-o", mageutil.BinDir(), "./...")
4468
if err != nil {
4569
return mageutil.PrintAndReturnError("Build failed.", ErrBuild, err)
4670
}
@@ -56,7 +80,12 @@ func Install() error {
5680

5781
mageutil.MagePrintln(mageutil.MsgStart, "Installing...")
5882

59-
err := sh.Run(mg.GoCmd(), "install", "./cmd/azldev")
83+
ldflags, err := getBuildLdflags()
84+
if err != nil {
85+
return mageutil.PrintAndReturnError("Failed to get build ldflags.", ErrInstall, err)
86+
}
87+
88+
err = sh.Run(mg.GoCmd(), "install", "-ldflags", ldflags, "./cmd/azldev")
6089
if err != nil {
6190
return mageutil.PrintAndReturnError("Install failed.", ErrInstall, err)
6291
}

0 commit comments

Comments
 (0)