github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/build/ci.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // +build none
    18  
    19  /*
    20  The ci command is called from Continuous Integration scripts.
    21  
    22  Usage: go run build/ci.go <command> <command flags/arguments>
    23  
    24  Available commands are:
    25  
    26     install    [ -arch architecture ] [ -cc compiler ] [ packages... ]                          -- builds packages and executables
    27     test       [ -coverage ] [ packages... ]                                                    -- runs the tests
    28     lint                                                                                        -- runs certain pre-selected linters
    29     archive    [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -upload dest ] -- archives build artifacts
    30     importkeys                                                                                  -- imports signing keys from env
    31     debsrc     [ -signer key-id ] [ -upload dest ]                                              -- creates a debian source package
    32     nsis                                                                                        -- creates a Windows NSIS installer
    33     aar        [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ]                      -- creates an Android archive
    34     xcode      [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ]                      -- creates an iOS XCode framework
    35     xgo        [ -alltools ] [ options ]                                                        -- cross builds according to options
    36     purge      [ -store blobstore ] [ -days threshold ]                                         -- purges old archives from the blobstore
    37  
    38  For all commands, -n prevents execution of external programs (dry run mode).
    39  
    40  */
    41  package main
    42  
    43  import (
    44  	"bufio"
    45  	"bytes"
    46  	"encoding/base64"
    47  	"flag"
    48  	"fmt"
    49  	"go/parser"
    50  	"go/token"
    51  	"io/ioutil"
    52  	"log"
    53  	"os"
    54  	"os/exec"
    55  	"path/filepath"
    56  	"regexp"
    57  	"runtime"
    58  	"strings"
    59  	"time"
    60  
    61  	"github.com/ethereum/go-ethereum/internal/build"
    62  	"github.com/ethereum/go-ethereum/params"
    63  	sv "github.com/ethereum/go-ethereum/swarm/version"
    64  )
    65  
    66  var (
    67  	// Files that end up in the geth*.zip archive.
    68  	gethArchiveFiles = []string{
    69  		"COPYING",
    70  		executablePath("geth"),
    71  	}
    72  
    73  	// Files that end up in the geth-alltools*.zip archive.
    74  	allToolsArchiveFiles = []string{
    75  		"COPYING",
    76  		executablePath("abigen"),
    77  		executablePath("bootnode"),
    78  		executablePath("evm"),
    79  		executablePath("geth"),
    80  		executablePath("puppeth"),
    81  		executablePath("rlpdump"),
    82  		executablePath("wnode"),
    83  	}
    84  
    85  	// Files that end up in the swarm*.zip archive.
    86  	swarmArchiveFiles = []string{
    87  		"COPYING",
    88  		executablePath("swarm"),
    89  	}
    90  
    91  	// A debian package is created for all executables listed here.
    92  	debExecutables = []debExecutable{
    93  		{
    94  			BinaryName:  "abigen",
    95  			Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
    96  		},
    97  		{
    98  			BinaryName:  "bootnode",
    99  			Description: "Ethereum bootnode.",
   100  		},
   101  		{
   102  			BinaryName:  "evm",
   103  			Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
   104  		},
   105  		{
   106  			BinaryName:  "geth",
   107  			Description: "Ethereum CLI client.",
   108  		},
   109  		{
   110  			BinaryName:  "puppeth",
   111  			Description: "Ethereum private network manager.",
   112  		},
   113  		{
   114  			BinaryName:  "rlpdump",
   115  			Description: "Developer utility tool that prints RLP structures.",
   116  		},
   117  		{
   118  			BinaryName:  "wnode",
   119  			Description: "Ethereum Whisper diagnostic tool",
   120  		},
   121  	}
   122  
   123  	// A debian package is created for all executables listed here.
   124  	debSwarmExecutables = []debExecutable{
   125  		{
   126  			BinaryName:  "swarm",
   127  			PackageName: "ethereum-swarm",
   128  			Description: "Ethereum Swarm daemon and tools",
   129  		},
   130  	}
   131  
   132  	debEthereum = debPackage{
   133  		Name:        "ethereum",
   134  		Version:     params.Version,
   135  		Executables: debExecutables,
   136  	}
   137  
   138  	debSwarm = debPackage{
   139  		Name:        "ethereum-swarm",
   140  		Version:     sv.Version,
   141  		Executables: debSwarmExecutables,
   142  	}
   143  
   144  	// Debian meta packages to build and push to Ubuntu PPA
   145  	debPackages = []debPackage{
   146  		debSwarm,
   147  		debEthereum,
   148  	}
   149  
   150  	// Packages to be cross-compiled by the xgo command
   151  	allCrossCompiledArchiveFiles = append(allToolsArchiveFiles, swarmArchiveFiles...)
   152  
   153  	// Distros for which packages are created.
   154  	// Note: vivid is unsupported because there is no golang-1.6 package for it.
   155  	// Note: wily is unsupported because it was officially deprecated on lanchpad.
   156  	// Note: yakkety is unsupported because it was officially deprecated on lanchpad.
   157  	// Note: zesty is unsupported because it was officially deprecated on lanchpad.
   158  	// Note: artful is unsupported because it was officially deprecated on lanchpad.
   159  	debDistros = []string{"trusty", "xenial", "bionic", "cosmic"}
   160  )
   161  
   162  var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
   163  
   164  func executablePath(name string) string {
   165  	if runtime.GOOS == "windows" {
   166  		name += ".exe"
   167  	}
   168  	return filepath.Join(GOBIN, name)
   169  }
   170  
   171  func main() {
   172  	log.SetFlags(log.Lshortfile)
   173  
   174  	if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
   175  		log.Fatal("this script must be run from the root of the repository")
   176  	}
   177  	if len(os.Args) < 2 {
   178  		log.Fatal("need subcommand as first argument")
   179  	}
   180  	switch os.Args[1] {
   181  	case "install":
   182  		doInstall(os.Args[2:])
   183  	case "test":
   184  		doTest(os.Args[2:])
   185  	case "lint":
   186  		doLint(os.Args[2:])
   187  	case "archive":
   188  		doArchive(os.Args[2:])
   189  	case "debsrc":
   190  		doDebianSource(os.Args[2:])
   191  	case "nsis":
   192  		doWindowsInstaller(os.Args[2:])
   193  	case "aar":
   194  		doAndroidArchive(os.Args[2:])
   195  	case "xcode":
   196  		doXCodeFramework(os.Args[2:])
   197  	case "xgo":
   198  		doXgo(os.Args[2:])
   199  	case "purge":
   200  		doPurge(os.Args[2:])
   201  	default:
   202  		log.Fatal("unknown command ", os.Args[1])
   203  	}
   204  }
   205  
   206  // Compiling
   207  
   208  func doInstall(cmdline []string) {
   209  	var (
   210  		arch = flag.String("arch", "", "Architecture to cross build for")
   211  		cc   = flag.String("cc", "", "C compiler to cross build with")
   212  	)
   213  	flag.CommandLine.Parse(cmdline)
   214  	env := build.Env()
   215  
   216  	// Check Go version. People regularly open issues about compilation
   217  	// failure with outdated Go. This should save them the trouble.
   218  	if !strings.Contains(runtime.Version(), "devel") {
   219  		// Figure out the minor version number since we can't textually compare (1.10 < 1.9)
   220  		var minor int
   221  		fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
   222  
   223  		if minor < 9 {
   224  			log.Println("You have Go version", runtime.Version())
   225  			log.Println("go-ethereum requires at least Go version 1.9 and cannot")
   226  			log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
   227  			os.Exit(1)
   228  		}
   229  	}
   230  	// Compile packages given as arguments, or everything if there are no arguments.
   231  	packages := []string{"./..."}
   232  	if flag.NArg() > 0 {
   233  		packages = flag.Args()
   234  	}
   235  	packages = build.ExpandPackagesNoVendor(packages)
   236  
   237  	if *arch == "" || *arch == runtime.GOARCH {
   238  		goinstall := goTool("install", buildFlags(env)...)
   239  		goinstall.Args = append(goinstall.Args, "-v")
   240  		goinstall.Args = append(goinstall.Args, packages...)
   241  		build.MustRun(goinstall)
   242  		return
   243  	}
   244  	// If we are cross compiling to ARMv5 ARMv6 or ARMv7, clean any previous builds
   245  	if *arch == "arm" {
   246  		os.RemoveAll(filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_arm"))
   247  		for _, path := range filepath.SplitList(build.GOPATH()) {
   248  			os.RemoveAll(filepath.Join(path, "pkg", runtime.GOOS+"_arm"))
   249  		}
   250  	}
   251  	// Seems we are cross compiling, work around forbidden GOBIN
   252  	goinstall := goToolArch(*arch, *cc, "install", buildFlags(env)...)
   253  	goinstall.Args = append(goinstall.Args, "-v")
   254  	goinstall.Args = append(goinstall.Args, []string{"-buildmode", "archive"}...)
   255  	goinstall.Args = append(goinstall.Args, packages...)
   256  	build.MustRun(goinstall)
   257  
   258  	if cmds, err := ioutil.ReadDir("cmd"); err == nil {
   259  		for _, cmd := range cmds {
   260  			pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
   261  			if err != nil {
   262  				log.Fatal(err)
   263  			}
   264  			for name := range pkgs {
   265  				if name == "main" {
   266  					gobuild := goToolArch(*arch, *cc, "build", buildFlags(env)...)
   267  					gobuild.Args = append(gobuild.Args, "-v")
   268  					gobuild.Args = append(gobuild.Args, []string{"-o", executablePath(cmd.Name())}...)
   269  					gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
   270  					build.MustRun(gobuild)
   271  					break
   272  				}
   273  			}
   274  		}
   275  	}
   276  }
   277  
   278  func buildFlags(env build.Environment) (flags []string) {
   279  	var ld []string
   280  	if env.Commit != "" {
   281  		ld = append(ld, "-X", "main.gitCommit="+env.Commit)
   282  	}
   283  	if runtime.GOOS == "darwin" {
   284  		ld = append(ld, "-s")
   285  	}
   286  
   287  	if len(ld) > 0 {
   288  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   289  	}
   290  	return flags
   291  }
   292  
   293  func goTool(subcmd string, args ...string) *exec.Cmd {
   294  	return goToolArch(runtime.GOARCH, os.Getenv("CC"), subcmd, args...)
   295  }
   296  
   297  func goToolArch(arch string, cc string, subcmd string, args ...string) *exec.Cmd {
   298  	cmd := build.GoTool(subcmd, args...)
   299  	cmd.Env = []string{"GOPATH=" + build.GOPATH()}
   300  	if arch == "" || arch == runtime.GOARCH {
   301  		cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
   302  	} else {
   303  		cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
   304  		cmd.Env = append(cmd.Env, "GOARCH="+arch)
   305  	}
   306  	if cc != "" {
   307  		cmd.Env = append(cmd.Env, "CC="+cc)
   308  	}
   309  	for _, e := range os.Environ() {
   310  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
   311  			continue
   312  		}
   313  		cmd.Env = append(cmd.Env, e)
   314  	}
   315  	return cmd
   316  }
   317  
   318  // Running The Tests
   319  //
   320  // "tests" also includes static analysis tools such as vet.
   321  
   322  func doTest(cmdline []string) {
   323  	coverage := flag.Bool("coverage", false, "Whether to record code coverage")
   324  	flag.CommandLine.Parse(cmdline)
   325  	env := build.Env()
   326  
   327  	packages := []string{"./..."}
   328  	if len(flag.CommandLine.Args()) > 0 {
   329  		packages = flag.CommandLine.Args()
   330  	}
   331  	packages = build.ExpandPackagesNoVendor(packages)
   332  
   333  	// Run the actual tests.
   334  	// Test a single package at a time. CI builders are slow
   335  	// and some tests run into timeouts under load.
   336  	gotest := goTool("test", buildFlags(env)...)
   337  	gotest.Args = append(gotest.Args, "-p", "1", "-timeout", "5m")
   338  	if *coverage {
   339  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   340  	}
   341  
   342  	gotest.Args = append(gotest.Args, packages...)
   343  	build.MustRun(gotest)
   344  }
   345  
   346  // runs gometalinter on requested packages
   347  func doLint(cmdline []string) {
   348  	flag.CommandLine.Parse(cmdline)
   349  
   350  	packages := []string{"./..."}
   351  	if len(flag.CommandLine.Args()) > 0 {
   352  		packages = flag.CommandLine.Args()
   353  	}
   354  	// Get metalinter and install all supported linters
   355  	build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
   356  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
   357  
   358  	// Run fast linters batched together
   359  	configs := []string{
   360  		"--vendor",
   361  		"--tests",
   362  		"--deadline=2m",
   363  		"--disable-all",
   364  		"--enable=goimports",
   365  		"--enable=varcheck",
   366  		"--enable=vet",
   367  		"--enable=gofmt",
   368  		"--enable=misspell",
   369  		"--enable=goconst",
   370  		"--min-occurrences=6", // for goconst
   371  	}
   372  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   373  
   374  	// Run slow linters one by one
   375  	for _, linter := range []string{"unconvert", "gosimple"} {
   376  		configs = []string{"--vendor", "--tests", "--deadline=10m", "--disable-all", "--enable=" + linter}
   377  		build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   378  	}
   379  }
   380  
   381  // Release Packaging
   382  func doArchive(cmdline []string) {
   383  	var (
   384  		arch   = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
   385  		atype  = flag.String("type", "zip", "Type of archive to write (zip|tar)")
   386  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
   387  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   388  		ext    string
   389  	)
   390  	flag.CommandLine.Parse(cmdline)
   391  	switch *atype {
   392  	case "zip":
   393  		ext = ".zip"
   394  	case "tar":
   395  		ext = ".tar.gz"
   396  	default:
   397  		log.Fatal("unknown archive type: ", atype)
   398  	}
   399  
   400  	var (
   401  		env = build.Env()
   402  
   403  		basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
   404  		geth     = "geth-" + basegeth + ext
   405  		alltools = "geth-alltools-" + basegeth + ext
   406  
   407  		baseswarm = archiveBasename(*arch, sv.ArchiveVersion(env.Commit))
   408  		swarm     = "swarm-" + baseswarm + ext
   409  	)
   410  	maybeSkipArchive(env)
   411  	if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
   412  		log.Fatal(err)
   413  	}
   414  	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
   415  		log.Fatal(err)
   416  	}
   417  	if err := build.WriteArchive(swarm, swarmArchiveFiles); err != nil {
   418  		log.Fatal(err)
   419  	}
   420  	for _, archive := range []string{geth, alltools, swarm} {
   421  		if err := archiveUpload(archive, *upload, *signer); err != nil {
   422  			log.Fatal(err)
   423  		}
   424  	}
   425  }
   426  
   427  func archiveBasename(arch string, archiveVersion string) string {
   428  	platform := runtime.GOOS + "-" + arch
   429  	if arch == "arm" {
   430  		platform += os.Getenv("GOARM")
   431  	}
   432  	if arch == "android" {
   433  		platform = "android-all"
   434  	}
   435  	if arch == "ios" {
   436  		platform = "ios-all"
   437  	}
   438  	return platform + "-" + archiveVersion
   439  }
   440  
   441  func archiveUpload(archive string, blobstore string, signer string) error {
   442  	// If signing was requested, generate the signature files
   443  	if signer != "" {
   444  		pgpkey, err := base64.StdEncoding.DecodeString(os.Getenv(signer))
   445  		if err != nil {
   446  			return fmt.Errorf("invalid base64 %s", signer)
   447  		}
   448  		if err := build.PGPSignFile(archive, archive+".asc", string(pgpkey)); err != nil {
   449  			return err
   450  		}
   451  	}
   452  	// If uploading to Azure was requested, push the archive possibly with its signature
   453  	if blobstore != "" {
   454  		auth := build.AzureBlobstoreConfig{
   455  			Account:   strings.Split(blobstore, "/")[0],
   456  			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
   457  			Container: strings.SplitN(blobstore, "/", 2)[1],
   458  		}
   459  		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
   460  			return err
   461  		}
   462  		if signer != "" {
   463  			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
   464  				return err
   465  			}
   466  		}
   467  	}
   468  	return nil
   469  }
   470  
   471  // skips archiving for some build configurations.
   472  func maybeSkipArchive(env build.Environment) {
   473  	if env.IsPullRequest {
   474  		log.Printf("skipping because this is a PR build")
   475  		os.Exit(0)
   476  	}
   477  	if env.IsCronJob {
   478  		log.Printf("skipping because this is a cron job")
   479  		os.Exit(0)
   480  	}
   481  	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
   482  		log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
   483  		os.Exit(0)
   484  	}
   485  }
   486  
   487  // Debian Packaging
   488  func doDebianSource(cmdline []string) {
   489  	var (
   490  		signer  = flag.String("signer", "", `Signing key name, also used as package author`)
   491  		upload  = flag.String("upload", "", `Where to upload the source package (usually "ppa:ethereum/ethereum")`)
   492  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   493  		now     = time.Now()
   494  	)
   495  	flag.CommandLine.Parse(cmdline)
   496  	*workdir = makeWorkdir(*workdir)
   497  	env := build.Env()
   498  	maybeSkipArchive(env)
   499  
   500  	// Import the signing key.
   501  	if b64key := os.Getenv("PPA_SIGNING_KEY"); b64key != "" {
   502  		key, err := base64.StdEncoding.DecodeString(b64key)
   503  		if err != nil {
   504  			log.Fatal("invalid base64 PPA_SIGNING_KEY")
   505  		}
   506  		gpg := exec.Command("gpg", "--import")
   507  		gpg.Stdin = bytes.NewReader(key)
   508  		build.MustRun(gpg)
   509  	}
   510  
   511  	// Create Debian packages and upload them
   512  	for _, pkg := range debPackages {
   513  		for _, distro := range debDistros {
   514  			meta := newDebMetadata(distro, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
   515  			pkgdir := stageDebianSource(*workdir, meta)
   516  			debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc")
   517  			debuild.Dir = pkgdir
   518  			build.MustRun(debuild)
   519  
   520  			changes := fmt.Sprintf("%s_%s_source.changes", meta.Name(), meta.VersionString())
   521  			changes = filepath.Join(*workdir, changes)
   522  			if *signer != "" {
   523  				build.MustRunCommand("debsign", changes)
   524  			}
   525  			if *upload != "" {
   526  				build.MustRunCommand("dput", *upload, changes)
   527  			}
   528  		}
   529  	}
   530  }
   531  
   532  func makeWorkdir(wdflag string) string {
   533  	var err error
   534  	if wdflag != "" {
   535  		err = os.MkdirAll(wdflag, 0744)
   536  	} else {
   537  		wdflag, err = ioutil.TempDir("", "geth-build-")
   538  	}
   539  	if err != nil {
   540  		log.Fatal(err)
   541  	}
   542  	return wdflag
   543  }
   544  
   545  func isUnstableBuild(env build.Environment) bool {
   546  	if env.Tag != "" {
   547  		return false
   548  	}
   549  	return true
   550  }
   551  
   552  type debPackage struct {
   553  	Name        string          // the name of the Debian package to produce, e.g. "ethereum", or "ethereum-swarm"
   554  	Version     string          // the clean version of the debPackage, e.g. 1.8.12 or 0.3.0, without any metadata
   555  	Executables []debExecutable // executables to be included in the package
   556  }
   557  
   558  type debMetadata struct {
   559  	Env build.Environment
   560  
   561  	PackageName string
   562  
   563  	// go-ethereum version being built. Note that this
   564  	// is not the debian package version. The package version
   565  	// is constructed by VersionString.
   566  	Version string
   567  
   568  	Author       string // "name <email>", also selects signing key
   569  	Distro, Time string
   570  	Executables  []debExecutable
   571  }
   572  
   573  type debExecutable struct {
   574  	PackageName string
   575  	BinaryName  string
   576  	Description string
   577  }
   578  
   579  // Package returns the name of the package if present, or
   580  // fallbacks to BinaryName
   581  func (d debExecutable) Package() string {
   582  	if d.PackageName != "" {
   583  		return d.PackageName
   584  	}
   585  	return d.BinaryName
   586  }
   587  
   588  func newDebMetadata(distro, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
   589  	if author == "" {
   590  		// No signing key, use default author.
   591  		author = "Ethereum Builds <fjl@ethereum.org>"
   592  	}
   593  	return debMetadata{
   594  		PackageName: name,
   595  		Env:         env,
   596  		Author:      author,
   597  		Distro:      distro,
   598  		Version:     version,
   599  		Time:        t.Format(time.RFC1123Z),
   600  		Executables: exes,
   601  	}
   602  }
   603  
   604  // Name returns the name of the metapackage that depends
   605  // on all executable packages.
   606  func (meta debMetadata) Name() string {
   607  	if isUnstableBuild(meta.Env) {
   608  		return meta.PackageName + "-unstable"
   609  	}
   610  	return meta.PackageName
   611  }
   612  
   613  // VersionString returns the debian version of the packages.
   614  func (meta debMetadata) VersionString() string {
   615  	vsn := meta.Version
   616  	if meta.Env.Buildnum != "" {
   617  		vsn += "+build" + meta.Env.Buildnum
   618  	}
   619  	if meta.Distro != "" {
   620  		vsn += "+" + meta.Distro
   621  	}
   622  	return vsn
   623  }
   624  
   625  // ExeList returns the list of all executable packages.
   626  func (meta debMetadata) ExeList() string {
   627  	names := make([]string, len(meta.Executables))
   628  	for i, e := range meta.Executables {
   629  		names[i] = meta.ExeName(e)
   630  	}
   631  	return strings.Join(names, ", ")
   632  }
   633  
   634  // ExeName returns the package name of an executable package.
   635  func (meta debMetadata) ExeName(exe debExecutable) string {
   636  	if isUnstableBuild(meta.Env) {
   637  		return exe.Package() + "-unstable"
   638  	}
   639  	return exe.Package()
   640  }
   641  
   642  // ExeConflicts returns the content of the Conflicts field
   643  // for executable packages.
   644  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   645  	if isUnstableBuild(meta.Env) {
   646  		// Set up the conflicts list so that the *-unstable packages
   647  		// cannot be installed alongside the regular version.
   648  		//
   649  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   650  		// is very explicit about Conflicts: and says that Breaks: should
   651  		// be preferred and the conflicting files should be handled via
   652  		// alternates. We might do this eventually but using a conflict is
   653  		// easier now.
   654  		return "ethereum, " + exe.Package()
   655  	}
   656  	return ""
   657  }
   658  
   659  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   660  	pkg := meta.Name() + "-" + meta.VersionString()
   661  	pkgdir = filepath.Join(tmpdir, pkg)
   662  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   663  		log.Fatal(err)
   664  	}
   665  
   666  	// Copy the source code.
   667  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   668  
   669  	// Put the debian build files in place.
   670  	debian := filepath.Join(pkgdir, "debian")
   671  	build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   672  	build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   673  	build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
   674  	build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   675  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   676  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   677  	for _, exe := range meta.Executables {
   678  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   679  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   680  		build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
   681  		build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
   682  	}
   683  
   684  	return pkgdir
   685  }
   686  
   687  // Windows installer
   688  func doWindowsInstaller(cmdline []string) {
   689  	// Parse the flags and make skip installer generation on PRs
   690  	var (
   691  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   692  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   693  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   694  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   695  	)
   696  	flag.CommandLine.Parse(cmdline)
   697  	*workdir = makeWorkdir(*workdir)
   698  	env := build.Env()
   699  	maybeSkipArchive(env)
   700  
   701  	// Aggregate binaries that are included in the installer
   702  	var (
   703  		devTools []string
   704  		allTools []string
   705  		gethTool string
   706  	)
   707  	for _, file := range allToolsArchiveFiles {
   708  		if file == "COPYING" { // license, copied later
   709  			continue
   710  		}
   711  		allTools = append(allTools, filepath.Base(file))
   712  		if filepath.Base(file) == "geth.exe" {
   713  			gethTool = file
   714  		} else {
   715  			devTools = append(devTools, file)
   716  		}
   717  	}
   718  
   719  	// Render NSIS scripts: Installer NSIS contains two installer sections,
   720  	// first section contains the geth binary, second section holds the dev tools.
   721  	templateData := map[string]interface{}{
   722  		"License":  "COPYING",
   723  		"Geth":     gethTool,
   724  		"DevTools": devTools,
   725  	}
   726  	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
   727  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
   728  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
   729  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
   730  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
   731  	build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
   732  	build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
   733  
   734  	// Build the installer. This assumes that all the needed files have been previously
   735  	// built (don't mix building and packaging to keep cross compilation complexity to a
   736  	// minimum).
   737  	version := strings.Split(params.Version, ".")
   738  	if env.Commit != "" {
   739  		version[2] += "-" + env.Commit[:8]
   740  	}
   741  	installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
   742  	build.MustRunCommand("makensis.exe",
   743  		"/DOUTPUTFILE="+installer,
   744  		"/DMAJORVERSION="+version[0],
   745  		"/DMINORVERSION="+version[1],
   746  		"/DBUILDVERSION="+version[2],
   747  		"/DARCH="+*arch,
   748  		filepath.Join(*workdir, "geth.nsi"),
   749  	)
   750  
   751  	// Sign and publish installer.
   752  	if err := archiveUpload(installer, *upload, *signer); err != nil {
   753  		log.Fatal(err)
   754  	}
   755  }
   756  
   757  // Android archives
   758  
   759  func doAndroidArchive(cmdline []string) {
   760  	var (
   761  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   762  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
   763  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
   764  		upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
   765  	)
   766  	flag.CommandLine.Parse(cmdline)
   767  	env := build.Env()
   768  
   769  	// Sanity check that the SDK and NDK are installed and set
   770  	if os.Getenv("ANDROID_HOME") == "" {
   771  		log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
   772  	}
   773  	if os.Getenv("ANDROID_NDK") == "" {
   774  		log.Fatal("Please ensure ANDROID_NDK points to your Android NDK")
   775  	}
   776  	// Build the Android archive and Maven resources
   777  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   778  	build.MustRun(gomobileTool("init", "--ndk", os.Getenv("ANDROID_NDK")))
   779  	build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
   780  
   781  	if *local {
   782  		// If we're building locally, copy bundle to build dir and skip Maven
   783  		os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
   784  		return
   785  	}
   786  	meta := newMavenMetadata(env)
   787  	build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
   788  
   789  	// Skip Maven deploy and Azure upload for PR builds
   790  	maybeSkipArchive(env)
   791  
   792  	// Sign and upload the archive to Azure
   793  	archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
   794  	os.Rename("geth.aar", archive)
   795  
   796  	if err := archiveUpload(archive, *upload, *signer); err != nil {
   797  		log.Fatal(err)
   798  	}
   799  	// Sign and upload all the artifacts to Maven Central
   800  	os.Rename(archive, meta.Package+".aar")
   801  	if *signer != "" && *deploy != "" {
   802  		// Import the signing key into the local GPG instance
   803  		b64key := os.Getenv(*signer)
   804  		key, err := base64.StdEncoding.DecodeString(b64key)
   805  		if err != nil {
   806  			log.Fatalf("invalid base64 %s", *signer)
   807  		}
   808  		gpg := exec.Command("gpg", "--import")
   809  		gpg.Stdin = bytes.NewReader(key)
   810  		build.MustRun(gpg)
   811  
   812  		keyID, err := build.PGPKeyID(string(key))
   813  		if err != nil {
   814  			log.Fatal(err)
   815  		}
   816  		// Upload the artifacts to Sonatype and/or Maven Central
   817  		repo := *deploy + "/service/local/staging/deploy/maven2"
   818  		if meta.Develop {
   819  			repo = *deploy + "/content/repositories/snapshots"
   820  		}
   821  		build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
   822  			"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
   823  			"-Dgpg.keyname="+keyID,
   824  			"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
   825  	}
   826  }
   827  
   828  func gomobileTool(subcmd string, args ...string) *exec.Cmd {
   829  	cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
   830  	cmd.Args = append(cmd.Args, args...)
   831  	cmd.Env = []string{
   832  		"GOPATH=" + build.GOPATH(),
   833  		"PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
   834  	}
   835  	for _, e := range os.Environ() {
   836  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") {
   837  			continue
   838  		}
   839  		cmd.Env = append(cmd.Env, e)
   840  	}
   841  	return cmd
   842  }
   843  
   844  type mavenMetadata struct {
   845  	Version      string
   846  	Package      string
   847  	Develop      bool
   848  	Contributors []mavenContributor
   849  }
   850  
   851  type mavenContributor struct {
   852  	Name  string
   853  	Email string
   854  }
   855  
   856  func newMavenMetadata(env build.Environment) mavenMetadata {
   857  	// Collect the list of authors from the repo root
   858  	contribs := []mavenContributor{}
   859  	if authors, err := os.Open("AUTHORS"); err == nil {
   860  		defer authors.Close()
   861  
   862  		scanner := bufio.NewScanner(authors)
   863  		for scanner.Scan() {
   864  			// Skip any whitespace from the authors list
   865  			line := strings.TrimSpace(scanner.Text())
   866  			if line == "" || line[0] == '#' {
   867  				continue
   868  			}
   869  			// Split the author and insert as a contributor
   870  			re := regexp.MustCompile("([^<]+) <(.+)>")
   871  			parts := re.FindStringSubmatch(line)
   872  			if len(parts) == 3 {
   873  				contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
   874  			}
   875  		}
   876  	}
   877  	// Render the version and package strings
   878  	version := params.Version
   879  	if isUnstableBuild(env) {
   880  		version += "-SNAPSHOT"
   881  	}
   882  	return mavenMetadata{
   883  		Version:      version,
   884  		Package:      "geth-" + version,
   885  		Develop:      isUnstableBuild(env),
   886  		Contributors: contribs,
   887  	}
   888  }
   889  
   890  // XCode frameworks
   891  
   892  func doXCodeFramework(cmdline []string) {
   893  	var (
   894  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   895  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
   896  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
   897  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   898  	)
   899  	flag.CommandLine.Parse(cmdline)
   900  	env := build.Env()
   901  
   902  	// Build the iOS XCode framework
   903  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   904  	build.MustRun(gomobileTool("init"))
   905  	bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "--tags", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
   906  
   907  	if *local {
   908  		// If we're building locally, use the build folder and stop afterwards
   909  		bind.Dir, _ = filepath.Abs(GOBIN)
   910  		build.MustRun(bind)
   911  		return
   912  	}
   913  	archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
   914  	if err := os.Mkdir(archive, os.ModePerm); err != nil {
   915  		log.Fatal(err)
   916  	}
   917  	bind.Dir, _ = filepath.Abs(archive)
   918  	build.MustRun(bind)
   919  	build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
   920  
   921  	// Skip CocoaPods deploy and Azure upload for PR builds
   922  	maybeSkipArchive(env)
   923  
   924  	// Sign and upload the framework to Azure
   925  	if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
   926  		log.Fatal(err)
   927  	}
   928  	// Prepare and upload a PodSpec to CocoaPods
   929  	if *deploy != "" {
   930  		meta := newPodMetadata(env, archive)
   931  		build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
   932  		build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
   933  	}
   934  }
   935  
   936  type podMetadata struct {
   937  	Version      string
   938  	Commit       string
   939  	Archive      string
   940  	Contributors []podContributor
   941  }
   942  
   943  type podContributor struct {
   944  	Name  string
   945  	Email string
   946  }
   947  
   948  func newPodMetadata(env build.Environment, archive string) podMetadata {
   949  	// Collect the list of authors from the repo root
   950  	contribs := []podContributor{}
   951  	if authors, err := os.Open("AUTHORS"); err == nil {
   952  		defer authors.Close()
   953  
   954  		scanner := bufio.NewScanner(authors)
   955  		for scanner.Scan() {
   956  			// Skip any whitespace from the authors list
   957  			line := strings.TrimSpace(scanner.Text())
   958  			if line == "" || line[0] == '#' {
   959  				continue
   960  			}
   961  			// Split the author and insert as a contributor
   962  			re := regexp.MustCompile("([^<]+) <(.+)>")
   963  			parts := re.FindStringSubmatch(line)
   964  			if len(parts) == 3 {
   965  				contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
   966  			}
   967  		}
   968  	}
   969  	version := params.Version
   970  	if isUnstableBuild(env) {
   971  		version += "-unstable." + env.Buildnum
   972  	}
   973  	return podMetadata{
   974  		Archive:      archive,
   975  		Version:      version,
   976  		Commit:       env.Commit,
   977  		Contributors: contribs,
   978  	}
   979  }
   980  
   981  // Cross compilation
   982  
   983  func doXgo(cmdline []string) {
   984  	var (
   985  		alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
   986  	)
   987  	flag.CommandLine.Parse(cmdline)
   988  	env := build.Env()
   989  
   990  	// Make sure xgo is available for cross compilation
   991  	gogetxgo := goTool("get", "github.com/karalabe/xgo")
   992  	build.MustRun(gogetxgo)
   993  
   994  	// If all tools building is requested, build everything the builder wants
   995  	args := append(buildFlags(env), flag.Args()...)
   996  
   997  	if *alltools {
   998  		args = append(args, []string{"--dest", GOBIN}...)
   999  		for _, res := range allCrossCompiledArchiveFiles {
  1000  			if strings.HasPrefix(res, GOBIN) {
  1001  				// Binary tool found, cross build it explicitly
  1002  				args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  1003  				xgo := xgoTool(args)
  1004  				build.MustRun(xgo)
  1005  				args = args[:len(args)-1]
  1006  			}
  1007  		}
  1008  		return
  1009  	}
  1010  	// Otherwise xxecute the explicit cross compilation
  1011  	path := args[len(args)-1]
  1012  	args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  1013  
  1014  	xgo := xgoTool(args)
  1015  	build.MustRun(xgo)
  1016  }
  1017  
  1018  func xgoTool(args []string) *exec.Cmd {
  1019  	cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  1020  	cmd.Env = []string{
  1021  		"GOPATH=" + build.GOPATH(),
  1022  		"GOBIN=" + GOBIN,
  1023  	}
  1024  	for _, e := range os.Environ() {
  1025  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  1026  			continue
  1027  		}
  1028  		cmd.Env = append(cmd.Env, e)
  1029  	}
  1030  	return cmd
  1031  }
  1032  
  1033  // Binary distribution cleanups
  1034  
  1035  func doPurge(cmdline []string) {
  1036  	var (
  1037  		store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1038  		limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1039  	)
  1040  	flag.CommandLine.Parse(cmdline)
  1041  
  1042  	if env := build.Env(); !env.IsCronJob {
  1043  		log.Printf("skipping because not a cron job")
  1044  		os.Exit(0)
  1045  	}
  1046  	// Create the azure authentication and list the current archives
  1047  	auth := build.AzureBlobstoreConfig{
  1048  		Account:   strings.Split(*store, "/")[0],
  1049  		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1050  		Container: strings.SplitN(*store, "/", 2)[1],
  1051  	}
  1052  	blobs, err := build.AzureBlobstoreList(auth)
  1053  	if err != nil {
  1054  		log.Fatal(err)
  1055  	}
  1056  	// Iterate over the blobs, collect and sort all unstable builds
  1057  	for i := 0; i < len(blobs); i++ {
  1058  		if !strings.Contains(blobs[i].Name, "unstable") {
  1059  			blobs = append(blobs[:i], blobs[i+1:]...)
  1060  			i--
  1061  		}
  1062  	}
  1063  	for i := 0; i < len(blobs); i++ {
  1064  		for j := i + 1; j < len(blobs); j++ {
  1065  			if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1066  				blobs[i], blobs[j] = blobs[j], blobs[i]
  1067  			}
  1068  		}
  1069  	}
  1070  	// Filter out all archives more recent that the given threshold
  1071  	for i, blob := range blobs {
  1072  		if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1073  			blobs = blobs[:i]
  1074  			break
  1075  		}
  1076  	}
  1077  	// Delete all marked as such and return
  1078  	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1079  		log.Fatal(err)
  1080  	}
  1081  }