build.go 42 KB

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