build.go 43 KB

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