build.go 36 KB

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