build.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  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("github.com/syncthing/syncthing/lib/...", "github.com/syncthing/syncthing/cmd/...")
  281. case "bench":
  282. bench("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(pkgs ...string) {
  345. lazyRebuildAssets()
  346. args := []string{"test", "-short", "-timeout", timeout, "-tags", "purego"}
  347. if runtime.GOARCH == "amd64" {
  348. switch runtime.GOOS {
  349. case "darwin", "linux", "freebsd": // , "windows": # See https://github.com/golang/go/issues/27089
  350. args = append(args, "-race")
  351. }
  352. }
  353. if coverage {
  354. args = append(args, "-covermode", "atomic", "-coverprofile", "coverage.txt", "-coverpkg", strings.Join(pkgs, ","))
  355. }
  356. args = append(args, runArgs()...)
  357. runPrint(goCmd, append(args, pkgs...)...)
  358. }
  359. func bench(pkgs ...string) {
  360. lazyRebuildAssets()
  361. args := append([]string{"test", "-run", "NONE"}, benchArgs()...)
  362. runPrint(goCmd, append(args, pkgs...)...)
  363. }
  364. func integration(bench bool) {
  365. lazyRebuildAssets()
  366. args := []string{"test", "-v", "-timeout", "60m", "-tags"}
  367. tags := "purego,integration"
  368. if bench {
  369. tags += ",benchmark"
  370. }
  371. args = append(args, tags)
  372. args = append(args, runArgs()...)
  373. if bench {
  374. if run == "" {
  375. args = append(args, "-run", "Benchmark")
  376. }
  377. args = append(args, benchArgs()...)
  378. }
  379. args = append(args, "./test")
  380. fmt.Println(args)
  381. runPrint(goCmd, args...)
  382. }
  383. func runArgs() []string {
  384. if run == "" {
  385. return nil
  386. }
  387. return []string{"-run", run}
  388. }
  389. func benchArgs() []string {
  390. if benchRun == "" {
  391. return []string{"-bench", "."}
  392. }
  393. return []string{"-bench", benchRun}
  394. }
  395. func install(target target, tags []string) {
  396. lazyRebuildAssets()
  397. tags = append(target.tags, tags...)
  398. cwd, err := os.Getwd()
  399. if err != nil {
  400. log.Fatal(err)
  401. }
  402. os.Setenv("GOBIN", filepath.Join(cwd, "bin"))
  403. setBuildEnvVars()
  404. // On Windows generate a special file which the Go compiler will
  405. // automatically use when generating Windows binaries to set things like
  406. // the file icon, version, etc.
  407. if goos == "windows" {
  408. sysoPath, err := shouldBuildSyso(cwd)
  409. if err != nil {
  410. log.Printf("Warning: Windows binaries will not have file information encoded: %v", err)
  411. }
  412. defer shouldCleanupSyso(sysoPath)
  413. }
  414. args := []string{"install", "-v"}
  415. args = appendParameters(args, tags, target.buildPkgs...)
  416. runPrint(goCmd, args...)
  417. }
  418. func build(target target, tags []string) {
  419. lazyRebuildAssets()
  420. tags = append(target.tags, tags...)
  421. rmr(target.BinaryName())
  422. setBuildEnvVars()
  423. // On Windows generate a special file which the Go compiler will
  424. // automatically use when generating Windows binaries to set things like
  425. // the file icon, version, etc.
  426. if goos == "windows" {
  427. cwd, err := os.Getwd()
  428. if err != nil {
  429. log.Fatal(err)
  430. }
  431. sysoPath, err := shouldBuildSyso(cwd)
  432. if err != nil {
  433. log.Printf("Warning: Windows binaries will not have file information encoded: %v", err)
  434. }
  435. defer shouldCleanupSyso(sysoPath)
  436. }
  437. args := []string{"build", "-v"}
  438. args = appendParameters(args, tags, target.buildPkgs...)
  439. runPrint(goCmd, args...)
  440. }
  441. func setBuildEnvVars() {
  442. os.Setenv("GOOS", goos)
  443. os.Setenv("GOARCH", goarch)
  444. os.Setenv("CC", cc)
  445. if os.Getenv("CGO_ENABLED") == "" {
  446. switch goos {
  447. case "darwin", "solaris":
  448. default:
  449. os.Setenv("CGO_ENABLED", "0")
  450. }
  451. }
  452. }
  453. func appendParameters(args []string, tags []string, pkgs ...string) []string {
  454. if pkgdir != "" {
  455. args = append(args, "-pkgdir", pkgdir)
  456. }
  457. if len(tags) > 0 {
  458. args = append(args, "-tags", strings.Join(tags, " "))
  459. }
  460. if installSuffix != "" {
  461. args = append(args, "-installsuffix", installSuffix)
  462. }
  463. if race {
  464. args = append(args, "-race")
  465. }
  466. if !debugBinary {
  467. // Regular binaries get version tagged and skip some debug symbols
  468. args = append(args, "-ldflags", ldflags())
  469. } else {
  470. // -gcflags to disable optimizations and inlining. Skip -ldflags
  471. // because `Could not launch program: decoding dwarf section info at
  472. // offset 0x0: too short` on 'dlv exec ...' see
  473. // https://github.com/derekparker/delve/issues/79
  474. args = append(args, "-gcflags", "-N -l")
  475. }
  476. return append(args, pkgs...)
  477. }
  478. func buildTar(target target) {
  479. name := archiveName(target)
  480. filename := name + ".tar.gz"
  481. var tags []string
  482. if noupgrade {
  483. tags = []string{"noupgrade"}
  484. name += "-noupgrade"
  485. }
  486. build(target, tags)
  487. codesign(target)
  488. for i := range target.archiveFiles {
  489. target.archiveFiles[i].src = strings.Replace(target.archiveFiles[i].src, "{{binary}}", target.BinaryName(), 1)
  490. target.archiveFiles[i].dst = strings.Replace(target.archiveFiles[i].dst, "{{binary}}", target.BinaryName(), 1)
  491. target.archiveFiles[i].dst = name + "/" + target.archiveFiles[i].dst
  492. }
  493. tarGz(filename, target.archiveFiles)
  494. fmt.Println(filename)
  495. }
  496. func buildZip(target target) {
  497. name := archiveName(target)
  498. filename := name + ".zip"
  499. var tags []string
  500. if noupgrade {
  501. tags = []string{"noupgrade"}
  502. name += "-noupgrade"
  503. }
  504. build(target, tags)
  505. codesign(target)
  506. for i := range target.archiveFiles {
  507. target.archiveFiles[i].src = strings.Replace(target.archiveFiles[i].src, "{{binary}}", target.BinaryName(), 1)
  508. target.archiveFiles[i].dst = strings.Replace(target.archiveFiles[i].dst, "{{binary}}", target.BinaryName(), 1)
  509. target.archiveFiles[i].dst = name + "/" + target.archiveFiles[i].dst
  510. }
  511. zipFile(filename, target.archiveFiles)
  512. fmt.Println(filename)
  513. }
  514. func buildDeb(target target) {
  515. os.RemoveAll("deb")
  516. // "goarch" here is set to whatever the Debian packages expect. We correct
  517. // it to what we actually know how to build and keep the Debian variant
  518. // name in "debarch".
  519. debarch := goarch
  520. switch goarch {
  521. case "i386":
  522. goarch = "386"
  523. case "armel", "armhf":
  524. goarch = "arm"
  525. }
  526. build(target, []string{"noupgrade"})
  527. for i := range target.installationFiles {
  528. target.installationFiles[i].src = strings.Replace(target.installationFiles[i].src, "{{binary}}", target.BinaryName(), 1)
  529. target.installationFiles[i].dst = strings.Replace(target.installationFiles[i].dst, "{{binary}}", target.BinaryName(), 1)
  530. }
  531. for _, af := range target.installationFiles {
  532. if err := copyFile(af.src, af.dst, af.perm); err != nil {
  533. log.Fatal(err)
  534. }
  535. }
  536. maintainer := "Syncthing Release Management <[email protected]>"
  537. debver := version
  538. if strings.HasPrefix(debver, "v") {
  539. debver = debver[1:]
  540. // Debian interprets dashes as separator between main version and
  541. // Debian package version, and thus thinks 0.14.26-rc.1 is better
  542. // than just 0.14.26. This rectifies that.
  543. debver = strings.Replace(debver, "-", "~", -1)
  544. }
  545. args := []string{
  546. "-t", "deb",
  547. "-s", "dir",
  548. "-C", "deb",
  549. "-n", target.debname,
  550. "-v", debver,
  551. "-a", debarch,
  552. "-m", maintainer,
  553. "--vendor", maintainer,
  554. "--description", target.description,
  555. "--url", "https://syncthing.net/",
  556. "--license", "MPL-2",
  557. }
  558. for _, dep := range target.debdeps {
  559. args = append(args, "-d", dep)
  560. }
  561. for _, service := range target.systemdServices {
  562. args = append(args, "--deb-systemd", service)
  563. }
  564. if target.debpost != "" {
  565. args = append(args, "--after-upgrade", target.debpost)
  566. }
  567. if target.debpre != "" {
  568. args = append(args, "--before-install", target.debpre)
  569. }
  570. runPrint("fpm", args...)
  571. }
  572. func shouldBuildSyso(dir string) (string, error) {
  573. type M map[string]interface{}
  574. version := getVersion()
  575. version = strings.TrimPrefix(version, "v")
  576. major, minor, patch := semanticVersion()
  577. bs, err := json.Marshal(M{
  578. "FixedFileInfo": M{
  579. "FileVersion": M{
  580. "Major": major,
  581. "Minor": minor,
  582. "Patch": patch,
  583. },
  584. "ProductVersion": M{
  585. "Major": major,
  586. "Minor": minor,
  587. "Patch": patch,
  588. },
  589. },
  590. "StringFileInfo": M{
  591. "FileDescription": "Open Source Continuous File Synchronization",
  592. "LegalCopyright": "The Syncthing Authors",
  593. "FileVersion": version,
  594. "ProductVersion": version,
  595. "ProductName": "Syncthing",
  596. },
  597. "IconPath": "assets/logo.ico",
  598. })
  599. if err != nil {
  600. return "", err
  601. }
  602. jsonPath := filepath.Join(dir, "versioninfo.json")
  603. err = ioutil.WriteFile(jsonPath, bs, 0644)
  604. if err != nil {
  605. return "", errors.New("failed to create " + jsonPath + ": " + err.Error())
  606. }
  607. defer func() {
  608. if err := os.Remove(jsonPath); err != nil {
  609. log.Printf("Warning: unable to remove generated %s: %v. Please remove it manually.", jsonPath, err)
  610. }
  611. }()
  612. sysoPath := filepath.Join(dir, "cmd", "syncthing", "resource.syso")
  613. if _, err := runError("goversioninfo", "-o", sysoPath); err != nil {
  614. return "", errors.New("failed to create " + sysoPath + ": " + err.Error())
  615. }
  616. return sysoPath, nil
  617. }
  618. func shouldCleanupSyso(sysoFilePath string) {
  619. if sysoFilePath == "" {
  620. return
  621. }
  622. if err := os.Remove(sysoFilePath); err != nil {
  623. log.Printf("Warning: unable to remove generated %s: %v. Please remove it manually.", sysoFilePath, err)
  624. }
  625. }
  626. // copyFile copies a file from src to dst, ensuring the containing directory
  627. // exists. The permission bits are copied as well. If dst already exists and
  628. // the contents are identical to src the modification time is not updated.
  629. func copyFile(src, dst string, perm os.FileMode) error {
  630. in, err := ioutil.ReadFile(src)
  631. if err != nil {
  632. return err
  633. }
  634. out, err := ioutil.ReadFile(dst)
  635. if err != nil {
  636. // The destination probably doesn't exist, we should create
  637. // it.
  638. goto copy
  639. }
  640. if bytes.Equal(in, out) {
  641. // The permission bits may have changed without the contents
  642. // changing so we always mirror them.
  643. os.Chmod(dst, perm)
  644. return nil
  645. }
  646. copy:
  647. os.MkdirAll(filepath.Dir(dst), 0777)
  648. if err := ioutil.WriteFile(dst, in, perm); err != nil {
  649. return err
  650. }
  651. return nil
  652. }
  653. func listFiles(dir string) []string {
  654. var res []string
  655. filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
  656. if err != nil {
  657. return err
  658. }
  659. if fi.Mode().IsRegular() {
  660. res = append(res, path)
  661. }
  662. return nil
  663. })
  664. return res
  665. }
  666. func rebuildAssets() {
  667. os.Setenv("SOURCE_DATE_EPOCH", fmt.Sprint(buildStamp()))
  668. runPrint(goCmd, "generate", "github.com/syncthing/syncthing/lib/api/auto", "github.com/syncthing/syncthing/cmd/strelaypoolsrv/auto")
  669. }
  670. func lazyRebuildAssets() {
  671. if shouldRebuildAssets("lib/api/auto/gui.files.go", "gui") || shouldRebuildAssets("cmd/strelaypoolsrv/auto/gui.files.go", "cmd/strelaypoolsrv/gui") {
  672. rebuildAssets()
  673. }
  674. }
  675. func shouldRebuildAssets(target, srcdir string) bool {
  676. info, err := os.Stat(target)
  677. if err != nil {
  678. // If the file doesn't exist, we must rebuild it
  679. return true
  680. }
  681. // Check if any of the files in gui/ are newer than the asset file. If
  682. // so we should rebuild it.
  683. currentBuild := info.ModTime()
  684. assetsAreNewer := false
  685. stop := errors.New("no need to iterate further")
  686. filepath.Walk(srcdir, func(path string, info os.FileInfo, err error) error {
  687. if err != nil {
  688. return err
  689. }
  690. if info.ModTime().After(currentBuild) {
  691. assetsAreNewer = true
  692. return stop
  693. }
  694. return nil
  695. })
  696. return assetsAreNewer
  697. }
  698. func proto() {
  699. pv := protobufVersion()
  700. dependencyRepos = append(dependencyRepos,
  701. dependencyRepo{path: "protobuf", repo: "https://github.com/gogo/protobuf.git", commit: pv},
  702. )
  703. runPrint(goCmd, "get", fmt.Sprintf("github.com/gogo/protobuf/protoc-gen-gogofast@%v", pv))
  704. os.MkdirAll("repos", 0755)
  705. for _, dep := range dependencyRepos {
  706. path := filepath.Join("repos", dep.path)
  707. if _, err := os.Stat(path); err != nil {
  708. runPrintInDir("repos", "git", "clone", dep.repo, dep.path)
  709. } else {
  710. runPrintInDir(path, "git", "fetch")
  711. }
  712. runPrintInDir(path, "git", "checkout", dep.commit)
  713. }
  714. runPrint(goCmd, "generate", "github.com/syncthing/syncthing/lib/...", "github.com/syncthing/syncthing/cmd/stdiscosrv")
  715. }
  716. func translate() {
  717. os.Chdir("gui/default/assets/lang")
  718. runPipe("lang-en-new.json", goCmd, "run", "../../../../script/translate.go", "lang-en.json", "../../../")
  719. os.Remove("lang-en.json")
  720. err := os.Rename("lang-en-new.json", "lang-en.json")
  721. if err != nil {
  722. log.Fatal(err)
  723. }
  724. os.Chdir("../../../..")
  725. }
  726. func transifex() {
  727. os.Chdir("gui/default/assets/lang")
  728. runPrint(goCmd, "run", "../../../../script/transifexdl.go")
  729. }
  730. func ldflags() string {
  731. b := new(strings.Builder)
  732. b.WriteString("-w")
  733. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Version=%s", version)
  734. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Stamp=%d", buildStamp())
  735. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.User=%s", buildUser())
  736. fmt.Fprintf(b, " -X github.com/syncthing/syncthing/lib/build.Host=%s", buildHost())
  737. if v := os.Getenv("EXTRA_LDFLAGS"); v != "" {
  738. fmt.Fprintf(b, " %s", v)
  739. }
  740. return b.String()
  741. }
  742. func rmr(paths ...string) {
  743. for _, path := range paths {
  744. if debug {
  745. log.Println("rm -r", path)
  746. }
  747. os.RemoveAll(path)
  748. }
  749. }
  750. func getReleaseVersion() (string, error) {
  751. bs, err := ioutil.ReadFile("RELEASE")
  752. if err != nil {
  753. return "", err
  754. }
  755. return string(bytes.TrimSpace(bs)), nil
  756. }
  757. func getGitVersion() (string, error) {
  758. // The current version as Git sees it
  759. bs, err := runError("git", "describe", "--always", "--dirty", "--abbrev=8")
  760. if err != nil {
  761. return "", err
  762. }
  763. vcur := string(bs)
  764. // The closest current tag name
  765. bs, err = runError("git", "describe", "--always", "--abbrev=0")
  766. if err != nil {
  767. return "", err
  768. }
  769. v0 := string(bs)
  770. // To be more semantic-versionish and ensure proper ordering in our
  771. // upgrade process, we make sure there's only one hypen in the version.
  772. versionRe := regexp.MustCompile(`-([0-9]{1,3}-g[0-9a-f]{5,10}(-dirty)?)`)
  773. if m := versionRe.FindStringSubmatch(vcur); len(m) > 0 {
  774. suffix := strings.ReplaceAll(m[1], "-", ".")
  775. if strings.Contains(v0, "-") {
  776. // We're based of a tag with a prerelease string. We can just
  777. // add our dev stuff directly.
  778. return fmt.Sprintf("%s.dev.%s", v0, suffix), nil
  779. }
  780. // We're based on a release version. We need to bump the patch
  781. // version and then add a -dev prerelease string.
  782. next := nextPatchVersion(v0)
  783. return fmt.Sprintf("%s-dev.%s", next, suffix), nil
  784. }
  785. return vcur, nil
  786. }
  787. func getVersion() string {
  788. // First try for a RELEASE file,
  789. if ver, err := getReleaseVersion(); err == nil {
  790. return ver
  791. }
  792. // ... then see if we have a Git tag.
  793. if ver, err := getGitVersion(); err == nil {
  794. if strings.Contains(ver, "-") {
  795. // The version already contains a hash and stuff. See if we can
  796. // find a current branch name to tack onto it as well.
  797. return ver + getBranchSuffix()
  798. }
  799. return ver
  800. }
  801. // This seems to be a dev build.
  802. return "unknown-dev"
  803. }
  804. func semanticVersion() (major, minor, patch int) {
  805. r := regexp.MustCompile(`v(\d+)\.(\d+).(\d+)`)
  806. matches := r.FindStringSubmatch(getVersion())
  807. if len(matches) != 4 {
  808. return 0, 0, 0
  809. }
  810. var ints [3]int
  811. for i, s := range matches[1:] {
  812. ints[i], _ = strconv.Atoi(s)
  813. }
  814. return ints[0], ints[1], ints[2]
  815. }
  816. func getBranchSuffix() string {
  817. bs, err := runError("git", "branch", "-a", "--contains")
  818. if err != nil {
  819. return ""
  820. }
  821. branches := strings.Split(string(bs), "\n")
  822. if len(branches) == 0 {
  823. return ""
  824. }
  825. branch := ""
  826. for i, candidate := range branches {
  827. if strings.HasPrefix(candidate, "*") {
  828. // This is the current branch. Select it!
  829. branch = strings.TrimLeft(candidate, " \t*")
  830. break
  831. } else if i == 0 {
  832. // Otherwise the first branch in the list will do.
  833. branch = strings.TrimSpace(branch)
  834. }
  835. }
  836. if branch == "" {
  837. return ""
  838. }
  839. // The branch name may be on the form "remotes/origin/foo" from which we
  840. // just want "foo".
  841. parts := strings.Split(branch, "/")
  842. if len(parts) == 0 || len(parts[len(parts)-1]) == 0 {
  843. return ""
  844. }
  845. branch = parts[len(parts)-1]
  846. switch branch {
  847. case "master", "release", "main":
  848. // these are not special
  849. return ""
  850. }
  851. validBranchRe := regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
  852. if !validBranchRe.MatchString(branch) {
  853. // There's some odd stuff in the branch name. Better skip it.
  854. return ""
  855. }
  856. return "-" + branch
  857. }
  858. func buildStamp() int64 {
  859. // If SOURCE_DATE_EPOCH is set, use that.
  860. if s, _ := strconv.ParseInt(os.Getenv("SOURCE_DATE_EPOCH"), 10, 64); s > 0 {
  861. return s
  862. }
  863. // Try to get the timestamp of the latest commit.
  864. bs, err := runError("git", "show", "-s", "--format=%ct")
  865. if err != nil {
  866. // Fall back to "now".
  867. return time.Now().Unix()
  868. }
  869. s, _ := strconv.ParseInt(string(bs), 10, 64)
  870. return s
  871. }
  872. func buildUser() string {
  873. if v := os.Getenv("BUILD_USER"); v != "" {
  874. return v
  875. }
  876. u, err := user.Current()
  877. if err != nil {
  878. return "unknown-user"
  879. }
  880. return strings.Replace(u.Username, " ", "-", -1)
  881. }
  882. func buildHost() string {
  883. if v := os.Getenv("BUILD_HOST"); v != "" {
  884. return v
  885. }
  886. h, err := os.Hostname()
  887. if err != nil {
  888. return "unknown-host"
  889. }
  890. return h
  891. }
  892. func buildArch() string {
  893. os := goos
  894. if os == "darwin" {
  895. os = "macos"
  896. }
  897. return fmt.Sprintf("%s-%s", os, goarch)
  898. }
  899. func archiveName(target target) string {
  900. return fmt.Sprintf("%s-%s-%s", target.name, buildArch(), version)
  901. }
  902. func runError(cmd string, args ...string) ([]byte, error) {
  903. if debug {
  904. t0 := time.Now()
  905. log.Println("runError:", cmd, strings.Join(args, " "))
  906. defer func() {
  907. log.Println("... in", time.Since(t0))
  908. }()
  909. }
  910. ecmd := exec.Command(cmd, args...)
  911. bs, err := ecmd.CombinedOutput()
  912. return bytes.TrimSpace(bs), err
  913. }
  914. func runPrint(cmd string, args ...string) {
  915. runPrintInDir(".", cmd, args...)
  916. }
  917. func runPrintInDir(dir string, cmd string, args ...string) {
  918. if debug {
  919. t0 := time.Now()
  920. log.Println("runPrint:", cmd, strings.Join(args, " "))
  921. defer func() {
  922. log.Println("... in", time.Since(t0))
  923. }()
  924. }
  925. ecmd := exec.Command(cmd, args...)
  926. ecmd.Stdout = os.Stdout
  927. ecmd.Stderr = os.Stderr
  928. ecmd.Dir = dir
  929. err := ecmd.Run()
  930. if err != nil {
  931. log.Fatal(err)
  932. }
  933. }
  934. func runPipe(file, cmd string, args ...string) {
  935. if debug {
  936. t0 := time.Now()
  937. log.Println("runPipe:", cmd, strings.Join(args, " "))
  938. defer func() {
  939. log.Println("... in", time.Since(t0))
  940. }()
  941. }
  942. fd, err := os.Create(file)
  943. if err != nil {
  944. log.Fatal(err)
  945. }
  946. ecmd := exec.Command(cmd, args...)
  947. ecmd.Stdout = fd
  948. ecmd.Stderr = os.Stderr
  949. err = ecmd.Run()
  950. if err != nil {
  951. log.Fatal(err)
  952. }
  953. fd.Close()
  954. }
  955. func tarGz(out string, files []archiveFile) {
  956. fd, err := os.Create(out)
  957. if err != nil {
  958. log.Fatal(err)
  959. }
  960. gw, err := gzip.NewWriterLevel(fd, gzip.BestCompression)
  961. if err != nil {
  962. log.Fatal(err)
  963. }
  964. tw := tar.NewWriter(gw)
  965. for _, f := range files {
  966. sf, err := os.Open(f.src)
  967. if err != nil {
  968. log.Fatal(err)
  969. }
  970. info, err := sf.Stat()
  971. if err != nil {
  972. log.Fatal(err)
  973. }
  974. h := &tar.Header{
  975. Name: f.dst,
  976. Size: info.Size(),
  977. Mode: int64(info.Mode()),
  978. ModTime: info.ModTime(),
  979. }
  980. err = tw.WriteHeader(h)
  981. if err != nil {
  982. log.Fatal(err)
  983. }
  984. _, err = io.Copy(tw, sf)
  985. if err != nil {
  986. log.Fatal(err)
  987. }
  988. sf.Close()
  989. }
  990. err = tw.Close()
  991. if err != nil {
  992. log.Fatal(err)
  993. }
  994. err = gw.Close()
  995. if err != nil {
  996. log.Fatal(err)
  997. }
  998. err = fd.Close()
  999. if err != nil {
  1000. log.Fatal(err)
  1001. }
  1002. }
  1003. func zipFile(out string, files []archiveFile) {
  1004. fd, err := os.Create(out)
  1005. if err != nil {
  1006. log.Fatal(err)
  1007. }
  1008. zw := zip.NewWriter(fd)
  1009. var fw *flate.Writer
  1010. // Register the deflator.
  1011. zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
  1012. var err error
  1013. if fw == nil {
  1014. // Creating a flate compressor for every file is
  1015. // expensive, create one and reuse it.
  1016. fw, err = flate.NewWriter(out, flate.BestCompression)
  1017. } else {
  1018. fw.Reset(out)
  1019. }
  1020. return fw, err
  1021. })
  1022. for _, f := range files {
  1023. sf, err := os.Open(f.src)
  1024. if err != nil {
  1025. log.Fatal(err)
  1026. }
  1027. info, err := sf.Stat()
  1028. if err != nil {
  1029. log.Fatal(err)
  1030. }
  1031. fh, err := zip.FileInfoHeader(info)
  1032. if err != nil {
  1033. log.Fatal(err)
  1034. }
  1035. fh.Name = filepath.ToSlash(f.dst)
  1036. fh.Method = zip.Deflate
  1037. if strings.HasSuffix(f.dst, ".txt") {
  1038. // Text file. Read it and convert line endings.
  1039. bs, err := ioutil.ReadAll(sf)
  1040. if err != nil {
  1041. log.Fatal(err)
  1042. }
  1043. bs = bytes.Replace(bs, []byte{'\n'}, []byte{'\n', '\r'}, -1)
  1044. fh.UncompressedSize = uint32(len(bs))
  1045. fh.UncompressedSize64 = uint64(len(bs))
  1046. of, err := zw.CreateHeader(fh)
  1047. if err != nil {
  1048. log.Fatal(err)
  1049. }
  1050. of.Write(bs)
  1051. } else {
  1052. // Binary file. Copy verbatim.
  1053. of, err := zw.CreateHeader(fh)
  1054. if err != nil {
  1055. log.Fatal(err)
  1056. }
  1057. _, err = io.Copy(of, sf)
  1058. if err != nil {
  1059. log.Fatal(err)
  1060. }
  1061. }
  1062. }
  1063. err = zw.Close()
  1064. if err != nil {
  1065. log.Fatal(err)
  1066. }
  1067. err = fd.Close()
  1068. if err != nil {
  1069. log.Fatal(err)
  1070. }
  1071. }
  1072. func codesign(target target) {
  1073. switch goos {
  1074. case "windows":
  1075. windowsCodesign(target.BinaryName())
  1076. case "darwin":
  1077. macosCodesign(target.BinaryName())
  1078. }
  1079. }
  1080. func macosCodesign(file string) {
  1081. if pass := os.Getenv("CODESIGN_KEYCHAIN_PASS"); pass != "" {
  1082. bs, err := runError("security", "unlock-keychain", "-p", pass)
  1083. if err != nil {
  1084. log.Println("Codesign: unlocking keychain failed:", string(bs))
  1085. return
  1086. }
  1087. }
  1088. if id := os.Getenv("CODESIGN_IDENTITY"); id != "" {
  1089. bs, err := runError("codesign", "--options=runtime", "-s", id, file)
  1090. if err != nil {
  1091. log.Println("Codesign: signing failed:", string(bs))
  1092. return
  1093. }
  1094. log.Println("Codesign: successfully signed", file)
  1095. }
  1096. }
  1097. func windowsCodesign(file string) {
  1098. st := "signtool.exe"
  1099. if path := os.Getenv("CODESIGN_SIGNTOOL"); path != "" {
  1100. st = path
  1101. }
  1102. for i, algo := range []string{"sha1", "sha256"} {
  1103. args := []string{"sign", "/fd", algo}
  1104. if f := os.Getenv("CODESIGN_CERTIFICATE_FILE"); f != "" {
  1105. args = append(args, "/f", f)
  1106. }
  1107. if p := os.Getenv("CODESIGN_CERTIFICATE_PASSWORD"); p != "" {
  1108. args = append(args, "/p", p)
  1109. }
  1110. if tr := os.Getenv("CODESIGN_TIMESTAMP_SERVER"); tr != "" {
  1111. switch algo {
  1112. case "sha256":
  1113. args = append(args, "/tr", tr, "/td", algo)
  1114. default:
  1115. args = append(args, "/t", tr)
  1116. }
  1117. }
  1118. if i > 0 {
  1119. args = append(args, "/as")
  1120. }
  1121. args = append(args, file)
  1122. bs, err := runError(st, args...)
  1123. if err != nil {
  1124. log.Println("Codesign: signing failed:", string(bs))
  1125. return
  1126. }
  1127. log.Println("Codesign: successfully signed", file, "using", algo)
  1128. }
  1129. }
  1130. func metalint() {
  1131. lazyRebuildAssets()
  1132. runPrint(goCmd, "test", "-run", "Metalint", "./meta")
  1133. }
  1134. func metalintShort() {
  1135. lazyRebuildAssets()
  1136. runPrint(goCmd, "test", "-short", "-run", "Metalint", "./meta")
  1137. }
  1138. func temporaryBuildDir() (string, error) {
  1139. // The base of our temp dir is "syncthing-xxxxxxxx" where the x:es
  1140. // are eight bytes from the sha256 of our working directory. We do
  1141. // this because we want a name in the global temp dir that doesn't
  1142. // conflict with someone else building syncthing on the same
  1143. // machine, yet is persistent between runs from the same source
  1144. // directory.
  1145. wd, err := os.Getwd()
  1146. if err != nil {
  1147. return "", err
  1148. }
  1149. hash := sha256.Sum256([]byte(wd))
  1150. base := fmt.Sprintf("syncthing-%x", hash[:4])
  1151. // The temp dir is taken from $STTMPDIR if set, otherwise the system
  1152. // default (potentially infrluenced by $TMPDIR on unixes).
  1153. var tmpDir string
  1154. if t := os.Getenv("STTMPDIR"); t != "" {
  1155. tmpDir = t
  1156. } else {
  1157. tmpDir = os.TempDir()
  1158. }
  1159. return filepath.Join(tmpDir, base), nil
  1160. }
  1161. func (t target) BinaryName() string {
  1162. if goos == "windows" {
  1163. return t.binaryName + ".exe"
  1164. }
  1165. return t.binaryName
  1166. }
  1167. func protobufVersion() string {
  1168. bs, err := runError(goCmd, "list", "-f", "{{.Version}}", "-m", "github.com/gogo/protobuf")
  1169. if err != nil {
  1170. log.Fatal("Getting protobuf version:", err)
  1171. }
  1172. return string(bs)
  1173. }
  1174. func currentAndLatestVersions(n int) ([]string, error) {
  1175. bs, err := runError("git", "tag", "--sort", "taggerdate")
  1176. if err != nil {
  1177. return nil, err
  1178. }
  1179. lines := strings.Split(string(bs), "\n")
  1180. reverseStrings(lines)
  1181. // The one at the head is the latest version. We always keep that one.
  1182. // Then we filter out remaining ones with dashes (pre-releases etc).
  1183. latest := lines[:1]
  1184. nonPres := filterStrings(lines[1:], func(s string) bool { return !strings.Contains(s, "-") })
  1185. vers := append(latest, nonPres...)
  1186. return vers[:n], nil
  1187. }
  1188. func reverseStrings(ss []string) {
  1189. for i := 0; i < len(ss)/2; i++ {
  1190. ss[i], ss[len(ss)-1-i] = ss[len(ss)-1-i], ss[i]
  1191. }
  1192. }
  1193. func filterStrings(ss []string, op func(string) bool) []string {
  1194. n := ss[:0]
  1195. for _, s := range ss {
  1196. if op(s) {
  1197. n = append(n, s)
  1198. }
  1199. }
  1200. return n
  1201. }
  1202. func tagMessage(tag string) (string, error) {
  1203. hash, err := runError("git", "rev-parse", tag)
  1204. if err != nil {
  1205. return "", err
  1206. }
  1207. obj, err := runError("git", "cat-file", "-p", string(hash))
  1208. if err != nil {
  1209. return "", err
  1210. }
  1211. return trimTagMessage(string(obj), tag), nil
  1212. }
  1213. func trimTagMessage(msg, tag string) string {
  1214. firstBlank := strings.Index(msg, "\n\n")
  1215. if firstBlank > 0 {
  1216. msg = msg[firstBlank+2:]
  1217. }
  1218. msg = strings.TrimPrefix(msg, tag)
  1219. beginSig := strings.Index(msg, "-----BEGIN PGP")
  1220. if beginSig > 0 {
  1221. msg = msg[:beginSig]
  1222. }
  1223. return strings.TrimSpace(msg)
  1224. }
  1225. func nextPatchVersion(ver string) string {
  1226. parts := strings.SplitN(ver, "-", 2)
  1227. digits := strings.Split(parts[0], ".")
  1228. n, _ := strconv.Atoi(digits[len(digits)-1])
  1229. digits[len(digits)-1] = strconv.Itoa(n + 1)
  1230. return strings.Join(digits, ".")
  1231. }