ci.go 31.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

// +build none

/*
The ci command is called from Continuous Integration scripts.

Z
Zach 已提交
22
Usage: go run build/ci.go <command> <command flags/arguments>
23 24 25

Available commands are:

26
   install    [ -arch architecture ] [ -cc compiler ] [ packages... ]                          -- builds packages and executables
27 28
   test       [ -coverage ] [ packages... ]                                                    -- runs the tests
   lint                                                                                        -- runs certain pre-selected linters
29 30 31 32 33 34 35
   archive    [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -upload dest ] -- archives build artefacts
   importkeys                                                                                  -- imports signing keys from env
   debsrc     [ -signer key-id ] [ -upload dest ]                                              -- creates a debian source package
   nsis                                                                                        -- creates a Windows NSIS installer
   aar        [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ]                      -- creates an Android archive
   xcode      [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ]                      -- creates an iOS XCode framework
   xgo        [ -alltools ] [ options ]                                                        -- cross builds according to options
36
   purge      [ -store blobstore ] [ -days threshold ]                                         -- purges old archives from the blobstore
37 38 39 40 41 42 43

For all commands, -n prevents execution of external programs (dry run mode).

*/
package main

import (
44
	"bufio"
45 46 47 48
	"bytes"
	"encoding/base64"
	"flag"
	"fmt"
49 50
	"go/parser"
	"go/token"
51 52 53 54 55
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
56
	"regexp"
57 58 59 60
	"runtime"
	"strings"
	"time"

61
	"github.com/ethereum/go-ethereum/internal/build"
62 63 64 65 66 67 68 69 70 71 72 73 74
)

var (
	// Files that end up in the geth*.zip archive.
	gethArchiveFiles = []string{
		"COPYING",
		executablePath("geth"),
	}

	// Files that end up in the geth-alltools*.zip archive.
	allToolsArchiveFiles = []string{
		"COPYING",
		executablePath("abigen"),
75
		executablePath("bootnode"),
76 77
		executablePath("evm"),
		executablePath("geth"),
78
		executablePath("puppeth"),
79
		executablePath("rlpdump"),
80
		executablePath("swarm"),
81
		executablePath("wnode"),
82 83 84 85 86
	}

	// A debian package is created for all executables listed here.
	debExecutables = []debExecutable{
		{
87 88
			Name:        "abigen",
			Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
89
		},
90 91 92 93
		{
			Name:        "bootnode",
			Description: "Ethereum bootnode.",
		},
94 95 96 97
		{
			Name:        "evm",
			Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
		},
98
		{
99 100
			Name:        "geth",
			Description: "Ethereum CLI client.",
101
		},
102
		{
103 104 105 106 107 108 109 110 111 112
			Name:        "puppeth",
			Description: "Ethereum private network manager.",
		},
		{
			Name:        "rlpdump",
			Description: "Developer utility tool that prints RLP structures.",
		},
		{
			Name:        "swarm",
			Description: "Ethereum Swarm daemon and tools",
113
		},
114 115 116 117
		{
			Name:        "wnode",
			Description: "Ethereum Whisper diagnostic tool",
		},
118 119 120 121
	}

	// Distros for which packages are created.
	// 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 125
	// Note: zesty is unsupported because it was officially deprecated on lanchpad.
	debDistros = []string{"trusty", "xenial", "artful", "bionic"}
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
)

var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))

func executablePath(name string) string {
	if runtime.GOOS == "windows" {
		name += ".exe"
	}
	return filepath.Join(GOBIN, name)
}

