build.go 40 KB

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