build.go 35 KB

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