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