build.go 40 KB

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