build.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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. // These are repos we need to clone to run "go generate"
  198. type dependencyRepo struct {
  199. path string
  200. repo string
  201. commit string
  202. }
  203. var dependencyRepos = []dependencyRepo{
  204. {path: "xdr", repo: "https://github.com/calmh/xdr.git", commit: "08e072f9cb16"},
  205. }
  206. func initTargets() {
  207. all := targets["all"]
  208. pkgs, _ := filepath.Glob("cmd/*")
  209. for _, pkg := range pkgs {
  210. pkg = filepath.Base(pkg)
  211. if strings.HasPrefix(pkg, ".") {
  212. // ignore dotfiles
  213. continue
  214. }
  215. if noupgrade && pkg == "stupgrades" {
  216. continue
  217. }
  218. all.buildPkgs = append(all.buildPkgs, fmt.Sprintf("github.com/syncthing/syncthing/cmd/%s", pkg))
  219. }
  220. targets["all"] = all
  221. // The "syncthing" target includes a few more files found in the "etc"
  222. // and "extra" dirs.
  223. syncthingPkg := targets["syncthing"]
  224. for _, file := range listFiles("etc") {
  225. syncthingPkg.archiveFiles = append(syncthingPkg.archiveFiles, archiveFile{src: file, dst: file, perm: 0644})
  226. }
  227. for _, file := range listFiles("extra") {
  228. syncthingPkg.archiveFiles = append(syncthingPkg.archiveFiles, archiveFile{src: file, dst: file, perm: 0644})
  229. }
  230. for _, file := range listFiles("extra") {
  231. syncthingPkg.installationFiles = append(syncthingPkg.installationFiles, archiveFile{src: file, dst: "deb/usr/share/doc/syncthing/" + filepath.Base(file), perm: 0644})
  232. }
  233. targets["syncthing"] = syncthingPkg
  234. }
  235. func main() {
  236. log.SetFlags(0)
  237. parseFlags()
  238. if debug {
  239. t0 := time.Now()
  240. defer func() {
  241. log.Println("... build completed in", time.Since(t0))
  242. }()
  243. }
  244. initTargets()
  245. // Invoking build.go with no parameters at all builds everything (incrementally),
  246. // which is what you want for maximum error checking during development.
  247. if flag.NArg() == 0 {
  248. runCommand("install", targets["all"])
  249. } else {
  250. // with any command given but not a target, the target is
  251. // "syncthing". So "go run build.go install" is "go run build.go install
  252. // syncthing" etc.
  253. targetName := "syncthing"
  254. if flag.NArg() > 1 {
  255. targetName = flag.Arg(1)
  256. }
  257. target, ok := targets[targetName]
  258. if !ok {
  259. log.Fatalln("Unknown target", target)
  260. }
  261. runCommand(flag.Arg(0), target)
  262. }
  263. }
  264. func runCommand(cmd string, target target) {
  265. var tags []string
  266. if noupgrade {
  267. tags = []string{"noupgrade"}
  268. }
  269. tags = append(tags, strings.Fields(extraTags)...)
  270. switch cmd {
  271. case "install":
  272. install(target, tags)
  273. metalintShort()
  274. case "build":
  275. build(target, tags)
  276. case "test":
  277. test(strings.Fields(extraTags), "github.com/syncthing/syncthing/lib/...", "github.com/syncthing/syncthing/cmd/...")
  278. case "bench":
  279. bench(strings.Fields(extraTags), "github.com/syncthing/syncthing/lib/...", "github.com/syncthing/syncthing/cmd/...")
  280. case "integration":
  281. integration(false)
  282. case "integrationbench":
  283. integration(true)
  284. case "assets":
  285. rebuildAssets()
  286. case "proto":
  287. proto()
  288. case "testmocks":
  289. testmocks()
  290. case "translate":
  291. translate()
  292. case "transifex":
  293. transifex()
  294. case "tar":
  295. buildTar(target, tags)
  296. case "zip":
  297. buildZip(target, tags)
  298. case "deb":
  299. buildDeb(target)
  300. case "vet":
  301. metalintShort()
  302. case "lint":
  303. metalintShort()
  304. case "metalint":
  305. metalint()
  306. case "version":
  307. fmt.Println(getVersion())
  308. case "changelog":
  309. vers, err := currentAndLatestVersions(numVersions)
  310. if err != nil {
  311. log.Fatal(err)
  312. }
  313. for _, ver := range vers {
  314. underline := strings.Repeat("=", len(ver))
  315. msg, err := tagMessage(ver)
  316. if err != nil {
  317. log.Fatal(err)
  318. }
  319. fmt.Printf("%s\n%s\n\n%s\n\n", ver, underline, msg)
  320. }
  321. default:
  322. log.Fatalf("Unknown command %q", cmd)
  323. }
  324. }
  325. func parseFlags() {
  326. flag.StringVar(&goarch, "goarch", runtime.GOARCH, "GOARCH")
  327. flag.StringVar(&goos, "goos", runtime.GOOS, "GOOS")
  328. flag.StringVar(&goCmd, "gocmd", "go", "Specify `go` command")
  329. flag.BoolVar(&noupgrade, "no-upgrade", noupgrade, "Disable upgrade functionality")
  330. flag.StringVar(&version, "version", getVersion(), "Set compiled in version string")
  331. flag.BoolVar(&race, "race", race, "Use race detector")
  332. flag.StringVar(&extraTags, "tags", extraTags, "Extra tags, space separated")
  333. flag.StringVar(&installSuffix, "installsuffix", installSuffix, "Install suffix, optional")
  334. flag.StringVar(&pkgdir, "pkgdir", "", "Set -pkgdir parameter for `go build`")
  335. flag.StringVar(&cc, "cc", os.Getenv("CC"), "Set CC environment variable for `go build`")
  336. flag.BoolVar(&debugBinary, "debug-binary", debugBinary, "Create unoptimized binary to use with delve, set -gcflags='-N -l' and omit -ldflags")
  337. flag.BoolVar(&coverage, "coverage", coverage, "Write coverage profile of tests to coverage.txt")
  338. flag.IntVar(&numVersions, "num-versions", numVersions, "Number of versions for changelog command")
  339. flag.StringVar(&run, "run", "", "Specify which tests to run")
  340. flag.StringVar(&benchRun, "bench", "", "Specify which benchmarks to run")
  341. flag.BoolVar(&withNextGenGUI, "with-next-gen-gui", withNextGenGUI, "Also build 'newgui'")
  342. flag.Parse()
  343. }
  344. func test(tags []string, pkgs ...string) {
  345. lazyRebuildAssets()
  346. tags = append(tags, "purego")
  347. args := []string{"test", "-short", "-timeout", timeout, "-tags", strings.Join(tags, " ")}
  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 <[email protected]>"
  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. dependencyRepos = append(dependencyRepos,
  763. dependencyRepo{path: "protobuf", repo: "https://github.com/gogo/protobuf.git", commit: pv},
  764. )
  765. runPrint(goCmd, "get", fmt.Sprintf("github.com/gogo/protobuf/protoc-gen-gogofast@%v", pv))
  766. os.MkdirAll("repos", 0755)
  767. for _, dep := range dependencyRepos {
  768. path := filepath.Join("repos", dep.path)
  769. if _, err := os.Stat(path); err != nil {
  770. runPrintInDir("repos", "git", "clone", dep.repo, dep.path)
  771. } else {
  772. runPrintInDir(path, "git", "fetch")
  773. }
  774. runPrintInDir(path, "git", "checkout", dep.commit)
  775. }
  776. runPrint(goCmd, "generate", "github.com/syncthing/syncthing/cmd/stdiscosrv")
  777. runPrint(goCmd, "generate", "proto/generate.go")
  778. }
  779. func testmocks() {
  780. runPrint(goCmd, "get", "golang.org/x/tools/cmd/goimports")
  781. runPrint(goCmd, "get", "github.com/maxbrunsfeld/counterfeiter/v6")
  782. args := []string{
  783. "generate",
  784. "github.com/syncthing/syncthing/lib/config",
  785. "github.com/syncthing/syncthing/lib/connections",
  786. "github.com/syncthing/syncthing/lib/discover",
  787. "github.com/syncthing/syncthing/lib/events",
  788. "github.com/syncthing/syncthing/lib/logger",
  789. "github.com/syncthing/syncthing/lib/model",
  790. "github.com/syncthing/syncthing/lib/protocol",
  791. }
  792. runPrint(goCmd, args...)
  793. }
  794. func translate() {
  795. os.Chdir("gui/default/assets/lang")
  796. runPipe("lang-en-new.json", goCmd, "run", "../../../../script/translate.go", "lang-en.json", "../../../")
  797. os.Remove("lang-en.json")
  798. err := os.Rename("lang-en-new.json", "lang-en.json")
  799. if err != nil {
  800. log.Fatal(err)
  801. }
  802. os.Chdir("../../../..")
  803. }
  804. func transifex() {
  805. os.Chdir("gui/default/assets/lang")
  806. runPrint(goCmd, "run", "../../../../script/transifexdl.go")
  807. }
  808. func ldflags(tags []string) string {
  809. b := new(strings.Builder)
  810. b.WriteString("-w")
  811. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Version=%s", version)
  812. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Stamp=%d", buildStamp())
  813. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.User=%s", buildUser())
  814. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Host=%s", buildHost())
  815. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Tags=%s", strings.Join(tags, ","))
  816. if v := os.Getenv("EXTRA_LDFLAGS"); v != "" {
  817. fmt.Fprintf(b, " %s", v)
  818. }
  819. return b.String()
  820. }
  821. func rmr(paths ...string) {
  822. for _, path := range paths {
  823. if debug {
  824. log.Println("rm -r", path)
  825. }
  826. os.RemoveAll(path)
  827. }
  828. }
  829. func getReleaseVersion() (string, error) {
  830. bs, err := ioutil.ReadFile("RELEASE")
  831. if err != nil {
  832. return "", err
  833. }
  834. return string(bytes.TrimSpace(bs)), nil
  835. }
  836. func getGitVersion() (string, error) {
  837. // The current version as Git sees it
  838. bs, err := runError("git", "describe", "--always", "--dirty", "--abbrev=8")
  839. if err != nil {
  840. return "", err
  841. }
  842. vcur := string(bs)
  843. // The closest current tag name
  844. bs, err = runError("git", "describe", "--always", "--abbrev=0")
  845. if err != nil {
  846. return "", err
  847. }
  848. v0 := string(bs)
  849. // To be more semantic-versionish and ensure proper ordering in our
  850. // upgrade process, we make sure there's only one hypen in the version.
  851. versionRe := regexp.MustCompile(`-([0-9]{1,3}-g[0-9a-f]{5,10}(-dirty)?)`)
  852. if m := versionRe.FindStringSubmatch(vcur); len(m) > 0 {
  853. suffix := strings.ReplaceAll(m[1], "-", ".")
  854. if strings.Contains(v0, "-") {
  855. // We're based of a tag with a prerelease string. We can just
  856. // add our dev stuff directly.
  857. return fmt.Sprintf("%s.dev.%s", v0, suffix), nil
  858. }
  859. // We're based on a release version. We need to bump the patch
  860. // version and then add a -dev prerelease string.
  861. next := nextPatchVersion(v0)
  862. return fmt.Sprintf("%s-dev.%s", next, suffix), nil
  863. }
  864. return vcur, nil
  865. }
  866. func getVersion() string {
  867. // First try for a RELEASE file,
  868. if ver, err := getReleaseVersion(); err == nil {
  869. return ver
  870. }
  871. // ... then see if we have a Git tag.
  872. if ver, err := getGitVersion(); err == nil {
  873. if strings.Contains(ver, "-") {
  874. // The version already contains a hash and stuff. See if we can
  875. // find a current branch name to tack onto it as well.
  876. return ver + getBranchSuffix()
  877. }
  878. return ver
  879. }
  880. // This seems to be a dev build.
  881. return "unknown-dev"
  882. }
  883. func semanticVersion() (major, minor, patch int) {
  884. r := regexp.MustCompile(`v(\d+)\.(\d+).(\d+)`)
  885. matches := r.FindStringSubmatch(getVersion())
  886. if len(matches) != 4 {
  887. return 0, 0, 0
  888. }
  889. var ints [3]int
  890. for i, s := range matches[1:] {
  891. ints[i], _ = strconv.Atoi(s)
  892. }
  893. return ints[0], ints[1], ints[2]
  894. }
  895. func getBranchSuffix() string {
  896. bs, err := runError("git", "branch", "-a", "--contains")
  897. if err != nil {
  898. return ""
  899. }
  900. branches := strings.Split(string(bs), "\n")
  901. if len(branches) == 0 {
  902. return ""
  903. }
  904. branch := ""
  905. for i, candidate := range branches {
  906. if strings.HasPrefix(candidate, "*") {
  907. // This is the current branch. Select it!
  908. branch = strings.TrimLeft(candidate, " \t*")
  909. break
  910. } else if i == 0 {
  911. // Otherwise the first branch in the list will do.
  912. branch = strings.TrimSpace(branch)
  913. }
  914. }
  915. if branch == "" {
  916. return ""
  917. }
  918. // The branch name may be on the form "remotes/origin/foo" from which we
  919. // just want "foo".
  920. parts := strings.Split(branch, "/")
  921. if len(parts) == 0 || len(parts[len(parts)-1]) == 0 {
  922. return ""
  923. }
  924. branch = parts[len(parts)-1]
  925. switch branch {
  926. case "master", "release", "main":
  927. // these are not special
  928. return ""
  929. }
  930. validBranchRe := regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
  931. if !validBranchRe.MatchString(branch) {
  932. // There's some odd stuff in the branch name. Better skip it.
  933. return ""
  934. }
  935. return "-" + branch
  936. }
  937. func buildStamp() int64 {
  938. // If SOURCE_DATE_EPOCH is set, use that.
  939. if s, _ := strconv.ParseInt(os.Getenv("SOURCE_DATE_EPOCH"), 10, 64); s > 0 {
  940. return s
  941. }
  942. // Try to get the timestamp of the latest commit.
  943. bs, err := runError("git", "show", "-s", "--format=%ct")
  944. if err != nil {
  945. // Fall back to "now".
  946. return time.Now().Unix()
  947. }
  948. s, _ := strconv.ParseInt(string(bs), 10, 64)
  949. return s
  950. }
  951. func buildUser() string {
  952. if v := os.Getenv("BUILD_USER"); v != "" {
  953. return v
  954. }
  955. u, err := user.Current()
  956. if err != nil {
  957. return "unknown-user"
  958. }
  959. return strings.Replace(u.Username, " ", "-", -1)
  960. }
  961. func buildHost() string {
  962. if v := os.Getenv("BUILD_HOST"); v != "" {
  963. return v
  964. }
  965. h, err := os.Hostname()
  966. if err != nil {
  967. return "unknown-host"
  968. }
  969. return h
  970. }
  971. func buildArch() string {
  972. os := goos
  973. if os == "darwin" {
  974. os = "macos"
  975. }
  976. return fmt.Sprintf("%s-%s", os, goarch)
  977. }
  978. func archiveName(target target) string {
  979. return fmt.Sprintf("%s-%s-%s", target.name, buildArch(), version)
  980. }
  981. func runError(cmd string, args ...string) ([]byte, error) {
  982. if debug {
  983. t0 := time.Now()
  984. log.Println("runError:", cmd, strings.Join(args, " "))
  985. defer func() {
  986. log.Println("... in", time.Since(t0))
  987. }()
  988. }
  989. ecmd := exec.Command(cmd, args...)
  990. bs, err := ecmd.CombinedOutput()
  991. return bytes.TrimSpace(bs), err
  992. }
  993. func runPrint(cmd string, args ...string) {
  994. runPrintInDir(".", cmd, args...)
  995. }
  996. func runPrintInDir(dir string, cmd string, args ...string) {
  997. if debug {
  998. t0 := time.Now()
  999. log.Println("runPrint:", cmd, strings.Join(args, " "))
  1000. defer func() {
  1001. log.Println("... in", time.Since(t0))
  1002. }()
  1003. }
  1004. ecmd := exec.Command(cmd, args...)
  1005. ecmd.Stdout = os.Stdout
  1006. ecmd.Stderr = os.Stderr
  1007. ecmd.Dir = dir
  1008. err := ecmd.Run()
  1009. if err != nil {
  1010. log.Fatal(err)
  1011. }
  1012. }
  1013. func runPipe(file, cmd string, args ...string) {
  1014. if debug {
  1015. t0 := time.Now()
  1016. log.Println("runPipe:", cmd, strings.Join(args, " "))
  1017. defer func() {
  1018. log.Println("... in", time.Since(t0))
  1019. }()
  1020. }
  1021. fd, err := os.Create(file)
  1022. if err != nil {
  1023. log.Fatal(err)
  1024. }
  1025. ecmd := exec.Command(cmd, args...)
  1026. ecmd.Stdout = fd
  1027. ecmd.Stderr = os.Stderr
  1028. err = ecmd.Run()
  1029. if err != nil {
  1030. log.Fatal(err)
  1031. }
  1032. fd.Close()
  1033. }
  1034. func tarGz(out string, files []archiveFile) {
  1035. fd, err := os.Create(out)
  1036. if err != nil {
  1037. log.Fatal(err)
  1038. }
  1039. gw, err := gzip.NewWriterLevel(fd, gzip.BestCompression)
  1040. if err != nil {
  1041. log.Fatal(err)
  1042. }
  1043. tw := tar.NewWriter(gw)
  1044. for _, f := range files {
  1045. sf, err := os.Open(f.src)
  1046. if err != nil {
  1047. log.Fatal(err)
  1048. }
  1049. info, err := sf.Stat()
  1050. if err != nil {
  1051. log.Fatal(err)
  1052. }
  1053. h := &tar.Header{
  1054. Name: f.dst,
  1055. Size: info.Size(),
  1056. Mode: int64(info.Mode()),
  1057. ModTime: info.ModTime(),
  1058. }
  1059. err = tw.WriteHeader(h)
  1060. if err != nil {
  1061. log.Fatal(err)
  1062. }
  1063. _, err = io.Copy(tw, sf)
  1064. if err != nil {
  1065. log.Fatal(err)
  1066. }
  1067. sf.Close()
  1068. }
  1069. err = tw.Close()
  1070. if err != nil {
  1071. log.Fatal(err)
  1072. }
  1073. err = gw.Close()
  1074. if err != nil {
  1075. log.Fatal(err)
  1076. }
  1077. err = fd.Close()
  1078. if err != nil {
  1079. log.Fatal(err)
  1080. }
  1081. }
  1082. func zipFile(out string, files []archiveFile) {
  1083. fd, err := os.Create(out)
  1084. if err != nil {
  1085. log.Fatal(err)
  1086. }
  1087. zw := zip.NewWriter(fd)
  1088. var fw *flate.Writer
  1089. // Register the deflator.
  1090. zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
  1091. var err error
  1092. if fw == nil {
  1093. // Creating a flate compressor for every file is
  1094. // expensive, create one and reuse it.
  1095. fw, err = flate.NewWriter(out, flate.BestCompression)
  1096. } else {
  1097. fw.Reset(out)
  1098. }
  1099. return fw, err
  1100. })
  1101. for _, f := range files {
  1102. sf, err := os.Open(f.src)
  1103. if err != nil {
  1104. log.Fatal(err)
  1105. }
  1106. info, err := sf.Stat()
  1107. if err != nil {
  1108. log.Fatal(err)
  1109. }
  1110. fh, err := zip.FileInfoHeader(info)
  1111. if err != nil {
  1112. log.Fatal(err)
  1113. }
  1114. fh.Name = filepath.ToSlash(f.dst)
  1115. fh.Method = zip.Deflate
  1116. if strings.HasSuffix(f.dst, ".txt") {
  1117. // Text file. Read it and convert line endings.
  1118. bs, err := ioutil.ReadAll(sf)
  1119. if err != nil {
  1120. log.Fatal(err)
  1121. }
  1122. bs = bytes.Replace(bs, []byte{'\n'}, []byte{'\n', '\r'}, -1)
  1123. fh.UncompressedSize = uint32(len(bs))
  1124. fh.UncompressedSize64 = uint64(len(bs))
  1125. of, err := zw.CreateHeader(fh)
  1126. if err != nil {
  1127. log.Fatal(err)
  1128. }
  1129. of.Write(bs)
  1130. } else {
  1131. // Binary file. Copy verbatim.
  1132. of, err := zw.CreateHeader(fh)
  1133. if err != nil {
  1134. log.Fatal(err)
  1135. }
  1136. _, err = io.Copy(of, sf)
  1137. if err != nil {
  1138. log.Fatal(err)
  1139. }
  1140. }
  1141. }
  1142. err = zw.Close()
  1143. if err != nil {
  1144. log.Fatal(err)
  1145. }
  1146. err = fd.Close()
  1147. if err != nil {
  1148. log.Fatal(err)
  1149. }
  1150. }
  1151. func codesign(target target) {
  1152. switch goos {
  1153. case "windows":
  1154. windowsCodesign(target.BinaryName())
  1155. case "darwin":
  1156. macosCodesign(target.BinaryName())
  1157. }
  1158. }
  1159. func macosCodesign(file string) {
  1160. if pass := os.Getenv("CODESIGN_KEYCHAIN_PASS"); pass != "" {
  1161. bs, err := runError("security", "unlock-keychain", "-p", pass)
  1162. if err != nil {
  1163. log.Println("Codesign: unlocking keychain failed:", string(bs))
  1164. return
  1165. }
  1166. }
  1167. if id := os.Getenv("CODESIGN_IDENTITY"); id != "" {
  1168. bs, err := runError("codesign", "--options=runtime", "-s", id, file)
  1169. if err != nil {
  1170. log.Println("Codesign: signing failed:", string(bs))
  1171. return
  1172. }
  1173. log.Println("Codesign: successfully signed", file)
  1174. }
  1175. }
  1176. func windowsCodesign(file string) {
  1177. st := "signtool.exe"
  1178. if path := os.Getenv("CODESIGN_SIGNTOOL"); path != "" {
  1179. st = path
  1180. }
  1181. for i, algo := range []string{"sha1", "sha256"} {
  1182. args := []string{"sign", "/fd", algo}
  1183. if f := os.Getenv("CODESIGN_CERTIFICATE_FILE"); f != "" {
  1184. args = append(args, "/f", f)
  1185. }
  1186. if p := os.Getenv("CODESIGN_CERTIFICATE_PASSWORD"); p != "" {
  1187. args = append(args, "/p", p)
  1188. }
  1189. if tr := os.Getenv("CODESIGN_TIMESTAMP_SERVER"); tr != "" {
  1190. switch algo {
  1191. case "sha256":
  1192. args = append(args, "/tr", tr, "/td", algo)
  1193. default:
  1194. args = append(args, "/t", tr)
  1195. }
  1196. }
  1197. if i > 0 {
  1198. args = append(args, "/as")
  1199. }
  1200. args = append(args, file)
  1201. bs, err := runError(st, args...)
  1202. if err != nil {
  1203. log.Println("Codesign: signing failed:", string(bs))
  1204. return
  1205. }
  1206. log.Println("Codesign: successfully signed", file, "using", algo)
  1207. }
  1208. }
  1209. func metalint() {
  1210. lazyRebuildAssets()
  1211. runPrint(goCmd, "test", "-run", "Metalint", "./meta")
  1212. }
  1213. func metalintShort() {
  1214. lazyRebuildAssets()
  1215. runPrint(goCmd, "test", "-short", "-run", "Metalint", "./meta")
  1216. }
  1217. func temporaryBuildDir() (string, error) {
  1218. // The base of our temp dir is "syncthing-xxxxxxxx" where the x:es
  1219. // are eight bytes from the sha256 of our working directory. We do
  1220. // this because we want a name in the global temp dir that doesn't
  1221. // conflict with someone else building syncthing on the same
  1222. // machine, yet is persistent between runs from the same source
  1223. // directory.
  1224. wd, err := os.Getwd()
  1225. if err != nil {
  1226. return "", err
  1227. }
  1228. hash := sha256.Sum256([]byte(wd))
  1229. base := fmt.Sprintf("syncthing-%x", hash[:4])
  1230. // The temp dir is taken from $STTMPDIR if set, otherwise the system
  1231. // default (potentially infrluenced by $TMPDIR on unixes).
  1232. var tmpDir string
  1233. if t := os.Getenv("STTMPDIR"); t != "" {
  1234. tmpDir = t
  1235. } else {
  1236. tmpDir = os.TempDir()
  1237. }
  1238. return filepath.Join(tmpDir, base), nil
  1239. }
  1240. func (t target) BinaryName() string {
  1241. if goos == "windows" {
  1242. return t.binaryName + ".exe"
  1243. }
  1244. return t.binaryName
  1245. }
  1246. func protobufVersion() string {
  1247. bs, err := runError(goCmd, "list", "-f", "{{.Version}}", "-m", "github.com/gogo/protobuf")
  1248. if err != nil {
  1249. log.Fatal("Getting protobuf version:", err)
  1250. }
  1251. return string(bs)
  1252. }
  1253. func currentAndLatestVersions(n int) ([]string, error) {
  1254. bs, err := runError("git", "tag", "--sort", "taggerdate")
  1255. if err != nil {
  1256. return nil, err
  1257. }
  1258. lines := strings.Split(string(bs), "\n")
  1259. reverseStrings(lines)
  1260. // The one at the head is the latest version. We always keep that one.
  1261. // Then we filter out remaining ones with dashes (pre-releases etc).
  1262. latest := lines[:1]
  1263. nonPres := filterStrings(lines[1:], func(s string) bool { return !strings.Contains(s, "-") })
  1264. vers := append(latest, nonPres...)
  1265. return vers[:n], nil
  1266. }
  1267. func reverseStrings(ss []string) {
  1268. for i := 0; i < len(ss)/2; i++ {
  1269. ss[i], ss[len(ss)-1-i] = ss[len(ss)-1-i], ss[i]
  1270. }
  1271. }
  1272. func filterStrings(ss []string, op func(string) bool) []string {
  1273. n := ss[:0]
  1274. for _, s := range ss {
  1275. if op(s) {
  1276. n = append(n, s)
  1277. }
  1278. }
  1279. return n
  1280. }
  1281. func tagMessage(tag string) (string, error) {
  1282. hash, err := runError("git", "rev-parse", tag)
  1283. if err != nil {
  1284. return "", err
  1285. }
  1286. obj, err := runError("git", "cat-file", "-p", string(hash))
  1287. if err != nil {
  1288. return "", err
  1289. }
  1290. return trimTagMessage(string(obj), tag), nil
  1291. }
  1292. func trimTagMessage(msg, tag string) string {
  1293. firstBlank := strings.Index(msg, "\n\n")
  1294. if firstBlank > 0 {
  1295. msg = msg[firstBlank+2:]
  1296. }
  1297. msg = strings.TrimPrefix(msg, tag)
  1298. beginSig := strings.Index(msg, "-----BEGIN PGP")
  1299. if beginSig > 0 {
  1300. msg = msg[:beginSig]
  1301. }
  1302. return strings.TrimSpace(msg)
  1303. }
  1304. func nextPatchVersion(ver string) string {
  1305. parts := strings.SplitN(ver, "-", 2)
  1306. digits := strings.Split(parts[0], ".")
  1307. n, _ := strconv.Atoi(digits[len(digits)-1])
  1308. digits[len(digits)-1] = strconv.Itoa(n + 1)
  1309. return strings.Join(digits, ".")
  1310. }