func main() {
	log.SetFlags(log.Lshortfile)

	if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
		log.Fatal("this script must be run from the root of the repository")
	}
	if len(os.Args) < 2 {
		log.Fatal("need subcommand as first argument")
	}
	switch os.Args[1] {
	case "install":
		doInstall(os.Args[2:])
	case "test":
		doTest(os.Args[2:])
151 152
	case "lint":
		doLint(os.Args[2:])
153 154 155 156
	case "archive":
		doArchive(os.Args[2:])
	case "debsrc":
		doDebianSource(os.Args[2:])
157 158
	case "nsis":
		doWindowsInstaller(os.Args[2:])
159 160
	case "aar":
		doAndroidArchive(os.Args[2:])
161 162
	case "xcode":
		doXCodeFramework(os.Args[2:])
163 164
	case "xgo":
		doXgo(os.Args[2:])
165 166
	case "purge":
		doPurge(os.Args[2:])
167 168 169 170 171 172 173 174
	default:
		log.Fatal("unknown command ", os.Args[1])
	}
}

// Compiling

func doInstall(cmdline []string) {
175 176
	var (
		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)
F
Felix Lange 已提交
180
	env := build.Env()
181 182 183

	// Check Go version. People regularly open issues about compilation
	// 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 187 188
		var minor int
		fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)

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 193 194
			log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
			os.Exit(1)
		}
195 196 197 198 199 200
	}
	// Compile packages given as arguments, or everything if there are no arguments.
	packages := []string{"./..."}
	if flag.NArg() > 0 {
		packages = flag.Args()
	}
F
Felix Lange 已提交
201
	packages = build.ExpandPackagesNoVendor(packages)
202

203 204 205 206 207 208 209
	if *arch == "" || *arch == runtime.GOARCH {
		goinstall := goTool("install", buildFlags(env)...)
		goinstall.Args = append(goinstall.Args, "-v")
		goinstall.Args = append(goinstall.Args, packages...)
		build.MustRun(goinstall)
		return
	}
Z
Zoe Nolan 已提交
210
	// If we are cross compiling to ARMv5 ARMv6 or ARMv7, clean any previous builds
211 212 213 214 215 216
	if *arch == "arm" {
		os.RemoveAll(filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_arm"))
		for _, path := range filepath.SplitList(build.GOPATH()) {
			os.RemoveAll(filepath.Join(path, "pkg", runtime.GOOS+"_arm"))
		}
	}
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 222
	goinstall.Args = append(goinstall.Args, packages...)
	build.MustRun(goinstall)
223 224 225 226 227 228 229

	if cmds, err := ioutil.ReadDir("cmd"); err == nil {
		for _, cmd := range cmds {
			pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
			if err != nil {
				log.Fatal(err)
			}
F
Felix Lange 已提交
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 236 237 238 239 240 241
					gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
					build.MustRun(gobuild)
					break
				}
			}
		}
	}
242 243
}

F
Felix Lange 已提交
244
func buildFlags(env build.Environment) (flags []string) {
245
	var ld []string
F
Felix Lange 已提交
246
	if env.Commit != "" {
247 248 249 250 251 252 253 254
		ld = append(ld, "-X", "main.gitCommit="+env.Commit)
	}
	if runtime.GOOS == "darwin" {
		ld = append(ld, "-s")
	}

	if len(ld) > 0 {
		flags = append(flags, "-ldflags", strings.Join(ld, " "))
255 256 257 258 259
	}
	return flags
}

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...)
F
Felix Lange 已提交
265
	cmd.Env = []string{"GOPATH=" + build.GOPATH()}
266 267 268 269 270
	if arch == "" || arch == runtime.GOARCH {
		cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
	} else {
		cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
		cmd.Env = append(cmd.Env, "GOARCH="+arch)
271
	}
272 273 274
	if cc != "" {
		cmd.Env = append(cmd.Env, "CC="+cc)
	}
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	for _, e := range os.Environ() {
		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
			continue
		}
		cmd.Env = append(cmd.Env, e)
	}
	return cmd
}

// Running The Tests
//
// "tests" also includes static analysis tools such as vet.

