build.go 42 KB

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