build.go 41 KB

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