build.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  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. args := []string{
  566. "-t", "deb",
  567. "-s", "dir",
  568. "-C", "deb",
  569. "-n", target.debname,
  570. "-v", debver,
  571. "-a", debarch,
  572. "-m", maintainer,
  573. "--vendor", maintainer,
  574. "--description", target.description,
  575. "--url", "https://syncthing.net/",
  576. "--license", "MPL-2",
  577. }
  578. for _, dep := range target.debdeps {
  579. args = append(args, "-d", dep)
  580. }
  581. if target.systemdService != "" {
  582. debpost, err := createPostInstScript(target)
  583. defer os.Remove(debpost)
  584. if err != nil {
  585. log.Fatal(err)
  586. }
  587. args = append(args, "--after-upgrade", debpost)
  588. }
  589. if target.debpre != "" {
  590. args = append(args, "--before-install", target.debpre)
  591. }
  592. runPrint("fpm", args...)
  593. }
  594. func createPostInstScript(target target) (string, error) {
  595. scriptname := filepath.Join("script", "deb-post-inst.template")
  596. t, err := template.ParseFiles(scriptname)
  597. if err != nil {
  598. return "", err
  599. }
  600. scriptname = strings.TrimSuffix(scriptname, ".template")
  601. w, err := os.Create(scriptname)
  602. if err != nil {
  603. return "", err
  604. }
  605. defer w.Close()
  606. if err = t.Execute(w, struct {
  607. Service, Command string
  608. }{
  609. target.systemdService, target.binaryName,
  610. }); err != nil {
  611. return "", err
  612. }
  613. return scriptname, nil
  614. }
  615. func shouldBuildSyso(dir string) (string, error) {
  616. type M map[string]interface{}
  617. version := getVersion()
  618. version = strings.TrimPrefix(version, "v")
  619. major, minor, patch := semanticVersion()
  620. bs, err := json.Marshal(M{
  621. "FixedFileInfo": M{
  622. "FileVersion": M{
  623. "Major": major,
  624. "Minor": minor,
  625. "Patch": patch,
  626. },
  627. "ProductVersion": M{
  628. "Major": major,
  629. "Minor": minor,
  630. "Patch": patch,
  631. },
  632. },
  633. "StringFileInfo": M{
  634. "CompanyName": "The Syncthing Authors",
  635. "FileDescription": "Syncthing - Open Source Continuous File Synchronization",
  636. "FileVersion": version,
  637. "InternalName": "syncthing",
  638. "LegalCopyright": "The Syncthing Authors",
  639. "OriginalFilename": "syncthing",
  640. "ProductName": "Syncthing",
  641. "ProductVersion": version,
  642. },
  643. "IconPath": "assets/logo.ico",
  644. })
  645. if err != nil {
  646. return "", err
  647. }
  648. jsonPath := filepath.Join(dir, "versioninfo.json")
  649. err = os.WriteFile(jsonPath, bs, 0o644)
  650. if err != nil {
  651. return "", errors.New("failed to create " + jsonPath + ": " + err.Error())
  652. }
  653. defer func() {
  654. if err := os.Remove(jsonPath); err != nil {
  655. log.Printf("Warning: unable to remove generated %s: %v. Please remove it manually.", jsonPath, err)
  656. }
  657. }()
  658. sysoPath := filepath.Join(dir, "cmd", "syncthing", "resource.syso")
  659. // See https://github.com/josephspurrier/goversioninfo#command-line-flags
  660. armOption := ""
  661. if strings.Contains(goarch, "arm") {
  662. armOption = "-arm=true"
  663. }
  664. if _, err := runError("goversioninfo", "-o", sysoPath, armOption); err != nil {
  665. return "", errors.New("failed to create " + sysoPath + ": " + err.Error())
  666. }
  667. return sysoPath, nil
  668. }
  669. func shouldCleanupSyso(sysoFilePath string) {
  670. if sysoFilePath == "" {
  671. return
  672. }
  673. if err := os.Remove(sysoFilePath); err != nil {
  674. log.Printf("Warning: unable to remove generated %s: %v. Please remove it manually.", sysoFilePath, err)
  675. }
  676. }
  677. // copyFile copies a file from src to dst, ensuring the containing directory
  678. // exists. The permission bits are copied as well. If dst already exists and
  679. // the contents are identical to src the modification time is not updated.
  680. func copyFile(src, dst string, perm os.FileMode) error {
  681. in, err := os.ReadFile(src)
  682. if err != nil {
  683. return err
  684. }
  685. out, err := os.ReadFile(dst)
  686. if err != nil {
  687. // The destination probably doesn't exist, we should create
  688. // it.
  689. goto copy
  690. }
  691. if bytes.Equal(in, out) {
  692. // The permission bits may have changed without the contents
  693. // changing so we always mirror them.
  694. os.Chmod(dst, perm)
  695. return nil
  696. }
  697. copy:
  698. os.MkdirAll(filepath.Dir(dst), 0o777)
  699. if err := os.WriteFile(dst, in, perm); err != nil {
  700. return err
  701. }
  702. return nil
  703. }
  704. func listFiles(dir string) []string {
  705. var res []string
  706. filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
  707. if err != nil {
  708. return err
  709. }
  710. if fi.Mode().IsRegular() {
  711. res = append(res, path)
  712. }
  713. return nil
  714. })
  715. return res
  716. }
  717. func rebuildAssets() {
  718. os.Setenv("SOURCE_DATE_EPOCH", fmt.Sprint(buildStamp()))
  719. runPrint(goCmd, "generate", "github.com/syncthing/syncthing/lib/api/auto", "github.com/syncthing/syncthing/cmd/infra/strelaypoolsrv/auto")
  720. }
  721. func lazyRebuildAssets() {
  722. shouldRebuild := shouldRebuildAssets("lib/api/auto/gui.files.go", "gui") ||
  723. shouldRebuildAssets("cmd/infra/strelaypoolsrv/auto/gui.files.go", "cmd/infra/strelaypoolsrv/gui")
  724. if withNextGenGUI {
  725. shouldRebuild = buildNextGenGUI() || shouldRebuild
  726. }
  727. if shouldRebuild {
  728. rebuildAssets()
  729. }
  730. }
  731. func buildNextGenGUI() bool {
  732. // Check if we need to run the npm process, and if so also set the flag
  733. // to rebuild Go assets afterwards. The index.html is regenerated every
  734. // time by the build process. This assumes the new GUI ends up in
  735. // next-gen-gui/dist/next-gen-gui.
  736. if !shouldRebuildAssets("gui/next-gen-gui/index.html", "next-gen-gui") {
  737. // The GUI is up to date.
  738. return false
  739. }
  740. runPrintInDir("next-gen-gui", "npm", "install")
  741. runPrintInDir("next-gen-gui", "npm", "run", "build", "--", "--prod", "--subresource-integrity")
  742. rmr("gui/tech-ui")
  743. for _, src := range listFiles("next-gen-gui/dist") {
  744. rel, _ := filepath.Rel("next-gen-gui/dist", src)
  745. dst := filepath.Join("gui", rel)
  746. if err := copyFile(src, dst, 0o644); err != nil {
  747. fmt.Println("copy:", err)
  748. os.Exit(1)
  749. }
  750. }
  751. return true
  752. }
  753. func shouldRebuildAssets(target, srcdir string) bool {
  754. info, err := os.Stat(target)
  755. if err != nil {
  756. // If the file doesn't exist, we must rebuild it
  757. return true
  758. }
  759. // Check if any of the files in gui/ are newer than the asset file. If
  760. // so we should rebuild it.
  761. currentBuild := info.ModTime()
  762. assetsAreNewer := false
  763. stop := errors.New("no need to iterate further")
  764. filepath.Walk(srcdir, func(path string, info os.FileInfo, err error) error {
  765. if err != nil {
  766. return err
  767. }
  768. if info.ModTime().After(currentBuild) {
  769. assetsAreNewer = true
  770. return stop
  771. }
  772. return nil
  773. })
  774. return assetsAreNewer
  775. }
  776. func updateDependencies() {
  777. // Figure out desired Go version
  778. bs, err := os.ReadFile("go.mod")
  779. if err != nil {
  780. log.Fatal(err)
  781. }
  782. re := regexp.MustCompile(`(?m)^go\s+([0-9.]+)`)
  783. matches := re.FindSubmatch(bs)
  784. if len(matches) != 2 {
  785. log.Fatal("failed to parse go.mod")
  786. }
  787. goVersion := string(matches[1])
  788. runPrint(goCmd, "get", "-u", "./...")
  789. runPrint(goCmd, "mod", "tidy", "-go="+goVersion, "-compat="+goVersion)
  790. // We might have updated the protobuf package and should regenerate to match.
  791. proto()
  792. }
  793. func proto() {
  794. // buf needs to be installed
  795. // https://buf.build/docs/installation/
  796. runPrint("buf", "generate")
  797. }
  798. func testmocks() {
  799. args := []string{
  800. "generate",
  801. "github.com/syncthing/syncthing/lib/config",
  802. "github.com/syncthing/syncthing/lib/connections",
  803. "github.com/syncthing/syncthing/lib/discover",
  804. "github.com/syncthing/syncthing/lib/events",
  805. "github.com/syncthing/syncthing/lib/logger",
  806. "github.com/syncthing/syncthing/lib/model",
  807. "github.com/syncthing/syncthing/lib/protocol",
  808. }
  809. runPrint(goCmd, args...)
  810. }
  811. func translate() {
  812. os.Chdir("gui/default/assets/lang")
  813. runPipe("lang-en-new.json", goCmd, "run", "../../../../script/translate.go", "lang-en.json", "../../../")
  814. os.Remove("lang-en.json")
  815. err := os.Rename("lang-en-new.json", "lang-en.json")
  816. if err != nil {
  817. log.Fatal(err)
  818. }
  819. os.Chdir("../../../..")
  820. }
  821. func transifex() {
  822. os.Chdir("gui/default/assets/lang")
  823. runPrint(goCmd, "run", "../../../../script/transifexdl.go")
  824. }
  825. func weblate() {
  826. os.Chdir("gui/default/assets/lang")
  827. runPrint(goCmd, "run", "../../../../script/weblatedl.go")
  828. }
  829. func ldflags(tags []string) string {
  830. b := new(strings.Builder)
  831. b.WriteString("-w")
  832. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Version=%s", version)
  833. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Stamp=%d", buildStamp())
  834. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.User=%s", buildUser())
  835. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Host=%s", buildHost())
  836. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Tags=%s", strings.Join(tags, ","))
  837. if v := os.Getenv("EXTRA_LDFLAGS"); v != "" {
  838. fmt.Fprintf(b, " %s", v)
  839. }
  840. return b.String()
  841. }
  842. func rmr(paths ...string) {
  843. for _, path := range paths {
  844. if debug {
  845. log.Println("rm -r", path)
  846. }
  847. os.RemoveAll(path)
  848. }
  849. }
  850. func getReleaseVersion() (string, error) {
  851. bs, err := os.ReadFile("RELEASE")
  852. if err != nil {
  853. return "", err
  854. }
  855. return string(bytes.TrimSpace(bs)), nil
  856. }
  857. func getGitVersion() (string, error) {
  858. // The current version as Git sees it
  859. bs, err := runError("git", "describe", "--always", "--dirty", "--abbrev=8")
  860. if err != nil {
  861. return "", err
  862. }
  863. vcur := string(bs)
  864. // The closest current tag name
  865. bs, err = runError("git", "describe", "--always", "--abbrev=0")
  866. if err != nil {
  867. return "", err
  868. }
  869. v0 := string(bs)
  870. // To be more semantic-versionish and ensure proper ordering in our
  871. // upgrade process, we make sure there's only one hyphen in the version.
  872. versionRe := regexp.MustCompile(`-([0-9]{1,3}-g[0-9a-f]{5,10}(-dirty)?)`)
  873. if m := versionRe.FindStringSubmatch(vcur); len(m) > 0 {
  874. suffix := strings.ReplaceAll(m[1], "-", ".")
  875. if strings.Contains(v0, "-") {
  876. // We're based of a tag with a prerelease string. We can just
  877. // add our dev stuff directly.
  878. return fmt.Sprintf("%s.dev.%s", v0, suffix), nil
  879. }
  880. // We're based on a release version. We need to bump the patch
  881. // version and then add a -dev prerelease string.
  882. next := nextPatchVersion(v0)
  883. return fmt.Sprintf("%s-dev.%s", next, suffix), nil
  884. }
  885. return vcur, nil
  886. }
  887. func getVersion() string {
  888. // First try for a RELEASE file,
  889. if ver, err := getReleaseVersion(); err == nil {
  890. return ver
  891. }
  892. // ... then see if we have a Git tag.
  893. if ver, err := getGitVersion(); err == nil {
  894. if strings.Contains(ver, "-") {
  895. // The version already contains a hash and stuff. See if we can
  896. // find a current branch name to tack onto it as well.
  897. return ver + getBranchSuffix()
  898. }
  899. return ver
  900. }
  901. // This seems to be a dev build.
  902. return "unknown-dev"
  903. }
  904. func semanticVersion() (major, minor, patch int) {
  905. r := regexp.MustCompile(`v(\d+)\.(\d+).(\d+)`)
  906. matches := r.FindStringSubmatch(getVersion())
  907. if len(matches) != 4 {
  908. return 0, 0, 0
  909. }
  910. var ints [3]int
  911. for i, s := range matches[1:] {
  912. ints[i], _ = strconv.Atoi(s)
  913. }
  914. return ints[0], ints[1], ints[2]
  915. }
  916. func getBranchSuffix() string {
  917. bs, err := runError("git", "branch", "-a", "--contains")
  918. if err != nil {
  919. return ""
  920. }
  921. branches := strings.Split(string(bs), "\n")
  922. if len(branches) == 0 {
  923. return ""
  924. }
  925. branch := ""
  926. for i, candidate := range branches {
  927. if strings.HasPrefix(candidate, "*") {
  928. // This is the current branch. Select it!
  929. branch = strings.TrimLeft(candidate, " \t*")
  930. break
  931. } else if i == 0 {
  932. // Otherwise the first branch in the list will do.
  933. branch = strings.TrimSpace(branch)
  934. }
  935. }
  936. if branch == "" {
  937. return ""
  938. }
  939. // The branch name may be on the form "remotes/origin/foo" from which we
  940. // just want "foo".
  941. parts := strings.Split(branch, "/")
  942. if len(parts) == 0 || len(parts[len(parts)-1]) == 0 {
  943. return ""
  944. }
  945. branch = parts[len(parts)-1]
  946. switch branch {
  947. case "release", "main":
  948. // these are not special
  949. return ""
  950. }
  951. if strings.HasPrefix(branch, "release-") {
  952. // release branches are not special
  953. return ""
  954. }
  955. validBranchRe := regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
  956. if !validBranchRe.MatchString(branch) {
  957. // There's some odd stuff in the branch name. Better skip it.
  958. return ""
  959. }
  960. return "-" + branch
  961. }
  962. func buildStamp() int64 {
  963. // If SOURCE_DATE_EPOCH is set, use that.
  964. if s, _ := strconv.ParseInt(os.Getenv("SOURCE_DATE_EPOCH"), 10, 64); s > 0 {
  965. return s
  966. }
  967. // Try to get the timestamp of the latest commit.
  968. bs, err := runError("git", "show", "-s", "--format=%ct")
  969. if err != nil {
  970. // Fall back to "now".
  971. return time.Now().Unix()
  972. }
  973. s, _ := strconv.ParseInt(string(bs), 10, 64)
  974. return s
  975. }
  976. func buildUser() string {
  977. if v := os.Getenv("BUILD_USER"); v != "" {
  978. return v
  979. }
  980. u, err := user.Current()
  981. if err != nil {
  982. return "unknown-user"
  983. }
  984. return strings.Replace(u.Username, " ", "-", -1)
  985. }
  986. func buildHost() string {
  987. if v := os.Getenv("BUILD_HOST"); v != "" {
  988. return v
  989. }
  990. h, err := os.Hostname()
  991. if err != nil {
  992. return "unknown-host"
  993. }
  994. return h
  995. }
  996. func buildArch() string {
  997. os := goos
  998. if os == "darwin" {
  999. os = "macos"
  1000. }
  1001. return fmt.Sprintf("%s-%s", os, goarch)
  1002. }
  1003. func archiveName(target target) string {
  1004. return fmt.Sprintf("%s-%s-%s", target.name, buildArch(), version)
  1005. }
  1006. func runError(cmd string, args ...string) ([]byte, error) {
  1007. if debug {
  1008. t0 := time.Now()
  1009. log.Println("runError:", cmd, strings.Join(args, " "))
  1010. defer func() {
  1011. log.Println("... in", time.Since(t0))
  1012. }()
  1013. }
  1014. ecmd := exec.Command(cmd, args...)
  1015. bs, err := ecmd.CombinedOutput()
  1016. return bytes.TrimSpace(bs), err
  1017. }
  1018. func runPrint(cmd string, args ...string) {
  1019. runPrintInDir(".", cmd, args...)
  1020. }
  1021. func runPrintInDir(dir string, cmd string, args ...string) {
  1022. if debug {
  1023. t0 := time.Now()
  1024. log.Println("runPrint:", cmd, strings.Join(args, " "))
  1025. defer func() {
  1026. log.Println("... in", time.Since(t0))
  1027. }()
  1028. }
  1029. ecmd := exec.Command(cmd, args...)
  1030. ecmd.Stdout = os.Stdout
  1031. ecmd.Stderr = os.Stderr
  1032. ecmd.Dir = dir
  1033. err := ecmd.Run()
  1034. if err != nil {
  1035. log.Fatal(err)
  1036. }
  1037. }
  1038. func runPipe(file, cmd string, args ...string) {
  1039. if debug {
  1040. t0 := time.Now()
  1041. log.Println("runPipe:", cmd, strings.Join(args, " "))
  1042. defer func() {
  1043. log.Println("... in", time.Since(t0))
  1044. }()
  1045. }
  1046. fd, err := os.Create(file)
  1047. if err != nil {
  1048. log.Fatal(err)
  1049. }
  1050. ecmd := exec.Command(cmd, args...)
  1051. ecmd.Stdout = fd
  1052. ecmd.Stderr = os.Stderr
  1053. err = ecmd.Run()
  1054. if err != nil {
  1055. log.Fatal(err)
  1056. }
  1057. fd.Close()
  1058. }
  1059. func tarGz(out string, files []archiveFile) {
  1060. fd, err := os.Create(out)
  1061. if err != nil {
  1062. log.Fatal(err)
  1063. }
  1064. gw, err := gzip.NewWriterLevel(fd, gzip.BestCompression)
  1065. if err != nil {
  1066. log.Fatal(err)
  1067. }
  1068. tw := tar.NewWriter(gw)
  1069. for _, f := range files {
  1070. sf, err := os.Open(f.src)
  1071. if err != nil {
  1072. log.Fatal(err)
  1073. }
  1074. info, err := sf.Stat()
  1075. if err != nil {
  1076. log.Fatal(err)
  1077. }
  1078. h := &tar.Header{
  1079. Name: f.dst,
  1080. Size: info.Size(),
  1081. Mode: int64(info.Mode()),
  1082. ModTime: info.ModTime(),
  1083. }
  1084. err = tw.WriteHeader(h)
  1085. if err != nil {
  1086. log.Fatal(err)
  1087. }
  1088. _, err = io.Copy(tw, sf)
  1089. if err != nil {
  1090. log.Fatal(err)
  1091. }
  1092. sf.Close()
  1093. }
  1094. err = tw.Close()
  1095. if err != nil {
  1096. log.Fatal(err)
  1097. }
  1098. err = gw.Close()
  1099. if err != nil {
  1100. log.Fatal(err)
  1101. }
  1102. err = fd.Close()
  1103. if err != nil {
  1104. log.Fatal(err)
  1105. }
  1106. }
  1107. func zipFile(out string, files []archiveFile) {
  1108. fd, err := os.Create(out)
  1109. if err != nil {
  1110. log.Fatal(err)
  1111. }
  1112. zw := zip.NewWriter(fd)
  1113. var fw *flate.Writer
  1114. // Register the deflator.
  1115. zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
  1116. var err error
  1117. if fw == nil {
  1118. // Creating a flate compressor for every file is
  1119. // expensive, create one and reuse it.
  1120. fw, err = flate.NewWriter(out, flate.BestCompression)
  1121. } else {
  1122. fw.Reset(out)
  1123. }
  1124. return fw, err
  1125. })
  1126. for _, f := range files {
  1127. sf, err := os.Open(f.src)
  1128. if err != nil {
  1129. log.Fatal(err)
  1130. }
  1131. info, err := sf.Stat()
  1132. if err != nil {
  1133. log.Fatal(err)
  1134. }
  1135. fh, err := zip.FileInfoHeader(info)
  1136. if err != nil {
  1137. log.Fatal(err)
  1138. }
  1139. fh.Name = filepath.ToSlash(f.dst)
  1140. fh.Method = zip.Deflate
  1141. if strings.HasSuffix(f.dst, ".txt") {
  1142. // Text file. Read it and convert line endings.
  1143. bs, err := io.ReadAll(sf)
  1144. if err != nil {
  1145. log.Fatal(err)
  1146. }
  1147. bs = bytes.Replace(bs, []byte{'\n'}, []byte{'\r', '\n'}, -1)
  1148. fh.UncompressedSize = uint32(len(bs))
  1149. fh.UncompressedSize64 = uint64(len(bs))
  1150. of, err := zw.CreateHeader(fh)
  1151. if err != nil {
  1152. log.Fatal(err)
  1153. }
  1154. of.Write(bs)
  1155. } else {
  1156. // Binary file. Copy verbatim.
  1157. of, err := zw.CreateHeader(fh)
  1158. if err != nil {
  1159. log.Fatal(err)
  1160. }
  1161. _, err = io.Copy(of, sf)
  1162. if err != nil {
  1163. log.Fatal(err)
  1164. }
  1165. }
  1166. }
  1167. err = zw.Close()
  1168. if err != nil {
  1169. log.Fatal(err)
  1170. }
  1171. err = fd.Close()
  1172. if err != nil {
  1173. log.Fatal(err)
  1174. }
  1175. }
  1176. func codesign(target target) {
  1177. if goos == "darwin" {
  1178. macosCodesign(target.BinaryName())
  1179. }
  1180. }
  1181. func macosCodesign(file string) {
  1182. if pass := os.Getenv("CODESIGN_KEYCHAIN_PASS"); pass != "" {
  1183. bs, err := runError("security", "unlock-keychain", "-p", pass)
  1184. if err != nil {
  1185. log.Println("Codesign: unlocking keychain failed:", string(bs))
  1186. return
  1187. }
  1188. }
  1189. if id := os.Getenv("CODESIGN_IDENTITY"); id != "" {
  1190. bs, err := runError("codesign", "--options=runtime", "-s", id, file)
  1191. if err != nil {
  1192. log.Println("Codesign: signing failed:", string(bs))
  1193. return
  1194. }
  1195. log.Println("Codesign: successfully signed", file)
  1196. }
  1197. }
  1198. func metalint() {
  1199. lazyRebuildAssets()
  1200. runPrint(goCmd, "test", "-run", "Metalint", "./meta")
  1201. }
  1202. func metalintShort() {
  1203. lazyRebuildAssets()
  1204. runPrint(goCmd, "test", "-short", "-run", "Metalint", "./meta")
  1205. }
  1206. func (t target) BinaryName() string {
  1207. if goos == "windows" {
  1208. return t.binaryName + ".exe"
  1209. }
  1210. return t.binaryName
  1211. }
  1212. func currentAndLatestVersions(n int) ([]string, error) {
  1213. bs, err := runError("git", "tag", "--sort", "taggerdate")
  1214. if err != nil {
  1215. return nil, err
  1216. }
  1217. lines := strings.Split(string(bs), "\n")
  1218. reverseStrings(lines)
  1219. // The one at the head is the latest version. We always keep that one.
  1220. // Then we filter out remaining ones with dashes (pre-releases etc).
  1221. latest := lines[:1]
  1222. nonPres := filterStrings(lines[1:], func(s string) bool { return !strings.Contains(s, "-") })
  1223. vers := append(latest, nonPres...)
  1224. return vers[:n], nil
  1225. }
  1226. func reverseStrings(ss []string) {
  1227. for i := 0; i < len(ss)/2; i++ {
  1228. ss[i], ss[len(ss)-1-i] = ss[len(ss)-1-i], ss[i]
  1229. }
  1230. }
  1231. func filterStrings(ss []string, op func(string) bool) []string {
  1232. n := ss[:0]
  1233. for _, s := range ss {
  1234. if op(s) {
  1235. n = append(n, s)
  1236. }
  1237. }
  1238. return n
  1239. }
  1240. func tagMessage(tag string) (string, error) {
  1241. hash, err := runError("git", "rev-parse", tag)
  1242. if err != nil {
  1243. return "", err
  1244. }
  1245. obj, err := runError("git", "cat-file", "-p", string(hash))
  1246. if err != nil {
  1247. return "", err
  1248. }
  1249. return trimTagMessage(string(obj), tag), nil
  1250. }
  1251. func trimTagMessage(msg, tag string) string {
  1252. firstBlank := strings.Index(msg, "\n\n")
  1253. if firstBlank > 0 {
  1254. msg = msg[firstBlank+2:]
  1255. }
  1256. msg = strings.TrimPrefix(msg, tag)
  1257. beginSig := strings.Index(msg, "-----BEGIN PGP")
  1258. if beginSig > 0 {
  1259. msg = msg[:beginSig]
  1260. }
  1261. return strings.TrimSpace(msg)
  1262. }
  1263. func nextPatchVersion(ver string) string {
  1264. parts := strings.SplitN(ver, "-", 2)
  1265. digits := strings.Split(parts[0], ".")
  1266. n, _ := strconv.Atoi(digits[len(digits)-1])
  1267. digits[len(digits)-1] = strconv.Itoa(n + 1)
  1268. return strings.Join(digits, ".")
  1269. }
  1270. func writeCompatJSON() {
  1271. bs, err := os.ReadFile("compat.yaml")
  1272. if err != nil {
  1273. log.Fatal("Reading compat.yaml:", err)
  1274. }
  1275. var entries []upgrade.ReleaseCompatibility
  1276. if err := yaml.Unmarshal(bs, &entries); err != nil {
  1277. log.Fatal("Parsing compat.yaml:", err)
  1278. }
  1279. rt := runtime.Version()
  1280. for _, e := range entries {
  1281. if !strings.HasPrefix(rt, e.Runtime) {
  1282. continue
  1283. }
  1284. bs, _ := json.MarshalIndent(e, "", " ")
  1285. if err := os.WriteFile("compat.json", bs, 0o644); err != nil {
  1286. log.Fatal("Writing compat.json:", err)
  1287. }
  1288. return
  1289. }
  1290. log.Fatalf("runtime %v not found in compat.yaml", rt)
  1291. }