func doTest(cmdline []string) {
	var (
		coverage = flag.Bool("coverage", false, "Whether to record code coverage")
	)
	flag.CommandLine.Parse(cmdline)
293
	env := build.Env()
294

295 296 297 298
	packages := []string{"./..."}
	if len(flag.CommandLine.Args()) > 0 {
		packages = flag.CommandLine.Args()
	}
F
Felix Lange 已提交
299 300
	packages = build.ExpandPackagesNoVendor(packages)

301
	// Run analysis tools before the tests.
F
Felix Lange 已提交
302
	build.MustRun(goTool("vet", packages...))
303

304
	// Run the actual tests.
305
	gotest := goTool("test", buildFlags(env)...)
F
Felix Lange 已提交
306 307 308
	// Test a single package at a time. CI builders are slow
	// and some tests run into timeouts under load.
	gotest.Args = append(gotest.Args, "-p", "1")
309 310 311
	if *coverage {
		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
	}
312

313 314 315 316
	gotest.Args = append(gotest.Args, packages...)
	build.MustRun(gotest)
}

317 318 319 320 321 322 323
// runs gometalinter on requested packages
func doLint(cmdline []string) {
	flag.CommandLine.Parse(cmdline)

	packages := []string{"./..."}
	if len(flag.CommandLine.Args()) > 0 {
		packages = flag.CommandLine.Args()
324
	}
325
	// Get metalinter and install all supported linters
326 327
	build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
328

329
	// Run fast linters batched together
Z
Zach 已提交
330 331 332 333 334 335 336 337 338
	configs := []string{
		"--vendor",
		"--disable-all",
		"--enable=vet",
		"--enable=gofmt",
		"--enable=misspell",
		"--enable=goconst",
		"--min-occurrences=6", // for goconst
	}
339
	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
340 341

	// Run slow linters one by one
342
	for _, linter := range []string{"unconvert", "gosimple"} {
343
		configs = []string{"--vendor", "--deadline=10m", "--disable-all", "--enable=" + linter}
344
		build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
345
	}
346 347
}

348 349 350 351
// Release Packaging

func doArchive(cmdline []string) {
	var (
352
		arch   = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
353 354 355 356
		atype  = flag.String("type", "zip", "Type of archive to write (zip|tar)")
		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
		ext    string
357 358 359 360 361 362 363 364 365 366
	)
	flag.CommandLine.Parse(cmdline)
	switch *atype {
	case "zip":
		ext = ".zip"
	case "tar":
		ext = ".tar.gz"
	default:
		log.Fatal("unknown archive type: ", atype)
	}
F
Felix Lange 已提交
367

368 369 370 371 372 373
	var (
		env      = build.Env()
		base     = archiveBasename(*arch, env)
		geth     = "geth-" + base + ext
		alltools = "geth-alltools-" + base + ext
	)
F
Felix Lange 已提交
374
	maybeSkipArchive(env)
375
	if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
376 377
		log.Fatal(err)
	}
378
	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
379 380
		log.Fatal(err)
	}
381
	for _, archive := range []string{geth, alltools} {
382 383 384 385
		if err := archiveUpload(archive, *upload, *signer); err != nil {
			log.Fatal(err)
		}
	}
386 387
}

388 389
func archiveBasename(arch string, env build.Environment) string {
	platform := runtime.GOOS + "-" + arch
390 391 392
	if arch == "arm" {
		platform += os.Getenv("GOARM")
	}
393 394 395
	if arch == "android" {
		platform = "android-all"
	}
396 397 398 399 400 401 402 403
	if arch == "ios" {
		platform = "ios-all"
	}
	return platform + "-" + archiveVersion(env)
}

func archiveVersion(env build.Environment) string {
	version := build.VERSION()
404
	if isUnstableBuild(env) {
405
		version += "-unstable"
406
	}
F
Felix Lange 已提交
407
	if env.Commit != "" {
408
		version += "-" + env.Commit[:8]
409
	}
410
	return version
411 412
}

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
func archiveUpload(archive string, blobstore string, signer string) error {
	// If signing was requested, generate the signature files
	if signer != "" {
		pgpkey, err := base64.StdEncoding.DecodeString(os.Getenv(signer))
		if err != nil {
			return fmt.Errorf("invalid base64 %s", signer)
		}
		if err := build.PGPSignFile(archive, archive+".asc", string(pgpkey)); err != nil {
			return err
		}
	}
	// If uploading to Azure was requested, push the archive possibly with its signature
	if blobstore != "" {
		auth := build.AzureBlobstoreConfig{
			Account:   strings.Split(blobstore, "/")[0],
			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
			Container: strings.SplitN(blobstore, "/", 2)[1],
		}
431
		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
432 433 434
			return err
		}
		if signer != "" {
435
			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
436 437 438 439 440 441 442
				return err
			}
		}
	}
	return nil
}

