github.com/truechain/truechain-fpow@v1.8.11/build/ci.go (about)

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