github.com/needkane/go-ethereum@v1.7.4-0.20180131070256-c212876ea2b7/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  	debDistros = []string{"trusty", "xenial", "zesty", "artful"}
   125  )
   126  
   127  var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
   128  
   129  func executablePath(name string) string {
   130  	if runtime.GOOS == "windows" {
   131  		name += ".exe"
   132  	}
   133  	return filepath.Join(GOBIN, name)
   134  }
   135  
   136  func main() {
   137  	log.SetFlags(log.Lshortfile)
   138  
   139  	if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
   140  		log.Fatal("this script must be run from the root of the repository")
   141  	}
   142  	if len(os.Args) < 2 {
   143  		log.Fatal("need subcommand as first argument")
   144  	}
   145  	switch os.Args[1] {
   146  	case "install":
   147  		doInstall(os.Args[2:])
   148  	case "test":
   149  		doTest(os.Args[2:])
   150  	case "lint":
   151  		doLint(os.Args[2:])
   152  	case "archive":
   153  		doArchive(os.Args[2:])
   154  	case "debsrc":
   155  		doDebianSource(os.Args[2:])
   156  	case "nsis":
   157  		doWindowsInstaller(os.Args[2:])
   158  	case "aar":
   159  		doAndroidArchive(os.Args[2:])
   160  	case "xcode":
   161  		doXCodeFramework(os.Args[2:])
   162  	case "xgo":
   163  		doXgo(os.Args[2:])
   164  	case "purge":
   165  		doPurge(os.Args[2:])
   166  	default:
   167  		log.Fatal("unknown command ", os.Args[1])
   168  	}
   169  }
   170  
   171  // Compiling
   172  
   173  func doInstall(cmdline []string) {
   174  	var (
   175  		arch = flag.String("arch", "", "Architecture to cross build for")
   176  		cc   = flag.String("cc", "", "C compiler to cross build with")
   177  	)
   178  	flag.CommandLine.Parse(cmdline)
   179  	env := build.Env()
   180  
   181  	// Check Go version. People regularly open issues about compilation
   182  	// failure with outdated Go. This should save them the trouble.
   183  	if !strings.Contains(runtime.Version(), "devel") {
   184  		// Figure out the minor version number since we can't textually compare (1.10 < 1.7)
   185  		var minor int
   186  		fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
   187  
   188  		if minor < 7 {
   189  			log.Println("You have Go version", runtime.Version())
   190  			log.Println("go-ethereum requires at least Go version 1.7 and cannot")
   191  			log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
   192  			os.Exit(1)
   193  		}
   194  	}
   195  	// Compile packages given as arguments, or everything if there are no arguments.
   196  	packages := []string{"./..."}
   197  	if flag.NArg() > 0 {
   198  		packages = flag.Args()
   199  	}
   200  	packages = build.ExpandPackagesNoVendor(packages)
   201  
   202  	if *arch == "" || *arch == runtime.GOARCH {
   203  		goinstall := goTool("install", buildFlags(env)...)
   204  		goinstall.Args = append(goinstall.Args, "-v")
   205  		goinstall.Args = append(goinstall.Args, packages...)
   206  		build.MustRun(goinstall)
   207  		return
   208  	}
   209  	// If we are cross compiling to ARMv5 ARMv6 or ARMv7, clean any previous builds
   210  	if *arch == "arm" {
   211  		os.RemoveAll(filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_arm"))
   212  		for _, path := range filepath.SplitList(build.GOPATH()) {
   213  			os.RemoveAll(filepath.Join(path, "pkg", runtime.GOOS+"_arm"))
   214  		}
   215  	}
   216  	// Seems we are cross compiling, work around forbidden GOBIN
   217  	goinstall := goToolArch(*arch, *cc, "install", buildFlags(env)...)
   218  	goinstall.Args = append(goinstall.Args, "-v")
   219  	goinstall.Args = append(goinstall.Args, []string{"-buildmode", "archive"}...)
   220  	goinstall.Args = append(goinstall.Args, packages...)
   221  	build.MustRun(goinstall)
   222  
   223  	if cmds, err := ioutil.ReadDir("cmd"); err == nil {
   224  		for _, cmd := range cmds {
   225  			pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
   226  			if err != nil {
   227  				log.Fatal(err)
   228  			}
   229  			for name := range pkgs {
   230  				if name == "main" {
   231  					gobuild := goToolArch(*arch, *cc, "build", buildFlags(env)...)
   232  					gobuild.Args = append(gobuild.Args, "-v")
   233  					gobuild.Args = append(gobuild.Args, []string{"-o", executablePath(cmd.Name())}...)
   234  					gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
   235  					build.MustRun(gobuild)
   236  					break
   237  				}
   238  			}
   239  		}
   240  	}
   241  }
   242  
   243  func buildFlags(env build.Environment) (flags []string) {
   244  	var ld []string
   245  	if env.Commit != "" {
   246  		ld = append(ld, "-X", "main.gitCommit="+env.Commit)
   247  	}
   248  	if runtime.GOOS == "darwin" {
   249  		ld = append(ld, "-s")
   250  	}
   251  
   252  	if len(ld) > 0 {
   253  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   254  	}
   255  	return flags
   256  }
   257  
   258  func goTool(subcmd string, args ...string) *exec.Cmd {
   259  	return goToolArch(runtime.GOARCH, os.Getenv("CC"), subcmd, args...)
   260  }
   261  
   262  func goToolArch(arch string, cc string, subcmd string, args ...string) *exec.Cmd {
   263  	cmd := build.GoTool(subcmd, args...)
   264  	if subcmd == "build" || subcmd == "install" || subcmd == "test" {
   265  		// Go CGO has a Windows linker error prior to 1.8 (https://github.com/golang/go/issues/8756).
   266  		// Work around issue by allowing multiple definitions for <1.8 builds.
   267  		var minor int
   268  		fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
   269  
   270  		if runtime.GOOS == "windows" && minor < 8 {
   271  			cmd.Args = append(cmd.Args, []string{"-ldflags", "-extldflags -Wl,--allow-multiple-definition"}...)
   272  		}
   273  	}
   274  	cmd.Env = []string{"GOPATH=" + build.GOPATH()}
   275  	if arch == "" || arch == runtime.GOARCH {
   276  		cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
   277  	} else {
   278  		cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
   279  		cmd.Env = append(cmd.Env, "GOARCH="+arch)
   280  	}
   281  	if cc != "" {
   282  		cmd.Env = append(cmd.Env, "CC="+cc)
   283  	}
   284  	for _, e := range os.Environ() {
   285  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
   286  			continue
   287  		}
   288  		cmd.Env = append(cmd.Env, e)
   289  	}
   290  	return cmd
   291  }
   292  
   293  // Running The Tests
   294  //
   295  // "tests" also includes static analysis tools such as vet.
   296  
   297  func doTest(cmdline []string) {
   298  	var (
   299  		coverage = flag.Bool("coverage", false, "Whether to record code coverage")
   300  	)
   301  	flag.CommandLine.Parse(cmdline)
   302  	env := build.Env()
   303  
   304  	packages := []string{"./..."}
   305  	if len(flag.CommandLine.Args()) > 0 {
   306  		packages = flag.CommandLine.Args()
   307  	}
   308  	packages = build.ExpandPackagesNoVendor(packages)
   309  
   310  	// Run analysis tools before the tests.
   311  	build.MustRun(goTool("vet", packages...))
   312  
   313  	// Run the actual tests.
   314  	gotest := goTool("test", buildFlags(env)...)
   315  	// Test a single package at a time. CI builders are slow
   316  	// and some tests run into timeouts under load.
   317  	gotest.Args = append(gotest.Args, "-p", "1")
   318  	if *coverage {
   319  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   320  	}
   321  
   322  	gotest.Args = append(gotest.Args, packages...)
   323  	build.MustRun(gotest)
   324  }
   325  
   326  // runs gometalinter on requested packages
   327  func doLint(cmdline []string) {
   328  	flag.CommandLine.Parse(cmdline)
   329  
   330  	packages := []string{"./..."}
   331  	if len(flag.CommandLine.Args()) > 0 {
   332  		packages = flag.CommandLine.Args()
   333  	}
   334  	// Get metalinter and install all supported linters
   335  	build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
   336  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
   337  
   338  	// Run fast linters batched together
   339  	configs := []string{
   340  		"--vendor",
   341  		"--disable-all",
   342  		"--enable=vet",
   343  		"--enable=gofmt",
   344  		"--enable=misspell",
   345  		"--enable=goconst",
   346  		"--min-occurrences=6", // for goconst
   347  	}
   348  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   349  
   350  	// Run slow linters one by one
   351  	for _, linter := range []string{"unconvert", "gosimple"} {
   352  		configs = []string{"--vendor", "--deadline=10m", "--disable-all", "--enable=" + linter}
   353  		build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   354  	}
   355  }
   356  
   357  // Release Packaging
   358  
   359  func doArchive(cmdline []string) {
   360  	var (
   361  		arch   = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
   362  		atype  = flag.String("type", "zip", "Type of archive to write (zip|tar)")
   363  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
   364  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   365  		ext    string
   366  	)
   367  	flag.CommandLine.Parse(cmdline)
   368  	switch *atype {
   369  	case "zip":
   370  		ext = ".zip"
   371  	case "tar":
   372  		ext = ".tar.gz"
   373  	default:
   374  		log.Fatal("unknown archive type: ", atype)
   375  	}
   376  
   377  	var (
   378  		env      = build.Env()
   379  		base     = archiveBasename(*arch, env)
   380  		geth     = "geth-" + base + ext
   381  		alltools = "geth-alltools-" + base + ext
   382  	)
   383  	maybeSkipArchive(env)
   384  	if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
   385  		log.Fatal(err)
   386  	}
   387  	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
   388  		log.Fatal(err)
   389  	}
   390  	for _, archive := range []string{geth, alltools} {
   391  		if err := archiveUpload(archive, *upload, *signer); err != nil {
   392  			log.Fatal(err)
   393  		}
   394  	}
   395  }
   396  
   397  func archiveBasename(arch string, env build.Environment) string {
   398  	platform := runtime.GOOS + "-" + arch
   399  	if arch == "arm" {
   400  		platform += os.Getenv("GOARM")
   401  	}
   402  	if arch == "android" {
   403  		platform = "android-all"
   404  	}
   405  	if arch == "ios" {
   406  		platform = "ios-all"
   407  	}
   408  	return platform + "-" + archiveVersion(env)
   409  }
   410  
   411  func archiveVersion(env build.Environment) string {
   412  	version := build.VERSION()
   413  	if isUnstableBuild(env) {
   414  		version += "-unstable"
   415  	}
   416  	if env.Commit != "" {
   417  		version += "-" + env.Commit[:8]
   418  	}
   419  	return version
   420  }
   421  
   422  func archiveUpload(archive string, blobstore string, signer string) error {
   423  	// If signing was requested, generate the signature files
   424  	if signer != "" {
   425  		pgpkey, err := base64.StdEncoding.DecodeString(os.Getenv(signer))
   426  		if err != nil {
   427  			return fmt.Errorf("invalid base64 %s", signer)
   428  		}
   429  		if err := build.PGPSignFile(archive, archive+".asc", string(pgpkey)); err != nil {
   430  			return err
   431  		}
   432  	}
   433  	// If uploading to Azure was requested, push the archive possibly with its signature
   434  	if blobstore != "" {
   435  		auth := build.AzureBlobstoreConfig{
   436  			Account:   strings.Split(blobstore, "/")[0],
   437  			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
   438  			Container: strings.SplitN(blobstore, "/", 2)[1],
   439  		}
   440  		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
   441  			return err
   442  		}
   443  		if signer != "" {
   444  			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
   445  				return err
   446  			}
   447  		}
   448  	}
   449  	return nil
   450  }
   451  
   452  // skips archiving for some build configurations.
   453  func maybeSkipArchive(env build.Environment) {
   454  	if env.IsPullRequest {
   455  		log.Printf("skipping because this is a PR build")
   456  		os.Exit(0)
   457  	}
   458  	if env.IsCronJob {
   459  		log.Printf("skipping because this is a cron job")
   460  		os.Exit(0)
   461  	}
   462  	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
   463  		log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
   464  		os.Exit(0)
   465  	}
   466  }
   467  
   468  // Debian Packaging
   469  
   470  func doDebianSource(cmdline []string) {
   471  	var (
   472  		signer  = flag.String("signer", "", `Signing key name, also used as package author`)
   473  		upload  = flag.String("upload", "", `Where to upload the source package (usually "ppa:ethereum/ethereum")`)
   474  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   475  		now     = time.Now()
   476  	)
   477  	flag.CommandLine.Parse(cmdline)
   478  	*workdir = makeWorkdir(*workdir)
   479  	env := build.Env()
   480  	maybeSkipArchive(env)
   481  
   482  	// Import the signing key.
   483  	if b64key := os.Getenv("PPA_SIGNING_KEY"); b64key != "" {
   484  		key, err := base64.StdEncoding.DecodeString(b64key)
   485  		if err != nil {
   486  			log.Fatal("invalid base64 PPA_SIGNING_KEY")
   487  		}
   488  		gpg := exec.Command("gpg", "--import")
   489  		gpg.Stdin = bytes.NewReader(key)
   490  		build.MustRun(gpg)
   491  	}
   492  
   493  	// Create the packages.
   494  	for _, distro := range debDistros {
   495  		meta := newDebMetadata(distro, *signer, env, now)
   496  		pkgdir := stageDebianSource(*workdir, meta)
   497  		debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc")
   498  		debuild.Dir = pkgdir
   499  		build.MustRun(debuild)
   500  
   501  		changes := fmt.Sprintf("%s_%s_source.changes", meta.Name(), meta.VersionString())
   502  		changes = filepath.Join(*workdir, changes)
   503  		if *signer != "" {
   504  			build.MustRunCommand("debsign", changes)
   505  		}
   506  		if *upload != "" {
   507  			build.MustRunCommand("dput", *upload, changes)
   508  		}
   509  	}
   510  }
   511  
   512  func makeWorkdir(wdflag string) string {
   513  	var err error
   514  	if wdflag != "" {
   515  		err = os.MkdirAll(wdflag, 0744)
   516  	} else {
   517  		wdflag, err = ioutil.TempDir("", "geth-build-")
   518  	}
   519  	if err != nil {
   520  		log.Fatal(err)
   521  	}
   522  	return wdflag
   523  }
   524  
   525  func isUnstableBuild(env build.Environment) bool {
   526  	if env.Tag != "" {
   527  		return false
   528  	}
   529  	return true
   530  }
   531  
   532  type debMetadata struct {
   533  	Env build.Environment
   534  
   535  	// go-ethereum version being built. Note that this
   536  	// is not the debian package version. The package version
   537  	// is constructed by VersionString.
   538  	Version string
   539  
   540  	Author       string // "name <email>", also selects signing key
   541  	Distro, Time string
   542  	Executables  []debExecutable
   543  }
   544  
   545  type debExecutable struct {
   546  	Name, Description string
   547  }
   548  
   549  func newDebMetadata(distro, author string, env build.Environment, t time.Time) debMetadata {
   550  	if author == "" {
   551  		// No signing key, use default author.
   552  		author = "Ethereum Builds <fjl@ethereum.org>"
   553  	}
   554  	return debMetadata{
   555  		Env:         env,
   556  		Author:      author,
   557  		Distro:      distro,
   558  		Version:     build.VERSION(),
   559  		Time:        t.Format(time.RFC1123Z),
   560  		Executables: debExecutables,
   561  	}
   562  }
   563  
   564  // Name returns the name of the metapackage that depends
   565  // on all executable packages.
   566  func (meta debMetadata) Name() string {
   567  	if isUnstableBuild(meta.Env) {
   568  		return "ethereum-unstable"
   569  	}
   570  	return "ethereum"
   571  }
   572  
   573  // VersionString returns the debian version of the packages.
   574  func (meta debMetadata) VersionString() string {
   575  	vsn := meta.Version
   576  	if meta.Env.Buildnum != "" {
   577  		vsn += "+build" + meta.Env.Buildnum
   578  	}
   579  	if meta.Distro != "" {
   580  		vsn += "+" + meta.Distro
   581  	}
   582  	return vsn
   583  }
   584  
   585  // ExeList returns the list of all executable packages.
   586  func (meta debMetadata) ExeList() string {
   587  	names := make([]string, len(meta.Executables))
   588  	for i, e := range meta.Executables {
   589  		names[i] = meta.ExeName(e)
   590  	}
   591  	return strings.Join(names, ", ")
   592  }
   593  
   594  // ExeName returns the package name of an executable package.
   595  func (meta debMetadata) ExeName(exe debExecutable) string {
   596  	if isUnstableBuild(meta.Env) {
   597  		return exe.Name + "-unstable"
   598  	}
   599  	return exe.Name
   600  }
   601  
   602  // ExeConflicts returns the content of the Conflicts field
   603  // for executable packages.
   604  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   605  	if isUnstableBuild(meta.Env) {
   606  		// Set up the conflicts list so that the *-unstable packages
   607  		// cannot be installed alongside the regular version.
   608  		//
   609  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   610  		// is very explicit about Conflicts: and says that Breaks: should
   611  		// be preferred and the conflicting files should be handled via
   612  		// alternates. We might do this eventually but using a conflict is
   613  		// easier now.
   614  		return "ethereum, " + exe.Name
   615  	}
   616  	return ""
   617  }
   618  
   619  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   620  	pkg := meta.Name() + "-" + meta.VersionString()
   621  	pkgdir = filepath.Join(tmpdir, pkg)
   622  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   623  		log.Fatal(err)
   624  	}
   625  
   626  	// Copy the source code.
   627  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   628  
   629  	// Put the debian build files in place.
   630  	debian := filepath.Join(pkgdir, "debian")
   631  	build.Render("build/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   632  	build.Render("build/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   633  	build.Render("build/deb.control", filepath.Join(debian, "control"), 0644, meta)
   634  	build.Render("build/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   635  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   636  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   637  	for _, exe := range meta.Executables {
   638  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   639  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   640  		build.Render("build/deb.install", install, 0644, exe)
   641  		build.Render("build/deb.docs", docs, 0644, exe)
   642  	}
   643  
   644  	return pkgdir
   645  }
   646  
   647  // Windows installer
   648  
   649  func doWindowsInstaller(cmdline []string) {
   650  	// Parse the flags and make skip installer generation on PRs
   651  	var (
   652  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   653  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   654  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   655  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   656  	)
   657  	flag.CommandLine.Parse(cmdline)
   658  	*workdir = makeWorkdir(*workdir)
   659  	env := build.Env()
   660  	maybeSkipArchive(env)
   661  
   662  	// Aggregate binaries that are included in the installer
   663  	var (
   664  		devTools []string
   665  		allTools []string
   666  		gethTool string
   667  	)
   668  	for _, file := range allToolsArchiveFiles {
   669  		if file == "COPYING" { // license, copied later
   670  			continue
   671  		}
   672  		allTools = append(allTools, filepath.Base(file))
   673  		if filepath.Base(file) == "geth.exe" {
   674  			gethTool = file
   675  		} else {
   676  			devTools = append(devTools, file)
   677  		}
   678  	}
   679  
   680  	// Render NSIS scripts: Installer NSIS contains two installer sections,
   681  	// first section contains the geth binary, second section holds the dev tools.
   682  	templateData := map[string]interface{}{
   683  		"License":  "COPYING",
   684  		"Geth":     gethTool,
   685  		"DevTools": devTools,
   686  	}
   687  	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
   688  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
   689  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
   690  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
   691  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
   692  	build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
   693  	build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
   694  
   695  	// Build the installer. This assumes that all the needed files have been previously
   696  	// built (don't mix building and packaging to keep cross compilation complexity to a
   697  	// minimum).
   698  	version := strings.Split(build.VERSION(), ".")
   699  	if env.Commit != "" {
   700  		version[2] += "-" + env.Commit[:8]
   701  	}
   702  	installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, env) + ".exe")
   703  	build.MustRunCommand("makensis.exe",
   704  		"/DOUTPUTFILE="+installer,
   705  		"/DMAJORVERSION="+version[0],
   706  		"/DMINORVERSION="+version[1],
   707  		"/DBUILDVERSION="+version[2],
   708  		"/DARCH="+*arch,
   709  		filepath.Join(*workdir, "geth.nsi"),
   710  	)
   711  
   712  	// Sign and publish installer.
   713  	if err := archiveUpload(installer, *upload, *signer); err != nil {
   714  		log.Fatal(err)
   715  	}
   716  }
   717  
   718  // Android archives
   719  
   720  func doAndroidArchive(cmdline []string) {
   721  	var (
   722  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   723  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
   724  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
   725  		upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
   726  	)
   727  	flag.CommandLine.Parse(cmdline)
   728  	env := build.Env()
   729  
   730  	// Sanity check that the SDK and NDK are installed and set
   731  	if os.Getenv("ANDROID_HOME") == "" {
   732  		log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
   733  	}
   734  	if os.Getenv("ANDROID_NDK") == "" {
   735  		log.Fatal("Please ensure ANDROID_NDK points to your Android NDK")
   736  	}
   737  	// Build the Android archive and Maven resources
   738  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile"))
   739  	build.MustRun(gomobileTool("init", "--ndk", os.Getenv("ANDROID_NDK")))
   740  	build.MustRun(gomobileTool("bind", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
   741  
   742  	if *local {
   743  		// If we're building locally, copy bundle to build dir and skip Maven
   744  		os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
   745  		return
   746  	}
   747  	meta := newMavenMetadata(env)
   748  	build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
   749  
   750  	// Skip Maven deploy and Azure upload for PR builds
   751  	maybeSkipArchive(env)
   752  
   753  	// Sign and upload the archive to Azure
   754  	archive := "geth-" + archiveBasename("android", env) + ".aar"
   755  	os.Rename("geth.aar", archive)
   756  
   757  	if err := archiveUpload(archive, *upload, *signer); err != nil {
   758  		log.Fatal(err)
   759  	}
   760  	// Sign and upload all the artifacts to Maven Central
   761  	os.Rename(archive, meta.Package+".aar")
   762  	if *signer != "" && *deploy != "" {
   763  		// Import the signing key into the local GPG instance
   764  		if b64key := os.Getenv(*signer); b64key != "" {
   765  			key, err := base64.StdEncoding.DecodeString(b64key)
   766  			if err != nil {
   767  				log.Fatalf("invalid base64 %s", *signer)
   768  			}
   769  			gpg := exec.Command("gpg", "--import")
   770  			gpg.Stdin = bytes.NewReader(key)
   771  			build.MustRun(gpg)
   772  		}
   773  		// Upload the artifacts to Sonatype and/or Maven Central
   774  		repo := *deploy + "/service/local/staging/deploy/maven2"
   775  		if meta.Develop {
   776  			repo = *deploy + "/content/repositories/snapshots"
   777  		}
   778  		build.MustRunCommand("mvn", "gpg:sign-and-deploy-file",
   779  			"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
   780  			"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
   781  	}
   782  }
   783  
   784  func gomobileTool(subcmd string, args ...string) *exec.Cmd {
   785  	cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
   786  	cmd.Args = append(cmd.Args, args...)
   787  	cmd.Env = []string{
   788  		"GOPATH=" + build.GOPATH(),
   789  	}
   790  	for _, e := range os.Environ() {
   791  		if strings.HasPrefix(e, "GOPATH=") {
   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"))
   859  	build.MustRun(gomobileTool("init"))
   860  	bind := gomobileTool("bind", "--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  }