ci.go 32 KB

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