build.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. // +build ignore
  7. package main
  8. import (
  9. "archive/tar"
  10. "archive/zip"
  11. "bytes"
  12. "compress/flate"
  13. "compress/gzip"
  14. "encoding/json"
  15. "errors"
  16. "flag"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "log"
  21. "os"
  22. "os/exec"
  23. "os/user"
  24. "path/filepath"
  25. "regexp"
  26. "runtime"
  27. "strconv"
  28. "strings"
  29. "text/template"
  30. "time"
  31. )
  32. var (
  33. goarch string
  34. goos string
  35. noupgrade bool
  36. version string
  37. goCmd string
  38. race bool
  39. debug = os.Getenv("BUILDDEBUG") != ""
  40. extraTags string
  41. installSuffix string
  42. pkgdir string
  43. cc string
  44. run string
  45. benchRun string
  46. debugBinary bool
  47. coverage bool
  48. long bool
  49. timeout = "120s"
  50. longTimeout = "600s"
  51. numVersions = 5
  52. withNextGenGUI = os.Getenv("BUILD_NEXT_GEN_GUI") != ""
  53. )
  54. type target struct {
  55. name string
  56. debname string
  57. debdeps []string
  58. debpre string
  59. description string
  60. buildPkgs []string
  61. binaryName string
  62. archiveFiles []archiveFile
  63. systemdService string
  64. installationFiles []archiveFile
  65. tags []string
  66. }
  67. type archiveFile struct {
  68. src string
  69. dst string
  70. perm os.FileMode
  71. }
  72. var targets = map[string]target{
  73. "all": {
  74. // Only valid for the "build" and "install" commands as it lacks all
  75. // the archive creation stuff. buildPkgs gets filled out in init()
  76. tags: []string{"purego"},
  77. },
  78. "syncthing": {
  79. // The default target for "build", "install", "tar", "zip", "deb", etc.
  80. name: "syncthing",
  81. debname: "syncthing",
  82. debdeps: []string{"libc6", "procps"},
  83. description: "Open Source Continuous File Synchronization",
  84. buildPkgs: []string{"github.com/syncthing/syncthing/cmd/syncthing"},
  85. binaryName: "syncthing", // .exe will be added automatically for Windows builds
  86. archiveFiles: []archiveFile{
  87. {src: "{{binary}}", dst: "{{binary}}", perm: 0755},
  88. {src: "README.md", dst: "README.txt", perm: 0644},
  89. {src: "LICENSE", dst: "LICENSE.txt", perm: 0644},
  90. {src: "AUTHORS", dst: "AUTHORS.txt", perm: 0644},
  91. // All files from etc/ and extra/ added automatically in init().
  92. },
  93. systemdService: "syncthing@*.service",
  94. installationFiles: []archiveFile{
  95. {src: "{{binary}}", dst: "deb/usr/bin/{{binary}}", perm: 0755},
  96. {src: "README.md", dst: "deb/usr/share/doc/syncthing/README.txt", perm: 0644},
  97. {src: "LICENSE", dst: "deb/usr/share/doc/syncthing/LICENSE.txt", perm: 0644},
  98. {src: "AUTHORS", dst: "deb/usr/share/doc/syncthing/AUTHORS.txt", perm: 0644},
  99. {src: "man/syncthing.1", dst: "deb/usr/share/man/man1/syncthing.1", perm: 0644},
  100. {src: "man/syncthing-config.5", dst: "deb/usr/share/man/man5/syncthing-config.5", perm: 0644},
  101. {src: "man/syncthing-stignore.5", dst: "deb/usr/share/man/man5/syncthing-stignore.5", perm: 0644},
  102. {src: "man/syncthing-device-ids.7", dst: "deb/usr/share/man/man7/syncthing-device-ids.7", perm: 0644},
  103. {src: "man/syncthing-event-api.7", dst: "deb/usr/share/man/man7/syncthing-event-api.7", perm: 0644},
  104. {src: "man/syncthing-faq.7", dst: "deb/usr/share/man/man7/syncthing-faq.7", perm: 0644},
  105. {src: "man/syncthing-networking.7", dst: "deb/usr/share/man/man7/syncthing-networking.7", perm: 0644},
  106. {src: "man/syncthing-rest-api.7", dst: "deb/usr/share/man/man7/syncthing-rest-api.7", perm: 0644},
  107. {src: "man/syncthing-security.7", dst: "deb/usr/share/man/man7/syncthing-security.7", perm: 0644},
  108. {src: "man/syncthing-versioning.7", dst: "deb/usr/share/man/man7/syncthing-versioning.7", perm: 0644},
  109. {src: "etc/linux-systemd/system/syncthing@.service", dst: "deb/lib/systemd/system/syncthing@.service", perm: 0644},
  110. {src: "etc/linux-systemd/system/syncthing-resume.service", dst: "deb/lib/systemd/system/syncthing-resume.service", perm: 0644},
  111. {src: "etc/linux-systemd/user/syncthing.service", dst: "deb/usr/lib/systemd/user/syncthing.service", perm: 0644},
  112. {src: "etc/linux-sysctl/30-syncthing.conf", dst: "deb/usr/lib/sysctl.d/30-syncthing.conf", perm: 0644},
  113. {src: "etc/firewall-ufw/syncthing", dst: "deb/etc/ufw/applications.d/syncthing", perm: 0644},
  114. {src: "etc/linux-desktop/syncthing-start.desktop", dst: "deb/usr/share/applications/syncthing-start.desktop", perm: 0644},
  115. {src: "etc/linux-desktop/syncthing-ui.desktop", dst: "deb/usr/share/applications/syncthing-ui.desktop", perm: 0644},
  116. {src: "assets/logo-32.png", dst: "deb/usr/share/icons/hicolor/32x32/apps/syncthing.png", perm: 0644},
  117. {src: "assets/logo-64.png", dst: "deb/usr/share/icons/hicolor/64x64/apps/syncthing.png", perm: 0644},
  118. {src: "assets/logo-128.png", dst: "deb/usr/share/icons/hicolor/128x128/apps/syncthing.png", perm: 0644},
  119. {src: "assets/logo-256.png", dst: "deb/usr/share/icons/hicolor/256x256/apps/syncthing.png", perm: 0644},
  120. {src: "assets/logo-512.png", dst: "deb/usr/share/icons/hicolor/512x512/apps/syncthing.png", perm: 0644},
  121. {src: "assets/logo-only.svg", dst: "deb/usr/share/icons/hicolor/scalable/apps/syncthing.svg", perm: 0644},
  122. },
  123. },
  124. "stdiscosrv": {
  125. name: "stdiscosrv",
  126. debname: "syncthing-discosrv",
  127. debdeps: []string{"libc6"},
  128. debpre: "cmd/stdiscosrv/scripts/preinst",
  129. description: "Syncthing Discovery Server",
  130. buildPkgs: []string{"github.com/syncthing/syncthing/cmd/stdiscosrv"},
  131. binaryName: "stdiscosrv", // .exe will be added automatically for Windows builds
  132. archiveFiles: []archiveFile{
  133. {src: "{{binary}}", dst: "{{binary}}", perm: 0755},
  134. {src: "cmd/stdiscosrv/README.md", dst: "README.txt", perm: 0644},
  135. {src: "LICENSE", dst: "LICENSE.txt", perm: 0644},
  136. {src: "AUTHORS", dst: "AUTHORS.txt", perm: 0644},
  137. },
  138. systemdService: "cmd/stdiscosrv/etc/linux-systemd/stdiscosrv.service",
  139. installationFiles: []archiveFile{
  140. {src: "{{binary}}", dst: "deb/usr/bin/{{binary}}", perm: 0755},
  141. {src: "cmd/stdiscosrv/README.md", dst: "deb/usr/share/doc/syncthing-discosrv/README.txt", perm: 0644},
  142. {src: "LICENSE", dst: "deb/usr/share/doc/syncthing-discosrv/LICENSE.txt", perm: 0644},
  143. {src: "AUTHORS", dst: "deb/usr/share/doc/syncthing-discosrv/AUTHORS.txt", perm: 0644},
  144. {src: "man/stdiscosrv.1", dst: "deb/usr/share/man/man1/stdiscosrv.1", perm: 0644},
  145. {src: "cmd/stdiscosrv/etc/linux-systemd/stdiscosrv.service", dst: "deb/lib/systemd/system/stdiscosrv.service", perm: 0644},
  146. {src: "cmd/stdiscosrv/etc/linux-systemd/default", dst: "deb/etc/default/syncthing-discosrv", perm: 0644},
  147. {src: "cmd/stdiscosrv/etc/firewall-ufw/stdiscosrv", dst: "deb/etc/ufw/applications.d/stdiscosrv", perm: 0644},
  148. },
  149. tags: []string{"purego"},
  150. },
  151. "strelaysrv": {
  152. name: "strelaysrv",
  153. debname: "syncthing-relaysrv",
  154. debdeps: []string{"libc6"},
  155. debpre: "cmd/strelaysrv/scripts/preinst",
  156. description: "Syncthing Relay Server",
  157. buildPkgs: []string{"github.com/syncthing/syncthing/cmd/strelaysrv"},
  158. binaryName: "strelaysrv", // .exe will be added automatically for Windows builds
  159. archiveFiles: []archiveFile{
  160. {src: "{{binary}}", dst: "{{binary}}", perm: 0755},
  161. {src: "cmd/strelaysrv/README.md", dst: "README.txt", perm: 0644},
  162. {src: "cmd/strelaysrv/LICENSE", dst: "LICENSE.txt", perm: 0644},
  163. {src: "LICENSE", dst: "LICENSE.txt", perm: 0644},
  164. {src: "AUTHORS", dst: "AUTHORS.txt", perm: 0644},
  165. },
  166. systemdService: "cmd/strelaysrv/etc/linux-systemd/strelaysrv.service",
  167. installationFiles: []archiveFile{
  168. {src: "{{binary}}", dst: "deb/usr/bin/{{binary}}", perm: 0755},
  169. {src: "cmd/strelaysrv/README.md", dst: "deb/usr/share/doc/syncthing-relaysrv/README.txt", perm: 0644},
  170. {src: "cmd/strelaysrv/LICENSE", dst: "deb/usr/share/doc/syncthing-relaysrv/LICENSE.txt", perm: 0644},
  171. {src: "LICENSE", dst: "deb/usr/share/doc/syncthing-relaysrv/LICENSE.txt", perm: 0644},
  172. {src: "AUTHORS", dst: "deb/usr/share/doc/syncthing-relaysrv/AUTHORS.txt", perm: 0644},
  173. {src: "man/strelaysrv.1", dst: "deb/usr/share/man/man1/strelaysrv.1", perm: 0644},
  174. {src: "cmd/strelaysrv/etc/linux-systemd/strelaysrv.service", dst: "deb/lib/systemd/system/strelaysrv.service", perm: 0644},
  175. {src: "cmd/strelaysrv/etc/linux-systemd/default", dst: "deb/etc/default/syncthing-relaysrv", perm: 0644},
  176. {src: "cmd/strelaysrv/etc/firewall-ufw/strelaysrv", dst: "deb/etc/ufw/applications.d/strelaysrv", perm: 0644},
  177. },
  178. },
  179. "strelaypoolsrv": {
  180. name: "strelaypoolsrv",
  181. debname: "syncthing-relaypoolsrv",
  182. debdeps: []string{"libc6"},
  183. description: "Syncthing Relay Pool Server",
  184. buildPkgs: []string{"github.com/syncthing/syncthing/cmd/strelaypoolsrv"},
  185. binaryName: "strelaypoolsrv", // .exe will be added automatically for Windows builds
  186. archiveFiles: []archiveFile{
  187. {src: "{{binary}}", dst: "{{binary}}", perm: 0755},
  188. {src: "cmd/strelaypoolsrv/README.md", dst: "README.txt", perm: 0644},
  189. {src: "cmd/strelaypoolsrv/LICENSE", dst: "LICENSE.txt", perm: 0644},
  190. {src: "AUTHORS", dst: "AUTHORS.txt", perm: 0644},
  191. },
  192. installationFiles: []archiveFile{
  193. {src: "{{binary}}", dst: "deb/usr/bin/{{binary}}", perm: 0755},
  194. {src: "cmd/strelaypoolsrv/README.md", dst: "deb/usr/share/doc/syncthing-relaypoolsrv/README.txt", perm: 0644},
  195. {src: "cmd/strelaypoolsrv/LICENSE", dst: "deb/usr/share/doc/syncthing-relaypoolsrv/LICENSE.txt", perm: 0644},
  196. {src: "AUTHORS", dst: "deb/usr/share/doc/syncthing-relaypoolsrv/AUTHORS.txt", perm: 0644},
  197. },
  198. },
  199. }
  200. func initTargets() {
  201. all := targets["all"]
  202. pkgs, _ := filepath.Glob("cmd/*")
  203. for _, pkg := range pkgs {
  204. pkg = filepath.Base(pkg)
  205. if strings.HasPrefix(pkg, ".") {
  206. // ignore dotfiles
  207. continue
  208. }
  209. if noupgrade && pkg == "stupgrades" {
  210. continue
  211. }
  212. all.buildPkgs = append(all.buildPkgs, fmt.Sprintf("github.com/syncthing/syncthing/cmd/%s", pkg))
  213. }
  214. targets["all"] = all
  215. // The "syncthing" target includes a few more files found in the "etc"
  216. // and "extra" dirs.
  217. syncthingPkg := targets["syncthing"]
  218. for _, file := range listFiles("etc") {
  219. syncthingPkg.archiveFiles = append(syncthingPkg.archiveFiles, archiveFile{src: file, dst: file, perm: 0644})
  220. }
  221. for _, file := range listFiles("extra") {
  222. syncthingPkg.archiveFiles = append(syncthingPkg.archiveFiles, archiveFile{src: file, dst: file, perm: 0644})
  223. }
  224. for _, file := range listFiles("extra") {
  225. syncthingPkg.installationFiles = append(syncthingPkg.installationFiles, archiveFile{src: file, dst: "deb/usr/share/doc/syncthing/" + filepath.Base(file), perm: 0644})
  226. }
  227. targets["syncthing"] = syncthingPkg
  228. }
  229. func main() {
  230. log.SetFlags(0)
  231. parseFlags()
  232. if debug {
  233. t0 := time.Now()
  234. defer func() {
  235. log.Println("... build completed in", time.Since(t0))
  236. }()
  237. }
  238. initTargets()
  239. // Invoking build.go with no parameters at all builds everything (incrementally),
  240. // which is what you want for maximum error checking during development.
  241. if flag.NArg() == 0 {
  242. runCommand("install", targets["all"])
  243. } else {
  244. // with any command given but not a target, the target is
  245. // "syncthing". So "go run build.go install" is "go run build.go install
  246. // syncthing" etc.
  247. targetName := "syncthing"
  248. if flag.NArg() > 1 {
  249. targetName = flag.Arg(1)
  250. }
  251. target, ok := targets[targetName]
  252. if !ok {
  253. log.Fatalln("Unknown target", target)
  254. }
  255. runCommand(flag.Arg(0), target)
  256. }
  257. }
  258. func runCommand(cmd string, target target) {
  259. var tags []string
  260. if noupgrade {
  261. tags = []string{"noupgrade"}
  262. }
  263. tags = append(tags, strings.Fields(extraTags)...)
  264. switch cmd {
  265. case "install":
  266. install(target, tags)
  267. metalintShort()
  268. case "build":
  269. build(target, tags)
  270. case "test":
  271. test(strings.Fields(extraTags), "github.com/syncthing/syncthing/lib/...", "github.com/syncthing/syncthing/cmd/...")
  272. case "bench":
  273. bench(strings.Fields(extraTags), "github.com/syncthing/syncthing/lib/...", "github.com/syncthing/syncthing/cmd/...")
  274. case "integration":
  275. integration(false)
  276. case "integrationbench":
  277. integration(true)
  278. case "assets":
  279. rebuildAssets()
  280. case "proto":
  281. proto()
  282. case "testmocks":
  283. testmocks()
  284. case "translate":
  285. translate()
  286. case "transifex":
  287. transifex()
  288. case "tar":
  289. buildTar(target, tags)
  290. case "zip":
  291. buildZip(target, tags)
  292. case "deb":
  293. buildDeb(target)
  294. case "vet":
  295. metalintShort()
  296. case "lint":
  297. metalintShort()
  298. case "metalint":
  299. metalint()
  300. case "version":
  301. fmt.Println(getVersion())
  302. case "changelog":
  303. vers, err := currentAndLatestVersions(numVersions)
  304. if err != nil {
  305. log.Fatal(err)
  306. }
  307. for _, ver := range vers {
  308. underline := strings.Repeat("=", len(ver))
  309. msg, err := tagMessage(ver)
  310. if err != nil {
  311. log.Fatal(err)
  312. }
  313. fmt.Printf("%s\n%s\n\n%s\n\n", ver, underline, msg)
  314. }
  315. default:
  316. log.Fatalf("Unknown command %q", cmd)
  317. }
  318. }
  319. func parseFlags() {
  320. flag.StringVar(&goarch, "goarch", runtime.GOARCH, "GOARCH")
  321. flag.StringVar(&goos, "goos", runtime.GOOS, "GOOS")
  322. flag.StringVar(&goCmd, "gocmd", "go", "Specify `go` command")
  323. flag.BoolVar(&noupgrade, "no-upgrade", noupgrade, "Disable upgrade functionality")
  324. flag.StringVar(&version, "version", getVersion(), "Set compiled in version string")
  325. flag.BoolVar(&race, "race", race, "Use race detector")
  326. flag.StringVar(&extraTags, "tags", extraTags, "Extra tags, space separated")
  327. flag.StringVar(&installSuffix, "installsuffix", installSuffix, "Install suffix, optional")
  328. flag.StringVar(&pkgdir, "pkgdir", "", "Set -pkgdir parameter for `go build`")
  329. flag.StringVar(&cc, "cc", os.Getenv("CC"), "Set CC environment variable for `go build`")
  330. flag.BoolVar(&debugBinary, "debug-binary", debugBinary, "Create unoptimized binary to use with delve, set -gcflags='-N -l' and omit -ldflags")
  331. flag.BoolVar(&coverage, "coverage", coverage, "Write coverage profile of tests to coverage.txt")
  332. flag.BoolVar(&long, "long", long, "Run tests without the -short flag")
  333. flag.IntVar(&numVersions, "num-versions", numVersions, "Number of versions for changelog command")
  334. flag.StringVar(&run, "run", "", "Specify which tests to run")
  335. flag.StringVar(&benchRun, "bench", "", "Specify which benchmarks to run")
  336. flag.BoolVar(&withNextGenGUI, "with-next-gen-gui", withNextGenGUI, "Also build 'newgui'")
  337. flag.Parse()
  338. }
  339. func test(tags []string, pkgs ...string) {
  340. lazyRebuildAssets()
  341. tags = append(tags, "purego")
  342. args := []string{"test", "-tags", strings.Join(tags, " ")}
  343. if long {
  344. timeout = longTimeout
  345. } else {
  346. args = append(args, "-short")
  347. }
  348. args = append(args, "-timeout", timeout)
  349. if runtime.GOARCH == "amd64" {
  350. switch runtime.GOOS {
  351. case "darwin", "linux", "freebsd": // , "windows": # See https://github.com/golang/go/issues/27089
  352. args = append(args, "-race")
  353. }
  354. }
  355. if coverage {
  356. args = append(args, "-covermode", "atomic", "-coverprofile", "coverage.txt", "-coverpkg", strings.Join(pkgs, ","))
  357. }
  358. args = append(args, runArgs()...)
  359. runPrint(goCmd, append(args, pkgs...)...)
  360. }
  361. func bench(tags []string, pkgs ...string) {
  362. lazyRebuildAssets()
  363. args := append([]string{"test", "-run", "NONE", "-tags", strings.Join(tags, " ")}, benchArgs()...)
  364. runPrint(goCmd, append(args, pkgs...)...)
  365. }
  366. func integration(bench bool) {
  367. lazyRebuildAssets()
  368. args := []string{"test", "-v", "-timeout", "60m", "-tags"}
  369. tags := "purego,integration"
  370. if bench {
  371. tags += ",benchmark"
  372. }
  373. args = append(args, tags)
  374. args = append(args, runArgs()...)
  375. if bench {
  376. if run == "" {
  377. args = append(args, "-run", "Benchmark")
  378. }
  379. args = append(args, benchArgs()...)
  380. }
  381. args = append(args, "./test")
  382. fmt.Println(args)
  383. runPrint(goCmd, args...)
  384. }
  385. func runArgs() []string {
  386. if run == "" {
  387. return nil
  388. }
  389. return []string{"-run", run}
  390. }
  391. func benchArgs() []string {
  392. if benchRun == "" {
  393. return []string{"-bench", "."}
  394. }
  395. return []string{"-bench", benchRun}
  396. }
  397. func install(target target, tags []string) {
  398. if (target.name == "syncthing" || target.name == "") && !withNextGenGUI {
  399. log.Println("Notice: Next generation GUI will not be built; see --with-next-gen-gui.")
  400. }
  401. lazyRebuildAssets()
  402. tags = append(target.tags, tags...)
  403. cwd, err := os.Getwd()
  404. if err != nil {
  405. log.Fatal(err)
  406. }
  407. os.Setenv("GOBIN", filepath.Join(cwd, "bin"))
  408. setBuildEnvVars()
  409. // On Windows generate a special file which the Go compiler will
  410. // automatically use when generating Windows binaries to set things like
  411. // the file icon, version, etc.
  412. if goos == "windows" {
  413. sysoPath, err := shouldBuildSyso(cwd)
  414. if err != nil {
  415. log.Printf("Warning: Windows binaries will not have file information encoded: %v", err)
  416. }
  417. defer shouldCleanupSyso(sysoPath)
  418. }
  419. args := []string{"install", "-v"}
  420. args = appendParameters(args, tags, target.buildPkgs...)
  421. runPrint(goCmd, args...)
  422. }
  423. func build(target target, tags []string) {
  424. if (target.name == "syncthing" || target.name == "") && !withNextGenGUI {
  425. log.Println("Notice: Next generation GUI will not be built; see --with-next-gen-gui.")
  426. }
  427. lazyRebuildAssets()
  428. tags = append(target.tags, tags...)
  429. rmr(target.BinaryName())
  430. setBuildEnvVars()
  431. // On Windows generate a special file which the Go compiler will
  432. // automatically use when generating Windows binaries to set things like
  433. // the file icon, version, etc.
  434. if goos == "windows" {
  435. cwd, err := os.Getwd()
  436. if err != nil {
  437. log.Fatal(err)
  438. }
  439. sysoPath, err := shouldBuildSyso(cwd)
  440. if err != nil {
  441. log.Printf("Warning: Windows binaries will not have file information encoded: %v", err)
  442. }
  443. defer shouldCleanupSyso(sysoPath)
  444. }
  445. args := []string{"build", "-v"}
  446. args = appendParameters(args, tags, target.buildPkgs...)
  447. runPrint(goCmd, args...)
  448. }
  449. func setBuildEnvVars() {
  450. os.Setenv("GOOS", goos)
  451. os.Setenv("GOARCH", goarch)
  452. os.Setenv("CC", cc)
  453. if os.Getenv("CGO_ENABLED") == "" {
  454. switch goos {
  455. case "darwin", "solaris":
  456. default:
  457. os.Setenv("CGO_ENABLED", "0")
  458. }
  459. }
  460. }
  461. func appendParameters(args []string, tags []string, pkgs ...string) []string {
  462. if pkgdir != "" {
  463. args = append(args, "-pkgdir", pkgdir)
  464. }
  465. if len(tags) > 0 {
  466. args = append(args, "-tags", strings.Join(tags, " "))
  467. }
  468. if installSuffix != "" {
  469. args = append(args, "-installsuffix", installSuffix)
  470. }
  471. if race {
  472. args = append(args, "-race")
  473. }
  474. if !debugBinary {
  475. // Regular binaries get version tagged and skip some debug symbols
  476. args = append(args, "-trimpath", "-ldflags", ldflags(tags))
  477. } else {
  478. // -gcflags to disable optimizations and inlining. Skip -ldflags
  479. // because `Could not launch program: decoding dwarf section info at
  480. // offset 0x0: too short` on 'dlv exec ...' see
  481. // https://github.com/go-delve/delve/issues/79
  482. args = append(args, "-gcflags", "all=-N -l")
  483. }
  484. return append(args, pkgs...)
  485. }
  486. func buildTar(target target, tags []string) {
  487. name := archiveName(target)
  488. filename := name + ".tar.gz"
  489. for _, tag := range tags {
  490. if tag == "noupgrade" {
  491. name += "-noupgrade"
  492. break
  493. }
  494. }
  495. build(target, tags)
  496. codesign(target)
  497. for i := range target.archiveFiles {
  498. target.archiveFiles[i].src = strings.Replace(target.archiveFiles[i].src, "{{binary}}", target.BinaryName(), 1)
  499. target.archiveFiles[i].dst = strings.Replace(target.archiveFiles[i].dst, "{{binary}}", target.BinaryName(), 1)
  500. target.archiveFiles[i].dst = name + "/" + target.archiveFiles[i].dst
  501. }
  502. tarGz(filename, target.archiveFiles)
  503. fmt.Println(filename)
  504. }
  505. func buildZip(target target, tags []string) {
  506. name := archiveName(target)
  507. filename := name + ".zip"
  508. for _, tag := range tags {
  509. if tag == "noupgrade" {
  510. name += "-noupgrade"
  511. break
  512. }
  513. }
  514. build(target, tags)
  515. codesign(target)
  516. for i := range target.archiveFiles {
  517. target.archiveFiles[i].src = strings.Replace(target.archiveFiles[i].src, "{{binary}}", target.BinaryName(), 1)
  518. target.archiveFiles[i].dst = strings.Replace(target.archiveFiles[i].dst, "{{binary}}", target.BinaryName(), 1)
  519. target.archiveFiles[i].dst = name + "/" + target.archiveFiles[i].dst
  520. }
  521. zipFile(filename, target.archiveFiles)
  522. fmt.Println(filename)
  523. }
  524. func buildDeb(target target) {
  525. os.RemoveAll("deb")
  526. // "goarch" here is set to whatever the Debian packages expect. We correct
  527. // it to what we actually know how to build and keep the Debian variant
  528. // name in "debarch".
  529. debarch := goarch
  530. switch goarch {
  531. case "i386":
  532. goarch = "386"
  533. case "armel", "armhf":
  534. goarch = "arm"
  535. }
  536. build(target, []string{"noupgrade"})
  537. for i := range target.installationFiles {
  538. target.installationFiles[i].src = strings.Replace(target.installationFiles[i].src, "{{binary}}", target.BinaryName(), 1)
  539. target.installationFiles[i].dst = strings.Replace(target.installationFiles[i].dst, "{{binary}}", target.BinaryName(), 1)
  540. }
  541. for _, af := range target.installationFiles {
  542. if err := copyFile(af.src, af.dst, af.perm); err != nil {
  543. log.Fatal(err)
  544. }
  545. }
  546. maintainer := "Syncthing Release Management <release@syncthing.net>"
  547. debver := version
  548. if strings.HasPrefix(debver, "v") {
  549. debver = debver[1:]
  550. // Debian interprets dashes as separator between main version and
  551. // Debian package version, and thus thinks 0.14.26-rc.1 is better
  552. // than just 0.14.26. This rectifies that.
  553. debver = strings.Replace(debver, "-", "~", -1)
  554. }
  555. args := []string{
  556. "-t", "deb",
  557. "-s", "dir",
  558. "-C", "deb",
  559. "-n", target.debname,
  560. "-v", debver,
  561. "-a", debarch,
  562. "-m", maintainer,
  563. "--vendor", maintainer,
  564. "--description", target.description,
  565. "--url", "https://syncthing.net/",
  566. "--license", "MPL-2",
  567. }
  568. for _, dep := range target.debdeps {
  569. args = append(args, "-d", dep)
  570. }
  571. if target.systemdService != "" {
  572. debpost, err := createPostInstScript(target)
  573. defer os.Remove(debpost)
  574. if err != nil {
  575. log.Fatal(err)
  576. }
  577. args = append(args, "--after-upgrade", debpost)
  578. }
  579. if target.debpre != "" {
  580. args = append(args, "--before-install", target.debpre)
  581. }
  582. runPrint("fpm", args...)
  583. }
  584. func createPostInstScript(target target) (string, error) {
  585. scriptname := filepath.Join("script", "deb-post-inst.template")
  586. t, err := template.ParseFiles(scriptname)
  587. if err != nil {
  588. return "", err
  589. }
  590. scriptname = strings.TrimSuffix(scriptname, ".template")
  591. w, err := os.Create(scriptname)
  592. if err != nil {
  593. return "", err
  594. }
  595. defer w.Close()
  596. if err = t.Execute(w, struct {
  597. Service, Command string
  598. }{
  599. target.systemdService, target.binaryName,
  600. }); err != nil {
  601. return "", err
  602. }
  603. return scriptname, nil
  604. }
  605. func shouldBuildSyso(dir string) (string, error) {
  606. type M map[string]interface{}
  607. version := getVersion()
  608. version = strings.TrimPrefix(version, "v")
  609. major, minor, patch := semanticVersion()
  610. bs, err := json.Marshal(M{
  611. "FixedFileInfo": M{
  612. "FileVersion": M{
  613. "Major": major,
  614. "Minor": minor,
  615. "Patch": patch,
  616. },
  617. "ProductVersion": M{
  618. "Major": major,
  619. "Minor": minor,
  620. "Patch": patch,
  621. },
  622. },
  623. "StringFileInfo": M{
  624. "CompanyName": "The Syncthing Authors",
  625. "FileDescription": "Syncthing - Open Source Continuous File Synchronization",
  626. "FileVersion": version,
  627. "InternalName": "syncthing",
  628. "LegalCopyright": "The Syncthing Authors",
  629. "OriginalFilename": "syncthing",
  630. "ProductName": "Syncthing",
  631. "ProductVersion": version,
  632. },
  633. "IconPath": "assets/logo.ico",
  634. })
  635. if err != nil {
  636. return "", err
  637. }
  638. jsonPath := filepath.Join(dir, "versioninfo.json")
  639. err = ioutil.WriteFile(jsonPath, bs, 0644)
  640. if err != nil {
  641. return "", errors.New("failed to create " + jsonPath + ": " + err.Error())
  642. }
  643. defer func() {
  644. if err := os.Remove(jsonPath); err != nil {
  645. log.Printf("Warning: unable to remove generated %s: %v. Please remove it manually.", jsonPath, err)
  646. }
  647. }()
  648. sysoPath := filepath.Join(dir, "cmd", "syncthing", "resource.syso")
  649. if _, err := runError("goversioninfo", "-o", sysoPath); err != nil {
  650. return "", errors.New("failed to create " + sysoPath + ": " + err.Error())
  651. }
  652. return sysoPath, nil
  653. }
  654. func shouldCleanupSyso(sysoFilePath string) {
  655. if sysoFilePath == "" {
  656. return
  657. }
  658. if err := os.Remove(sysoFilePath); err != nil {
  659. log.Printf("Warning: unable to remove generated %s: %v. Please remove it manually.", sysoFilePath, err)
  660. }
  661. }
  662. // copyFile copies a file from src to dst, ensuring the containing directory
  663. // exists. The permission bits are copied as well. If dst already exists and
  664. // the contents are identical to src the modification time is not updated.
  665. func copyFile(src, dst string, perm os.FileMode) error {
  666. in, err := ioutil.ReadFile(src)
  667. if err != nil {
  668. return err
  669. }
  670. out, err := ioutil.ReadFile(dst)
  671. if err != nil {
  672. // The destination probably doesn't exist, we should create
  673. // it.
  674. goto copy
  675. }
  676. if bytes.Equal(in, out) {
  677. // The permission bits may have changed without the contents
  678. // changing so we always mirror them.
  679. os.Chmod(dst, perm)
  680. return nil
  681. }
  682. copy:
  683. os.MkdirAll(filepath.Dir(dst), 0777)
  684. if err := ioutil.WriteFile(dst, in, perm); err != nil {
  685. return err
  686. }
  687. return nil
  688. }
  689. func listFiles(dir string) []string {
  690. var res []string
  691. filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
  692. if err != nil {
  693. return err
  694. }
  695. if fi.Mode().IsRegular() {
  696. res = append(res, path)
  697. }
  698. return nil
  699. })
  700. return res
  701. }
  702. func rebuildAssets() {
  703. os.Setenv("SOURCE_DATE_EPOCH", fmt.Sprint(buildStamp()))
  704. runPrint(goCmd, "generate", "github.com/syncthing/syncthing/lib/api/auto", "github.com/syncthing/syncthing/cmd/strelaypoolsrv/auto")
  705. }
  706. func lazyRebuildAssets() {
  707. shouldRebuild := shouldRebuildAssets("lib/api/auto/gui.files.go", "gui") ||
  708. shouldRebuildAssets("cmd/strelaypoolsrv/auto/gui.files.go", "cmd/strelaypoolsrv/gui")
  709. if withNextGenGUI {
  710. shouldRebuild = buildNextGenGUI() || shouldRebuild
  711. }
  712. if shouldRebuild {
  713. rebuildAssets()
  714. }
  715. }
  716. func buildNextGenGUI() bool {
  717. // Check if we need to run the npm process, and if so also set the flag
  718. // to rebuild Go assets afterwards. The index.html is regenerated every
  719. // time by the build process. This assumes the new GUI ends up in
  720. // next-gen-gui/dist/next-gen-gui.
  721. if !shouldRebuildAssets("gui/next-gen-gui/index.html", "next-gen-gui") {
  722. // The GUI is up to date.
  723. return false
  724. }
  725. runPrintInDir("next-gen-gui", "npm", "install")
  726. runPrintInDir("next-gen-gui", "npm", "run", "build", "--", "--prod", "--subresource-integrity")
  727. rmr("gui/tech-ui")
  728. for _, src := range listFiles("next-gen-gui/dist") {
  729. rel, _ := filepath.Rel("next-gen-gui/dist", src)
  730. dst := filepath.Join("gui", rel)
  731. if err := copyFile(src, dst, 0644); err != nil {
  732. fmt.Println("copy:", err)
  733. os.Exit(1)
  734. }
  735. }
  736. return true
  737. }
  738. func shouldRebuildAssets(target, srcdir string) bool {
  739. info, err := os.Stat(target)
  740. if err != nil {
  741. // If the file doesn't exist, we must rebuild it
  742. return true
  743. }
  744. // Check if any of the files in gui/ are newer than the asset file. If
  745. // so we should rebuild it.
  746. currentBuild := info.ModTime()
  747. assetsAreNewer := false
  748. stop := errors.New("no need to iterate further")
  749. filepath.Walk(srcdir, func(path string, info os.FileInfo, err error) error {
  750. if err != nil {
  751. return err
  752. }
  753. if info.ModTime().After(currentBuild) {
  754. assetsAreNewer = true
  755. return stop
  756. }
  757. return nil
  758. })
  759. return assetsAreNewer
  760. }
  761. func proto() {
  762. pv := protobufVersion()
  763. repo := "https://github.com/gogo/protobuf.git"
  764. path := filepath.Join("repos", "protobuf")
  765. runPrint(goCmd, "get", fmt.Sprintf("github.com/gogo/protobuf/protoc-gen-gogofast@%v", pv))
  766. os.MkdirAll("repos", 0755)
  767. if _, err := os.Stat(path); err != nil {
  768. runPrint("git", "clone", repo, path)
  769. } else {
  770. runPrintInDir(path, "git", "fetch")
  771. }
  772. runPrintInDir(path, "git", "checkout", pv)
  773. runPrint(goCmd, "generate", "github.com/syncthing/syncthing/cmd/stdiscosrv")
  774. runPrint(goCmd, "generate", "proto/generate.go")
  775. }
  776. func testmocks() {
  777. args := []string{
  778. "generate",
  779. "github.com/syncthing/syncthing/lib/config",
  780. "github.com/syncthing/syncthing/lib/connections",
  781. "github.com/syncthing/syncthing/lib/discover",
  782. "github.com/syncthing/syncthing/lib/events",
  783. "github.com/syncthing/syncthing/lib/logger",
  784. "github.com/syncthing/syncthing/lib/model",
  785. "github.com/syncthing/syncthing/lib/protocol",
  786. }
  787. runPrint(goCmd, args...)
  788. }
  789. func translate() {
  790. os.Chdir("gui/default/assets/lang")
  791. runPipe("lang-en-new.json", goCmd, "run", "../../../../script/translate.go", "lang-en.json", "../../../")
  792. os.Remove("lang-en.json")
  793. err := os.Rename("lang-en-new.json", "lang-en.json")
  794. if err != nil {
  795. log.Fatal(err)
  796. }
  797. os.Chdir("../../../..")
  798. }
  799. func transifex() {
  800. os.Chdir("gui/default/assets/lang")
  801. runPrint(goCmd, "run", "../../../../script/transifexdl.go")
  802. }
  803. func ldflags(tags []string) string {
  804. b := new(strings.Builder)
  805. b.WriteString("-w")
  806. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Version=%s", version)
  807. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Stamp=%d", buildStamp())
  808. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.User=%s", buildUser())
  809. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Host=%s", buildHost())
  810. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Tags=%s", strings.Join(tags, ","))
  811. if v := os.Getenv("EXTRA_LDFLAGS"); v != "" {
  812. fmt.Fprintf(b, " %s", v)
  813. }
  814. return b.String()
  815. }
  816. func rmr(paths ...string) {
  817. for _, path := range paths {
  818. if debug {
  819. log.Println("rm -r", path)
  820. }
  821. os.RemoveAll(path)
  822. }
  823. }
  824. func getReleaseVersion() (string, error) {
  825. bs, err := ioutil.ReadFile("RELEASE")
  826. if err != nil {
  827. return "", err
  828. }
  829. return string(bytes.TrimSpace(bs)), nil
  830. }
  831. func getGitVersion() (string, error) {
  832. // The current version as Git sees it
  833. bs, err := runError("git", "describe", "--always", "--dirty", "--abbrev=8")
  834. if err != nil {
  835. return "", err
  836. }
  837. vcur := string(bs)
  838. // The closest current tag name
  839. bs, err = runError("git", "describe", "--always", "--abbrev=0")
  840. if err != nil {
  841. return "", err
  842. }
  843. v0 := string(bs)
  844. // To be more semantic-versionish and ensure proper ordering in our
  845. // upgrade process, we make sure there's only one hypen in the version.
  846. versionRe := regexp.MustCompile(`-([0-9]{1,3}-g[0-9a-f]{5,10}(-dirty)?)`)
  847. if m := versionRe.FindStringSubmatch(vcur); len(m) > 0 {
  848. suffix := strings.ReplaceAll(m[1], "-", ".")
  849. if strings.Contains(v0, "-") {
  850. // We're based of a tag with a prerelease string. We can just
  851. // add our dev stuff directly.
  852. return fmt.Sprintf("%s.dev.%s", v0, suffix), nil
  853. }
  854. // We're based on a release version. We need to bump the patch
  855. // version and then add a -dev prerelease string.
  856. next := nextPatchVersion(v0)
  857. return fmt.Sprintf("%s-dev.%s", next, suffix), nil
  858. }
  859. return vcur, nil
  860. }
  861. func getVersion() string {
  862. // First try for a RELEASE file,
  863. if ver, err := getReleaseVersion(); err == nil {
  864. return ver
  865. }
  866. // ... then see if we have a Git tag.
  867. if ver, err := getGitVersion(); err == nil {
  868. if strings.Contains(ver, "-") {
  869. // The version already contains a hash and stuff. See if we can
  870. // find a current branch name to tack onto it as well.
  871. return ver + getBranchSuffix()
  872. }
  873. return ver
  874. }
  875. // This seems to be a dev build.
  876. return "unknown-dev"
  877. }
  878. func semanticVersion() (major, minor, patch int) {
  879. r := regexp.MustCompile(`v(\d+)\.(\d+).(\d+)`)
  880. matches := r.FindStringSubmatch(getVersion())
  881. if len(matches) != 4 {
  882. return 0, 0, 0
  883. }
  884. var ints [3]int
  885. for i, s := range matches[1:] {
  886. ints[i], _ = strconv.Atoi(s)
  887. }
  888. return ints[0], ints[1], ints[2]
  889. }
  890. func getBranchSuffix() string {
  891. bs, err := runError("git", "branch", "-a", "--contains")
  892. if err != nil {
  893. return ""
  894. }
  895. branches := strings.Split(string(bs), "\n")
  896. if len(branches) == 0 {
  897. return ""
  898. }
  899. branch := ""
  900. for i, candidate := range branches {
  901. if strings.HasPrefix(candidate, "*") {
  902. // This is the current branch. Select it!
  903. branch = strings.TrimLeft(candidate, " \t*")
  904. break
  905. } else if i == 0 {
  906. // Otherwise the first branch in the list will do.
  907. branch = strings.TrimSpace(branch)
  908. }
  909. }
  910. if branch == "" {
  911. return ""
  912. }
  913. // The branch name may be on the form "remotes/origin/foo" from which we
  914. // just want "foo".
  915. parts := strings.Split(branch, "/")
  916. if len(parts) == 0 || len(parts[len(parts)-1]) == 0 {
  917. return ""
  918. }
  919. branch = parts[len(parts)-1]
  920. switch branch {
  921. case "master", "release", "main":
  922. // these are not special
  923. return ""
  924. }
  925. validBranchRe := regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
  926. if !validBranchRe.MatchString(branch) {
  927. // There's some odd stuff in the branch name. Better skip it.
  928. return ""
  929. }
  930. return "-" + branch
  931. }
  932. func buildStamp() int64 {
  933. // If SOURCE_DATE_EPOCH is set, use that.
  934. if s, _ := strconv.ParseInt(os.Getenv("SOURCE_DATE_EPOCH"), 10, 64); s > 0 {
  935. return s
  936. }
  937. // Try to get the timestamp of the latest commit.
  938. bs, err := runError("git", "show", "-s", "--format=%ct")
  939. if err != nil {
  940. // Fall back to "now".
  941. return time.Now().Unix()
  942. }
  943. s, _ := strconv.ParseInt(string(bs), 10, 64)
  944. return s
  945. }
  946. func buildUser() string {
  947. if v := os.Getenv("BUILD_USER"); v != "" {
  948. return v
  949. }
  950. u, err := user.Current()
  951. if err != nil {
  952. return "unknown-user"
  953. }
  954. return strings.Replace(u.Username, " ", "-", -1)
  955. }
  956. func buildHost() string {
  957. if v := os.Getenv("BUILD_HOST"); v != "" {
  958. return v
  959. }
  960. h, err := os.Hostname()
  961. if err != nil {
  962. return "unknown-host"
  963. }
  964. return h
  965. }
  966. func buildArch() string {
  967. os := goos
  968. if os == "darwin" {
  969. os = "macos"
  970. }
  971. return fmt.Sprintf("%s-%s", os, goarch)
  972. }
  973. func archiveName(target target) string {
  974. return fmt.Sprintf("%s-%s-%s", target.name, buildArch(), version)
  975. }
  976. func runError(cmd string, args ...string) ([]byte, error) {
  977. if debug {
  978. t0 := time.Now()
  979. log.Println("runError:", cmd, strings.Join(args, " "))
  980. defer func() {
  981. log.Println("... in", time.Since(t0))
  982. }()
  983. }
  984. ecmd := exec.Command(cmd, args...)
  985. bs, err := ecmd.CombinedOutput()
  986. return bytes.TrimSpace(bs), err
  987. }
  988. func runPrint(cmd string, args ...string) {
  989. runPrintInDir(".", cmd, args...)
  990. }
  991. func runPrintInDir(dir string, cmd string, args ...string) {
  992. if debug {
  993. t0 := time.Now()
  994. log.Println("runPrint:", cmd, strings.Join(args, " "))
  995. defer func() {
  996. log.Println("... in", time.Since(t0))
  997. }()
  998. }
  999. ecmd := exec.Command(cmd, args...)
  1000. ecmd.Stdout = os.Stdout
  1001. ecmd.Stderr = os.Stderr
  1002. ecmd.Dir = dir
  1003. err := ecmd.Run()
  1004. if err != nil {
  1005. log.Fatal(err)
  1006. }
  1007. }
  1008. func runPipe(file, cmd string, args ...string) {
  1009. if debug {
  1010. t0 := time.Now()
  1011. log.Println("runPipe:", cmd, strings.Join(args, " "))
  1012. defer func() {
  1013. log.Println("... in", time.Since(t0))
  1014. }()
  1015. }
  1016. fd, err := os.Create(file)
  1017. if err != nil {
  1018. log.Fatal(err)
  1019. }
  1020. ecmd := exec.Command(cmd, args...)
  1021. ecmd.Stdout = fd
  1022. ecmd.Stderr = os.Stderr
  1023. err = ecmd.Run()
  1024. if err != nil {
  1025. log.Fatal(err)
  1026. }
  1027. fd.Close()
  1028. }
  1029. func tarGz(out string, files []archiveFile) {
  1030. fd, err := os.Create(out)
  1031. if err != nil {
  1032. log.Fatal(err)
  1033. }
  1034. gw, err := gzip.NewWriterLevel(fd, gzip.BestCompression)
  1035. if err != nil {
  1036. log.Fatal(err)
  1037. }
  1038. tw := tar.NewWriter(gw)
  1039. for _, f := range files {
  1040. sf, err := os.Open(f.src)
  1041. if err != nil {
  1042. log.Fatal(err)
  1043. }
  1044. info, err := sf.Stat()
  1045. if err != nil {
  1046. log.Fatal(err)
  1047. }
  1048. h := &tar.Header{
  1049. Name: f.dst,
  1050. Size: info.Size(),
  1051. Mode: int64(info.Mode()),
  1052. ModTime: info.ModTime(),
  1053. }
  1054. err = tw.WriteHeader(h)
  1055. if err != nil {
  1056. log.Fatal(err)
  1057. }
  1058. _, err = io.Copy(tw, sf)
  1059. if err != nil {
  1060. log.Fatal(err)
  1061. }
  1062. sf.Close()
  1063. }
  1064. err = tw.Close()
  1065. if err != nil {
  1066. log.Fatal(err)
  1067. }
  1068. err = gw.Close()
  1069. if err != nil {
  1070. log.Fatal(err)
  1071. }
  1072. err = fd.Close()
  1073. if err != nil {
  1074. log.Fatal(err)
  1075. }
  1076. }
  1077. func zipFile(out string, files []archiveFile) {
  1078. fd, err := os.Create(out)
  1079. if err != nil {
  1080. log.Fatal(err)
  1081. }
  1082. zw := zip.NewWriter(fd)
  1083. var fw *flate.Writer
  1084. // Register the deflator.
  1085. zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
  1086. var err error
  1087. if fw == nil {
  1088. // Creating a flate compressor for every file is
  1089. // expensive, create one and reuse it.
  1090. fw, err = flate.NewWriter(out, flate.BestCompression)
  1091. } else {
  1092. fw.Reset(out)
  1093. }
  1094. return fw, err
  1095. })
  1096. for _, f := range files {
  1097. sf, err := os.Open(f.src)
  1098. if err != nil {
  1099. log.Fatal(err)
  1100. }
  1101. info, err := sf.Stat()
  1102. if err != nil {
  1103. log.Fatal(err)
  1104. }
  1105. fh, err := zip.FileInfoHeader(info)
  1106. if err != nil {
  1107. log.Fatal(err)
  1108. }
  1109. fh.Name = filepath.ToSlash(f.dst)
  1110. fh.Method = zip.Deflate
  1111. if strings.HasSuffix(f.dst, ".txt") {
  1112. // Text file. Read it and convert line endings.
  1113. bs, err := ioutil.ReadAll(sf)
  1114. if err != nil {
  1115. log.Fatal(err)
  1116. }
  1117. bs = bytes.Replace(bs, []byte{'\n'}, []byte{'\n', '\r'}, -1)
  1118. fh.UncompressedSize = uint32(len(bs))
  1119. fh.UncompressedSize64 = uint64(len(bs))
  1120. of, err := zw.CreateHeader(fh)
  1121. if err != nil {
  1122. log.Fatal(err)
  1123. }
  1124. of.Write(bs)
  1125. } else {
  1126. // Binary file. Copy verbatim.
  1127. of, err := zw.CreateHeader(fh)
  1128. if err != nil {
  1129. log.Fatal(err)
  1130. }
  1131. _, err = io.Copy(of, sf)
  1132. if err != nil {
  1133. log.Fatal(err)
  1134. }
  1135. }
  1136. }
  1137. err = zw.Close()
  1138. if err != nil {
  1139. log.Fatal(err)
  1140. }
  1141. err = fd.Close()
  1142. if err != nil {
  1143. log.Fatal(err)
  1144. }
  1145. }
  1146. func codesign(target target) {
  1147. switch goos {
  1148. case "windows":
  1149. windowsCodesign(target.BinaryName())
  1150. case "darwin":
  1151. macosCodesign(target.BinaryName())
  1152. }
  1153. }
  1154. func macosCodesign(file string) {
  1155. if pass := os.Getenv("CODESIGN_KEYCHAIN_PASS"); pass != "" {
  1156. bs, err := runError("security", "unlock-keychain", "-p", pass)
  1157. if err != nil {
  1158. log.Println("Codesign: unlocking keychain failed:", string(bs))
  1159. return
  1160. }
  1161. }
  1162. if id := os.Getenv("CODESIGN_IDENTITY"); id != "" {
  1163. bs, err := runError("codesign", "--options=runtime", "-s", id, file)
  1164. if err != nil {
  1165. log.Println("Codesign: signing failed:", string(bs))
  1166. return
  1167. }
  1168. log.Println("Codesign: successfully signed", file)
  1169. }
  1170. }
  1171. func windowsCodesign(file string) {
  1172. st := "signtool.exe"
  1173. if path := os.Getenv("CODESIGN_SIGNTOOL"); path != "" {
  1174. st = path
  1175. }
  1176. for i, algo := range []string{"sha1", "sha256"} {
  1177. args := []string{"sign", "/fd", algo}
  1178. if f := os.Getenv("CODESIGN_CERTIFICATE_FILE"); f != "" {
  1179. args = append(args, "/f", f)
  1180. }
  1181. if p := os.Getenv("CODESIGN_CERTIFICATE_PASSWORD"); p != "" {
  1182. args = append(args, "/p", p)
  1183. }
  1184. if tr := os.Getenv("CODESIGN_TIMESTAMP_SERVER"); tr != "" {
  1185. switch algo {
  1186. case "sha256":
  1187. args = append(args, "/tr", tr, "/td", algo)
  1188. default:
  1189. args = append(args, "/t", tr)
  1190. }
  1191. }
  1192. if i > 0 {
  1193. args = append(args, "/as")
  1194. }
  1195. args = append(args, file)
  1196. bs, err := runError(st, args...)
  1197. if err != nil {
  1198. log.Println("Codesign: signing failed:", string(bs))
  1199. return
  1200. }
  1201. log.Println("Codesign: successfully signed", file, "using", algo)
  1202. }
  1203. }
  1204. func metalint() {
  1205. lazyRebuildAssets()
  1206. runPrint(goCmd, "test", "-run", "Metalint", "./meta")
  1207. }
  1208. func metalintShort() {
  1209. lazyRebuildAssets()
  1210. runPrint(goCmd, "test", "-short", "-run", "Metalint", "./meta")
  1211. }
  1212. func (t target) BinaryName() string {
  1213. if goos == "windows" {
  1214. return t.binaryName + ".exe"
  1215. }
  1216. return t.binaryName
  1217. }
  1218. func protobufVersion() string {
  1219. bs, err := runError(goCmd, "list", "-f", "{{.Version}}", "-m", "github.com/gogo/protobuf")
  1220. if err != nil {
  1221. log.Fatal("Getting protobuf version:", err)
  1222. }
  1223. return string(bs)
  1224. }
  1225. func currentAndLatestVersions(n int) ([]string, error) {
  1226. bs, err := runError("git", "tag", "--sort", "taggerdate")
  1227. if err != nil {
  1228. return nil, err
  1229. }
  1230. lines := strings.Split(string(bs), "\n")
  1231. reverseStrings(lines)
  1232. // The one at the head is the latest version. We always keep that one.
  1233. // Then we filter out remaining ones with dashes (pre-releases etc).
  1234. latest := lines[:1]
  1235. nonPres := filterStrings(lines[1:], func(s string) bool { return !strings.Contains(s, "-") })
  1236. vers := append(latest, nonPres...)
  1237. return vers[:n], nil
  1238. }
  1239. func reverseStrings(ss []string) {
  1240. for i := 0; i < len(ss)/2; i++ {
  1241. ss[i], ss[len(ss)-1-i] = ss[len(ss)-1-i], ss[i]
  1242. }
  1243. }
  1244. func filterStrings(ss []string, op func(string) bool) []string {
  1245. n := ss[:0]
  1246. for _, s := range ss {
  1247. if op(s) {
  1248. n = append(n, s)
  1249. }
  1250. }
  1251. return n
  1252. }
  1253. func tagMessage(tag string) (string, error) {
  1254. hash, err := runError("git", "rev-parse", tag)
  1255. if err != nil {
  1256. return "", err
  1257. }
  1258. obj, err := runError("git", "cat-file", "-p", string(hash))
  1259. if err != nil {
  1260. return "", err
  1261. }
  1262. return trimTagMessage(string(obj), tag), nil
  1263. }
  1264. func trimTagMessage(msg, tag string) string {
  1265. firstBlank := strings.Index(msg, "\n\n")
  1266. if firstBlank > 0 {
  1267. msg = msg[firstBlank+2:]
  1268. }
  1269. msg = strings.TrimPrefix(msg, tag)
  1270. beginSig := strings.Index(msg, "-----BEGIN PGP")
  1271. if beginSig > 0 {
  1272. msg = msg[:beginSig]
  1273. }
  1274. return strings.TrimSpace(msg)
  1275. }
  1276. func nextPatchVersion(ver string) string {
  1277. parts := strings.SplitN(ver, "-", 2)
  1278. digits := strings.Split(parts[0], ".")
  1279. n, _ := strconv.Atoi(digits[len(digits)-1])
  1280. digits[len(digits)-1] = strconv.Itoa(n + 1)
  1281. return strings.Join(digits, ".")
  1282. }