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