build.go 40 KB

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