F
Felix Lange 已提交
443 444 445 446 447 448
// skips archiving for some build configurations.
func maybeSkipArchive(env build.Environment) {
	if env.IsPullRequest {
		log.Printf("skipping because this is a PR build")
		os.Exit(0)
	}
449 450 451 452
	if env.IsCronJob {
		log.Printf("skipping because this is a cron job")
		os.Exit(0)
	}
F
Felix Lange 已提交
453
	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
F
Felix Lange 已提交
454 455 456 457 458
		log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
		os.Exit(0)
	}
}

459 460
// Debian Packaging

F
Felix Lange 已提交
461 462 463 464 465 466 467
func doDebianSource(cmdline []string) {
	var (
		signer  = flag.String("signer", "", `Signing key name, also used as package author`)
		upload  = flag.String("upload", "", `Where to upload the source package (usually "ppa:ethereum/ethereum")`)
		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
		now     = time.Now()
	)
468
	flag.CommandLine.Parse(cmdline)
F
Felix Lange 已提交
469 470 471
	*workdir = makeWorkdir(*workdir)
	env := build.Env()
	maybeSkipArchive(env)
472 473 474 475 476 477 478 479 480 481 482 483

	// Import the signing key.
	if b64key := os.Getenv("PPA_SIGNING_KEY"); b64key != "" {
		key, err := base64.StdEncoding.DecodeString(b64key)
		if err != nil {
			log.Fatal("invalid base64 PPA_SIGNING_KEY")
		}
		gpg := exec.Command("gpg", "--import")
		gpg.Stdin = bytes.NewReader(key)
		build.MustRun(gpg)
	}

F
Felix Lange 已提交
484
	// Create the packages.
485
	for _, distro := range debDistros {
F
Felix Lange 已提交
486 487
		meta := newDebMetadata(distro, *signer, env, now)
		pkgdir := stageDebianSource(*workdir, meta)
488 489 490 491 492
		debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc")
		debuild.Dir = pkgdir
		build.MustRun(debuild)

		changes := fmt.Sprintf("%s_%s_source.changes", meta.Name(), meta.VersionString())
F
Felix Lange 已提交
493
		changes = filepath.Join(*workdir, changes)
494 495 496 497 498 499 500 501 502
		if *signer != "" {
			build.MustRunCommand("debsign", changes)
		}
		if *upload != "" {
			build.MustRunCommand("dput", *upload, changes)
		}
	}
}

F
Felix Lange 已提交
503 504 505 506 507
func makeWorkdir(wdflag string) string {
	var err error
	if wdflag != "" {
		err = os.MkdirAll(wdflag, 0744)
	} else {
508
		wdflag, err = ioutil.TempDir("", "geth-build-")
F
Felix Lange 已提交
509 510 511 512 513 514 515 516
	}
	if err != nil {
		log.Fatal(err)
	}
	return wdflag
}

func isUnstableBuild(env build.Environment) bool {
F
Felix Lange 已提交
517
	if env.Tag != "" {
F
Felix Lange 已提交
518 519 520
		return false
	}
	return true
521 522 523
}

type debMetadata struct {
F
Felix Lange 已提交
524 525
	Env build.Environment

526 527 528 529 530
	// go-ethereum version being built. Note that this
	// is not the debian package version. The package version
	// is constructed by VersionString.
	Version string

F
Felix Lange 已提交
531 532 533
	Author       string // "name <email>", also selects signing key
	Distro, Time string
	Executables  []debExecutable
534 535
}

