github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/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  	} else {
   286  		ld = append(ld, "-extldflags")
   287  		ld = append(ld, "-pthread")
   288  	}
   289  
   290  	if len(ld) > 0 {
   291  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   292  	}
   293  	return flags
   294  }
   295  
   296  func goTool(subcmd string, args ...string) *exec.Cmd {
   297  	return goToolArch(runtime.GOARCH, os.Getenv("CC"), subcmd, args...)
   298  }
   299  
   300  func goToolArch(arch string, cc string, subcmd string, args ...string) *exec.Cmd {
   301  	cmd := build.GoTool(subcmd, args...)
   302  	cmd.Env = []string{"GOPATH=" + build.GOPATH()}
   303  	if arch == "" || arch == runtime.GOARCH {
   304  		cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
   305  	} else {
   306  		cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
   307  		cmd.Env = append(cmd.Env, "GOARCH="+arch)
   308  	}
   309  	if cc != "" {
   310  		cmd.Env = append(cmd.Env, "CC="+cc)
   311  	}
   312  	for _, e := range os.Environ() {
   313  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
   314  			continue
   315  		}
   316  		cmd.Env = append(cmd.Env, e)
   317  	}
   318  	return cmd
   319  }
   320  
   321  func Filter(vs []string, pred func(string) bool) []string {
   322  	filtered := make([]string, 0)
   323  	for _, v := range vs {
   324  		if pred(v) {
   325  			filtered = append(filtered, v)
   326  		}
   327  	}
   328  	return filtered
   329  }
   330  
   331  // Running The Tests
   332  //
   333  // "tests" also includes static analysis tools such as vet.
   334  
   335  func doTest(cmdline []string) {
   336  	coverage := flag.Bool("coverage", false, "Whether to record code coverage")
   337  	flag.CommandLine.Parse(cmdline)
   338  	env := build.Env()
   339  
   340  	packages := []string{"./..."}
   341  	if len(flag.CommandLine.Args()) > 0 {
   342  		packages = flag.CommandLine.Args()
   343  	}
   344  	packages = build.ExpandPackagesNoVendor(packages)
   345  
   346  	// Skip all swarm tests as it's not needed for Celo.
   347  	packages = Filter(packages, func(p string) bool {
   348  		return !strings.Contains(p, "swarm")
   349  	})
   350  
   351  	// Run the actual tests.
   352  	// Test a single package at a time. CI builders are slow
   353  	// and some tests run into timeouts under load.
   354  	gotest := goTool("test", buildFlags(env)...)
   355  	gotest.Args = append(gotest.Args, "-p", "1", "-timeout", "5m")
   356  	if *coverage {
   357  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   358  	}
   359  
   360  	gotest.Args = append(gotest.Args, packages...)
   361  	build.MustRun(gotest)
   362  }
   363  
   364  // runs gometalinter on requested packages
   365  func doLint(cmdline []string) {
   366  	flag.CommandLine.Parse(cmdline)
   367  
   368  	packages := []string{"./..."}
   369  	if len(flag.CommandLine.Args()) > 0 {
   370  		packages = flag.CommandLine.Args()
   371  	}
   372  	// Get metalinter and install all supported linters
   373  	build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
   374  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
   375  
   376  	// Run fast linters batched together
   377  	configs := []string{
   378  		"--vendor",
   379  		"--tests",
   380  		"--deadline=2m",
   381  		"--disable-all",
   382  		// TODO (kevjue) - The goimports lint check is disabled since it was raising false errors.  Changes should be made
   383  		//                 so that this check can be re-enabled without raising false errors.
   384  		// "--enable=goimports",
   385  		"--enable=varcheck",
   386  		"--enable=vet",
   387  		"--enable=gofmt",
   388  		"--enable=misspell",
   389  		"--enable=goconst",
   390  		"--min-occurrences=6", // for goconst
   391  	}
   392  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   393  
   394  	// Run slow linters one by one
   395  	for _, linter := range []string{"unconvert", "gosimple"} {
   396  		configs = []string{"--vendor", "--tests", "--deadline=10m", "--disable-all", "--enable=" + linter}
   397  		build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   398  	}
   399  }
   400  
   401  // Release Packaging
   402  func doArchive(cmdline []string) {
   403  	var (
   404  		arch   = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
   405  		atype  = flag.String("type", "zip", "Type of archive to write (zip|tar)")
   406  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
   407  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   408  		ext    string
   409  	)
   410  	flag.CommandLine.Parse(cmdline)
   411  	switch *atype {
   412  	case "zip":
   413  		ext = ".zip"
   414  	case "tar":
   415  		ext = ".tar.gz"
   416  	default:
   417  		log.Fatal("unknown archive type: ", atype)
   418  	}
   419  
   420  	var (
   421  		env = build.Env()
   422  
   423  		basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
   424  		geth     = "geth-" + basegeth + ext
   425  		alltools = "geth-alltools-" + basegeth + ext
   426  
   427  		baseswarm = archiveBasename(*arch, sv.ArchiveVersion(env.Commit))
   428  		swarm     = "swarm-" + baseswarm + ext
   429  	)
   430  	maybeSkipArchive(env)
   431  	if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
   432  		log.Fatal(err)
   433  	}
   434  	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
   435  		log.Fatal(err)
   436  	}
   437  	if err := build.WriteArchive(swarm, swarmArchiveFiles); err != nil {
   438  		log.Fatal(err)
   439  	}
   440  	for _, archive := range []string{geth, alltools, swarm} {
   441  		if err := archiveUpload(archive, *upload, *signer); err != nil {
   442  			log.Fatal(err)
   443  		}
   444  	}
   445  }
   446  
   447  func archiveBasename(arch string, archiveVersion string) string {
   448  	platform := runtime.GOOS + "-" + arch
   449  	if arch == "arm" {
   450  		platform += os.Getenv("GOARM")
   451  	}
   452  	if arch == "android" {
   453  		platform = "android-all"
   454  	}
   455  	if arch == "ios" {
   456  		platform = "ios-all"
   457  	}
   458  	return platform + "-" + archiveVersion
   459  }
   460  
   461  func archiveUpload(archive string, blobstore string, signer string) error {
   462  	// If signing was requested, generate the signature files
   463  	if signer != "" {
   464  		key := getenvBase64(signer)
   465  		if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
   466  			return err
   467  		}
   468  	}
   469  	// If uploading to Azure was requested, push the archive possibly with its signature
   470  	if blobstore != "" {
   471  		auth := build.AzureBlobstoreConfig{
   472  			Account:   strings.Split(blobstore, "/")[0],
   473  			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
   474  			Container: strings.SplitN(blobstore, "/", 2)[1],
   475  		}
   476  		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
   477  			return err
   478  		}
   479  		if signer != "" {
   480  			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
   481  				return err
   482  			}
   483  		}
   484  	}
   485  	return nil
   486  }
   487  
   488  // skips archiving for some build configurations.
   489  func maybeSkipArchive(env build.Environment) {
   490  	if env.IsPullRequest {
   491  		log.Printf("skipping because this is a PR build")
   492  		os.Exit(0)
   493  	}
   494  	if env.IsCronJob {
   495  		log.Printf("skipping because this is a cron job")
   496  		os.Exit(0)
   497  	}
   498  	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
   499  		log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
   500  		os.Exit(0)
   501  	}
   502  }
   503  
   504  // Debian Packaging
   505  func doDebianSource(cmdline []string) {
   506  	var (
   507  		signer  = flag.String("signer", "", `Signing key name, also used as package author`)
   508  		upload  = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
   509  		sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
   510  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   511  		now     = time.Now()
   512  	)
   513  	flag.CommandLine.Parse(cmdline)
   514  	*workdir = makeWorkdir(*workdir)
   515  	env := build.Env()
   516  	maybeSkipArchive(env)
   517  
   518  	// Import the signing key.
   519  	if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
   520  		gpg := exec.Command("gpg", "--import")
   521  		gpg.Stdin = bytes.NewReader(key)
   522  		build.MustRun(gpg)
   523  	}
   524  
   525  	// Create Debian packages and upload them
   526  	for _, pkg := range debPackages {
   527  		for _, distro := range debDistros {
   528  			meta := newDebMetadata(distro, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
   529  			pkgdir := stageDebianSource(*workdir, meta)
   530  			debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz")
   531  			debuild.Dir = pkgdir
   532  			build.MustRun(debuild)
   533  
   534  			var (
   535  				basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
   536  				source   = filepath.Join(*workdir, basename+".tar.xz")
   537  				dsc      = filepath.Join(*workdir, basename+".dsc")
   538  				changes  = filepath.Join(*workdir, basename+"_source.changes")
   539  			)
   540  			if *signer != "" {
   541  				build.MustRunCommand("debsign", changes)
   542  			}
   543  			if *upload != "" {
   544  				ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes})
   545  			}
   546  		}
   547  	}
   548  }
   549  
   550  func ppaUpload(workdir, ppa, sshUser string, files []string) {
   551  	p := strings.Split(ppa, "/")
   552  	if len(p) != 2 {
   553  		log.Fatal("-upload PPA name must contain single /")
   554  	}
   555  	if sshUser == "" {
   556  		sshUser = p[0]
   557  	}
   558  	incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
   559  	// Create the SSH identity file if it doesn't exist.
   560  	var idfile string
   561  	if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
   562  		idfile = filepath.Join(workdir, "sshkey")
   563  		if _, err := os.Stat(idfile); os.IsNotExist(err) {
   564  			ioutil.WriteFile(idfile, sshkey, 0600)
   565  		}
   566  	}
   567  	// Upload
   568  	dest := sshUser + "@ppa.launchpad.net"
   569  	if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
   570  		log.Fatal(err)
   571  	}
   572  }
   573  
   574  func getenvBase64(variable string) []byte {
   575  	dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
   576  	if err != nil {
   577  		log.Fatal("invalid base64 " + variable)
   578  	}
   579  	return []byte(dec)
   580  }
   581  
   582  func makeWorkdir(wdflag string) string {
   583  	var err error
   584  	if wdflag != "" {
   585  		err = os.MkdirAll(wdflag, 0744)
   586  	} else {
   587  		wdflag, err = ioutil.TempDir("", "geth-build-")
   588  	}
   589  	if err != nil {
   590  		log.Fatal(err)
   591  	}
   592  	return wdflag
   593  }
   594  
   595  func isUnstableBuild(env build.Environment) bool {
   596  	if env.Tag != "" {
   597  		return false
   598  	}
   599  	return true
   600  }
   601  
   602  type debPackage struct {
   603  	Name        string          // the name of the Debian package to produce, e.g. "ethereum", or "ethereum-swarm"
   604  	Version     string          // the clean version of the debPackage, e.g. 1.8.12 or 0.3.0, without any metadata
   605  	Executables []debExecutable // executables to be included in the package
   606  }
   607  
   608  type debMetadata struct {
   609  	Env build.Environment
   610  
   611  	PackageName string
   612  
   613  	// go-ethereum version being built. Note that this
   614  	// is not the debian package version. The package version
   615  	// is constructed by VersionString.
   616  	Version string
   617  
   618  	Author       string // "name <email>", also selects signing key
   619  	Distro, Time string
   620  	Executables  []debExecutable
   621  }
   622  
   623  type debExecutable struct {
   624  	PackageName string
   625  	BinaryName  string
   626  	Description string
   627  }
   628  
   629  // Package returns the name of the package if present, or
   630  // fallbacks to BinaryName
   631  func (d debExecutable) Package() string {
   632  	if d.PackageName != "" {
   633  		return d.PackageName
   634  	}
   635  	return d.BinaryName
   636  }
   637  
   638  func newDebMetadata(distro, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
   639  	if author == "" {
   640  		// No signing key, use default author.
   641  		author = "Ethereum Builds <fjl@ethereum.org>"
   642  	}
   643  	return debMetadata{
   644  		PackageName: name,
   645  		Env:         env,
   646  		Author:      author,
   647  		Distro:      distro,
   648  		Version:     version,
   649  		Time:        t.Format(time.RFC1123Z),
   650  		Executables: exes,
   651  	}
   652  }
   653  
   654  // Name returns the name of the metapackage that depends
   655  // on all executable packages.
   656  func (meta debMetadata) Name() string {
   657  	if isUnstableBuild(meta.Env) {
   658  		return meta.PackageName + "-unstable"
   659  	}
   660  	return meta.PackageName
   661  }
   662  
   663  // VersionString returns the debian version of the packages.
   664  func (meta debMetadata) VersionString() string {
   665  	vsn := meta.Version
   666  	if meta.Env.Buildnum != "" {
   667  		vsn += "+build" + meta.Env.Buildnum
   668  	}
   669  	if meta.Distro != "" {
   670  		vsn += "+" + meta.Distro
   671  	}
   672  	return vsn
   673  }
   674  
   675  // ExeList returns the list of all executable packages.
   676  func (meta debMetadata) ExeList() string {
   677  	names := make([]string, len(meta.Executables))
   678  	for i, e := range meta.Executables {
   679  		names[i] = meta.ExeName(e)
   680  	}
   681  	return strings.Join(names, ", ")
   682  }
   683  
   684  // ExeName returns the package name of an executable package.
   685  func (meta debMetadata) ExeName(exe debExecutable) string {
   686  	if isUnstableBuild(meta.Env) {
   687  		return exe.Package() + "-unstable"
   688  	}
   689  	return exe.Package()
   690  }
   691  
   692  // ExeConflicts returns the content of the Conflicts field
   693  // for executable packages.
   694  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   695  	if isUnstableBuild(meta.Env) {
   696  		// Set up the conflicts list so that the *-unstable packages
   697  		// cannot be installed alongside the regular version.
   698  		//
   699  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   700  		// is very explicit about Conflicts: and says that Breaks: should
   701  		// be preferred and the conflicting files should be handled via
   702  		// alternates. We might do this eventually but using a conflict is
   703  		// easier now.
   704  		return "ethereum, " + exe.Package()
   705  	}
   706  	return ""
   707  }
   708  
   709  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   710  	pkg := meta.Name() + "-" + meta.VersionString()
   711  	pkgdir = filepath.Join(tmpdir, pkg)
   712  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   713  		log.Fatal(err)
   714  	}
   715  
   716  	// Copy the source code.
   717  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   718  
   719  	// Put the debian build files in place.
   720  	debian := filepath.Join(pkgdir, "debian")
   721  	build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   722  	build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   723  	build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
   724  	build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   725  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   726  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   727  	for _, exe := range meta.Executables {
   728  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   729  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   730  		build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
   731  		build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
   732  	}
   733  
   734  	return pkgdir
   735  }
   736  
   737  // Windows installer
   738  func doWindowsInstaller(cmdline []string) {
   739  	// Parse the flags and make skip installer generation on PRs
   740  	var (
   741  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   742  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   743  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   744  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   745  	)
   746  	flag.CommandLine.Parse(cmdline)
   747  	*workdir = makeWorkdir(*workdir)
   748  	env := build.Env()
   749  	maybeSkipArchive(env)
   750  
   751  	// Aggregate binaries that are included in the installer
   752  	var (
   753  		devTools []string
   754  		allTools []string
   755  		gethTool string
   756  	)
   757  	for _, file := range allToolsArchiveFiles {
   758  		if file == "COPYING" { // license, copied later
   759  			continue
   760  		}
   761  		allTools = append(allTools, filepath.Base(file))
   762  		if filepath.Base(file) == "geth.exe" {
   763  			gethTool = file
   764  		} else {
   765  			devTools = append(devTools, file)
   766  		}
   767  	}
   768  
   769  	// Render NSIS scripts: Installer NSIS contains two installer sections,
   770  	// first section contains the geth binary, second section holds the dev tools.
   771  	templateData := map[string]interface{}{
   772  		"License":  "COPYING",
   773  		"Geth":     gethTool,
   774  		"DevTools": devTools,
   775  	}
   776  	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
   777  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
   778  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
   779  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
   780  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
   781  	build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
   782  	build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
   783  
   784  	// Build the installer. This assumes that all the needed files have been previously
   785  	// built (don't mix building and packaging to keep cross compilation complexity to a
   786  	// minimum).
   787  	version := strings.Split(params.Version, ".")
   788  	if env.Commit != "" {
   789  		version[2] += "-" + env.Commit[:8]
   790  	}
   791  	installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
   792  	build.MustRunCommand("makensis.exe",
   793  		"/DOUTPUTFILE="+installer,
   794  		"/DMAJORVERSION="+version[0],
   795  		"/DMINORVERSION="+version[1],
   796  		"/DBUILDVERSION="+version[2],
   797  		"/DARCH="+*arch,
   798  		filepath.Join(*workdir, "geth.nsi"),
   799  	)
   800  
   801  	// Sign and publish installer.
   802  	if err := archiveUpload(installer, *upload, *signer); err != nil {
   803  		log.Fatal(err)
   804  	}
   805  }
   806  
   807  // Android archives
   808  
   809  func doAndroidArchive(cmdline []string) {
   810  	var (
   811  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   812  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
   813  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
   814  		upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
   815  	)
   816  	flag.CommandLine.Parse(cmdline)
   817  	env := build.Env()
   818  
   819  	// Sanity check that the SDK and NDK are installed and set
   820  	if os.Getenv("ANDROID_HOME") == "" {
   821  		log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
   822  	}
   823  	if os.Getenv("ANDROID_NDK") == "" {
   824  		log.Fatal("Please ensure ANDROID_NDK points to your Android NDK")
   825  	}
   826  	// Build the Android archive and Maven resources
   827  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   828  	build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
   829  
   830  	if *local {
   831  		// If we're building locally, copy bundle to build dir and skip Maven
   832  		os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
   833  		return
   834  	}
   835  	meta := newMavenMetadata(env)
   836  	build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
   837  
   838  	// Skip Maven deploy and Azure upload for PR builds
   839  	maybeSkipArchive(env)
   840  
   841  	// Sign and upload the archive to Azure
   842  	archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
   843  	os.Rename("geth.aar", archive)
   844  
   845  	if err := archiveUpload(archive, *upload, *signer); err != nil {
   846  		log.Fatal(err)
   847  	}
   848  	// Sign and upload all the artifacts to Maven Central
   849  	os.Rename(archive, meta.Package+".aar")
   850  	if *signer != "" && *deploy != "" {
   851  		// Import the signing key into the local GPG instance
   852  		key := getenvBase64(*signer)
   853  		gpg := exec.Command("gpg", "--import")
   854  		gpg.Stdin = bytes.NewReader(key)
   855  		build.MustRun(gpg)
   856  		keyID, err := build.PGPKeyID(string(key))
   857  		if err != nil {
   858  			log.Fatal(err)
   859  		}
   860  		// Upload the artifacts to Sonatype and/or Maven Central
   861  		repo := *deploy + "/service/local/staging/deploy/maven2"
   862  		if meta.Develop {
   863  			repo = *deploy + "/content/repositories/snapshots"
   864  		}
   865  		build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
   866  			"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
   867  			"-Dgpg.keyname="+keyID,
   868  			"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
   869  	}
   870  }
   871  
   872  func gomobileTool(subcmd string, args ...string) *exec.Cmd {
   873  	cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
   874  	cmd.Args = append(cmd.Args, args...)
   875  	cmd.Env = []string{
   876  		"GOPATH=" + build.GOPATH(),
   877  		"PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
   878  	}
   879  	for _, e := range os.Environ() {
   880  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") {
   881  			continue
   882  		}
   883  		cmd.Env = append(cmd.Env, e)
   884  	}
   885  	return cmd
   886  }
   887  
   888  type mavenMetadata struct {
   889  	Version      string
   890  	Package      string
   891  	Develop      bool
   892  	Contributors []mavenContributor
   893  }
   894  
   895  type mavenContributor struct {
   896  	Name  string
   897  	Email string
   898  }
   899  
   900  func newMavenMetadata(env build.Environment) mavenMetadata {
   901  	// Collect the list of authors from the repo root
   902  	contribs := []mavenContributor{}
   903  	if authors, err := os.Open("AUTHORS"); err == nil {
   904  		defer authors.Close()
   905  
   906  		scanner := bufio.NewScanner(authors)
   907  		for scanner.Scan() {
   908  			// Skip any whitespace from the authors list
   909  			line := strings.TrimSpace(scanner.Text())
   910  			if line == "" || line[0] == '#' {
   911  				continue
   912  			}
   913  			// Split the author and insert as a contributor
   914  			re := regexp.MustCompile("([^<]+) <(.+)>")
   915  			parts := re.FindStringSubmatch(line)
   916  			if len(parts) == 3 {
   917  				contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
   918  			}
   919  		}
   920  	}
   921  	// Render the version and package strings
   922  	version := params.Version
   923  	if isUnstableBuild(env) {
   924  		version += "-SNAPSHOT"
   925  	}
   926  	return mavenMetadata{
   927  		Version:      version,
   928  		Package:      "geth-" + version,
   929  		Develop:      isUnstableBuild(env),
   930  		Contributors: contribs,
   931  	}
   932  }
   933  
   934  // XCode frameworks
   935  
   936  func doXCodeFramework(cmdline []string) {
   937  	var (
   938  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   939  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
   940  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
   941  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   942  	)
   943  	flag.CommandLine.Parse(cmdline)
   944  	env := build.Env()
   945  
   946  	// Build the iOS XCode framework
   947  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   948  	// Patch gomobile to disable bitcode for now (rust generated bls lib output is not compatible)
   949  	build.MustRunCommand("sed", "-i", "", `/^[[:space:]]*cflags += \" -fembed-bitcode\"$/s/^/\/\//`, filepath.Join(build.GOPATH(), "src/golang.org/x/mobile/cmd/gomobile/env.go"))
   950  	bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
   951  
   952  	if *local {
   953  		// If we're building locally, use the build folder and stop afterwards
   954  		bind.Dir, _ = filepath.Abs(GOBIN)
   955  		build.MustRun(bind)
   956  		return
   957  	}
   958  	archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
   959  	if err := os.Mkdir(archive, os.ModePerm); err != nil {
   960  		log.Fatal(err)
   961  	}
   962  	bind.Dir, _ = filepath.Abs(archive)
   963  	build.MustRun(bind)
   964  	build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
   965  
   966  	// Skip CocoaPods deploy and Azure upload for PR builds
   967  	maybeSkipArchive(env)
   968  
   969  	// Sign and upload the framework to Azure
   970  	if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
   971  		log.Fatal(err)
   972  	}
   973  	// Prepare and upload a PodSpec to CocoaPods
   974  	if *deploy != "" {
   975  		meta := newPodMetadata(env, archive)
   976  		build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
   977  		build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
   978  	}
   979  }
   980  
   981  type podMetadata struct {
   982  	Version      string
   983  	Commit       string
   984  	Archive      string
   985  	Contributors []podContributor
   986  }
   987  
   988  type podContributor struct {
   989  	Name  string
   990  	Email string
   991  }
   992  
   993  func newPodMetadata(env build.Environment, archive string) podMetadata {
   994  	// Collect the list of authors from the repo root
   995  	contribs := []podContributor{}
   996  	if authors, err := os.Open("AUTHORS"); err == nil {
   997  		defer authors.Close()
   998  
   999  		scanner := bufio.NewScanner(authors)
  1000  		for scanner.Scan() {
  1001  			// Skip any whitespace from the authors list
  1002  			line := strings.TrimSpace(scanner.Text())
  1003  			if line == "" || line[0] == '#' {
  1004  				continue
  1005  			}
  1006  			// Split the author and insert as a contributor
  1007  			re := regexp.MustCompile("([^<]+) <(.+)>")
  1008  			parts := re.FindStringSubmatch(line)
  1009  			if len(parts) == 3 {
  1010  				contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  1011  			}
  1012  		}
  1013  	}
  1014  	version := params.Version
  1015  	if isUnstableBuild(env) {
  1016  		version += "-unstable." + env.Buildnum
  1017  	}
  1018  	return podMetadata{
  1019  		Archive:      archive,
  1020  		Version:      version,
  1021  		Commit:       env.Commit,
  1022  		Contributors: contribs,
  1023  	}
  1024  }
  1025  
  1026  // Cross compilation
  1027  
  1028  func doXgo(cmdline []string) {
  1029  	var (
  1030  		alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  1031  	)
  1032  	flag.CommandLine.Parse(cmdline)
  1033  	env := build.Env()
  1034  
  1035  	// Make sure xgo is available for cross compilation
  1036  	gogetxgo := goTool("get", "github.com/karalabe/xgo")
  1037  	build.MustRun(gogetxgo)
  1038  
  1039  	// If all tools building is requested, build everything the builder wants
  1040  	args := append(buildFlags(env), flag.Args()...)
  1041  
  1042  	if *alltools {
  1043  		args = append(args, []string{"--dest", GOBIN}...)
  1044  		for _, res := range allCrossCompiledArchiveFiles {
  1045  			if strings.HasPrefix(res, GOBIN) {
  1046  				// Binary tool found, cross build it explicitly
  1047  				args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  1048  				xgo := xgoTool(args)
  1049  				build.MustRun(xgo)
  1050  				args = args[:len(args)-1]
  1051  			}
  1052  		}
  1053  		return
  1054  	}
  1055  	// Otherwise xxecute the explicit cross compilation
  1056  	path := args[len(args)-1]
  1057  	args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  1058  
  1059  	xgo := xgoTool(args)
  1060  	build.MustRun(xgo)
  1061  }
  1062  
  1063  func xgoTool(args []string) *exec.Cmd {
  1064  	cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  1065  	cmd.Env = []string{
  1066  		"GOPATH=" + build.GOPATH(),
  1067  		"GOBIN=" + GOBIN,
  1068  	}
  1069  	for _, e := range os.Environ() {
  1070  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  1071  			continue
  1072  		}
  1073  		cmd.Env = append(cmd.Env, e)
  1074  	}
  1075  	return cmd
  1076  }
  1077  
  1078  // Binary distribution cleanups
  1079  
  1080  func doPurge(cmdline []string) {
  1081  	var (
  1082  		store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1083  		limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1084  	)
  1085  	flag.CommandLine.Parse(cmdline)
  1086  
  1087  	if env := build.Env(); !env.IsCronJob {
  1088  		log.Printf("skipping because not a cron job")
  1089  		os.Exit(0)
  1090  	}
  1091  	// Create the azure authentication and list the current archives
  1092  	auth := build.AzureBlobstoreConfig{
  1093  		Account:   strings.Split(*store, "/")[0],
  1094  		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1095  		Container: strings.SplitN(*store, "/", 2)[1],
  1096  	}
  1097  	blobs, err := build.AzureBlobstoreList(auth)
  1098  	if err != nil {
  1099  		log.Fatal(err)
  1100  	}
  1101  	// Iterate over the blobs, collect and sort all unstable builds
  1102  	for i := 0; i < len(blobs); i++ {
  1103  		if !strings.Contains(blobs[i].Name, "unstable") {
  1104  			blobs = append(blobs[:i], blobs[i+1:]...)
  1105  			i--
  1106  		}
  1107  	}
  1108  	for i := 0; i < len(blobs); i++ {
  1109  		for j := i + 1; j < len(blobs); j++ {
  1110  			if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1111  				blobs[i], blobs[j] = blobs[j], blobs[i]
  1112  			}
  1113  		}
  1114  	}
  1115  	// Filter out all archives more recent that the given threshold
  1116  	for i, blob := range blobs {
  1117  		if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1118  			blobs = blobs[:i]
  1119  			break
  1120  		}
  1121  	}
  1122  	// Delete all marked as such and return
  1123  	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1124  		log.Fatal(err)
  1125  	}
  1126  }