build.go 37 KB

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