F
Felix Lange 已提交
536 537 538 539 540
type debExecutable struct {
	Name, Description string
}

func newDebMetadata(distro, author string, env build.Environment, t time.Time) debMetadata {
541 542 543 544 545
	if author == "" {
		// No signing key, use default author.
		author = "Ethereum Builds <fjl@ethereum.org>"
	}
	return debMetadata{
F
Felix Lange 已提交
546
		Env:         env,
547 548 549 550 551 552 553 554 555 556 557
		Author:      author,
		Distro:      distro,
		Version:     build.VERSION(),
		Time:        t.Format(time.RFC1123Z),
		Executables: debExecutables,
	}
}

// Name returns the name of the metapackage that depends
// on all executable packages.
func (meta debMetadata) Name() string {
F
Felix Lange 已提交
558
	if isUnstableBuild(meta.Env) {
559 560 561 562 563 564 565 566
		return "ethereum-unstable"
	}
	return "ethereum"
}

// VersionString returns the debian version of the packages.
func (meta debMetadata) VersionString() string {
	vsn := meta.Version
F
Felix Lange 已提交
567 568
	if meta.Env.Buildnum != "" {
		vsn += "+build" + meta.Env.Buildnum
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
	}
	if meta.Distro != "" {
		vsn += "+" + meta.Distro
	}
	return vsn
}

// ExeList returns the list of all executable packages.
func (meta debMetadata) ExeList() string {
	names := make([]string, len(meta.Executables))
	for i, e := range meta.Executables {
		names[i] = meta.ExeName(e)
	}
	return strings.Join(names, ", ")
}

// ExeName returns the package name of an executable package.
func (meta debMetadata) ExeName(exe debExecutable) string {
F
Felix Lange 已提交
587
	if isUnstableBuild(meta.Env) {
588 589 590 591 592 593 594 595
		return exe.Name + "-unstable"
	}
	return exe.Name
}

// ExeConflicts returns the content of the Conflicts field
// for executable packages.
func (meta debMetadata) ExeConflicts(exe debExecutable) string {
F
Felix Lange 已提交
596
	if isUnstableBuild(meta.Env) {
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
		// Set up the conflicts list so that the *-unstable packages
		// cannot be installed alongside the regular version.
		//
		// https://www.debian.org/doc/debian-policy/ch-relationships.html
		// is very explicit about Conflicts: and says that Breaks: should
		// be preferred and the conflicting files should be handled via
		// alternates. We might do this eventually but using a conflict is
		// easier now.
		return "ethereum, " + exe.Name
	}
	return ""
}

func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
	pkg := meta.Name() + "-" + meta.VersionString()
	pkgdir = filepath.Join(tmpdir, pkg)
	if err := os.Mkdir(pkgdir, 0755); err != nil {
		log.Fatal(err)
	}

	// Copy the source code.
	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))

	// Put the debian build files in place.
	debian := filepath.Join(pkgdir, "debian")
	build.Render("build/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
	build.Render("build/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
	build.Render("build/deb.control", filepath.Join(debian, "control"), 0644, meta)
	build.Render("build/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
	for _, exe := range meta.Executables {
F
Felix Lange 已提交
629 630
		install := filepath.Join(debian, meta.ExeName(exe)+".install")
		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
631 632 633 634 635 636
		build.Render("build/deb.install", install, 0644, exe)
		build.Render("build/deb.docs", docs, 0644, exe)
	}

	return pkgdir
}
637

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
// Windows installer

func doWindowsInstaller(cmdline []string) {
	// Parse the flags and make skip installer generation on PRs
	var (
		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
	)
	flag.CommandLine.Parse(cmdline)
	*workdir = makeWorkdir(*workdir)
	env := build.Env()
	maybeSkipArchive(env)

	// Aggregate binaries that are included in the installer
	var (
		devTools []string
		allTools []string
		gethTool string
	)
	for _, file := range allToolsArchiveFiles {
		if file == "COPYING" { // license, copied later
			continue
		}
		allTools = append(allTools, filepath.Base(file))
		if filepath.Base(file) == "geth.exe" {
			gethTool = file
		} else {
			devTools = append(devTools, file)
		}
	}

	// Render NSIS scripts: Installer NSIS contains two installer sections,
	// first section contains the geth binary, second section holds the dev tools.
	templateData := map[string]interface{}{
		"License":  "COPYING",
		"Geth":     gethTool,
		"DevTools": devTools,
	}
	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
681
	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
	build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
	build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)

	// Build the installer. This assumes that all the needed files have been previously
	// built (don't mix building and packaging to keep cross compilation complexity to a
	// minimum).
	version := strings.Split(build.VERSION(), ".")
	if env.Commit != "" {
		version[2] += "-" + env.Commit[:8]
	}
	installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, env) + ".exe")
	build.MustRunCommand("makensis.exe",
		"/DOUTPUTFILE="+installer,
		"/DMAJORVERSION="+version[0],
		"/DMINORVERSION="+version[1],
		"/DBUILDVERSION="+version[2],
		"/DARCH="+*arch,
		filepath.Join(*workdir, "geth.nsi"),
	)

	// Sign and publish installer.
	if err := archiveUpload(installer, *upload, *signer); err != nil {
		log.Fatal(err)
	}
