ci.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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. // +build none
  17. /*
  18. The ci command is called from Continuous Integration scripts.
  19. Usage: go run ci.go <command> <command flags/arguments>
  20. Available commands are:
  21. install [ -arch architecture ] [ packages... ] -- builds packages and executables
  22. test [ -coverage ] [ -misspell ] [ packages... ] -- runs the tests
  23. archive [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -upload dest ] -- archives build artefacts
  24. importkeys -- imports signing keys from env
  25. debsrc [ -signer key-id ] [ -upload dest ] -- creates a debian source package
  26. nsis -- creates a Windows NSIS installer
  27. aar [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ] -- creates an Android archive
  28. xcode [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ] -- creates an iOS XCode framework
  29. xgo [ -alltools ] [ options ] -- cross builds according to options
  30. For all commands, -n prevents execution of external programs (dry run mode).
  31. */
  32. package main
  33. import (
  34. "bufio"
  35. "bytes"
  36. "encoding/base64"
  37. "flag"
  38. "fmt"
  39. "go/parser"
  40. "go/token"
  41. "io/ioutil"
  42. "log"
  43. "os"
  44. "os/exec"
  45. "path/filepath"
  46. "regexp"
  47. "runtime"
  48. "strings"
  49. "time"
  50. "github.com/ethereum/go-ethereum/internal/build"
  51. )
  52. var (
  53. // Files that end up in the geth*.zip archive.
  54. gethArchiveFiles = []string{
  55. "COPYING",
  56. executablePath("geth"),
  57. }
  58. // Files that end up in the geth-alltools*.zip archive.
  59. allToolsArchiveFiles = []string{
  60. "COPYING",
  61. executablePath("abigen"),
  62. executablePath("bootnode"),
  63. executablePath("evm"),
  64. executablePath("geth"),
  65. executablePath("swarm"),
  66. executablePath("rlpdump"),
  67. }
  68. // A debian package is created for all executables listed here.
  69. debExecutables = []debExecutable{
  70. {
  71. Name: "geth",
  72. Description: "Ethereum CLI client.",
  73. },
  74. {
  75. Name: "bootnode",
  76. Description: "Ethereum bootnode.",
  77. },
  78. {
  79. Name: "rlpdump",
  80. Description: "Developer utility tool that prints RLP structures.",
  81. },
  82. {
  83. Name: "evm",
  84. Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
  85. },
  86. {
  87. Name: "swarm",
  88. Description: "Ethereum Swarm daemon and tools",
  89. },
  90. {
  91. Name: "abigen",
  92. Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
  93. },
  94. }
  95. // Distros for which packages are created.
  96. // Note: vivid is unsupported because there is no golang-1.6 package for it.
  97. // Note: wily is unsupported because it was officially deprecated on lanchpad.
  98. debDistros = []string{"trusty", "xenial", "yakkety"}
  99. )
  100. var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
  101. func executablePath(name string) string {
  102. if runtime.GOOS == "windows" {
  103. name += ".exe"
  104. }
  105. return filepath.Join(GOBIN, name)
  106. }
  107. func main() {
  108. log.SetFlags(log.Lshortfile)
  109. if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
  110. log.Fatal("this script must be run from the root of the repository")
  111. }
  112. if len(os.Args) < 2 {
  113. log.Fatal("need subcommand as first argument")
  114. }
  115. switch os.Args[1] {
  116. case "install":
  117. doInstall(os.Args[2:])
  118. case "test":
  119. doTest(os.Args[2:])
  120. case "archive":
  121. doArchive(os.Args[2:])
  122. case "debsrc":
  123. doDebianSource(os.Args[2:])
  124. case "nsis":
  125. doWindowsInstaller(os.Args[2:])
  126. case "aar":
  127. doAndroidArchive(os.Args[2:])
  128. case "xcode":
  129. doXCodeFramework(os.Args[2:])
  130. case "xgo":
  131. doXgo(os.Args[2:])
  132. default:
  133. log.Fatal("unknown command ", os.Args[1])
  134. }
  135. }
  136. // Compiling
  137. func doInstall(cmdline []string) {
  138. var (
  139. arch = flag.String("arch", "", "Architecture to cross build for")
  140. )
  141. flag.CommandLine.Parse(cmdline)
  142. env := build.Env()
  143. // Check Go version. People regularly open issues about compilation
  144. // failure with outdated Go. This should save them the trouble.
  145. if runtime.Version() < "go1.7" && !strings.HasPrefix(runtime.Version(), "devel") {
  146. log.Println("You have Go version", runtime.Version())
  147. log.Println("go-ethereum requires at least Go version 1.7 and cannot")
  148. log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
  149. os.Exit(1)
  150. }
  151. // Compile packages given as arguments, or everything if there are no arguments.
  152. packages := []string{"./..."}
  153. if flag.NArg() > 0 {
  154. packages = flag.Args()
  155. }
  156. packages = build.ExpandPackagesNoVendor(packages)
  157. if *arch == "" || *arch == runtime.GOARCH {
  158. goinstall := goTool("install", buildFlags(env)...)
  159. goinstall.Args = append(goinstall.Args, "-v")
  160. goinstall.Args = append(goinstall.Args, packages...)
  161. build.MustRun(goinstall)
  162. return
  163. }
  164. // If we are cross compiling to ARMv5 ARMv6 or ARMv7, clean any prvious builds
  165. if *arch == "arm" {
  166. os.RemoveAll(filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_arm"))
  167. for _, path := range filepath.SplitList(build.GOPATH()) {
  168. os.RemoveAll(filepath.Join(path, "pkg", runtime.GOOS+"_arm"))
  169. }
  170. }
  171. // Seems we are cross compiling, work around forbidden GOBIN
  172. goinstall := goToolArch(*arch, "install", buildFlags(env)...)
  173. goinstall.Args = append(goinstall.Args, "-v")
  174. goinstall.Args = append(goinstall.Args, []string{"-buildmode", "archive"}...)
  175. goinstall.Args = append(goinstall.Args, packages...)
  176. build.MustRun(goinstall)
  177. if cmds, err := ioutil.ReadDir("cmd"); err == nil {
  178. for _, cmd := range cmds {
  179. pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
  180. if err != nil {
  181. log.Fatal(err)
  182. }
  183. for name := range pkgs {
  184. if name == "main" {
  185. gobuild := goToolArch(*arch, "build", buildFlags(env)...)
  186. gobuild.Args = append(gobuild.Args, "-v")
  187. gobuild.Args = append(gobuild.Args, []string{"-o", executablePath(cmd.Name())}...)
  188. gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
  189. build.MustRun(gobuild)
  190. break
  191. }
  192. }
  193. }
  194. }
  195. }
  196. func buildFlags(env build.Environment) (flags []string) {
  197. // Set gitCommit constant via link-time assignment.
  198. if env.Commit != "" {
  199. flags = append(flags, "-ldflags", "-X main.gitCommit="+env.Commit)
  200. }
  201. return flags
  202. }
  203. func goTool(subcmd string, args ...string) *exec.Cmd {
  204. return goToolArch(runtime.GOARCH, subcmd, args...)
  205. }
  206. func goToolArch(arch string, subcmd string, args ...string) *exec.Cmd {
  207. gocmd := filepath.Join(runtime.GOROOT(), "bin", "go")
  208. cmd := exec.Command(gocmd, subcmd)
  209. cmd.Args = append(cmd.Args, args...)
  210. if subcmd == "build" || subcmd == "install" || subcmd == "test" {
  211. // Go CGO has a Windows linker error prior to 1.8 (https://github.com/golang/go/issues/8756).
  212. // Work around issue by allowing multiple definitions for <1.8 builds.
  213. if runtime.GOOS == "windows" && runtime.Version() < "go1.8" {
  214. cmd.Args = append(cmd.Args, []string{"-ldflags", "-extldflags -Wl,--allow-multiple-definition"}...)
  215. }
  216. }
  217. cmd.Env = []string{"GOPATH=" + build.GOPATH()}
  218. if arch == "" || arch == runtime.GOARCH {
  219. cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  220. } else {
  221. cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
  222. cmd.Env = append(cmd.Env, "GOARCH="+arch)
  223. }
  224. for _, e := range os.Environ() {
  225. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  226. continue
  227. }
  228. cmd.Env = append(cmd.Env, e)
  229. }
  230. return cmd
  231. }
  232. // Running The Tests
  233. //
  234. // "tests" also includes static analysis tools such as vet.
  235. func doTest(cmdline []string) {
  236. var (
  237. misspell = flag.Bool("misspell", false, "Whether to run the spell checker")
  238. coverage = flag.Bool("coverage", false, "Whether to record code coverage")
  239. )
  240. flag.CommandLine.Parse(cmdline)
  241. packages := []string{"./..."}
  242. if len(flag.CommandLine.Args()) > 0 {
  243. packages = flag.CommandLine.Args()
  244. }
  245. packages = build.ExpandPackagesNoVendor(packages)
  246. // Run analysis tools before the tests.
  247. build.MustRun(goTool("vet", packages...))
  248. if *misspell {
  249. spellcheck(packages)
  250. }
  251. // Run the actual tests.
  252. gotest := goTool("test")
  253. // Test a single package at a time. CI builders are slow
  254. // and some tests run into timeouts under load.
  255. gotest.Args = append(gotest.Args, "-p", "1")
  256. if *coverage {
  257. gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
  258. }
  259. gotest.Args = append(gotest.Args, packages...)
  260. build.MustRun(gotest)
  261. }
  262. // spellcheck runs the client9/misspell spellchecker package on all Go, Cgo and
  263. // test files in the requested packages.
  264. func spellcheck(packages []string) {
  265. // Ensure the spellchecker is available
  266. build.MustRun(goTool("get", "github.com/client9/misspell/cmd/misspell"))
  267. // Windows chokes on long argument lists, check packages individually
  268. for _, pkg := range packages {
  269. // The spell checker doesn't work on packages, gather all .go files for it
  270. out, err := goTool("list", "-f", "{{.Dir}}{{range .GoFiles}}\n{{.}}{{end}}{{range .CgoFiles}}\n{{.}}{{end}}{{range .TestGoFiles}}\n{{.}}{{end}}", pkg).CombinedOutput()
  271. if err != nil {
  272. log.Fatalf("source file listing failed: %v\n%s", err, string(out))
  273. }
  274. // Retrieve the folder and assemble the source list
  275. lines := strings.Split(string(out), "\n")
  276. root := lines[0]
  277. sources := make([]string, 0, len(lines)-1)
  278. for _, line := range lines[1:] {
  279. if line = strings.TrimSpace(line); line != "" {
  280. sources = append(sources, filepath.Join(root, line))
  281. }
  282. }
  283. // Run the spell checker for this particular package
  284. build.MustRunCommand(filepath.Join(GOBIN, "misspell"), append([]string{"-error"}, sources...)...)
  285. }
  286. }
  287. // Release Packaging
  288. func doArchive(cmdline []string) {
  289. var (
  290. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  291. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  292. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  293. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  294. ext string
  295. )
  296. flag.CommandLine.Parse(cmdline)
  297. switch *atype {
  298. case "zip":
  299. ext = ".zip"
  300. case "tar":
  301. ext = ".tar.gz"
  302. default:
  303. log.Fatal("unknown archive type: ", atype)
  304. }
  305. var (
  306. env = build.Env()
  307. base = archiveBasename(*arch, env)
  308. geth = "geth-" + base + ext
  309. alltools = "geth-alltools-" + base + ext
  310. )
  311. maybeSkipArchive(env)
  312. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  313. log.Fatal(err)
  314. }
  315. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  316. log.Fatal(err)
  317. }
  318. for _, archive := range []string{geth, alltools} {
  319. if err := archiveUpload(archive, *upload, *signer); err != nil {
  320. log.Fatal(err)
  321. }
  322. }
  323. }
  324. func archiveBasename(arch string, env build.Environment) string {
  325. platform := runtime.GOOS + "-" + arch
  326. if arch == "arm" {
  327. platform += os.Getenv("GOARM")
  328. }
  329. if arch == "android" {
  330. platform = "android-all"
  331. }
  332. if arch == "ios" {
  333. platform = "ios-all"
  334. }
  335. return platform + "-" + archiveVersion(env)
  336. }
  337. func archiveVersion(env build.Environment) string {
  338. version := build.VERSION()
  339. if isUnstableBuild(env) {
  340. version += "-unstable"
  341. }
  342. if env.Commit != "" {
  343. version += "-" + env.Commit[:8]
  344. }
  345. return version
  346. }
  347. func archiveUpload(archive string, blobstore string, signer string) error {
  348. // If signing was requested, generate the signature files
  349. if signer != "" {
  350. pgpkey, err := base64.StdEncoding.DecodeString(os.Getenv(signer))
  351. if err != nil {
  352. return fmt.Errorf("invalid base64 %s", signer)
  353. }
  354. if err := build.PGPSignFile(archive, archive+".asc", string(pgpkey)); err != nil {
  355. return err
  356. }
  357. }
  358. // If uploading to Azure was requested, push the archive possibly with its signature
  359. if blobstore != "" {
  360. auth := build.AzureBlobstoreConfig{
  361. Account: strings.Split(blobstore, "/")[0],
  362. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  363. Container: strings.SplitN(blobstore, "/", 2)[1],
  364. }
  365. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  366. return err
  367. }
  368. if signer != "" {
  369. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  370. return err
  371. }
  372. }
  373. }
  374. return nil
  375. }
  376. // skips archiving for some build configurations.
  377. func maybeSkipArchive(env build.Environment) {
  378. if env.IsPullRequest {
  379. log.Printf("skipping because this is a PR build")
  380. os.Exit(0)
  381. }
  382. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  383. log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  384. os.Exit(0)
  385. }
  386. }
  387. // Debian Packaging
  388. func doDebianSource(cmdline []string) {
  389. var (
  390. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  391. upload = flag.String("upload", "", `Where to upload the source package (usually "ppa:ethereum/ethereum")`)
  392. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  393. now = time.Now()
  394. )
  395. flag.CommandLine.Parse(cmdline)
  396. *workdir = makeWorkdir(*workdir)
  397. env := build.Env()
  398. maybeSkipArchive(env)
  399. // Import the signing key.
  400. if b64key := os.Getenv("PPA_SIGNING_KEY"); b64key != "" {
  401. key, err := base64.StdEncoding.DecodeString(b64key)
  402. if err != nil {
  403. log.Fatal("invalid base64 PPA_SIGNING_KEY")
  404. }
  405. gpg := exec.Command("gpg", "--import")
  406. gpg.Stdin = bytes.NewReader(key)
  407. build.MustRun(gpg)
  408. }
  409. // Create the packages.
  410. for _, distro := range debDistros {
  411. meta := newDebMetadata(distro, *signer, env, now)
  412. pkgdir := stageDebianSource(*workdir, meta)
  413. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc")
  414. debuild.Dir = pkgdir
  415. build.MustRun(debuild)
  416. changes := fmt.Sprintf("%s_%s_source.changes", meta.Name(), meta.VersionString())
  417. changes = filepath.Join(*workdir, changes)
  418. if *signer != "" {
  419. build.MustRunCommand("debsign", changes)
  420. }
  421. if *upload != "" {
  422. build.MustRunCommand("dput", *upload, changes)
  423. }
  424. }
  425. }
  426. func makeWorkdir(wdflag string) string {
  427. var err error
  428. if wdflag != "" {
  429. err = os.MkdirAll(wdflag, 0744)
  430. } else {
  431. wdflag, err = ioutil.TempDir("", "geth-build-")
  432. }
  433. if err != nil {
  434. log.Fatal(err)
  435. }
  436. return wdflag
  437. }
  438. func isUnstableBuild(env build.Environment) bool {
  439. if env.Tag != "" {
  440. return false
  441. }
  442. return true
  443. }
  444. type debMetadata struct {
  445. Env build.Environment
  446. // go-ethereum version being built. Note that this
  447. // is not the debian package version. The package version
  448. // is constructed by VersionString.
  449. Version string
  450. Author string // "name <email>", also selects signing key
  451. Distro, Time string
  452. Executables []debExecutable
  453. }
  454. type debExecutable struct {
  455. Name, Description string
  456. }
  457. func newDebMetadata(distro, author string, env build.Environment, t time.Time) debMetadata {
  458. if author == "" {
  459. // No signing key, use default author.
  460. author = "Ethereum Builds <fjl@ethereum.org>"
  461. }
  462. return debMetadata{
  463. Env: env,
  464. Author: author,
  465. Distro: distro,
  466. Version: build.VERSION(),
  467. Time: t.Format(time.RFC1123Z),
  468. Executables: debExecutables,
  469. }
  470. }
  471. // Name returns the name of the metapackage that depends
  472. // on all executable packages.
  473. func (meta debMetadata) Name() string {
  474. if isUnstableBuild(meta.Env) {
  475. return "ethereum-unstable"
  476. }
  477. return "ethereum"
  478. }
  479. // VersionString returns the debian version of the packages.
  480. func (meta debMetadata) VersionString() string {
  481. vsn := meta.Version
  482. if meta.Env.Buildnum != "" {
  483. vsn += "+build" + meta.Env.Buildnum
  484. }
  485. if meta.Distro != "" {
  486. vsn += "+" + meta.Distro
  487. }
  488. return vsn
  489. }
  490. // ExeList returns the list of all executable packages.
  491. func (meta debMetadata) ExeList() string {
  492. names := make([]string, len(meta.Executables))
  493. for i, e := range meta.Executables {
  494. names[i] = meta.ExeName(e)
  495. }
  496. return strings.Join(names, ", ")
  497. }
  498. // ExeName returns the package name of an executable package.
  499. func (meta debMetadata) ExeName(exe debExecutable) string {
  500. if isUnstableBuild(meta.Env) {
  501. return exe.Name + "-unstable"
  502. }
  503. return exe.Name
  504. }
  505. // ExeConflicts returns the content of the Conflicts field
  506. // for executable packages.
  507. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  508. if isUnstableBuild(meta.Env) {
  509. // Set up the conflicts list so that the *-unstable packages
  510. // cannot be installed alongside the regular version.
  511. //
  512. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  513. // is very explicit about Conflicts: and says that Breaks: should
  514. // be preferred and the conflicting files should be handled via
  515. // alternates. We might do this eventually but using a conflict is
  516. // easier now.
  517. return "ethereum, " + exe.Name
  518. }
  519. return ""
  520. }
  521. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  522. pkg := meta.Name() + "-" + meta.VersionString()
  523. pkgdir = filepath.Join(tmpdir, pkg)
  524. if err := os.Mkdir(pkgdir, 0755); err != nil {
  525. log.Fatal(err)
  526. }
  527. // Copy the source code.
  528. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  529. // Put the debian build files in place.
  530. debian := filepath.Join(pkgdir, "debian")
  531. build.Render("build/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  532. build.Render("build/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  533. build.Render("build/deb.control", filepath.Join(debian, "control"), 0644, meta)
  534. build.Render("build/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  535. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  536. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  537. for _, exe := range meta.Executables {
  538. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  539. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  540. build.Render("build/deb.install", install, 0644, exe)
  541. build.Render("build/deb.docs", docs, 0644, exe)
  542. }
  543. return pkgdir
  544. }
  545. // Windows installer
  546. func doWindowsInstaller(cmdline []string) {
  547. // Parse the flags and make skip installer generation on PRs
  548. var (
  549. arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
  550. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
  551. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  552. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  553. )
  554. flag.CommandLine.Parse(cmdline)
  555. *workdir = makeWorkdir(*workdir)
  556. env := build.Env()
  557. maybeSkipArchive(env)
  558. // Aggregate binaries that are included in the installer
  559. var (
  560. devTools []string
  561. allTools []string
  562. gethTool string
  563. )
  564. for _, file := range allToolsArchiveFiles {
  565. if file == "COPYING" { // license, copied later
  566. continue
  567. }
  568. allTools = append(allTools, filepath.Base(file))
  569. if filepath.Base(file) == "geth.exe" {
  570. gethTool = file
  571. } else {
  572. devTools = append(devTools, file)
  573. }
  574. }
  575. // Render NSIS scripts: Installer NSIS contains two installer sections,
  576. // first section contains the geth binary, second section holds the dev tools.
  577. templateData := map[string]interface{}{
  578. "License": "COPYING",
  579. "Geth": gethTool,
  580. "DevTools": devTools,
  581. }
  582. build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
  583. build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  584. build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  585. build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  586. build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  587. build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
  588. build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
  589. // Build the installer. This assumes that all the needed files have been previously
  590. // built (don't mix building and packaging to keep cross compilation complexity to a
  591. // minimum).
  592. version := strings.Split(build.VERSION(), ".")
  593. if env.Commit != "" {
  594. version[2] += "-" + env.Commit[:8]
  595. }
  596. installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, env) + ".exe")
  597. build.MustRunCommand("makensis.exe",
  598. "/DOUTPUTFILE="+installer,
  599. "/DMAJORVERSION="+version[0],
  600. "/DMINORVERSION="+version[1],
  601. "/DBUILDVERSION="+version[2],
  602. "/DARCH="+*arch,
  603. filepath.Join(*workdir, "geth.nsi"),
  604. )
  605. // Sign and publish installer.
  606. if err := archiveUpload(installer, *upload, *signer); err != nil {
  607. log.Fatal(err)
  608. }
  609. }
  610. // Android archives
  611. func doAndroidArchive(cmdline []string) {
  612. var (
  613. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  614. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
  615. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
  616. upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
  617. )
  618. flag.CommandLine.Parse(cmdline)
  619. env := build.Env()
  620. // Sanity check that the SDK and NDK are installed and set
  621. if os.Getenv("ANDROID_HOME") == "" {
  622. log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
  623. }
  624. if os.Getenv("ANDROID_NDK") == "" {
  625. log.Fatal("Please ensure ANDROID_NDK points to your Android NDK")
  626. }
  627. // Build the Android archive and Maven resources
  628. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile"))
  629. build.MustRun(gomobileTool("init", "--ndk", os.Getenv("ANDROID_NDK")))
  630. build.MustRun(gomobileTool("bind", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
  631. if *local {
  632. // If we're building locally, copy bundle to build dir and skip Maven
  633. os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
  634. return
  635. }
  636. meta := newMavenMetadata(env)
  637. build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  638. // Skip Maven deploy and Azure upload for PR builds
  639. maybeSkipArchive(env)
  640. // Sign and upload the archive to Azure
  641. archive := "geth-" + archiveBasename("android", env) + ".aar"
  642. os.Rename("geth.aar", archive)
  643. if err := archiveUpload(archive, *upload, *signer); err != nil {
  644. log.Fatal(err)
  645. }
  646. // Sign and upload all the artifacts to Maven Central
  647. os.Rename(archive, meta.Package+".aar")
  648. if *signer != "" && *deploy != "" {
  649. // Import the signing key into the local GPG instance
  650. if b64key := os.Getenv(*signer); b64key != "" {
  651. key, err := base64.StdEncoding.DecodeString(b64key)
  652. if err != nil {
  653. log.Fatalf("invalid base64 %s", *signer)
  654. }
  655. gpg := exec.Command("gpg", "--import")
  656. gpg.Stdin = bytes.NewReader(key)
  657. build.MustRun(gpg)
  658. }
  659. // Upload the artifacts to Sonatype and/or Maven Central
  660. repo := *deploy + "/service/local/staging/deploy/maven2"
  661. if meta.Develop {
  662. repo = *deploy + "/content/repositories/snapshots"
  663. }
  664. build.MustRunCommand("mvn", "gpg:sign-and-deploy-file",
  665. "-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
  666. "-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
  667. }
  668. }
  669. func gomobileTool(subcmd string, args ...string) *exec.Cmd {
  670. cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
  671. cmd.Args = append(cmd.Args, args...)
  672. cmd.Env = []string{
  673. "GOPATH=" + build.GOPATH(),
  674. }
  675. for _, e := range os.Environ() {
  676. if strings.HasPrefix(e, "GOPATH=") {
  677. continue
  678. }
  679. cmd.Env = append(cmd.Env, e)
  680. }
  681. return cmd
  682. }
  683. type mavenMetadata struct {
  684. Version string
  685. Package string
  686. Develop bool
  687. Contributors []mavenContributor
  688. }
  689. type mavenContributor struct {
  690. Name string
  691. Email string
  692. }
  693. func newMavenMetadata(env build.Environment) mavenMetadata {
  694. // Collect the list of authors from the repo root
  695. contribs := []mavenContributor{}
  696. if authors, err := os.Open("AUTHORS"); err == nil {
  697. defer authors.Close()
  698. scanner := bufio.NewScanner(authors)
  699. for scanner.Scan() {
  700. // Skip any whitespace from the authors list
  701. line := strings.TrimSpace(scanner.Text())
  702. if line == "" || line[0] == '#' {
  703. continue
  704. }
  705. // Split the author and insert as a contributor
  706. re := regexp.MustCompile("([^<]+) <(.+)>")
  707. parts := re.FindStringSubmatch(line)
  708. if len(parts) == 3 {
  709. contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  710. }
  711. }
  712. }
  713. // Render the version and package strings
  714. version := build.VERSION()
  715. if isUnstableBuild(env) {
  716. version += "-SNAPSHOT"
  717. }
  718. return mavenMetadata{
  719. Version: version,
  720. Package: "geth-" + version,
  721. Develop: isUnstableBuild(env),
  722. Contributors: contribs,
  723. }
  724. }
  725. // XCode frameworks
  726. func doXCodeFramework(cmdline []string) {
  727. var (
  728. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  729. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  730. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  731. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  732. )
  733. flag.CommandLine.Parse(cmdline)
  734. env := build.Env()
  735. // Build the iOS XCode framework
  736. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile"))
  737. build.MustRun(gomobileTool("init"))
  738. bind := gomobileTool("bind", "--target", "ios", "--tags", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  739. if *local {
  740. // If we're building locally, use the build folder and stop afterwards
  741. bind.Dir, _ = filepath.Abs(GOBIN)
  742. build.MustRun(bind)
  743. return
  744. }
  745. archive := "geth-" + archiveBasename("ios", env)
  746. if err := os.Mkdir(archive, os.ModePerm); err != nil {
  747. log.Fatal(err)
  748. }
  749. bind.Dir, _ = filepath.Abs(archive)
  750. build.MustRun(bind)
  751. build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  752. // Skip CocoaPods deploy and Azure upload for PR builds
  753. maybeSkipArchive(env)
  754. // Sign and upload the framework to Azure
  755. if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
  756. log.Fatal(err)
  757. }
  758. // Prepare and upload a PodSpec to CocoaPods
  759. if *deploy != "" {
  760. meta := newPodMetadata(env, archive)
  761. build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  762. build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
  763. }
  764. }
  765. type podMetadata struct {
  766. Version string
  767. Commit string
  768. Archive string
  769. Contributors []podContributor
  770. }
  771. type podContributor struct {
  772. Name string
  773. Email string
  774. }
  775. func newPodMetadata(env build.Environment, archive string) podMetadata {
  776. // Collect the list of authors from the repo root
  777. contribs := []podContributor{}
  778. if authors, err := os.Open("AUTHORS"); err == nil {
  779. defer authors.Close()
  780. scanner := bufio.NewScanner(authors)
  781. for scanner.Scan() {
  782. // Skip any whitespace from the authors list
  783. line := strings.TrimSpace(scanner.Text())
  784. if line == "" || line[0] == '#' {
  785. continue
  786. }
  787. // Split the author and insert as a contributor
  788. re := regexp.MustCompile("([^<]+) <(.+)>")
  789. parts := re.FindStringSubmatch(line)
  790. if len(parts) == 3 {
  791. contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  792. }
  793. }
  794. }
  795. version := build.VERSION()
  796. if isUnstableBuild(env) {
  797. version += "-unstable." + env.Buildnum
  798. }
  799. return podMetadata{
  800. Archive: archive,
  801. Version: version,
  802. Commit: env.Commit,
  803. Contributors: contribs,
  804. }
  805. }
  806. // Cross compilation
  807. func doXgo(cmdline []string) {
  808. var (
  809. alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  810. )
  811. flag.CommandLine.Parse(cmdline)
  812. env := build.Env()
  813. // Make sure xgo is available for cross compilation
  814. gogetxgo := goTool("get", "github.com/karalabe/xgo")
  815. build.MustRun(gogetxgo)
  816. // If all tools building is requested, build everything the builder wants
  817. args := append(buildFlags(env), flag.Args()...)
  818. if *alltools {
  819. args = append(args, []string{"--dest", GOBIN}...)
  820. for _, res := range allToolsArchiveFiles {
  821. if strings.HasPrefix(res, GOBIN) {
  822. // Binary tool found, cross build it explicitly
  823. args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  824. xgo := xgoTool(args)
  825. build.MustRun(xgo)
  826. args = args[:len(args)-1]
  827. }
  828. }
  829. return
  830. }
  831. // Otherwise xxecute the explicit cross compilation
  832. path := args[len(args)-1]
  833. args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  834. xgo := xgoTool(args)
  835. build.MustRun(xgo)
  836. }
  837. func xgoTool(args []string) *exec.Cmd {
  838. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  839. cmd.Env = []string{
  840. "GOPATH=" + build.GOPATH(),
  841. "GOBIN=" + GOBIN,
  842. }
  843. for _, e := range os.Environ() {
  844. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  845. continue
  846. }
  847. cmd.Env = append(cmd.Env, e)
  848. }
  849. return cmd
  850. }