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