707
}
708 709 710 711 712

// Android archives

func doAndroidArchive(cmdline []string) {
	var (
713
		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
714
		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
715 716
		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
		upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
717 718 719 720
	)
	flag.CommandLine.Parse(cmdline)
	env := build.Env()

721 722 723 724 725 726 727
	// Sanity check that the SDK and NDK are installed and set
	if os.Getenv("ANDROID_HOME") == "" {
		log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
	}
	if os.Getenv("ANDROID_NDK") == "" {
		log.Fatal("Please ensure ANDROID_NDK points to your Android NDK")
	}
728 729
	// Build the Android archive and Maven resources
	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile"))
730
	build.MustRun(gomobileTool("init", "--ndk", os.Getenv("ANDROID_NDK")))
731 732
	build.MustRun(gomobileTool("bind", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))

733 734 735 736 737
	if *local {
		// If we're building locally, copy bundle to build dir and skip Maven
		os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
		return
	}
738
	meta := newMavenMetadata(env)
739
	build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
740 741 742 743

	// Skip Maven deploy and Azure upload for PR builds
	maybeSkipArchive(env)

744 745 746 747 748 749 750
	// Sign and upload the archive to Azure
	archive := "geth-" + archiveBasename("android", env) + ".aar"
	os.Rename("geth.aar", archive)

	if err := archiveUpload(archive, *upload, *signer); err != nil {
		log.Fatal(err)
	}
751
	// Sign and upload all the artifacts to Maven Central
752
	os.Rename(archive, meta.Package+".aar")
753 754 755 756 757 758 759 760 761 762 763 764 765
	if *signer != "" && *deploy != "" {
		// Import the signing key into the local GPG instance
		if b64key := os.Getenv(*signer); b64key != "" {
			key, err := base64.StdEncoding.DecodeString(b64key)
			if err != nil {
				log.Fatalf("invalid base64 %s", *signer)
			}
			gpg := exec.Command("gpg", "--import")
			gpg.Stdin = bytes.NewReader(key)
			build.MustRun(gpg)
		}
		// Upload the artifacts to Sonatype and/or Maven Central
		repo := *deploy + "/service/local/staging/deploy/maven2"
766
		if meta.Develop {
767 768 769 770
			repo = *deploy + "/content/repositories/snapshots"
		}
		build.MustRunCommand("mvn", "gpg:sign-and-deploy-file",
			"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
771
			"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
	}
}

func gomobileTool(subcmd string, args ...string) *exec.Cmd {
	cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
	cmd.Args = append(cmd.Args, args...)
	cmd.Env = []string{
		"GOPATH=" + build.GOPATH(),
	}
	for _, e := range os.Environ() {
		if strings.HasPrefix(e, "GOPATH=") {
			continue
		}
		cmd.Env = append(cmd.Env, e)
	}
	return cmd
}

type mavenMetadata struct {
	Version      string
792 793
	Package      string
	Develop      bool
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
	Contributors []mavenContributor
}

type mavenContributor struct {
	Name  string
	Email string
}

func newMavenMetadata(env build.Environment) mavenMetadata {
	// Collect the list of authors from the repo root
	contribs := []mavenContributor{}
	if authors, err := os.Open("AUTHORS"); err == nil {
		defer authors.Close()

		scanner := bufio.NewScanner(authors)
		for scanner.Scan() {
			// Skip any whitespace from the authors list
			line := strings.TrimSpace(scanner.Text())
			if line == "" || line[0] == '#' {
				continue
			}
			// Split the author and insert as a contributor
P
Péter Szilágyi 已提交
816
			re := regexp.MustCompile("([^<]+) <(.+)>")
817 818 819 820 821 822
			parts := re.FindStringSubmatch(line)
			if len(parts) == 3 {
				contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
			}
		}
	}
823 824 825 826 827
	// Render the version and package strings
	version := build.VERSION()
	if isUnstableBuild(env) {
		version += "-SNAPSHOT"
	}
828
	return mavenMetadata{
829 830 831
		Version:      version,
		Package:      "geth-" + version,
		Develop:      isUnstableBuild(env),
832 833 834 835
		Contributors: contribs,
	}
}

836 837 838 839
// XCode frameworks

func doXCodeFramework(cmdline []string) {
	var (
840
		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
841 842 843 844 845 846 847 848 849
		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
	)
	flag.CommandLine.Parse(cmdline)
	env := build.Env()

	// Build the iOS XCode framework
	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile"))
850
	build.MustRun(gomobileTool("init"))
851
	bind := gomobileTool("bind", "--target", "ios", "--tags", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
852

853 854 855 856 857 858
	if *local {
		// If we're building locally, use the build folder and stop afterwards
		bind.Dir, _ = filepath.Abs(GOBIN)
		build.MustRun(bind)
		return
	}
859 860 861
	archive := "geth-" + archiveBasename("ios", env)
	if err := os.Mkdir(archive, os.ModePerm); err != nil {
		log.Fatal(err)
862
	}
863 864 865 866 867 868 869 870 871 872 873 874 875
	bind.Dir, _ = filepath.Abs(archive)
	build.MustRun(bind)
	build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)

	// Skip CocoaPods deploy and Azure upload for PR builds
	maybeSkipArchive(env)

	// Sign and upload the framework to Azure
	if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
		log.Fatal(err)
	}
	// Prepare and upload a PodSpec to CocoaPods
	if *deploy != "" {
P
Péter Szilágyi 已提交
876
		meta := newPodMetadata(env, archive)
877 878
		build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
		build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
879 880 881 882 883 884
	}
}

