build.go 40 KB

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