ci.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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 artifacts
  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. "io/ioutil"
  42. "log"
  43. "os"
  44. "os/exec"
  45. "path"
  46. "path/filepath"
  47. "regexp"
  48. "runtime"
  49. "strings"
  50. "time"
  51. "github.com/cespare/cp"
  52. "github.com/ethereum/go-ethereum/internal/build"
  53. "github.com/ethereum/go-ethereum/params"
  54. )
  55. var (
  56. // Files that end up in the geth*.zip archive.
  57. gethArchiveFiles = []string{
  58. "COPYING",
  59. executablePath("geth"),
  60. }
  61. // Files that end up in the geth-alltools*.zip archive.
  62. allToolsArchiveFiles = []string{
  63. "COPYING",
  64. executablePath("abigen"),
  65. executablePath("bootnode"),
  66. executablePath("evm"),
  67. executablePath("geth"),
  68. executablePath("puppeth"),
  69. executablePath("rlpdump"),
  70. executablePath("clef"),
  71. }
  72. // A debian package is created for all executables listed here.
  73. debExecutables = []debExecutable{
  74. {
  75. BinaryName: "abigen",
  76. Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
  77. },
  78. {
  79. BinaryName: "bootnode",
  80. Description: "Ethereum bootnode.",
  81. },
  82. {
  83. BinaryName: "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. BinaryName: "geth",
  88. Description: "Ethereum CLI client.",
  89. },
  90. {
  91. BinaryName: "puppeth",
  92. Description: "Ethereum private network manager.",
  93. },
  94. {
  95. BinaryName: "rlpdump",
  96. Description: "Developer utility tool that prints RLP structures.",
  97. },
  98. {
  99. BinaryName: "clef",
  100. Description: "Ethereum account management tool.",
  101. },
  102. }
  103. // A debian package is created for all executables listed here.
  104. debEthereum = debPackage{
  105. Name: "ethereum",
  106. Version: params.Version,
  107. Executables: debExecutables,
  108. }
  109. // Debian meta packages to build and push to Ubuntu PPA
  110. debPackages = []debPackage{
  111. debEthereum,
  112. }
  113. // Distros for which packages are created.
  114. // Note: vivid is unsupported because there is no golang-1.6 package for it.
  115. // Note: wily is unsupported because it was officially deprecated on Launchpad.
  116. // Note: yakkety is unsupported because it was officially deprecated on Launchpad.
  117. // Note: zesty is unsupported because it was officially deprecated on Launchpad.
  118. // Note: artful is unsupported because it was officially deprecated on Launchpad.
  119. // Note: cosmic is unsupported because it was officially deprecated on Launchpad.
  120. // Note: disco is unsupported because it was officially deprecated on Launchpad.
  121. // Note: eoan is unsupported because it was officially deprecated on Launchpad.
  122. debDistroGoBoots = map[string]string{
  123. "trusty": "golang-1.11",
  124. "xenial": "golang-go",
  125. "bionic": "golang-go",
  126. "focal": "golang-go",
  127. "groovy": "golang-go",
  128. }
  129. debGoBootPaths = map[string]string{
  130. "golang-1.11": "/usr/lib/go-1.11",
  131. "golang-go": "/usr/lib/go",
  132. }
  133. // This is the version of go that will be downloaded by
  134. //
  135. // go run ci.go install -dlgo
  136. dlgoVersion = "1.15.5"
  137. )
  138. var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
  139. func executablePath(name string) string {
  140. if runtime.GOOS == "windows" {
  141. name += ".exe"
  142. }
  143. return filepath.Join(GOBIN, name)
  144. }
  145. func main() {
  146. log.SetFlags(log.Lshortfile)
  147. if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
  148. log.Fatal("this script must be run from the root of the repository")
  149. }
  150. if len(os.Args) < 2 {
  151. log.Fatal("need subcommand as first argument")
  152. }
  153. switch os.Args[1] {
  154. case "install":
  155. doInstall(os.Args[2:])
  156. case "test":
  157. doTest(os.Args[2:])
  158. case "lint":
  159. doLint(os.Args[2:])
  160. case "archive":
  161. doArchive(os.Args[2:])
  162. case "debsrc":
  163. doDebianSource(os.Args[2:])
  164. case "nsis":
  165. doWindowsInstaller(os.Args[2:])
  166. case "aar":
  167. doAndroidArchive(os.Args[2:])
  168. case "xcode":
  169. doXCodeFramework(os.Args[2:])
  170. case "xgo":
  171. doXgo(os.Args[2:])
  172. case "purge":
  173. doPurge(os.Args[2:])
  174. default:
  175. log.Fatal("unknown command ", os.Args[1])
  176. }
  177. }
  178. // Compiling
  179. func doInstall(cmdline []string) {
  180. var (
  181. dlgo = flag.Bool("dlgo", false, "Download Go and build with it")
  182. arch = flag.String("arch", "", "Architecture to cross build for")
  183. cc = flag.String("cc", "", "C compiler to cross build with")
  184. )
  185. flag.CommandLine.Parse(cmdline)
  186. env := build.Env()
  187. // Check local Go version. People regularly open issues about compilation
  188. // failure with outdated Go. This should save them the trouble.
  189. if !strings.Contains(runtime.Version(), "devel") {
  190. // Figure out the minor version number since we can't textually compare (1.10 < 1.9)
  191. var minor int
  192. fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
  193. if minor < 13 {
  194. log.Println("You have Go version", runtime.Version())
  195. log.Println("go-ethereum requires at least Go version 1.13 and cannot")
  196. log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
  197. os.Exit(1)
  198. }
  199. }
  200. // Choose which go command we're going to use.
  201. var gobuild *exec.Cmd
  202. if !*dlgo {
  203. // Default behavior: use the go version which runs ci.go right now.
  204. gobuild = goTool("build")
  205. } else {
  206. // Download of Go requested. This is for build environments where the
  207. // installed version is too old and cannot be upgraded easily.
  208. cachedir := filepath.Join("build", "cache")
  209. goroot := downloadGo(runtime.GOARCH, runtime.GOOS, cachedir)
  210. gobuild = localGoTool(goroot, "build")
  211. }
  212. // Configure environment for cross build.
  213. if *arch != "" || *arch != runtime.GOARCH {
  214. gobuild.Env = append(gobuild.Env, "CGO_ENABLED=1")
  215. gobuild.Env = append(gobuild.Env, "GOARCH="+*arch)
  216. }
  217. // Configure C compiler.
  218. if *cc != "" {
  219. gobuild.Env = append(gobuild.Env, "CC="+*cc)
  220. } else if os.Getenv("CC") != "" {
  221. gobuild.Env = append(gobuild.Env, "CC="+os.Getenv("CC"))
  222. }
  223. // arm64 CI builders are memory-constrained and can't handle concurrent builds,
  224. // better disable it. This check isn't the best, it should probably
  225. // check for something in env instead.
  226. if runtime.GOARCH == "arm64" {
  227. gobuild.Args = append(gobuild.Args, "-p", "1")
  228. }
  229. // Put the default settings in.
  230. gobuild.Args = append(gobuild.Args, buildFlags(env)...)
  231. // We use -trimpath to avoid leaking local paths into the built executables.
  232. gobuild.Args = append(gobuild.Args, "-trimpath")
  233. // Show packages during build.
  234. gobuild.Args = append(gobuild.Args, "-v")
  235. // Now we choose what we're even building.
  236. // Default: collect all 'main' packages in cmd/ and build those.
  237. packages := flag.Args()
  238. if len(packages) == 0 {
  239. packages = build.FindMainPackages("./cmd")
  240. }
  241. // Do the build!
  242. for _, pkg := range packages {
  243. args := make([]string, len(gobuild.Args))
  244. copy(args, gobuild.Args)
  245. args = append(args, "-o", executablePath(path.Base(pkg)))
  246. args = append(args, pkg)
  247. build.MustRun(&exec.Cmd{Path: gobuild.Path, Args: args, Env: gobuild.Env})
  248. }
  249. }
  250. // buildFlags returns the go tool flags for building.
  251. func buildFlags(env build.Environment) (flags []string) {
  252. var ld []string
  253. if env.Commit != "" {
  254. ld = append(ld, "-X", "main.gitCommit="+env.Commit)
  255. ld = append(ld, "-X", "main.gitDate="+env.Date)
  256. }
  257. // Strip DWARF on darwin. This used to be required for certain things,
  258. // and there is no downside to this, so we just keep doing it.
  259. if runtime.GOOS == "darwin" {
  260. ld = append(ld, "-s")
  261. }
  262. if len(ld) > 0 {
  263. flags = append(flags, "-ldflags", strings.Join(ld, " "))
  264. }
  265. return flags
  266. }
  267. // goTool returns the go tool. This uses the Go version which runs ci.go.
  268. func goTool(subcmd string, args ...string) *exec.Cmd {
  269. cmd := build.GoTool(subcmd, args...)
  270. goToolSetEnv(cmd)
  271. return cmd
  272. }
  273. // localGoTool returns the go tool from the given GOROOT.
  274. func localGoTool(goroot string, subcmd string, args ...string) *exec.Cmd {
  275. gotool := filepath.Join(goroot, "bin", "go")
  276. cmd := exec.Command(gotool, subcmd)
  277. goToolSetEnv(cmd)
  278. cmd.Env = append(cmd.Env, "GOROOT="+goroot)
  279. cmd.Args = append(cmd.Args, args...)
  280. return cmd
  281. }
  282. // goToolSetEnv forwards the build environment to the go tool.
  283. func goToolSetEnv(cmd *exec.Cmd) {
  284. cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  285. for _, e := range os.Environ() {
  286. if strings.HasPrefix(e, "GOBIN=") || strings.HasPrefix(e, "CC=") {
  287. continue
  288. }
  289. cmd.Env = append(cmd.Env, e)
  290. }
  291. }
  292. // Running The Tests
  293. //
  294. // "tests" also includes static analysis tools such as vet.
  295. func doTest(cmdline []string) {
  296. coverage := flag.Bool("coverage", false, "Whether to record code coverage")
  297. verbose := flag.Bool("v", false, "Whether to log verbosely")
  298. flag.CommandLine.Parse(cmdline)
  299. env := build.Env()
  300. packages := []string{"./..."}
  301. if len(flag.CommandLine.Args()) > 0 {
  302. packages = flag.CommandLine.Args()
  303. }
  304. // Run the actual tests.
  305. // Test a single package at a time. CI builders are slow
  306. // and some tests run into timeouts under load.
  307. gotest := goTool("test", buildFlags(env)...)
  308. gotest.Args = append(gotest.Args, "-p", "1")
  309. if *coverage {
  310. gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
  311. }
  312. if *verbose {
  313. gotest.Args = append(gotest.Args, "-v")
  314. }
  315. gotest.Args = append(gotest.Args, packages...)
  316. build.MustRun(gotest)
  317. }
  318. // doLint runs golangci-lint on requested packages.
  319. func doLint(cmdline []string) {
  320. var (
  321. cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
  322. )
  323. flag.CommandLine.Parse(cmdline)
  324. packages := []string{"./..."}
  325. if len(flag.CommandLine.Args()) > 0 {
  326. packages = flag.CommandLine.Args()
  327. }
  328. linter := downloadLinter(*cachedir)
  329. lflags := []string{"run", "--config", ".golangci.yml"}
  330. build.MustRunCommand(linter, append(lflags, packages...)...)
  331. fmt.Println("You have achieved perfection.")
  332. }
  333. // downloadLinter downloads and unpacks golangci-lint.
  334. func downloadLinter(cachedir string) string {
  335. const version = "1.27.0"
  336. csdb := build.MustLoadChecksums("build/checksums.txt")
  337. base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, runtime.GOARCH)
  338. url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s.tar.gz", version, base)
  339. archivePath := filepath.Join(cachedir, base+".tar.gz")
  340. if err := csdb.DownloadFile(url, archivePath); err != nil {
  341. log.Fatal(err)
  342. }
  343. if err := build.ExtractArchive(archivePath, cachedir); err != nil {
  344. log.Fatal(err)
  345. }
  346. return filepath.Join(cachedir, base, "golangci-lint")
  347. }
  348. // Release Packaging
  349. func doArchive(cmdline []string) {
  350. var (
  351. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  352. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  353. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  354. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  355. ext string
  356. )
  357. flag.CommandLine.Parse(cmdline)
  358. switch *atype {
  359. case "zip":
  360. ext = ".zip"
  361. case "tar":
  362. ext = ".tar.gz"
  363. default:
  364. log.Fatal("unknown archive type: ", atype)
  365. }
  366. var (
  367. env = build.Env()
  368. basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
  369. geth = "geth-" + basegeth + ext
  370. alltools = "geth-alltools-" + basegeth + ext
  371. )
  372. maybeSkipArchive(env)
  373. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  374. log.Fatal(err)
  375. }
  376. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  377. log.Fatal(err)
  378. }
  379. for _, archive := range []string{geth, alltools} {
  380. if err := archiveUpload(archive, *upload, *signer); err != nil {
  381. log.Fatal(err)
  382. }
  383. }
  384. }
  385. func archiveBasename(arch string, archiveVersion string) string {
  386. platform := runtime.GOOS + "-" + arch
  387. if arch == "arm" {
  388. platform += os.Getenv("GOARM")
  389. }
  390. if arch == "android" {
  391. platform = "android-all"
  392. }
  393. if arch == "ios" {
  394. platform = "ios-all"
  395. }
  396. return platform + "-" + archiveVersion
  397. }
  398. func archiveUpload(archive string, blobstore string, signer string) error {
  399. // If signing was requested, generate the signature files
  400. if signer != "" {
  401. key := getenvBase64(signer)
  402. if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
  403. return err
  404. }
  405. }
  406. // If uploading to Azure was requested, push the archive possibly with its signature
  407. if blobstore != "" {
  408. auth := build.AzureBlobstoreConfig{
  409. Account: strings.Split(blobstore, "/")[0],
  410. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  411. Container: strings.SplitN(blobstore, "/", 2)[1],
  412. }
  413. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  414. return err
  415. }
  416. if signer != "" {
  417. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  418. return err
  419. }
  420. }
  421. }
  422. return nil
  423. }
  424. // skips archiving for some build configurations.
  425. func maybeSkipArchive(env build.Environment) {
  426. if env.IsPullRequest {
  427. log.Printf("skipping because this is a PR build")
  428. os.Exit(0)
  429. }
  430. if env.IsCronJob {
  431. log.Printf("skipping because this is a cron job")
  432. os.Exit(0)
  433. }
  434. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  435. log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  436. os.Exit(0)
  437. }
  438. }
  439. // Debian Packaging
  440. func doDebianSource(cmdline []string) {
  441. var (
  442. cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
  443. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  444. upload = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
  445. sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
  446. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  447. now = time.Now()
  448. )
  449. flag.CommandLine.Parse(cmdline)
  450. *workdir = makeWorkdir(*workdir)
  451. env := build.Env()
  452. maybeSkipArchive(env)
  453. // Import the signing key.
  454. if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
  455. gpg := exec.Command("gpg", "--import")
  456. gpg.Stdin = bytes.NewReader(key)
  457. build.MustRun(gpg)
  458. }
  459. // Download and verify the Go source package.
  460. gobundle := downloadGoSources(*cachedir)
  461. // Download all the dependencies needed to build the sources and run the ci script
  462. srcdepfetch := goTool("mod", "download")
  463. srcdepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
  464. build.MustRun(srcdepfetch)
  465. cidepfetch := goTool("run", "./build/ci.go")
  466. cidepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
  467. cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
  468. // Create Debian packages and upload them.
  469. for _, pkg := range debPackages {
  470. for distro, goboot := range debDistroGoBoots {
  471. // Prepare the debian package with the go-ethereum sources.
  472. meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
  473. pkgdir := stageDebianSource(*workdir, meta)
  474. // Add Go source code
  475. if err := build.ExtractArchive(gobundle, pkgdir); err != nil {
  476. log.Fatalf("Failed to extract Go sources: %v", err)
  477. }
  478. if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
  479. log.Fatalf("Failed to rename Go source folder: %v", err)
  480. }
  481. // Add all dependency modules in compressed form
  482. os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
  483. if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
  484. log.Fatalf("Failed to copy Go module dependencies: %v", err)
  485. }
  486. // Run the packaging and upload to the PPA
  487. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
  488. debuild.Dir = pkgdir
  489. build.MustRun(debuild)
  490. var (
  491. basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
  492. source = filepath.Join(*workdir, basename+".tar.xz")
  493. dsc = filepath.Join(*workdir, basename+".dsc")
  494. changes = filepath.Join(*workdir, basename+"_source.changes")
  495. )
  496. if *signer != "" {
  497. build.MustRunCommand("debsign", changes)
  498. }
  499. if *upload != "" {
  500. ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes})
  501. }
  502. }
  503. }
  504. }
  505. // downloadGoSources downloads the Go source tarball.
  506. func downloadGoSources(cachedir string) string {
  507. csdb := build.MustLoadChecksums("build/checksums.txt")
  508. file := fmt.Sprintf("go%s.src.tar.gz", dlgoVersion)
  509. url := "https://dl.google.com/go/" + file
  510. dst := filepath.Join(cachedir, file)
  511. if err := csdb.DownloadFile(url, dst); err != nil {
  512. log.Fatal(err)
  513. }
  514. return dst
  515. }
  516. // downloadGo downloads the Go binary distribution and unpacks it into a temporary
  517. // directory. It returns the GOROOT of the unpacked toolchain.
  518. func downloadGo(goarch, goos, cachedir string) string {
  519. if goarch == "arm" {
  520. goarch = "armv6l"
  521. }
  522. csdb := build.MustLoadChecksums("build/checksums.txt")
  523. file := fmt.Sprintf("go%s.%s-%s", dlgoVersion, goos, goarch)
  524. if goos == "windows" {
  525. file += ".zip"
  526. } else {
  527. file += ".tar.gz"
  528. }
  529. url := "https://golang.org/dl/" + file
  530. dst := filepath.Join(cachedir, file)
  531. if err := csdb.DownloadFile(url, dst); err != nil {
  532. log.Fatal(err)
  533. }
  534. ucache, err := os.UserCacheDir()
  535. if err != nil {
  536. log.Fatal(err)
  537. }
  538. godir := filepath.Join(ucache, fmt.Sprintf("geth-go-%s-%s-%s", dlgoVersion, goos, goarch))
  539. if err := build.ExtractArchive(dst, godir); err != nil {
  540. log.Fatal(err)
  541. }
  542. goroot, err := filepath.Abs(filepath.Join(godir, "go"))
  543. if err != nil {
  544. log.Fatal(err)
  545. }
  546. return goroot
  547. }
  548. func ppaUpload(workdir, ppa, sshUser string, files []string) {
  549. p := strings.Split(ppa, "/")
  550. if len(p) != 2 {
  551. log.Fatal("-upload PPA name must contain single /")
  552. }
  553. if sshUser == "" {
  554. sshUser = p[0]
  555. }
  556. incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
  557. // Create the SSH identity file if it doesn't exist.
  558. var idfile string
  559. if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
  560. idfile = filepath.Join(workdir, "sshkey")
  561. if _, err := os.Stat(idfile); os.IsNotExist(err) {
  562. ioutil.WriteFile(idfile, sshkey, 0600)
  563. }
  564. }
  565. // Upload
  566. dest := sshUser + "@ppa.launchpad.net"
  567. if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
  568. log.Fatal(err)
  569. }
  570. }
  571. func getenvBase64(variable string) []byte {
  572. dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
  573. if err != nil {
  574. log.Fatal("invalid base64 " + variable)
  575. }
  576. return []byte(dec)
  577. }
  578. func makeWorkdir(wdflag string) string {
  579. var err error
  580. if wdflag != "" {
  581. err = os.MkdirAll(wdflag, 0744)
  582. } else {
  583. wdflag, err = ioutil.TempDir("", "geth-build-")
  584. }
  585. if err != nil {
  586. log.Fatal(err)
  587. }
  588. return wdflag
  589. }
  590. func isUnstableBuild(env build.Environment) bool {
  591. if env.Tag != "" {
  592. return false
  593. }
  594. return true
  595. }
  596. type debPackage struct {
  597. Name string // the name of the Debian package to produce, e.g. "ethereum"
  598. Version string // the clean version of the debPackage, e.g. 1.8.12, without any metadata
  599. Executables []debExecutable // executables to be included in the package
  600. }
  601. type debMetadata struct {
  602. Env build.Environment
  603. GoBootPackage string
  604. GoBootPath string
  605. PackageName string
  606. // go-ethereum version being built. Note that this
  607. // is not the debian package version. The package version
  608. // is constructed by VersionString.
  609. Version string
  610. Author string // "name <email>", also selects signing key
  611. Distro, Time string
  612. Executables []debExecutable
  613. }
  614. type debExecutable struct {
  615. PackageName string
  616. BinaryName string
  617. Description string
  618. }
  619. // Package returns the name of the package if present, or
  620. // fallbacks to BinaryName
  621. func (d debExecutable) Package() string {
  622. if d.PackageName != "" {
  623. return d.PackageName
  624. }
  625. return d.BinaryName
  626. }
  627. func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
  628. if author == "" {
  629. // No signing key, use default author.
  630. author = "Ethereum Builds <fjl@ethereum.org>"
  631. }
  632. return debMetadata{
  633. GoBootPackage: goboot,
  634. GoBootPath: debGoBootPaths[goboot],
  635. PackageName: name,
  636. Env: env,
  637. Author: author,
  638. Distro: distro,
  639. Version: version,
  640. Time: t.Format(time.RFC1123Z),
  641. Executables: exes,
  642. }
  643. }
  644. // Name returns the name of the metapackage that depends
  645. // on all executable packages.
  646. func (meta debMetadata) Name() string {
  647. if isUnstableBuild(meta.Env) {
  648. return meta.PackageName + "-unstable"
  649. }
  650. return meta.PackageName
  651. }
  652. // VersionString returns the debian version of the packages.
  653. func (meta debMetadata) VersionString() string {
  654. vsn := meta.Version
  655. if meta.Env.Buildnum != "" {
  656. vsn += "+build" + meta.Env.Buildnum
  657. }
  658. if meta.Distro != "" {
  659. vsn += "+" + meta.Distro
  660. }
  661. return vsn
  662. }
  663. // ExeList returns the list of all executable packages.
  664. func (meta debMetadata) ExeList() string {
  665. names := make([]string, len(meta.Executables))
  666. for i, e := range meta.Executables {
  667. names[i] = meta.ExeName(e)
  668. }
  669. return strings.Join(names, ", ")
  670. }
  671. // ExeName returns the package name of an executable package.
  672. func (meta debMetadata) ExeName(exe debExecutable) string {
  673. if isUnstableBuild(meta.Env) {
  674. return exe.Package() + "-unstable"
  675. }
  676. return exe.Package()
  677. }
  678. // ExeConflicts returns the content of the Conflicts field
  679. // for executable packages.
  680. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  681. if isUnstableBuild(meta.Env) {
  682. // Set up the conflicts list so that the *-unstable packages
  683. // cannot be installed alongside the regular version.
  684. //
  685. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  686. // is very explicit about Conflicts: and says that Breaks: should
  687. // be preferred and the conflicting files should be handled via
  688. // alternates. We might do this eventually but using a conflict is
  689. // easier now.
  690. return "ethereum, " + exe.Package()
  691. }
  692. return ""
  693. }
  694. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  695. pkg := meta.Name() + "-" + meta.VersionString()
  696. pkgdir = filepath.Join(tmpdir, pkg)
  697. if err := os.Mkdir(pkgdir, 0755); err != nil {
  698. log.Fatal(err)
  699. }
  700. // Copy the source code.
  701. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  702. // Put the debian build files in place.
  703. debian := filepath.Join(pkgdir, "debian")
  704. build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  705. build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  706. build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
  707. build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  708. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  709. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  710. for _, exe := range meta.Executables {
  711. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  712. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  713. build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
  714. build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
  715. }
  716. return pkgdir
  717. }
  718. // Windows installer
  719. func doWindowsInstaller(cmdline []string) {
  720. // Parse the flags and make skip installer generation on PRs
  721. var (
  722. arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
  723. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
  724. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  725. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  726. )
  727. flag.CommandLine.Parse(cmdline)
  728. *workdir = makeWorkdir(*workdir)
  729. env := build.Env()
  730. maybeSkipArchive(env)
  731. // Aggregate binaries that are included in the installer
  732. var (
  733. devTools []string
  734. allTools []string
  735. gethTool string
  736. )
  737. for _, file := range allToolsArchiveFiles {
  738. if file == "COPYING" { // license, copied later
  739. continue
  740. }
  741. allTools = append(allTools, filepath.Base(file))
  742. if filepath.Base(file) == "geth.exe" {
  743. gethTool = file
  744. } else {
  745. devTools = append(devTools, file)
  746. }
  747. }
  748. // Render NSIS scripts: Installer NSIS contains two installer sections,
  749. // first section contains the geth binary, second section holds the dev tools.
  750. templateData := map[string]interface{}{
  751. "License": "COPYING",
  752. "Geth": gethTool,
  753. "DevTools": devTools,
  754. }
  755. build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
  756. build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  757. build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  758. build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  759. build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  760. if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
  761. log.Fatal("Failed to copy SimpleFC.dll: %v", err)
  762. }
  763. if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
  764. log.Fatal("Failed to copy copyright note: %v", err)
  765. }
  766. // Build the installer. This assumes that all the needed files have been previously
  767. // built (don't mix building and packaging to keep cross compilation complexity to a
  768. // minimum).
  769. version := strings.Split(params.Version, ".")
  770. if env.Commit != "" {
  771. version[2] += "-" + env.Commit[:8]
  772. }
  773. installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
  774. build.MustRunCommand("makensis.exe",
  775. "/DOUTPUTFILE="+installer,
  776. "/DMAJORVERSION="+version[0],
  777. "/DMINORVERSION="+version[1],
  778. "/DBUILDVERSION="+version[2],
  779. "/DARCH="+*arch,
  780. filepath.Join(*workdir, "geth.nsi"),
  781. )
  782. // Sign and publish installer.
  783. if err := archiveUpload(installer, *upload, *signer); err != nil {
  784. log.Fatal(err)
  785. }
  786. }
  787. // Android archives
  788. func doAndroidArchive(cmdline []string) {
  789. var (
  790. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  791. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
  792. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
  793. upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
  794. )
  795. flag.CommandLine.Parse(cmdline)
  796. env := build.Env()
  797. // Sanity check that the SDK and NDK are installed and set
  798. if os.Getenv("ANDROID_HOME") == "" {
  799. log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
  800. }
  801. // Build the Android archive and Maven resources
  802. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  803. build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
  804. if *local {
  805. // If we're building locally, copy bundle to build dir and skip Maven
  806. os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
  807. os.Rename("geth-sources.jar", filepath.Join(GOBIN, "geth-sources.jar"))
  808. return
  809. }
  810. meta := newMavenMetadata(env)
  811. build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  812. // Skip Maven deploy and Azure upload for PR builds
  813. maybeSkipArchive(env)
  814. // Sign and upload the archive to Azure
  815. archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
  816. os.Rename("geth.aar", archive)
  817. if err := archiveUpload(archive, *upload, *signer); err != nil {
  818. log.Fatal(err)
  819. }
  820. // Sign and upload all the artifacts to Maven Central
  821. os.Rename(archive, meta.Package+".aar")
  822. if *signer != "" && *deploy != "" {
  823. // Import the signing key into the local GPG instance
  824. key := getenvBase64(*signer)
  825. gpg := exec.Command("gpg", "--import")
  826. gpg.Stdin = bytes.NewReader(key)
  827. build.MustRun(gpg)
  828. keyID, err := build.PGPKeyID(string(key))
  829. if err != nil {
  830. log.Fatal(err)
  831. }
  832. // Upload the artifacts to Sonatype and/or Maven Central
  833. repo := *deploy + "/service/local/staging/deploy/maven2"
  834. if meta.Develop {
  835. repo = *deploy + "/content/repositories/snapshots"
  836. }
  837. build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
  838. "-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
  839. "-Dgpg.keyname="+keyID,
  840. "-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
  841. }
  842. }
  843. func gomobileTool(subcmd string, args ...string) *exec.Cmd {
  844. cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
  845. cmd.Args = append(cmd.Args, args...)
  846. cmd.Env = []string{
  847. "PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
  848. }
  849. for _, e := range os.Environ() {
  850. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") || strings.HasPrefix(e, "GOBIN=") {
  851. continue
  852. }
  853. cmd.Env = append(cmd.Env, e)
  854. }
  855. cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  856. return cmd
  857. }
  858. type mavenMetadata struct {
  859. Version string
  860. Package string
  861. Develop bool
  862. Contributors []mavenContributor
  863. }
  864. type mavenContributor struct {
  865. Name string
  866. Email string
  867. }
  868. func newMavenMetadata(env build.Environment) mavenMetadata {
  869. // Collect the list of authors from the repo root
  870. contribs := []mavenContributor{}
  871. if authors, err := os.Open("AUTHORS"); err == nil {
  872. defer authors.Close()
  873. scanner := bufio.NewScanner(authors)
  874. for scanner.Scan() {
  875. // Skip any whitespace from the authors list
  876. line := strings.TrimSpace(scanner.Text())
  877. if line == "" || line[0] == '#' {
  878. continue
  879. }
  880. // Split the author and insert as a contributor
  881. re := regexp.MustCompile("([^<]+) <(.+)>")
  882. parts := re.FindStringSubmatch(line)
  883. if len(parts) == 3 {
  884. contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  885. }
  886. }
  887. }
  888. // Render the version and package strings
  889. version := params.Version
  890. if isUnstableBuild(env) {
  891. version += "-SNAPSHOT"
  892. }
  893. return mavenMetadata{
  894. Version: version,
  895. Package: "geth-" + version,
  896. Develop: isUnstableBuild(env),
  897. Contributors: contribs,
  898. }
  899. }
  900. // XCode frameworks
  901. func doXCodeFramework(cmdline []string) {
  902. var (
  903. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  904. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  905. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  906. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  907. )
  908. flag.CommandLine.Parse(cmdline)
  909. env := build.Env()
  910. // Build the iOS XCode framework
  911. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  912. build.MustRun(gomobileTool("init"))
  913. bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  914. if *local {
  915. // If we're building locally, use the build folder and stop afterwards
  916. bind.Dir = GOBIN
  917. build.MustRun(bind)
  918. return
  919. }
  920. archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
  921. if err := os.Mkdir(archive, os.ModePerm); err != nil {
  922. log.Fatal(err)
  923. }
  924. bind.Dir, _ = filepath.Abs(archive)
  925. build.MustRun(bind)
  926. build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  927. // Skip CocoaPods deploy and Azure upload for PR builds
  928. maybeSkipArchive(env)
  929. // Sign and upload the framework to Azure
  930. if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
  931. log.Fatal(err)
  932. }
  933. // Prepare and upload a PodSpec to CocoaPods
  934. if *deploy != "" {
  935. meta := newPodMetadata(env, archive)
  936. build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  937. build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings")
  938. }
  939. }
  940. type podMetadata struct {
  941. Version string
  942. Commit string
  943. Archive string
  944. Contributors []podContributor
  945. }
  946. type podContributor struct {
  947. Name string
  948. Email string
  949. }
  950. func newPodMetadata(env build.Environment, archive string) podMetadata {
  951. // Collect the list of authors from the repo root
  952. contribs := []podContributor{}
  953. if authors, err := os.Open("AUTHORS"); err == nil {
  954. defer authors.Close()
  955. scanner := bufio.NewScanner(authors)
  956. for scanner.Scan() {
  957. // Skip any whitespace from the authors list
  958. line := strings.TrimSpace(scanner.Text())
  959. if line == "" || line[0] == '#' {
  960. continue
  961. }
  962. // Split the author and insert as a contributor
  963. re := regexp.MustCompile("([^<]+) <(.+)>")
  964. parts := re.FindStringSubmatch(line)
  965. if len(parts) == 3 {
  966. contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  967. }
  968. }
  969. }
  970. version := params.Version
  971. if isUnstableBuild(env) {
  972. version += "-unstable." + env.Buildnum
  973. }
  974. return podMetadata{
  975. Archive: archive,
  976. Version: version,
  977. Commit: env.Commit,
  978. Contributors: contribs,
  979. }
  980. }
  981. // Cross compilation
  982. func doXgo(cmdline []string) {
  983. var (
  984. alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  985. )
  986. flag.CommandLine.Parse(cmdline)
  987. env := build.Env()
  988. // Make sure xgo is available for cross compilation
  989. gogetxgo := goTool("get", "github.com/karalabe/xgo")
  990. build.MustRun(gogetxgo)
  991. // If all tools building is requested, build everything the builder wants
  992. args := append(buildFlags(env), flag.Args()...)
  993. if *alltools {
  994. args = append(args, []string{"--dest", GOBIN}...)
  995. for _, res := range allToolsArchiveFiles {
  996. if strings.HasPrefix(res, GOBIN) {
  997. // Binary tool found, cross build it explicitly
  998. args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  999. xgo := xgoTool(args)
  1000. build.MustRun(xgo)
  1001. args = args[:len(args)-1]
  1002. }
  1003. }
  1004. return
  1005. }
  1006. // Otherwise xxecute the explicit cross compilation
  1007. path := args[len(args)-1]
  1008. args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  1009. xgo := xgoTool(args)
  1010. build.MustRun(xgo)
  1011. }
  1012. func xgoTool(args []string) *exec.Cmd {
  1013. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  1014. cmd.Env = os.Environ()
  1015. cmd.Env = append(cmd.Env, []string{
  1016. "GOBIN=" + GOBIN,
  1017. }...)
  1018. return cmd
  1019. }
  1020. // Binary distribution cleanups
  1021. func doPurge(cmdline []string) {
  1022. var (
  1023. store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1024. limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1025. )
  1026. flag.CommandLine.Parse(cmdline)
  1027. if env := build.Env(); !env.IsCronJob {
  1028. log.Printf("skipping because not a cron job")
  1029. os.Exit(0)
  1030. }
  1031. // Create the azure authentication and list the current archives
  1032. auth := build.AzureBlobstoreConfig{
  1033. Account: strings.Split(*store, "/")[0],
  1034. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1035. Container: strings.SplitN(*store, "/", 2)[1],
  1036. }
  1037. blobs, err := build.AzureBlobstoreList(auth)
  1038. if err != nil {
  1039. log.Fatal(err)
  1040. }
  1041. fmt.Printf("Found %d blobs\n", len(blobs))
  1042. // Iterate over the blobs, collect and sort all unstable builds
  1043. for i := 0; i < len(blobs); i++ {
  1044. if !strings.Contains(blobs[i].Name, "unstable") {
  1045. blobs = append(blobs[:i], blobs[i+1:]...)
  1046. i--
  1047. }
  1048. }
  1049. for i := 0; i < len(blobs); i++ {
  1050. for j := i + 1; j < len(blobs); j++ {
  1051. if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1052. blobs[i], blobs[j] = blobs[j], blobs[i]
  1053. }
  1054. }
  1055. }
  1056. // Filter out all archives more recent that the given threshold
  1057. for i, blob := range blobs {
  1058. if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1059. blobs = blobs[:i]
  1060. break
  1061. }
  1062. }
  1063. fmt.Printf("Deleting %d blobs\n", len(blobs))
  1064. // Delete all marked as such and return
  1065. if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1066. log.Fatal(err)
  1067. }
  1068. }