type podMetadata struct {
	Version      string
	Commit       string
P
Péter Szilágyi 已提交
885
	Archive      string
886
	Contributors []podContributor
887 888
}

889 890 891 892 893
type podContributor struct {
	Name  string
	Email string
}

P
Péter Szilágyi 已提交
894
func newPodMetadata(env build.Environment, archive string) podMetadata {
895 896 897 898 899 900 901 902 903 904 905 906 907
	// Collect the list of authors from the repo root
	contribs := []podContributor{}
	if authors, err := os.Open("AUTHORS"); err == nil {
		defer authors.Close()

		scanner := bufio.NewScanner(authors)
		for scanner.Scan() {
			// Skip any whitespace from the authors list
			line := strings.TrimSpace(scanner.Text())
			if line == "" || line[0] == '#' {
				continue
			}
			// Split the author and insert as a contributor
P
Péter Szilágyi 已提交
908
			re := regexp.MustCompile("([^<]+) <(.+)>")
909 910 911 912 913 914
			parts := re.FindStringSubmatch(line)
			if len(parts) == 3 {
				contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
			}
		}
	}
915
	version := build.VERSION()
916
	if isUnstableBuild(env) {
917
		version += "-unstable." + env.Buildnum
918 919
	}
	return podMetadata{
P
Péter Szilágyi 已提交
920
		Archive:      archive,
921
		Version:      version,
922 923 924
		Commit:       env.Commit,
		Contributors: contribs,
	}
925 926
}

