github.com/phillinzzz/newBsc@v1.1.6/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 ] [ -signify key-envvar ] [ -upload dest ] -- archives build artifacts 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 "io/ioutil" 50 "log" 51 "os" 52 "os/exec" 53 "path" 54 "path/filepath" 55 "regexp" 56 "runtime" 57 "strings" 58 "time" 59 60 "github.com/cespare/cp" 61 "github.com/phillinzzz/newBsc/crypto/signify" 62 "github.com/phillinzzz/newBsc/internal/build" 63 "github.com/phillinzzz/newBsc/params" 64 ) 65 66 var ( 67 // Files that end up in the geth*.zip archive. 68 gethArchiveFiles = []string{ 69 "COPYING", 70 executablePath("geth"), 71 } 72 73 // Files that end up in the geth-alltools*.zip archive. 74 allToolsArchiveFiles = []string{ 75 "COPYING", 76 executablePath("abigen"), 77 executablePath("bootnode"), 78 executablePath("evm"), 79 executablePath("geth"), 80 executablePath("puppeth"), 81 executablePath("rlpdump"), 82 executablePath("clef"), 83 } 84 85 // A debian package is created for all executables listed here. 86 debExecutables = []debExecutable{ 87 { 88 BinaryName: "abigen", 89 Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.", 90 }, 91 { 92 BinaryName: "bootnode", 93 Description: "Ethereum bootnode.", 94 }, 95 { 96 BinaryName: "evm", 97 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 BinaryName: "geth", 101 Description: "Ethereum CLI client.", 102 }, 103 { 104 BinaryName: "puppeth", 105 Description: "Ethereum private network manager.", 106 }, 107 { 108 BinaryName: "rlpdump", 109 Description: "Developer utility tool that prints RLP structures.", 110 }, 111 { 112 BinaryName: "clef", 113 Description: "Ethereum account management tool.", 114 }, 115 } 116 117 // A debian package is created for all executables listed here. 118 debEthereum = debPackage{ 119 Name: "ethereum", 120 Version: params.Version, 121 Executables: debExecutables, 122 } 123 124 // Debian meta packages to build and push to Ubuntu PPA 125 debPackages = []debPackage{ 126 debEthereum, 127 } 128 129 // Distros for which packages are created. 130 // Note: vivid is unsupported because there is no golang-1.6 package for it. 131 // Note: wily is unsupported because it was officially deprecated on Launchpad. 132 // Note: yakkety is unsupported because it was officially deprecated on Launchpad. 133 // Note: zesty is unsupported because it was officially deprecated on Launchpad. 134 // Note: artful is unsupported because it was officially deprecated on Launchpad. 135 // Note: cosmic is unsupported because it was officially deprecated on Launchpad. 136 // Note: disco is unsupported because it was officially deprecated on Launchpad. 137 // Note: eoan is unsupported because it was officially deprecated on Launchpad. 138 debDistroGoBoots = map[string]string{ 139 "trusty": "golang-1.11", 140 "xenial": "golang-go", 141 "bionic": "golang-go", 142 "focal": "golang-go", 143 "groovy": "golang-go", 144 "hirsute": "golang-go", 145 } 146 147 debGoBootPaths = map[string]string{ 148 "golang-1.11": "/usr/lib/go-1.11", 149 "golang-go": "/usr/lib/go", 150 } 151 152 // This is the version of go that will be downloaded by 153 // 154 // go run ci.go install -dlgo 155 dlgoVersion = "1.16.3" 156 ) 157 158 var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin")) 159 160 func executablePath(name string) string { 161 if runtime.GOOS == "windows" { 162 name += ".exe" 163 } 164 return filepath.Join(GOBIN, name) 165 } 166 167 func main() { 168 log.SetFlags(log.Lshortfile) 169 170 if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) { 171 log.Fatal("this script must be run from the root of the repository") 172 } 173 if len(os.Args) < 2 { 174 log.Fatal("need subcommand as first argument") 175 } 176 switch os.Args[1] { 177 case "install": 178 doInstall(os.Args[2:]) 179 case "test": 180 doTest(os.Args[2:]) 181 case "lint": 182 doLint(os.Args[2:]) 183 case "archive": 184 doArchive(os.Args[2:]) 185 case "debsrc": 186 doDebianSource(os.Args[2:]) 187 case "nsis": 188 doWindowsInstaller(os.Args[2:]) 189 case "aar": 190 doAndroidArchive(os.Args[2:]) 191 case "xcode": 192 doXCodeFramework(os.Args[2:]) 193 case "xgo": 194 doXgo(os.Args[2:]) 195 case "purge": 196 doPurge(os.Args[2:]) 197 default: 198 log.Fatal("unknown command ", os.Args[1]) 199 } 200 } 201 202 // Compiling 203 204 func doInstall(cmdline []string) { 205 var ( 206 dlgo = flag.Bool("dlgo", false, "Download Go and build with it") 207 arch = flag.String("arch", "", "Architecture to cross build for") 208 cc = flag.String("cc", "", "C compiler to cross build with") 209 ) 210 flag.CommandLine.Parse(cmdline) 211 212 // Configure the toolchain. 213 tc := build.GoToolchain{GOARCH: *arch, CC: *cc} 214 if *dlgo { 215 csdb := build.MustLoadChecksums("build/checksums.txt") 216 tc.Root = build.DownloadGo(csdb, dlgoVersion) 217 } 218 219 // Configure the build. 220 env := build.Env() 221 gobuild := tc.Go("build", buildFlags(env)...) 222 223 // arm64 CI builders are memory-constrained and can't handle concurrent builds, 224 // better disable it. This check isn't the best, it should probably 225 // check for something in env instead. 226 if env.CI && runtime.GOARCH == "arm64" { 227 gobuild.Args = append(gobuild.Args, "-p", "1") 228 } 229 230 // We use -trimpath to avoid leaking local paths into the built executables. 231 gobuild.Args = append(gobuild.Args, "-trimpath") 232 233 // Show packages during build. 234 gobuild.Args = append(gobuild.Args, "-v") 235 236 // Now we choose what we're even building. 237 // Default: collect all 'main' packages in cmd/ and build those. 238 packages := flag.Args() 239 if len(packages) == 0 { 240 packages = build.FindMainPackages("./cmd") 241 } 242 243 // Do the build! 244 for _, pkg := range packages { 245 args := make([]string, len(gobuild.Args)) 246 copy(args, gobuild.Args) 247 args = append(args, "-o", executablePath(path.Base(pkg))) 248 args = append(args, pkg) 249 build.MustRun(&exec.Cmd{Path: gobuild.Path, Args: args, Env: gobuild.Env}) 250 } 251 } 252 253 // buildFlags returns the go tool flags for building. 254 func buildFlags(env build.Environment) (flags []string) { 255 var ld []string 256 if env.Commit != "" { 257 ld = append(ld, "-X", "main.gitCommit="+env.Commit) 258 ld = append(ld, "-X", "main.gitDate="+env.Date) 259 } 260 // Strip DWARF on darwin. This used to be required for certain things, 261 // and there is no downside to this, so we just keep doing it. 262 if runtime.GOOS == "darwin" { 263 ld = append(ld, "-s") 264 } 265 if len(ld) > 0 { 266 flags = append(flags, "-ldflags", strings.Join(ld, " ")) 267 } 268 return flags 269 } 270 271 // Running The Tests 272 // 273 // "tests" also includes static analysis tools such as vet. 274 275 func doTest(cmdline []string) { 276 var ( 277 dlgo = flag.Bool("dlgo", false, "Download Go and build with it") 278 arch = flag.String("arch", "", "Run tests for given architecture") 279 cc = flag.String("cc", "", "Sets C compiler binary") 280 coverage = flag.Bool("coverage", false, "Whether to record code coverage") 281 verbose = flag.Bool("v", false, "Whether to log verbosely") 282 timeout = flag.String("timeout", "10m", `Timeout of runing tests`) 283 ) 284 flag.CommandLine.Parse(cmdline) 285 286 // Configure the toolchain. 287 tc := build.GoToolchain{GOARCH: *arch, CC: *cc} 288 if *dlgo { 289 csdb := build.MustLoadChecksums("build/checksums.txt") 290 tc.Root = build.DownloadGo(csdb, dlgoVersion) 291 } 292 gotest := tc.Go("test") 293 294 // Test a single package at a time. CI builders are slow 295 // and some tests run into timeouts under load. 296 gotest.Args = append(gotest.Args, "-p", "1") 297 if *coverage { 298 gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover") 299 } 300 if *verbose { 301 gotest.Args = append(gotest.Args, "-v") 302 } 303 if *timeout != "" { 304 gotest.Args = append(gotest.Args, []string{"-timeout", *timeout}...) 305 } 306 307 packages := []string{"./accounts/...", "./common/...", "./consensus/...", "./console/...", "./core/...", 308 "./crypto/...", "./eth/...", "./ethclient/...", "./ethdb/...", "./event/...", "./graphql/...", "./les/...", 309 "./light/...", "./log/...", "./metrics/...", "./miner/...", "./mobile/...", "./node/...", 310 "./p2p/...", "./params/...", "./rlp/...", "./rpc/...", "./tests/...", "./trie/..."} 311 if len(flag.CommandLine.Args()) > 0 { 312 packages = flag.CommandLine.Args() 313 } 314 gotest.Args = append(gotest.Args, packages...) 315 build.MustRun(gotest) 316 } 317 318 // doLint runs golangci-lint on requested packages. 319 func doLint(cmdline []string) { 320 var ( 321 cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.") 322 ) 323 flag.CommandLine.Parse(cmdline) 324 packages := []string{"./..."} 325 if len(flag.CommandLine.Args()) > 0 { 326 packages = flag.CommandLine.Args() 327 } 328 329 linter := downloadLinter(*cachedir) 330 lflags := []string{"run", "--config", ".golangci.yml"} 331 build.MustRunCommand(linter, append(lflags, packages...)...) 332 fmt.Println("You have achieved perfection.") 333 } 334 335 // downloadLinter downloads and unpacks golangci-lint. 336 func downloadLinter(cachedir string) string { 337 const version = "1.39.0" 338 339 csdb := build.MustLoadChecksums("build/checksums.txt") 340 base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, runtime.GOARCH) 341 url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s.tar.gz", version, base) 342 archivePath := filepath.Join(cachedir, base+".tar.gz") 343 if err := csdb.DownloadFile(url, archivePath); err != nil { 344 log.Fatal(err) 345 } 346 if err := build.ExtractArchive(archivePath, cachedir); err != nil { 347 log.Fatal(err) 348 } 349 return filepath.Join(cachedir, base, "golangci-lint") 350 } 351 352 // Release Packaging 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 signify = flag.String("signify", "", `Environment variable holding the signify key (e.g. LINUX_SIGNIFY_KEY)`) 359 upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`) 360 ext string 361 ) 362 flag.CommandLine.Parse(cmdline) 363 switch *atype { 364 case "zip": 365 ext = ".zip" 366 case "tar": 367 ext = ".tar.gz" 368 default: 369 log.Fatal("unknown archive type: ", atype) 370 } 371 372 var ( 373 env = build.Env() 374 basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit)) 375 geth = "geth-" + basegeth + ext 376 alltools = "geth-alltools-" + basegeth + ext 377 ) 378 maybeSkipArchive(env) 379 if err := build.WriteArchive(geth, gethArchiveFiles); err != nil { 380 log.Fatal(err) 381 } 382 if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil { 383 log.Fatal(err) 384 } 385 for _, archive := range []string{geth, alltools} { 386 if err := archiveUpload(archive, *upload, *signer, *signify); err != nil { 387 log.Fatal(err) 388 } 389 } 390 } 391 392 func archiveBasename(arch string, archiveVersion string) string { 393 platform := runtime.GOOS + "-" + arch 394 if arch == "arm" { 395 platform += os.Getenv("GOARM") 396 } 397 if arch == "android" { 398 platform = "android-all" 399 } 400 if arch == "ios" { 401 platform = "ios-all" 402 } 403 return platform + "-" + archiveVersion 404 } 405 406 func archiveUpload(archive string, blobstore string, signer string, signifyVar string) error { 407 // If signing was requested, generate the signature files 408 if signer != "" { 409 key := getenvBase64(signer) 410 if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil { 411 return err 412 } 413 } 414 if signifyVar != "" { 415 key := os.Getenv(signifyVar) 416 untrustedComment := "verify with geth-release.pub" 417 trustedComment := fmt.Sprintf("%s (%s)", archive, time.Now().UTC().Format(time.RFC1123)) 418 if err := signify.SignFile(archive, archive+".sig", key, untrustedComment, trustedComment); err != nil { 419 return err 420 } 421 } 422 // If uploading to Azure was requested, push the archive possibly with its signature 423 if blobstore != "" { 424 auth := build.AzureBlobstoreConfig{ 425 Account: strings.Split(blobstore, "/")[0], 426 Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"), 427 Container: strings.SplitN(blobstore, "/", 2)[1], 428 } 429 if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil { 430 return err 431 } 432 if signer != "" { 433 if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil { 434 return err 435 } 436 } 437 if signifyVar != "" { 438 if err := build.AzureBlobstoreUpload(archive+".sig", filepath.Base(archive+".sig"), 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 archive creation because this is a PR build") 450 os.Exit(0) 451 } 452 if env.IsCronJob { 453 log.Printf("skipping archive creation 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 archive creation 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 func doDebianSource(cmdline []string) { 464 var ( 465 cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`) 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 "ethereum/ethereum")`) 468 sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`) 469 workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`) 470 now = time.Now() 471 ) 472 flag.CommandLine.Parse(cmdline) 473 *workdir = makeWorkdir(*workdir) 474 env := build.Env() 475 tc := new(build.GoToolchain) 476 maybeSkipArchive(env) 477 478 // Import the signing key. 479 if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 { 480 gpg := exec.Command("gpg", "--import") 481 gpg.Stdin = bytes.NewReader(key) 482 build.MustRun(gpg) 483 } 484 485 // Download and verify the Go source package. 486 gobundle := downloadGoSources(*cachedir) 487 488 // Download all the dependencies needed to build the sources and run the ci script 489 srcdepfetch := tc.Go("mod", "download") 490 srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath")) 491 build.MustRun(srcdepfetch) 492 493 cidepfetch := tc.Go("run", "./build/ci.go") 494 cidepfetch.Env = append(cidepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath")) 495 cidepfetch.Run() // Command fails, don't care, we only need the deps to start it 496 497 // Create Debian packages and upload them. 498 for _, pkg := range debPackages { 499 for distro, goboot := range debDistroGoBoots { 500 // Prepare the debian package with the go-ethereum sources. 501 meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables) 502 pkgdir := stageDebianSource(*workdir, meta) 503 504 // Add Go source code 505 if err := build.ExtractArchive(gobundle, pkgdir); err != nil { 506 log.Fatalf("Failed to extract Go sources: %v", err) 507 } 508 if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil { 509 log.Fatalf("Failed to rename Go source folder: %v", err) 510 } 511 // Add all dependency modules in compressed form 512 os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755) 513 if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil { 514 log.Fatalf("Failed to copy Go module dependencies: %v", err) 515 } 516 // Run the packaging and upload to the PPA 517 debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc") 518 debuild.Dir = pkgdir 519 build.MustRun(debuild) 520 521 var ( 522 basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString()) 523 source = filepath.Join(*workdir, basename+".tar.xz") 524 dsc = filepath.Join(*workdir, basename+".dsc") 525 changes = filepath.Join(*workdir, basename+"_source.changes") 526 buildinfo = filepath.Join(*workdir, basename+"_source.buildinfo") 527 ) 528 if *signer != "" { 529 build.MustRunCommand("debsign", changes) 530 } 531 if *upload != "" { 532 ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes, buildinfo}) 533 } 534 } 535 } 536 } 537 538 // downloadGoSources downloads the Go source tarball. 539 func downloadGoSources(cachedir string) string { 540 csdb := build.MustLoadChecksums("build/checksums.txt") 541 file := fmt.Sprintf("go%s.src.tar.gz", dlgoVersion) 542 url := "https://dl.google.com/go/" + file 543 dst := filepath.Join(cachedir, file) 544 if err := csdb.DownloadFile(url, dst); err != nil { 545 log.Fatal(err) 546 } 547 return dst 548 } 549 550 func ppaUpload(workdir, ppa, sshUser string, files []string) { 551 p := strings.Split(ppa, "/") 552 if len(p) != 2 { 553 log.Fatal("-upload PPA name must contain single /") 554 } 555 if sshUser == "" { 556 sshUser = p[0] 557 } 558 incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1]) 559 // Create the SSH identity file if it doesn't exist. 560 var idfile string 561 if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 { 562 idfile = filepath.Join(workdir, "sshkey") 563 if _, err := os.Stat(idfile); os.IsNotExist(err) { 564 ioutil.WriteFile(idfile, sshkey, 0600) 565 } 566 } 567 // Upload 568 dest := sshUser + "@ppa.launchpad.net" 569 if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil { 570 log.Fatal(err) 571 } 572 } 573 574 func getenvBase64(variable string) []byte { 575 dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable)) 576 if err != nil { 577 log.Fatal("invalid base64 " + variable) 578 } 579 return []byte(dec) 580 } 581 582 func makeWorkdir(wdflag string) string { 583 var err error 584 if wdflag != "" { 585 err = os.MkdirAll(wdflag, 0744) 586 } else { 587 wdflag, err = ioutil.TempDir("", "geth-build-") 588 } 589 if err != nil { 590 log.Fatal(err) 591 } 592 return wdflag 593 } 594 595 func isUnstableBuild(env build.Environment) bool { 596 if env.Tag != "" { 597 return false 598 } 599 return true 600 } 601 602 type debPackage struct { 603 Name string // the name of the Debian package to produce, e.g. "ethereum" 604 Version string // the clean version of the debPackage, e.g. 1.8.12, without any metadata 605 Executables []debExecutable // executables to be included in the package 606 } 607 608 type debMetadata struct { 609 Env build.Environment 610 GoBootPackage string 611 GoBootPath string 612 613 PackageName string 614 615 // go-ethereum version being built. Note that this 616 // is not the debian package version. The package version 617 // is constructed by VersionString. 618 Version string 619 620 Author string // "name <email>", also selects signing key 621 Distro, Time string 622 Executables []debExecutable 623 } 624 625 type debExecutable struct { 626 PackageName string 627 BinaryName string 628 Description string 629 } 630 631 // Package returns the name of the package if present, or 632 // fallbacks to BinaryName 633 func (d debExecutable) Package() string { 634 if d.PackageName != "" { 635 return d.PackageName 636 } 637 return d.BinaryName 638 } 639 640 func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata { 641 if author == "" { 642 // No signing key, use default author. 643 author = "Ethereum Builds <fjl@ethereum.org>" 644 } 645 return debMetadata{ 646 GoBootPackage: goboot, 647 GoBootPath: debGoBootPaths[goboot], 648 PackageName: name, 649 Env: env, 650 Author: author, 651 Distro: distro, 652 Version: version, 653 Time: t.Format(time.RFC1123Z), 654 Executables: exes, 655 } 656 } 657 658 // Name returns the name of the metapackage that depends 659 // on all executable packages. 660 func (meta debMetadata) Name() string { 661 if isUnstableBuild(meta.Env) { 662 return meta.PackageName + "-unstable" 663 } 664 return meta.PackageName 665 } 666 667 // VersionString returns the debian version of the packages. 668 func (meta debMetadata) VersionString() string { 669 vsn := meta.Version 670 if meta.Env.Buildnum != "" { 671 vsn += "+build" + meta.Env.Buildnum 672 } 673 if meta.Distro != "" { 674 vsn += "+" + meta.Distro 675 } 676 return vsn 677 } 678 679 // ExeList returns the list of all executable packages. 680 func (meta debMetadata) ExeList() string { 681 names := make([]string, len(meta.Executables)) 682 for i, e := range meta.Executables { 683 names[i] = meta.ExeName(e) 684 } 685 return strings.Join(names, ", ") 686 } 687 688 // ExeName returns the package name of an executable package. 689 func (meta debMetadata) ExeName(exe debExecutable) string { 690 if isUnstableBuild(meta.Env) { 691 return exe.Package() + "-unstable" 692 } 693 return exe.Package() 694 } 695 696 // ExeConflicts returns the content of the Conflicts field 697 // for executable packages. 698 func (meta debMetadata) ExeConflicts(exe debExecutable) string { 699 if isUnstableBuild(meta.Env) { 700 // Set up the conflicts list so that the *-unstable packages 701 // cannot be installed alongside the regular version. 702 // 703 // https://www.debian.org/doc/debian-policy/ch-relationships.html 704 // is very explicit about Conflicts: and says that Breaks: should 705 // be preferred and the conflicting files should be handled via 706 // alternates. We might do this eventually but using a conflict is 707 // easier now. 708 return "ethereum, " + exe.Package() 709 } 710 return "" 711 } 712 713 func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) { 714 pkg := meta.Name() + "-" + meta.VersionString() 715 pkgdir = filepath.Join(tmpdir, pkg) 716 if err := os.Mkdir(pkgdir, 0755); err != nil { 717 log.Fatal(err) 718 } 719 // Copy the source code. 720 build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator)) 721 722 // Put the debian build files in place. 723 debian := filepath.Join(pkgdir, "debian") 724 build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta) 725 build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta) 726 build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta) 727 build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta) 728 build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta) 729 build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta) 730 for _, exe := range meta.Executables { 731 install := filepath.Join(debian, meta.ExeName(exe)+".install") 732 docs := filepath.Join(debian, meta.ExeName(exe)+".docs") 733 build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe) 734 build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe) 735 } 736 return pkgdir 737 } 738 739 // Windows installer 740 func doWindowsInstaller(cmdline []string) { 741 // Parse the flags and make skip installer generation on PRs 742 var ( 743 arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging") 744 signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`) 745 signify = flag.String("signify key", "", `Environment variable holding the signify signing key (e.g. WINDOWS_SIGNIFY_KEY)`) 746 upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`) 747 workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`) 748 ) 749 flag.CommandLine.Parse(cmdline) 750 *workdir = makeWorkdir(*workdir) 751 env := build.Env() 752 maybeSkipArchive(env) 753 754 // Aggregate binaries that are included in the installer 755 var ( 756 devTools []string 757 allTools []string 758 gethTool string 759 ) 760 for _, file := range allToolsArchiveFiles { 761 if file == "COPYING" { // license, copied later 762 continue 763 } 764 allTools = append(allTools, filepath.Base(file)) 765 if filepath.Base(file) == "geth.exe" { 766 gethTool = file 767 } else { 768 devTools = append(devTools, file) 769 } 770 } 771 772 // Render NSIS scripts: Installer NSIS contains two installer sections, 773 // first section contains the geth binary, second section holds the dev tools. 774 templateData := map[string]interface{}{ 775 "License": "COPYING", 776 "Geth": gethTool, 777 "DevTools": devTools, 778 } 779 build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil) 780 build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData) 781 build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools) 782 build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil) 783 build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil) 784 if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil { 785 log.Fatal("Failed to copy SimpleFC.dll: %v", err) 786 } 787 if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil { 788 log.Fatal("Failed to copy copyright note: %v", err) 789 } 790 // Build the installer. This assumes that all the needed files have been previously 791 // built (don't mix building and packaging to keep cross compilation complexity to a 792 // minimum). 793 version := strings.Split(params.Version, ".") 794 if env.Commit != "" { 795 version[2] += "-" + env.Commit[:8] 796 } 797 installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe") 798 build.MustRunCommand("makensis.exe", 799 "/DOUTPUTFILE="+installer, 800 "/DMAJORVERSION="+version[0], 801 "/DMINORVERSION="+version[1], 802 "/DBUILDVERSION="+version[2], 803 "/DARCH="+*arch, 804 filepath.Join(*workdir, "geth.nsi"), 805 ) 806 // Sign and publish installer. 807 if err := archiveUpload(installer, *upload, *signer, *signify); err != nil { 808 log.Fatal(err) 809 } 810 } 811 812 // Android archives 813 814 func doAndroidArchive(cmdline []string) { 815 var ( 816 local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`) 817 signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`) 818 signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. ANDROID_SIGNIFY_KEY)`) 819 deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`) 820 upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`) 821 ) 822 flag.CommandLine.Parse(cmdline) 823 env := build.Env() 824 tc := new(build.GoToolchain) 825 826 // Sanity check that the SDK and NDK are installed and set 827 if os.Getenv("ANDROID_HOME") == "" { 828 log.Fatal("Please ensure ANDROID_HOME points to your Android SDK") 829 } 830 831 // Build gomobile. 832 install := tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest") 833 install.Env = append(install.Env) 834 build.MustRun(install) 835 836 // Ensure all dependencies are available. This is required to make 837 // gomobile bind work because it expects go.sum to contain all checksums. 838 build.MustRun(tc.Go("mod", "download")) 839 840 // Build the Android archive and Maven resources 841 build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/phillinzzz/newBsc/mobile")) 842 843 if *local { 844 // If we're building locally, copy bundle to build dir and skip Maven 845 os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar")) 846 os.Rename("geth-sources.jar", filepath.Join(GOBIN, "geth-sources.jar")) 847 return 848 } 849 meta := newMavenMetadata(env) 850 build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta) 851 852 // Skip Maven deploy and Azure upload for PR builds 853 maybeSkipArchive(env) 854 855 // Sign and upload the archive to Azure 856 archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar" 857 os.Rename("geth.aar", archive) 858 859 if err := archiveUpload(archive, *upload, *signer, *signify); err != nil { 860 log.Fatal(err) 861 } 862 // Sign and upload all the artifacts to Maven Central 863 os.Rename(archive, meta.Package+".aar") 864 if *signer != "" && *deploy != "" { 865 // Import the signing key into the local GPG instance 866 key := getenvBase64(*signer) 867 gpg := exec.Command("gpg", "--import") 868 gpg.Stdin = bytes.NewReader(key) 869 build.MustRun(gpg) 870 keyID, err := build.PGPKeyID(string(key)) 871 if err != nil { 872 log.Fatal(err) 873 } 874 // Upload the artifacts to Sonatype and/or Maven Central 875 repo := *deploy + "/service/local/staging/deploy/maven2" 876 if meta.Develop { 877 repo = *deploy + "/content/repositories/snapshots" 878 } 879 build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X", 880 "-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh", 881 "-Dgpg.keyname="+keyID, 882 "-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar") 883 } 884 } 885 886 func gomobileTool(subcmd string, args ...string) *exec.Cmd { 887 cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd) 888 cmd.Args = append(cmd.Args, args...) 889 cmd.Env = []string{ 890 "PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"), 891 } 892 for _, e := range os.Environ() { 893 if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") || strings.HasPrefix(e, "GOBIN=") { 894 continue 895 } 896 cmd.Env = append(cmd.Env, e) 897 } 898 cmd.Env = append(cmd.Env, "GOBIN="+GOBIN) 899 return cmd 900 } 901 902 type mavenMetadata struct { 903 Version string 904 Package string 905 Develop bool 906 Contributors []mavenContributor 907 } 908 909 type mavenContributor struct { 910 Name string 911 Email string 912 } 913 914 func newMavenMetadata(env build.Environment) mavenMetadata { 915 // Collect the list of authors from the repo root 916 contribs := []mavenContributor{} 917 if authors, err := os.Open("AUTHORS"); err == nil { 918 defer authors.Close() 919 920 scanner := bufio.NewScanner(authors) 921 for scanner.Scan() { 922 // Skip any whitespace from the authors list 923 line := strings.TrimSpace(scanner.Text()) 924 if line == "" || line[0] == '#' { 925 continue 926 } 927 // Split the author and insert as a contributor 928 re := regexp.MustCompile("([^<]+) <(.+)>") 929 parts := re.FindStringSubmatch(line) 930 if len(parts) == 3 { 931 contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]}) 932 } 933 } 934 } 935 // Render the version and package strings 936 version := params.Version 937 if isUnstableBuild(env) { 938 version += "-SNAPSHOT" 939 } 940 return mavenMetadata{ 941 Version: version, 942 Package: "geth-" + version, 943 Develop: isUnstableBuild(env), 944 Contributors: contribs, 945 } 946 } 947 948 // XCode frameworks 949 950 func doXCodeFramework(cmdline []string) { 951 var ( 952 local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`) 953 signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`) 954 signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. IOS_SIGNIFY_KEY)`) 955 deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`) 956 upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`) 957 ) 958 flag.CommandLine.Parse(cmdline) 959 env := build.Env() 960 tc := new(build.GoToolchain) 961 962 // Build gomobile. 963 build.MustRun(tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest")) 964 965 // Ensure all dependencies are available. This is required to make 966 // gomobile bind work because it expects go.sum to contain all checksums. 967 build.MustRun(tc.Go("mod", "download")) 968 969 // Build the iOS XCode framework 970 bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/phillinzzz/newBsc/mobile") 971 972 if *local { 973 // If we're building locally, use the build folder and stop afterwards 974 bind.Dir = GOBIN 975 build.MustRun(bind) 976 return 977 } 978 979 // Create the archive. 980 maybeSkipArchive(env) 981 archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit)) 982 if err := os.MkdirAll(archive, 0755); err != nil { 983 log.Fatal(err) 984 } 985 bind.Dir, _ = filepath.Abs(archive) 986 build.MustRun(bind) 987 build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive) 988 989 // Sign and upload the framework to Azure 990 if err := archiveUpload(archive+".tar.gz", *upload, *signer, *signify); err != nil { 991 log.Fatal(err) 992 } 993 // Prepare and upload a PodSpec to CocoaPods 994 if *deploy != "" { 995 meta := newPodMetadata(env, archive) 996 build.Render("build/pod.podspec", "Geth.podspec", 0755, meta) 997 build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings") 998 } 999 } 1000 1001 type podMetadata struct { 1002 Version string 1003 Commit string 1004 Archive string 1005 Contributors []podContributor 1006 } 1007 1008 type podContributor struct { 1009 Name string 1010 Email string 1011 } 1012 1013 func newPodMetadata(env build.Environment, archive string) podMetadata { 1014 // Collect the list of authors from the repo root 1015 contribs := []podContributor{} 1016 if authors, err := os.Open("AUTHORS"); err == nil { 1017 defer authors.Close() 1018 1019 scanner := bufio.NewScanner(authors) 1020 for scanner.Scan() { 1021 // Skip any whitespace from the authors list 1022 line := strings.TrimSpace(scanner.Text()) 1023 if line == "" || line[0] == '#' { 1024 continue 1025 } 1026 // Split the author and insert as a contributor 1027 re := regexp.MustCompile("([^<]+) <(.+)>") 1028 parts := re.FindStringSubmatch(line) 1029 if len(parts) == 3 { 1030 contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]}) 1031 } 1032 } 1033 } 1034 version := params.Version 1035 if isUnstableBuild(env) { 1036 version += "-unstable." + env.Buildnum 1037 } 1038 return podMetadata{ 1039 Archive: archive, 1040 Version: version, 1041 Commit: env.Commit, 1042 Contributors: contribs, 1043 } 1044 } 1045 1046 // Cross compilation 1047 1048 func doXgo(cmdline []string) { 1049 var ( 1050 alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`) 1051 ) 1052 flag.CommandLine.Parse(cmdline) 1053 env := build.Env() 1054 var tc build.GoToolchain 1055 1056 // Make sure xgo is available for cross compilation 1057 build.MustRun(tc.Install(GOBIN, "github.com/karalabe/xgo@latest")) 1058 1059 // If all tools building is requested, build everything the builder wants 1060 args := append(buildFlags(env), flag.Args()...) 1061 1062 if *alltools { 1063 args = append(args, []string{"--dest", GOBIN}...) 1064 for _, res := range allToolsArchiveFiles { 1065 if strings.HasPrefix(res, GOBIN) { 1066 // Binary tool found, cross build it explicitly 1067 args = append(args, "./"+filepath.Join("cmd", filepath.Base(res))) 1068 build.MustRun(xgoTool(args)) 1069 args = args[:len(args)-1] 1070 } 1071 } 1072 return 1073 } 1074 1075 // Otherwise execute the explicit cross compilation 1076 path := args[len(args)-1] 1077 args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...) 1078 build.MustRun(xgoTool(args)) 1079 } 1080 1081 func xgoTool(args []string) *exec.Cmd { 1082 cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...) 1083 cmd.Env = os.Environ() 1084 cmd.Env = append(cmd.Env, []string{"GOBIN=" + GOBIN}...) 1085 return cmd 1086 } 1087 1088 // Binary distribution cleanups 1089 1090 func doPurge(cmdline []string) { 1091 var ( 1092 store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`) 1093 limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`) 1094 ) 1095 flag.CommandLine.Parse(cmdline) 1096 1097 if env := build.Env(); !env.IsCronJob { 1098 log.Printf("skipping because not a cron job") 1099 os.Exit(0) 1100 } 1101 // Create the azure authentication and list the current archives 1102 auth := build.AzureBlobstoreConfig{ 1103 Account: strings.Split(*store, "/")[0], 1104 Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"), 1105 Container: strings.SplitN(*store, "/", 2)[1], 1106 } 1107 blobs, err := build.AzureBlobstoreList(auth) 1108 if err != nil { 1109 log.Fatal(err) 1110 } 1111 fmt.Printf("Found %d blobs\n", len(blobs)) 1112 1113 // Iterate over the blobs, collect and sort all unstable builds 1114 for i := 0; i < len(blobs); i++ { 1115 if !strings.Contains(blobs[i].Name, "unstable") { 1116 blobs = append(blobs[:i], blobs[i+1:]...) 1117 i-- 1118 } 1119 } 1120 for i := 0; i < len(blobs); i++ { 1121 for j := i + 1; j < len(blobs); j++ { 1122 if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) { 1123 blobs[i], blobs[j] = blobs[j], blobs[i] 1124 } 1125 } 1126 } 1127 // Filter out all archives more recent that the given threshold 1128 for i, blob := range blobs { 1129 if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour { 1130 blobs = blobs[:i] 1131 break 1132 } 1133 } 1134 fmt.Printf("Deleting %d blobs\n", len(blobs)) 1135 // Delete all marked as such and return 1136 if err := build.AzureBlobstoreDelete(auth, blobs); err != nil { 1137 log.Fatal(err) 1138 } 1139 }