build.go 42 KB

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