build.go 40 KB

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