build.go 40 KB

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