build.go 38 KB

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