ci.go 32 KB

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