build.go 38 KB

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