build.go 35 KB

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