build.go 40 KB

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