build.go 40 KB

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