ci.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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 ] [ 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 prvious 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.v1"))
  289. build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v1"), "--install")
  290. configs := []string{"--vendor", "--disable-all", "--enable=vet", "--enable=gofmt", "--enable=misspell"}
  291. build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v1"), append(configs, packages...)...)
  292. }
  293. // Release Packaging
  294. func doArchive(cmdline []string) {
  295. var (
  296. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  297. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  298. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  299. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  300. ext string
  301. )
  302. flag.CommandLine.Parse(cmdline)
  303. switch *atype {
  304. case "zip":
  305. ext = ".zip"
  306. case "tar":
  307. ext = ".tar.gz"
  308. default:
  309. log.Fatal("unknown archive type: ", atype)
  310. }
  311. var (
  312. env = build.Env()
  313. base = archiveBasename(*arch, env)
  314. geth = "geth-" + base + ext
  315. alltools = "geth-alltools-" + base + ext
  316. )
  317. maybeSkipArchive(env)
  318. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  319. log.Fatal(err)
  320. }
  321. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  322. log.Fatal(err)
  323. }
  324. for _, archive := range []string{geth, alltools} {
  325. if err := archiveUpload(archive, *upload, *signer); err != nil {
  326. log.Fatal(err)
  327. }
  328. }
  329. }
  330. func archiveBasename(arch string, env build.Environment) string {
  331. platform := runtime.GOOS + "-" + arch
  332. if arch == "arm" {
  333. platform += os.Getenv("GOARM")
  334. }
  335. if arch == "android" {
  336. platform = "android-all"
  337. }
  338. if arch == "ios" {
  339. platform = "ios-all"
  340. }
  341. return platform + "-" + archiveVersion(env)
  342. }
  343. func archiveVersion(env build.Environment) string {
  344. version := build.VERSION()
  345. if isUnstableBuild(env) {
  346. version += "-unstable"
  347. }
  348. if env.Commit != "" {
  349. version += "-" + env.Commit[:8]
  350. }
  351. return version
  352. }
  353. func archiveUpload(archive string, blobstore string, signer string) error {
  354. // If signing was requested, generate the signature files
  355. if signer != "" {
  356. pgpkey, err := base64.StdEncoding.DecodeString(os.Getenv(signer))
  357. if err != nil {
  358. return fmt.Errorf("invalid base64 %s", signer)
  359. }
  360. if err := build.PGPSignFile(archive, archive+".asc", string(pgpkey)); err != nil {
  361. return err
  362. }
  363. }
  364. // If uploading to Azure was requested, push the archive possibly with its signature
  365. if blobstore != "" {
  366. auth := build.AzureBlobstoreConfig{
  367. Account: strings.Split(blobstore, "/")[0],
  368. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  369. Container: strings.SplitN(blobstore, "/", 2)[1],
  370. }
  371. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  372. return err
  373. }
  374. if signer != "" {
  375. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  376. return err
  377. }
  378. }
  379. }
  380. return nil
  381. }
  382. // skips archiving for some build configurations.
  383. func maybeSkipArchive(env build.Environment) {
  384. if env.IsPullRequest {
  385. log.Printf("skipping because this is a PR build")
  386. os.Exit(0)
  387. }
  388. if env.IsCronJob {
  389. log.Printf("skipping because this is a cron job")
  390. os.Exit(0)
  391. }
  392. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  393. log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  394. os.Exit(0)
  395. }
  396. }
  397. // Debian Packaging
  398. func doDebianSource(cmdline []string) {
  399. var (
  400. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  401. upload = flag.String("upload", "", `Where to upload the source package (usually "ppa:ethereum/ethereum")`)
  402. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  403. now = time.Now()
  404. )
  405. flag.CommandLine.Parse(cmdline)
  406. *workdir = makeWorkdir(*workdir)
  407. env := build.Env()
  408. maybeSkipArchive(env)
  409. // Import the signing key.
  410. if b64key := os.Getenv("PPA_SIGNING_KEY"); b64key != "" {
  411. key, err := base64.StdEncoding.DecodeString(b64key)
  412. if err != nil {
  413. log.Fatal("invalid base64 PPA_SIGNING_KEY")
  414. }
  415. gpg := exec.Command("gpg", "--import")
  416. gpg.Stdin = bytes.NewReader(key)
  417. build.MustRun(gpg)
  418. }
  419. // Create the packages.
  420. for _, distro := range debDistros {
  421. meta := newDebMetadata(distro, *signer, env, now)
  422. pkgdir := stageDebianSource(*workdir, meta)
  423. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc")
  424. debuild.Dir = pkgdir
  425. build.MustRun(debuild)
  426. changes := fmt.Sprintf("%s_%s_source.changes", meta.Name(), meta.VersionString())
  427. changes = filepath.Join(*workdir, changes)
  428. if *signer != "" {
  429. build.MustRunCommand("debsign", changes)
  430. }
  431. if *upload != "" {
  432. build.MustRunCommand("dput", *upload, changes)
  433. }
  434. }
  435. }
  436. func makeWorkdir(wdflag string) string {
  437. var err error
  438. if wdflag != "" {
  439. err = os.MkdirAll(wdflag, 0744)
  440. } else {
  441. wdflag, err = ioutil.TempDir("", "geth-build-")
  442. }
  443. if err != nil {
  444. log.Fatal(err)
  445. }
  446. return wdflag
  447. }
  448. func isUnstableBuild(env build.Environment) bool {
  449. if env.Tag != "" {
  450. return false
  451. }
  452. return true
  453. }
  454. type debMetadata struct {
  455. Env build.Environment
  456. // go-ethereum version being built. Note that this
  457. // is not the debian package version. The package version
  458. // is constructed by VersionString.
  459. Version string
  460. Author string // "name <email>", also selects signing key
  461. Distro, Time string
  462. Executables []debExecutable
  463. }
  464. type debExecutable struct {
  465. Name, Description string
  466. }
  467. func newDebMetadata(distro, author string, env build.Environment, t time.Time) debMetadata {
  468. if author == "" {
  469. // No signing key, use default author.
  470. author = "Ethereum Builds <fjl@ethereum.org>"
  471. }
  472. return debMetadata{
  473. Env: env,
  474. Author: author,
  475. Distro: distro,
  476. Version: build.VERSION(),
  477. Time: t.Format(time.RFC1123Z),
  478. Executables: debExecutables,
  479. }
  480. }
  481. // Name returns the name of the metapackage that depends
  482. // on all executable packages.
  483. func (meta debMetadata) Name() string {
  484. if isUnstableBuild(meta.Env) {
  485. return "ethereum-unstable"
  486. }
  487. return "ethereum"
  488. }
  489. // VersionString returns the debian version of the packages.
  490. func (meta debMetadata) VersionString() string {
  491. vsn := meta.Version
  492. if meta.Env.Buildnum != "" {
  493. vsn += "+build" + meta.Env.Buildnum
  494. }
  495. if meta.Distro != "" {
  496. vsn += "+" + meta.Distro
  497. }
  498. return vsn
  499. }
  500. // ExeList returns the list of all executable packages.
  501. func (meta debMetadata) ExeList() string {
  502. names := make([]string, len(meta.Executables))
  503. for i, e := range meta.Executables {
  504. names[i] = meta.ExeName(e)
  505. }
  506. return strings.Join(names, ", ")
  507. }
  508. // ExeName returns the package name of an executable package.
  509. func (meta debMetadata) ExeName(exe debExecutable) string {
  510. if isUnstableBuild(meta.Env) {
  511. return exe.Name + "-unstable"
  512. }
  513. return exe.Name
  514. }
  515. // ExeConflicts returns the content of the Conflicts field
  516. // for executable packages.
  517. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  518. if isUnstableBuild(meta.Env) {
  519. // Set up the conflicts list so that the *-unstable packages
  520. // cannot be installed alongside the regular version.
  521. //
  522. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  523. // is very explicit about Conflicts: and says that Breaks: should
  524. // be preferred and the conflicting files should be handled via
  525. // alternates. We might do this eventually but using a conflict is
  526. // easier now.
  527. return "ethereum, " + exe.Name
  528. }
  529. return ""
  530. }
  531. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  532. pkg := meta.Name() + "-" + meta.VersionString()
  533. pkgdir = filepath.Join(tmpdir, pkg)
  534. if err := os.Mkdir(pkgdir, 0755); err != nil {
  535. log.Fatal(err)
  536. }
  537. // Copy the source code.
  538. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  539. // Put the debian build files in place.
  540. debian := filepath.Join(pkgdir, "debian")
  541. build.Render("build/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  542. build.Render("build/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  543. build.Render("build/deb.control", filepath.Join(debian, "control"), 0644, meta)
  544. build.Render("build/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  545. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  546. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  547. for _, exe := range meta.Executables {
  548. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  549. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  550. build.Render("build/deb.install", install, 0644, exe)
  551. build.Render("build/deb.docs", docs, 0644, exe)
  552. }
  553. return pkgdir
  554. }
  555. // Windows installer
  556. func doWindowsInstaller(cmdline []string) {
  557. // Parse the flags and make skip installer generation on PRs
  558. var (
  559. arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
  560. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
  561. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  562. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  563. )
  564. flag.CommandLine.Parse(cmdline)
  565. *workdir = makeWorkdir(*workdir)
  566. env := build.Env()
  567. maybeSkipArchive(env)
  568. // Aggregate binaries that are included in the installer
  569. var (
  570. devTools []string
  571. allTools []string
  572. gethTool string
  573. )
  574. for _, file := range allToolsArchiveFiles {
  575. if file == "COPYING" { // license, copied later
  576. continue
  577. }
  578. allTools = append(allTools, filepath.Base(file))
  579. if filepath.Base(file) == "geth.exe" {
  580. gethTool = file
  581. } else {
  582. devTools = append(devTools, file)
  583. }
  584. }
  585. // Render NSIS scripts: Installer NSIS contains two installer sections,
  586. // first section contains the geth binary, second section holds the dev tools.
  587. templateData := map[string]interface{}{
  588. "License": "COPYING",
  589. "Geth": gethTool,
  590. "DevTools": devTools,
  591. }
  592. build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
  593. build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  594. build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  595. build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  596. build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  597. build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
  598. build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
  599. // Build the installer. This assumes that all the needed files have been previously
  600. // built (don't mix building and packaging to keep cross compilation complexity to a
  601. // minimum).
  602. version := strings.Split(build.VERSION(), ".")
  603. if env.Commit != "" {
  604. version[2] += "-" + env.Commit[:8]
  605. }
  606. installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, env) + ".exe")
  607. build.MustRunCommand("makensis.exe",
  608. "/DOUTPUTFILE="+installer,
  609. "/DMAJORVERSION="+version[0],
  610. "/DMINORVERSION="+version[1],
  611. "/DBUILDVERSION="+version[2],
  612. "/DARCH="+*arch,
  613. filepath.Join(*workdir, "geth.nsi"),
  614. )
  615. // Sign and publish installer.
  616. if err := archiveUpload(installer, *upload, *signer); err != nil {
  617. log.Fatal(err)
  618. }
  619. }
  620. // Android archives
  621. func doAndroidArchive(cmdline []string) {
  622. var (
  623. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  624. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
  625. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
  626. upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
  627. )
  628. flag.CommandLine.Parse(cmdline)
  629. env := build.Env()
  630. // Sanity check that the SDK and NDK are installed and set
  631. if os.Getenv("ANDROID_HOME") == "" {
  632. log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
  633. }
  634. if os.Getenv("ANDROID_NDK") == "" {
  635. log.Fatal("Please ensure ANDROID_NDK points to your Android NDK")
  636. }
  637. // Build the Android archive and Maven resources
  638. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile"))
  639. build.MustRun(gomobileTool("init", "--ndk", os.Getenv("ANDROID_NDK")))
  640. build.MustRun(gomobileTool("bind", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
  641. if *local {
  642. // If we're building locally, copy bundle to build dir and skip Maven
  643. os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
  644. return
  645. }
  646. meta := newMavenMetadata(env)
  647. build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  648. // Skip Maven deploy and Azure upload for PR builds
  649. maybeSkipArchive(env)
  650. // Sign and upload the archive to Azure
  651. archive := "geth-" + archiveBasename("android", env) + ".aar"
  652. os.Rename("geth.aar", archive)
  653. if err := archiveUpload(archive, *upload, *signer); err != nil {
  654. log.Fatal(err)
  655. }
  656. // Sign and upload all the artifacts to Maven Central
  657. os.Rename(archive, meta.Package+".aar")
  658. if *signer != "" && *deploy != "" {
  659. // Import the signing key into the local GPG instance
  660. if b64key := os.Getenv(*signer); b64key != "" {
  661. key, err := base64.StdEncoding.DecodeString(b64key)
  662. if err != nil {
  663. log.Fatalf("invalid base64 %s", *signer)
  664. }
  665. gpg := exec.Command("gpg", "--import")
  666. gpg.Stdin = bytes.NewReader(key)
  667. build.MustRun(gpg)
  668. }
  669. // Upload the artifacts to Sonatype and/or Maven Central
  670. repo := *deploy + "/service/local/staging/deploy/maven2"
  671. if meta.Develop {
  672. repo = *deploy + "/content/repositories/snapshots"
  673. }
  674. build.MustRunCommand("mvn", "gpg:sign-and-deploy-file",
  675. "-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
  676. "-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
  677. }
  678. }
  679. func gomobileTool(subcmd string, args ...string) *exec.Cmd {
  680. cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
  681. cmd.Args = append(cmd.Args, args...)
  682. cmd.Env = []string{
  683. "GOPATH=" + build.GOPATH(),
  684. }
  685. for _, e := range os.Environ() {
  686. if strings.HasPrefix(e, "GOPATH=") {
  687. continue
  688. }
  689. cmd.Env = append(cmd.Env, e)
  690. }
  691. return cmd
  692. }
  693. type mavenMetadata struct {
  694. Version string
  695. Package string
  696. Develop bool
  697. Contributors []mavenContributor
  698. }
  699. type mavenContributor struct {
  700. Name string
  701. Email string
  702. }
  703. func newMavenMetadata(env build.Environment) mavenMetadata {
  704. // Collect the list of authors from the repo root
  705. contribs := []mavenContributor{}
  706. if authors, err := os.Open("AUTHORS"); err == nil {
  707. defer authors.Close()
  708. scanner := bufio.NewScanner(authors)
  709. for scanner.Scan() {
  710. // Skip any whitespace from the authors list
  711. line := strings.TrimSpace(scanner.Text())
  712. if line == "" || line[0] == '#' {
  713. continue
  714. }
  715. // Split the author and insert as a contributor
  716. re := regexp.MustCompile("([^<]+) <(.+)>")
  717. parts := re.FindStringSubmatch(line)
  718. if len(parts) == 3 {
  719. contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  720. }
  721. }
  722. }
  723. // Render the version and package strings
  724. version := build.VERSION()
  725. if isUnstableBuild(env) {
  726. version += "-SNAPSHOT"
  727. }
  728. return mavenMetadata{
  729. Version: version,
  730. Package: "geth-" + version,
  731. Develop: isUnstableBuild(env),
  732. Contributors: contribs,
  733. }
  734. }
  735. // XCode frameworks
  736. func doXCodeFramework(cmdline []string) {
  737. var (
  738. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  739. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  740. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  741. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  742. )
  743. flag.CommandLine.Parse(cmdline)
  744. env := build.Env()
  745. // Build the iOS XCode framework
  746. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile"))
  747. build.MustRun(gomobileTool("init"))
  748. bind := gomobileTool("bind", "--target", "ios", "--tags", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  749. if *local {
  750. // If we're building locally, use the build folder and stop afterwards
  751. bind.Dir, _ = filepath.Abs(GOBIN)
  752. build.MustRun(bind)
  753. return
  754. }
  755. archive := "geth-" + archiveBasename("ios", env)
  756. if err := os.Mkdir(archive, os.ModePerm); err != nil {
  757. log.Fatal(err)
  758. }
  759. bind.Dir, _ = filepath.Abs(archive)
  760. build.MustRun(bind)
  761. build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  762. // Skip CocoaPods deploy and Azure upload for PR builds
  763. maybeSkipArchive(env)
  764. // Sign and upload the framework to Azure
  765. if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
  766. log.Fatal(err)
  767. }
  768. // Prepare and upload a PodSpec to CocoaPods
  769. if *deploy != "" {
  770. meta := newPodMetadata(env, archive)
  771. build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  772. build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
  773. }
  774. }
  775. type podMetadata struct {
  776. Version string
  777. Commit string
  778. Archive string
  779. Contributors []podContributor
  780. }
  781. type podContributor struct {
  782. Name string
  783. Email string
  784. }
  785. func newPodMetadata(env build.Environment, archive string) podMetadata {
  786. // Collect the list of authors from the repo root
  787. contribs := []podContributor{}
  788. if authors, err := os.Open("AUTHORS"); err == nil {
  789. defer authors.Close()
  790. scanner := bufio.NewScanner(authors)
  791. for scanner.Scan() {
  792. // Skip any whitespace from the authors list
  793. line := strings.TrimSpace(scanner.Text())
  794. if line == "" || line[0] == '#' {
  795. continue
  796. }
  797. // Split the author and insert as a contributor
  798. re := regexp.MustCompile("([^<]+) <(.+)>")
  799. parts := re.FindStringSubmatch(line)
  800. if len(parts) == 3 {
  801. contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  802. }
  803. }
  804. }
  805. version := build.VERSION()
  806. if isUnstableBuild(env) {
  807. version += "-unstable." + env.Buildnum
  808. }
  809. return podMetadata{
  810. Archive: archive,
  811. Version: version,
  812. Commit: env.Commit,
  813. Contributors: contribs,
  814. }
  815. }
  816. // Cross compilation
  817. func doXgo(cmdline []string) {
  818. var (
  819. alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  820. )
  821. flag.CommandLine.Parse(cmdline)
  822. env := build.Env()
  823. // Make sure xgo is available for cross compilation
  824. gogetxgo := goTool("get", "github.com/karalabe/xgo")
  825. build.MustRun(gogetxgo)
  826. // If all tools building is requested, build everything the builder wants
  827. args := append(buildFlags(env), flag.Args()...)
  828. if *alltools {
  829. args = append(args, []string{"--dest", GOBIN}...)
  830. for _, res := range allToolsArchiveFiles {
  831. if strings.HasPrefix(res, GOBIN) {
  832. // Binary tool found, cross build it explicitly
  833. args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  834. xgo := xgoTool(args)
  835. build.MustRun(xgo)
  836. args = args[:len(args)-1]
  837. }
  838. }
  839. return
  840. }
  841. // Otherwise xxecute the explicit cross compilation
  842. path := args[len(args)-1]
  843. args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  844. xgo := xgoTool(args)
  845. build.MustRun(xgo)
  846. }
  847. func xgoTool(args []string) *exec.Cmd {
  848. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  849. cmd.Env = []string{
  850. "GOPATH=" + build.GOPATH(),
  851. "GOBIN=" + GOBIN,
  852. }
  853. for _, e := range os.Environ() {
  854. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  855. continue
  856. }
  857. cmd.Env = append(cmd.Env, e)
  858. }
  859. return cmd
  860. }
  861. // Binary distribution cleanups
  862. func doPurge(cmdline []string) {
  863. var (
  864. store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  865. limit = flag.Int("days", 30, `Age threshold above which to delete unstalbe archives`)
  866. )
  867. flag.CommandLine.Parse(cmdline)
  868. if env := build.Env(); !env.IsCronJob {
  869. log.Printf("skipping because not a cron job")
  870. os.Exit(0)
  871. }
  872. // Create the azure authentication and list the current archives
  873. auth := build.AzureBlobstoreConfig{
  874. Account: strings.Split(*store, "/")[0],
  875. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  876. Container: strings.SplitN(*store, "/", 2)[1],
  877. }
  878. blobs, err := build.AzureBlobstoreList(auth)
  879. if err != nil {
  880. log.Fatal(err)
  881. }
  882. // Iterate over the blobs, collect and sort all unstable builds
  883. for i := 0; i < len(blobs); i++ {
  884. if !strings.Contains(blobs[i].Name, "unstable") {
  885. blobs = append(blobs[:i], blobs[i+1:]...)
  886. i--
  887. }
  888. }
  889. for i := 0; i < len(blobs); i++ {
  890. for j := i + 1; j < len(blobs); j++ {
  891. iTime, err := time.Parse(time.RFC1123, blobs[i].Properties.LastModified)
  892. if err != nil {
  893. log.Fatal(err)
  894. }
  895. jTime, err := time.Parse(time.RFC1123, blobs[j].Properties.LastModified)
  896. if err != nil {
  897. log.Fatal(err)
  898. }
  899. if iTime.After(jTime) {
  900. blobs[i], blobs[j] = blobs[j], blobs[i]
  901. }
  902. }
  903. }
  904. // Filter out all archives more recent that the given threshold
  905. for i, blob := range blobs {
  906. timestamp, _ := time.Parse(time.RFC1123, blob.Properties.LastModified)
  907. if time.Since(timestamp) < time.Duration(*limit)*24*time.Hour {
  908. blobs = blobs[:i]
  909. break
  910. }
  911. }
  912. // Delete all marked as such and return
  913. if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  914. log.Fatal(err)
  915. }
  916. }