ci.go 38 KB

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