build.go 38 KB

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