ci.go 31 KB

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