build.go 35 KB

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