ci.go 30 KB

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