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