build.go 36 KB

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