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