github.com/teknogeek/dnscontrol@v0.2.8/build/build.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"os/exec"
     9  	"strings"
    10  	"time"
    11  )
    12  
    13  var sha = flag.String("sha", "", "SHA of current commit")
    14  
    15  var goos = flag.String("os", "", "OS to build (linux, windows, or darwin) Defaults to all.")
    16  
    17  func main() {
    18  	flag.Parse()
    19  	flags := fmt.Sprintf(`-s -w -X main.SHA="%s" -X main.BuildTime=%d`, getVersion(), time.Now().Unix())
    20  	pkg := "github.com/StackExchange/dnscontrol"
    21  
    22  	build := func(out, goos string) {
    23  		log.Printf("Building %s", out)
    24  		cmd := exec.Command("go", "build", "-o", out, "-ldflags", flags, pkg)
    25  		os.Setenv("GOOS", goos)
    26  		cmd.Stderr = os.Stderr
    27  		cmd.Stdout = os.Stdout
    28  		err := cmd.Run()
    29  		if err != nil {
    30  			log.Fatal(err)
    31  		}
    32  	}
    33  
    34  	for _, env := range []struct {
    35  		binary, goos string
    36  	}{
    37  		{"dnscontrol-Linux", "linux"},
    38  		{"dnscontrol.exe", "windows"},
    39  		{"dnscontrol-Darwin", "darwin"},
    40  	} {
    41  		if *goos == "" || *goos == env.goos {
    42  			build(env.binary, env.goos)
    43  		}
    44  	}
    45  }
    46  
    47  func getVersion() string {
    48  	if *sha != "" {
    49  		return *sha
    50  	}
    51  	// check teamcity build version
    52  	if v := os.Getenv("BUILD_VCS_NUMBER"); v != "" {
    53  		return v
    54  	}
    55  	// check git
    56  	cmd := exec.Command("git", "rev-parse", "HEAD")
    57  	v, err := cmd.CombinedOutput()
    58  	if err != nil {
    59  		return ""
    60  	}
    61  	ver := strings.TrimSpace(string(v))
    62  	// see if dirty
    63  	cmd = exec.Command("git", "diff-index", "--quiet", "HEAD", "--")
    64  	err = cmd.Run()
    65  	// exit status 1 indicates dirty tree
    66  	if err != nil {
    67  		if err.Error() == "exit status 1" {
    68  			ver += "[dirty]"
    69  		} else {
    70  			log.Printf("!%s!", err.Error())
    71  		}
    72  	}
    73  	return ver
    74  }