ci.go 32 KB

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