927 928 929
// Cross compilation

func doXgo(cmdline []string) {
930 931 932
	var (
		alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
	)
F
Felix Lange 已提交
933 934 935
	flag.CommandLine.Parse(cmdline)
	env := build.Env()

936 937 938 939
	// Make sure xgo is available for cross compilation
	gogetxgo := goTool("get", "github.com/karalabe/xgo")
	build.MustRun(gogetxgo)

940 941 942 943
	// If all tools building is requested, build everything the builder wants
	args := append(buildFlags(env), flag.Args()...)

	if *alltools {
944
		args = append(args, []string{"--dest", GOBIN}...)
945 946 947 948 949 950 951 952 953 954 955 956
		for _, res := range allToolsArchiveFiles {
			if strings.HasPrefix(res, GOBIN) {
				// Binary tool found, cross build it explicitly
				args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
				xgo := xgoTool(args)
				build.MustRun(xgo)
				args = args[:len(args)-1]
			}
		}
		return
	}
	// Otherwise xxecute the explicit cross compilation
957 958 959
	path := args[len(args)-1]
	args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)

960
	xgo := xgoTool(args)
F
Felix Lange 已提交
961
	build.MustRun(xgo)
962 963
}

F
Felix Lange 已提交
964
func xgoTool(args []string) *exec.Cmd {
965 966 967 968 969 970 971 972 973 974 975 976 977
	cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
	cmd.Env = []string{
		"GOPATH=" + build.GOPATH(),
		"GOBIN=" + GOBIN,
	}
	for _, e := range os.Environ() {
		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
			continue
		}
		cmd.Env = append(cmd.Env, e)
	}
	return cmd
}
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036

// Binary distribution cleanups

func doPurge(cmdline []string) {
	var (
		store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
		limit = flag.Int("days", 30, `Age threshold above which to delete unstalbe archives`)
	)
	flag.CommandLine.Parse(cmdline)

	if env := build.Env(); !env.IsCronJob {
		log.Printf("skipping because not a cron job")
		os.Exit(0)
	}
	// Create the azure authentication and list the current archives
	auth := build.AzureBlobstoreConfig{
		Account:   strings.Split(*store, "/")[0],
		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
		Container: strings.SplitN(*store, "/", 2)[1],
	}
	blobs, err := build.AzureBlobstoreList(auth)
	if err != nil {
		log.Fatal(err)
	}
	// Iterate over the blobs, collect and sort all unstable builds
	for i := 0; i < len(blobs); i++ {
		if !strings.Contains(blobs[i].Name, "unstable") {
			blobs = append(blobs[:i], blobs[i+1:]...)
			i--
		}
	}
	for i := 0; i < len(blobs); i++ {
		for j := i + 1; j < len(blobs); j++ {
			iTime, err := time.Parse(time.RFC1123, blobs[i].Properties.LastModified)
			if err != nil {
				log.Fatal(err)
			}
			jTime, err := time.Parse(time.RFC1123, blobs[j].Properties.LastModified)
			if err != nil {
				log.Fatal(err)
			}
			if iTime.After(jTime) {
				blobs[i], blobs[j] = blobs[j], blobs[i]
			}
		}
	}
	// Filter out all archives more recent that the given threshold
	for i, blob := range blobs {
		timestamp, _ := time.Parse(time.RFC1123, blob.Properties.LastModified)
		if time.Since(timestamp) < time.Duration(*limit)*24*time.Hour {
			blobs = blobs[:i]
			break
		}
	}
	// Delete all marked as such and return
	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
		log.Fatal(err)
	}
}