build.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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 http://mozilla.org/MPL/2.0/.
  6. // +build ignore
  7. package main
  8. import (
  9. "archive/tar"
  10. "archive/zip"
  11. "bytes"
  12. "compress/gzip"
  13. "errors"
  14. "flag"
  15. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "log"
  19. "os"
  20. "os/exec"
  21. "os/user"
  22. "path/filepath"
  23. "regexp"
  24. "runtime"
  25. "strconv"
  26. "strings"
  27. "text/template"
  28. "time"
  29. )
  30. var (
  31. versionRe = regexp.MustCompile(`-[0-9]{1,3}-g[0-9a-f]{5,10}`)
  32. goarch string
  33. goos string
  34. noupgrade bool
  35. version string
  36. goVersion float64
  37. race bool
  38. debug = os.Getenv("BUILDDEBUG") != ""
  39. )
  40. type target struct {
  41. name string
  42. buildPkg string
  43. binaryName string
  44. archiveFiles []archiveFile
  45. installationFiles []archiveFile
  46. tags []string
  47. }
  48. type archiveFile struct {
  49. src string
  50. dst string
  51. perm os.FileMode
  52. }
  53. var targets = map[string]target{
  54. "all": {
  55. // Only valid for the "build" and "install" commands as it lacks all
  56. // the archive creation stuff.
  57. buildPkg: "./cmd/...",
  58. tags: []string{"purego"},
  59. },
  60. "syncthing": {
  61. // The default target for "build", "install", "tar", "zip", "deb", etc.
  62. name: "syncthing",
  63. buildPkg: "./cmd/syncthing",
  64. binaryName: "syncthing", // .exe will be added automatically for Windows builds
  65. archiveFiles: []archiveFile{
  66. {src: "{{binary}}", dst: "{{binary}}", perm: 0755},
  67. {src: "README.md", dst: "README.txt", perm: 0644},
  68. {src: "LICENSE", dst: "LICENSE.txt", perm: 0644},
  69. {src: "AUTHORS", dst: "AUTHORS.txt", perm: 0644},
  70. // All files from etc/ and extra/ added automatically in init().
  71. },
  72. installationFiles: []archiveFile{
  73. {src: "{{binary}}", dst: "deb/usr/bin/{{binary}}", perm: 0755},
  74. {src: "README.md", dst: "deb/usr/share/doc/syncthing/README.txt", perm: 0644},
  75. {src: "LICENSE", dst: "deb/usr/share/doc/syncthing/LICENSE.txt", perm: 0644},
  76. {src: "AUTHORS", dst: "deb/usr/share/doc/syncthing/AUTHORS.txt", perm: 0644},
  77. {src: "man/syncthing.1", dst: "deb/usr/share/man/man1/syncthing.1", perm: 0644},
  78. {src: "man/syncthing-config.5", dst: "deb/usr/share/man/man5/syncthing-config.5", perm: 0644},
  79. {src: "man/syncthing-stignore.5", dst: "deb/usr/share/man/man5/syncthing-stignore.5", perm: 0644},
  80. {src: "man/syncthing-device-ids.7", dst: "deb/usr/share/man/man7/syncthing-device-ids.7", perm: 0644},
  81. {src: "man/syncthing-event-api.7", dst: "deb/usr/share/man/man7/syncthing-event-api.7", perm: 0644},
  82. {src: "man/syncthing-faq.7", dst: "deb/usr/share/man/man7/syncthing-faq.7", perm: 0644},
  83. {src: "man/syncthing-networking.7", dst: "deb/usr/share/man/man7/syncthing-networking.7", perm: 0644},
  84. {src: "man/syncthing-rest-api.7", dst: "deb/usr/share/man/man7/syncthing-rest-api.7", perm: 0644},
  85. {src: "man/syncthing-security.7", dst: "deb/usr/share/man/man7/syncthing-security.7", perm: 0644},
  86. {src: "man/syncthing-versioning.7", dst: "deb/usr/share/man/man7/syncthing-versioning.7", perm: 0644},
  87. {src: "etc/linux-systemd/system/[email protected]", dst: "deb/lib/systemd/system/[email protected]", perm: 0644},
  88. {src: "etc/linux-systemd/system/syncthing-resume.service", dst: "deb/lib/systemd/system/syncthing-resume.service", perm: 0644},
  89. {src: "etc/linux-systemd/user/syncthing.service", dst: "deb/usr/lib/systemd/user/syncthing.service", perm: 0644},
  90. {src: "etc/firewall-ufw/syncthing", dst: "deb/etc/ufw/applications.d/syncthing", perm: 0644},
  91. },
  92. },
  93. "stdiscosrv": {
  94. name: "stdiscosrv",
  95. buildPkg: "./cmd/stdiscosrv",
  96. binaryName: "stdiscosrv", // .exe will be added automatically for Windows builds
  97. archiveFiles: []archiveFile{
  98. {src: "{{binary}}", dst: "{{binary}}", perm: 0755},
  99. {src: "cmd/stdiscosrv/README.md", dst: "README.txt", perm: 0644},
  100. {src: "cmd/stdiscosrv/LICENSE", dst: "LICENSE.txt", perm: 0644},
  101. {src: "AUTHORS", dst: "AUTHORS.txt", perm: 0644},
  102. },
  103. installationFiles: []archiveFile{
  104. {src: "{{binary}}", dst: "deb/usr/bin/{{binary}}", perm: 0755},
  105. {src: "cmd/stdiscosrv/README.md", dst: "deb/usr/share/doc/stdiscosrv/README.txt", perm: 0644},
  106. {src: "cmd/stdiscosrv/LICENSE", dst: "deb/usr/share/doc/stdiscosrv/LICENSE.txt", perm: 0644},
  107. {src: "AUTHORS", dst: "deb/usr/share/doc/stdiscosrv/AUTHORS.txt", perm: 0644},
  108. {src: "man/stdiscosrv.1", dst: "deb/usr/share/man/man1/stdiscosrv.1", perm: 0644},
  109. },
  110. tags: []string{"purego"},
  111. },
  112. "strelaysrv": {
  113. name: "strelaysrv",
  114. buildPkg: "./cmd/strelaysrv",
  115. binaryName: "strelaysrv", // .exe will be added automatically for Windows builds
  116. archiveFiles: []archiveFile{
  117. {src: "{{binary}}", dst: "{{binary}}", perm: 0755},
  118. {src: "cmd/strelaysrv/README.md", dst: "README.txt", perm: 0644},
  119. {src: "cmd/strelaysrv/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/strelaysrv/README.md", dst: "deb/usr/share/doc/strelaysrv/README.txt", perm: 0644},
  125. {src: "cmd/strelaysrv/LICENSE", dst: "deb/usr/share/doc/strelaysrv/LICENSE.txt", perm: 0644},
  126. {src: "AUTHORS", dst: "deb/usr/share/doc/strelaysrv/AUTHORS.txt", perm: 0644},
  127. {src: "man/strelaysrv.1", dst: "deb/usr/share/man/man1/strelaysrv.1", perm: 0644},
  128. },
  129. },
  130. "strelaypoolsrv": {
  131. name: "strelaypoolsrv",
  132. buildPkg: "./cmd/strelaypoolsrv",
  133. binaryName: "strelaypoolsrv", // .exe will be added automatically for Windows builds
  134. archiveFiles: []archiveFile{
  135. {src: "{{binary}}", dst: "{{binary}}", perm: 0755},
  136. {src: "cmd/strelaypoolsrv/README.md", dst: "README.txt", perm: 0644},
  137. {src: "cmd/strelaypoolsrv/LICENSE", dst: "LICENSE.txt", perm: 0644},
  138. {src: "AUTHORS", dst: "AUTHORS.txt", perm: 0644},
  139. },
  140. installationFiles: []archiveFile{
  141. {src: "{{binary}}", dst: "deb/usr/bin/{{binary}}", perm: 0755},
  142. {src: "cmd/strelaypoolsrv/README.md", dst: "deb/usr/share/doc/relaysrv/README.txt", perm: 0644},
  143. {src: "cmd/strelaypoolsrv/LICENSE", dst: "deb/usr/share/doc/relaysrv/LICENSE.txt", perm: 0644},
  144. {src: "AUTHORS", dst: "deb/usr/share/doc/relaysrv/AUTHORS.txt", perm: 0644},
  145. },
  146. },
  147. }
  148. var (
  149. // fast linters complete in a fraction of a second and might as well be
  150. // run always as part of the build
  151. fastLinters = []string{
  152. "deadcode",
  153. "golint",
  154. "ineffassign",
  155. "vet",
  156. }
  157. // slow linters take several seconds and are run only as part of the
  158. // "metalint" command.
  159. slowLinters = []string{
  160. "gosimple",
  161. "staticcheck",
  162. "structcheck",
  163. "unused",
  164. "varcheck",
  165. }
  166. // Which parts of the tree to lint
  167. lintDirs = []string{".", "./lib/...", "./cmd/..."}
  168. // Messages to ignore
  169. lintExcludes = []string{
  170. ".pb.go",
  171. "should have comment",
  172. "protocol.Vector composite literal uses unkeyed fields",
  173. "cli.Requires composite literal uses unkeyed fields",
  174. "Use DialContext instead", // Go 1.7
  175. "os.SEEK_SET is deprecated", // Go 1.7
  176. }
  177. )
  178. func init() {
  179. // The "syncthing" target includes a few more files found in the "etc"
  180. // and "extra" dirs.
  181. syncthingPkg := targets["syncthing"]
  182. for _, file := range listFiles("etc") {
  183. syncthingPkg.archiveFiles = append(syncthingPkg.archiveFiles, archiveFile{src: file, dst: file, perm: 0644})
  184. }
  185. for _, file := range listFiles("extra") {
  186. syncthingPkg.archiveFiles = append(syncthingPkg.archiveFiles, archiveFile{src: file, dst: file, perm: 0644})
  187. }
  188. for _, file := range listFiles("extra") {
  189. syncthingPkg.installationFiles = append(syncthingPkg.installationFiles, archiveFile{src: file, dst: "deb/usr/share/doc/syncthing/" + filepath.Base(file), perm: 0644})
  190. }
  191. targets["syncthing"] = syncthingPkg
  192. }
  193. const minGoVersion = 1.5
  194. func main() {
  195. log.SetOutput(os.Stdout)
  196. log.SetFlags(0)
  197. if debug {
  198. t0 := time.Now()
  199. defer func() {
  200. log.Println("... build completed in", time.Since(t0))
  201. }()
  202. }
  203. if os.Getenv("GOPATH") == "" {
  204. setGoPath()
  205. }
  206. // We use Go 1.5+ vendoring.
  207. os.Setenv("GO15VENDOREXPERIMENT", "1")
  208. // Set path to $GOPATH/bin:$PATH so that we can for sure find tools we
  209. // might have installed during "build.go setup".
  210. os.Setenv("PATH", fmt.Sprintf("%s%cbin%c%s", os.Getenv("GOPATH"), os.PathSeparator, os.PathListSeparator, os.Getenv("PATH")))
  211. parseFlags()
  212. checkArchitecture()
  213. goVersion, _ = checkRequiredGoVersion()
  214. // Invoking build.go with no parameters at all builds everything (incrementally),
  215. // which is what you want for maximum error checking during development.
  216. if flag.NArg() == 0 {
  217. runCommand("install", targets["all"])
  218. } else {
  219. // with any command given but not a target, the target is
  220. // "syncthing". So "go run build.go install" is "go run build.go install
  221. // syncthing" etc.
  222. targetName := "syncthing"
  223. if flag.NArg() > 1 {
  224. targetName = flag.Arg(1)
  225. }
  226. target, ok := targets[targetName]
  227. if !ok {
  228. log.Fatalln("Unknown target", target)
  229. }
  230. runCommand(flag.Arg(0), target)
  231. }
  232. }
  233. func checkArchitecture() {
  234. switch goarch {
  235. case "386", "amd64", "arm", "arm64", "ppc64", "ppc64le":
  236. break
  237. default:
  238. log.Printf("Unknown goarch %q; proceed with caution!", goarch)
  239. }
  240. }
  241. func runCommand(cmd string, target target) {
  242. switch cmd {
  243. case "setup":
  244. setup()
  245. case "install":
  246. var tags []string
  247. if noupgrade {
  248. tags = []string{"noupgrade"}
  249. }
  250. install(target, tags)
  251. metalint(fastLinters, lintDirs)
  252. case "build":
  253. var tags []string
  254. if noupgrade {
  255. tags = []string{"noupgrade"}
  256. }
  257. build(target, tags)
  258. metalint(fastLinters, lintDirs)
  259. case "test":
  260. test("./lib/...", "./cmd/...")
  261. case "bench":
  262. bench("./lib/...", "./cmd/...")
  263. case "assets":
  264. rebuildAssets()
  265. case "proto":
  266. proto()
  267. case "translate":
  268. translate()
  269. case "transifex":
  270. transifex()
  271. case "tar":
  272. buildTar(target)
  273. case "zip":
  274. buildZip(target)
  275. case "deb":
  276. buildDeb(target)
  277. case "snap":
  278. buildSnap(target)
  279. case "clean":
  280. clean()
  281. case "vet":
  282. metalint(fastLinters, lintDirs)
  283. case "lint":
  284. metalint(fastLinters, lintDirs)
  285. case "metalint":
  286. metalint(fastLinters, lintDirs)
  287. metalint(slowLinters, lintDirs)
  288. case "version":
  289. fmt.Println(getVersion())
  290. default:
  291. log.Fatalf("Unknown command %q", cmd)
  292. }
  293. }
  294. // setGoPath sets GOPATH correctly with the assumption that we are
  295. // in $GOPATH/src/github.com/syncthing/syncthing.
  296. func setGoPath() {
  297. cwd, err := os.Getwd()
  298. if err != nil {
  299. log.Fatal(err)
  300. }
  301. gopath := filepath.Clean(filepath.Join(cwd, "../../../../"))
  302. log.Println("GOPATH is", gopath)
  303. os.Setenv("GOPATH", gopath)
  304. }
  305. func parseFlags() {
  306. flag.StringVar(&goarch, "goarch", runtime.GOARCH, "GOARCH")
  307. flag.StringVar(&goos, "goos", runtime.GOOS, "GOOS")
  308. flag.BoolVar(&noupgrade, "no-upgrade", noupgrade, "Disable upgrade functionality")
  309. flag.StringVar(&version, "version", getVersion(), "Set compiled in version string")
  310. flag.BoolVar(&race, "race", race, "Use race detector")
  311. flag.Parse()
  312. }
  313. func checkRequiredGoVersion() (float64, bool) {
  314. re := regexp.MustCompile(`go(\d+\.\d+)`)
  315. ver := runtime.Version()
  316. if m := re.FindStringSubmatch(ver); len(m) == 2 {
  317. vs := string(m[1])
  318. // This is a standard go build. Verify that it's new enough.
  319. f, err := strconv.ParseFloat(vs, 64)
  320. if err != nil {
  321. log.Printf("*** Couldn't parse Go version out of %q.\n*** This isn't known to work, proceed on your own risk.", vs)
  322. return 0, false
  323. }
  324. if f < 1.5 {
  325. log.Printf("*** Go version %.01f doesn't support the vendoring mechanism.\n*** Ensure correct dependencies in your $GOPATH.", f)
  326. } else if f < minGoVersion {
  327. log.Fatalf("*** Go version %.01f is less than required %.01f.\n*** This is known not to work, not proceeding.", f, minGoVersion)
  328. }
  329. return f, true
  330. }
  331. log.Printf("*** Unknown Go version %q.\n*** This isn't known to work, proceed on your own risk.", ver)
  332. return 0, false
  333. }
  334. func setup() {
  335. packages := []string{
  336. "github.com/alecthomas/gometalinter",
  337. "github.com/AlekSi/gocov-xml",
  338. "github.com/axw/gocov/gocov",
  339. "github.com/FiloSottile/gvt",
  340. "github.com/golang/lint/golint",
  341. "github.com/gordonklaus/ineffassign",
  342. "github.com/mdempsky/unconvert",
  343. "github.com/mitchellh/go-wordwrap",
  344. "github.com/opennota/check/cmd/...",
  345. "github.com/tsenart/deadcode",
  346. "golang.org/x/net/html",
  347. "golang.org/x/tools/cmd/cover",
  348. "honnef.co/go/simple/cmd/gosimple",
  349. "honnef.co/go/staticcheck/cmd/staticcheck",
  350. "honnef.co/go/unused/cmd/unused",
  351. }
  352. for _, pkg := range packages {
  353. fmt.Println(pkg)
  354. runPrint("go", "get", "-u", pkg)
  355. }
  356. }
  357. func test(pkgs ...string) {
  358. lazyRebuildAssets()
  359. useRace := runtime.GOARCH == "amd64"
  360. switch runtime.GOOS {
  361. case "darwin", "linux", "freebsd", "windows":
  362. default:
  363. useRace = false
  364. }
  365. if useRace {
  366. runPrint("go", append([]string{"test", "-short", "-race", "-timeout", "60s", "-tags", "purego"}, pkgs...)...)
  367. } else {
  368. runPrint("go", append([]string{"test", "-short", "-timeout", "60s", "-tags", "purego"}, pkgs...)...)
  369. }
  370. }
  371. func bench(pkgs ...string) {
  372. lazyRebuildAssets()
  373. runPrint("go", append([]string{"test", "-run", "NONE", "-bench", "."}, pkgs...)...)
  374. }
  375. func install(target target, tags []string) {
  376. lazyRebuildAssets()
  377. tags = append(target.tags, tags...)
  378. cwd, err := os.Getwd()
  379. if err != nil {
  380. log.Fatal(err)
  381. }
  382. os.Setenv("GOBIN", filepath.Join(cwd, "bin"))
  383. args := []string{"install", "-v", "-ldflags", ldflags()}
  384. if len(tags) > 0 {
  385. args = append(args, "-tags", strings.Join(tags, " "))
  386. }
  387. if race {
  388. args = append(args, "-race")
  389. }
  390. args = append(args, target.buildPkg)
  391. os.Setenv("GOOS", goos)
  392. os.Setenv("GOARCH", goarch)
  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", "-ldflags", ldflags()}
  400. if len(tags) > 0 {
  401. args = append(args, "-tags", strings.Join(tags, " "))
  402. }
  403. if race {
  404. args = append(args, "-race")
  405. }
  406. args = append(args, target.buildPkg)
  407. os.Setenv("GOOS", goos)
  408. os.Setenv("GOARCH", goarch)
  409. runPrint("go", args...)
  410. }
  411. func buildTar(target target) {
  412. name := archiveName(target)
  413. filename := name + ".tar.gz"
  414. var tags []string
  415. if noupgrade {
  416. tags = []string{"noupgrade"}
  417. name += "-noupgrade"
  418. }
  419. build(target, tags)
  420. if goos == "darwin" {
  421. macosCodesign(target.binaryName)
  422. }
  423. for i := range target.archiveFiles {
  424. target.archiveFiles[i].src = strings.Replace(target.archiveFiles[i].src, "{{binary}}", target.binaryName, 1)
  425. target.archiveFiles[i].dst = strings.Replace(target.archiveFiles[i].dst, "{{binary}}", target.binaryName, 1)
  426. target.archiveFiles[i].dst = name + "/" + target.archiveFiles[i].dst
  427. }
  428. tarGz(filename, target.archiveFiles)
  429. log.Println(filename)
  430. }
  431. func buildZip(target target) {
  432. target.binaryName += ".exe"
  433. name := archiveName(target)
  434. filename := name + ".zip"
  435. var tags []string
  436. if noupgrade {
  437. tags = []string{"noupgrade"}
  438. name += "-noupgrade"
  439. }
  440. build(target, tags)
  441. for i := range target.archiveFiles {
  442. target.archiveFiles[i].src = strings.Replace(target.archiveFiles[i].src, "{{binary}}", target.binaryName, 1)
  443. target.archiveFiles[i].dst = strings.Replace(target.archiveFiles[i].dst, "{{binary}}", target.binaryName, 1)
  444. target.archiveFiles[i].dst = name + "/" + target.archiveFiles[i].dst
  445. }
  446. zipFile(filename, target.archiveFiles)
  447. log.Println(filename)
  448. }
  449. func buildDeb(target target) {
  450. os.RemoveAll("deb")
  451. // "goarch" here is set to whatever the Debian packages expect. We correct
  452. // it to what we actually know how to build and keep the Debian variant
  453. // name in "debarch".
  454. debarch := goarch
  455. switch goarch {
  456. case "i386":
  457. goarch = "386"
  458. case "armel", "armhf":
  459. goarch = "arm"
  460. }
  461. build(target, []string{"noupgrade"})
  462. for i := range target.installationFiles {
  463. target.installationFiles[i].src = strings.Replace(target.installationFiles[i].src, "{{binary}}", target.binaryName, 1)
  464. target.installationFiles[i].dst = strings.Replace(target.installationFiles[i].dst, "{{binary}}", target.binaryName, 1)
  465. }
  466. for _, af := range target.installationFiles {
  467. if err := copyFile(af.src, af.dst, af.perm); err != nil {
  468. log.Fatal(err)
  469. }
  470. }
  471. maintainer := "Syncthing Release Management <[email protected]>"
  472. debver := version
  473. if strings.HasPrefix(debver, "v") {
  474. debver = debver[1:]
  475. }
  476. runPrint("fpm", "-t", "deb", "-s", "dir", "-C", "deb",
  477. "-n", "syncthing", "-v", debver, "-a", debarch,
  478. "--vendor", maintainer, "-m", maintainer,
  479. "-d", "libc6",
  480. "-d", "procps", // because postinst script
  481. "--url", "https://syncthing.net/",
  482. "--description", "Open Source Continuous File Synchronization",
  483. "--after-upgrade", "script/post-upgrade",
  484. "--license", "MPL-2")
  485. }
  486. func buildSnap(target target) {
  487. os.RemoveAll("snap")
  488. tmpl, err := template.ParseFiles("snapcraft.yaml.template")
  489. if err != nil {
  490. log.Fatal(err)
  491. }
  492. f, err := os.Create("snapcraft.yaml")
  493. defer f.Close()
  494. if err != nil {
  495. log.Fatal(err)
  496. }
  497. snaparch := goarch
  498. if snaparch == "armhf" {
  499. goarch = "arm"
  500. }
  501. snapver := version
  502. if strings.HasPrefix(snapver, "v") {
  503. snapver = snapver[1:]
  504. }
  505. snapgrade := "devel"
  506. if matched, _ := regexp.MatchString(`^\d+\.\d+\.\d+$`, snapver); matched {
  507. snapgrade = "stable"
  508. }
  509. err = tmpl.Execute(f, map[string]string{
  510. "Version": snapver,
  511. "Architecture": snaparch,
  512. "Grade": snapgrade,
  513. })
  514. if err != nil {
  515. log.Fatal(err)
  516. }
  517. runPrint("snapcraft", "clean")
  518. build(target, []string{"noupgrade"})
  519. runPrint("snapcraft")
  520. }
  521. func copyFile(src, dst string, perm os.FileMode) error {
  522. dstDir := filepath.Dir(dst)
  523. os.MkdirAll(dstDir, 0755) // ignore error
  524. srcFd, err := os.Open(src)
  525. if err != nil {
  526. return err
  527. }
  528. defer srcFd.Close()
  529. dstFd, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, perm)
  530. if err != nil {
  531. return err
  532. }
  533. defer dstFd.Close()
  534. _, err = io.Copy(dstFd, srcFd)
  535. return err
  536. }
  537. func listFiles(dir string) []string {
  538. var res []string
  539. filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
  540. if err != nil {
  541. return err
  542. }
  543. if fi.Mode().IsRegular() {
  544. res = append(res, path)
  545. }
  546. return nil
  547. })
  548. return res
  549. }
  550. func rebuildAssets() {
  551. runPipe("lib/auto/gui.files.go", "go", "run", "script/genassets.go", "gui")
  552. runPipe("cmd/strelaypoolsrv/auto/gui.go", "go", "run", "script/genassets.go", "cmd/strelaypoolsrv/gui")
  553. }
  554. func lazyRebuildAssets() {
  555. if shouldRebuildAssets("lib/auto/gui.files.go", "gui") || shouldRebuildAssets("cmd/strelaypoolsrv/auto/gui.go", "cmd/strelaypoolsrv/auto/gui") {
  556. rebuildAssets()
  557. }
  558. }
  559. func shouldRebuildAssets(target, srcdir string) bool {
  560. info, err := os.Stat(target)
  561. if err != nil {
  562. // If the file doesn't exist, we must rebuild it
  563. return true
  564. }
  565. // Check if any of the files in gui/ are newer than the asset file. If
  566. // so we should rebuild it.
  567. currentBuild := info.ModTime()
  568. assetsAreNewer := false
  569. stop := errors.New("no need to iterate further")
  570. filepath.Walk(srcdir, func(path string, info os.FileInfo, err error) error {
  571. if err != nil {
  572. return err
  573. }
  574. if info.ModTime().After(currentBuild) {
  575. assetsAreNewer = true
  576. return stop
  577. }
  578. return nil
  579. })
  580. return assetsAreNewer
  581. }
  582. func proto() {
  583. runPrint("go", "generate", "./lib/...")
  584. }
  585. func translate() {
  586. os.Chdir("gui/default/assets/lang")
  587. runPipe("lang-en-new.json", "go", "run", "../../../../script/translate.go", "lang-en.json", "../../../")
  588. os.Remove("lang-en.json")
  589. err := os.Rename("lang-en-new.json", "lang-en.json")
  590. if err != nil {
  591. log.Fatal(err)
  592. }
  593. os.Chdir("../../../..")
  594. }
  595. func transifex() {
  596. os.Chdir("gui/default/assets/lang")
  597. runPrint("go", "run", "../../../../script/transifexdl.go")
  598. }
  599. func clean() {
  600. rmr("bin")
  601. rmr(filepath.Join(os.Getenv("GOPATH"), fmt.Sprintf("pkg/%s_%s/github.com/syncthing", goos, goarch)))
  602. }
  603. func ldflags() string {
  604. sep := '='
  605. if goVersion > 0 && goVersion < 1.5 {
  606. sep = ' '
  607. }
  608. b := new(bytes.Buffer)
  609. b.WriteString("-w")
  610. fmt.Fprintf(b, " -X main.Version%c%s", sep, version)
  611. fmt.Fprintf(b, " -X main.BuildStamp%c%d", sep, buildStamp())
  612. fmt.Fprintf(b, " -X main.BuildUser%c%s", sep, buildUser())
  613. fmt.Fprintf(b, " -X main.BuildHost%c%s", sep, buildHost())
  614. return b.String()
  615. }
  616. func rmr(paths ...string) {
  617. for _, path := range paths {
  618. if debug {
  619. log.Println("rm -r", path)
  620. }
  621. os.RemoveAll(path)
  622. }
  623. }
  624. func getReleaseVersion() (string, error) {
  625. fd, err := os.Open("RELEASE")
  626. if err != nil {
  627. return "", err
  628. }
  629. defer fd.Close()
  630. bs, err := ioutil.ReadAll(fd)
  631. if err != nil {
  632. return "", err
  633. }
  634. return string(bytes.TrimSpace(bs)), nil
  635. }
  636. func getGitVersion() (string, error) {
  637. v, err := runError("git", "describe", "--always", "--dirty")
  638. if err != nil {
  639. return "", err
  640. }
  641. v = versionRe.ReplaceAllFunc(v, func(s []byte) []byte {
  642. s[0] = '+'
  643. return s
  644. })
  645. return string(v), nil
  646. }
  647. func getVersion() string {
  648. // First try for a RELEASE file,
  649. if ver, err := getReleaseVersion(); err == nil {
  650. return ver
  651. }
  652. // ... then see if we have a Git tag.
  653. if ver, err := getGitVersion(); err == nil {
  654. if strings.Contains(ver, "-") {
  655. // The version already contains a hash and stuff. See if we can
  656. // find a current branch name to tack onto it as well.
  657. return ver + getBranchSuffix()
  658. }
  659. return ver
  660. }
  661. // This seems to be a dev build.
  662. return "unknown-dev"
  663. }
  664. func getBranchSuffix() string {
  665. bs, err := runError("git", "branch", "-a", "--contains")
  666. if err != nil {
  667. return ""
  668. }
  669. branches := strings.Split(string(bs), "\n")
  670. if len(branches) == 0 {
  671. return ""
  672. }
  673. branch := ""
  674. for i, candidate := range branches {
  675. if strings.HasPrefix(candidate, "*") {
  676. // This is the current branch. Select it!
  677. branch = strings.TrimLeft(candidate, " \t*")
  678. break
  679. } else if i == 0 {
  680. // Otherwise the first branch in the list will do.
  681. branch = strings.TrimSpace(branch)
  682. }
  683. }
  684. if branch == "" {
  685. return ""
  686. }
  687. // The branch name may be on the form "remotes/origin/foo" from which we
  688. // just want "foo".
  689. parts := strings.Split(branch, "/")
  690. if len(parts) == 0 || len(parts[len(parts)-1]) == 0 {
  691. return ""
  692. }
  693. branch = parts[len(parts)-1]
  694. if branch == "master" {
  695. // master builds are the default.
  696. return ""
  697. }
  698. validBranchRe := regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
  699. if !validBranchRe.MatchString(branch) {
  700. // There's some odd stuff in the branch name. Better skip it.
  701. return ""
  702. }
  703. return "-" + branch
  704. }
  705. func buildStamp() int64 {
  706. // If SOURCE_DATE_EPOCH is set, use that.
  707. if s, _ := strconv.ParseInt(os.Getenv("SOURCE_DATE_EPOCH"), 10, 64); s > 0 {
  708. return s
  709. }
  710. // Try to get the timestamp of the latest commit.
  711. bs, err := runError("git", "show", "-s", "--format=%ct")
  712. if err != nil {
  713. // Fall back to "now".
  714. return time.Now().Unix()
  715. }
  716. s, _ := strconv.ParseInt(string(bs), 10, 64)
  717. return s
  718. }
  719. func buildUser() string {
  720. if v := os.Getenv("BUILD_USER"); v != "" {
  721. return v
  722. }
  723. u, err := user.Current()
  724. if err != nil {
  725. return "unknown-user"
  726. }
  727. return strings.Replace(u.Username, " ", "-", -1)
  728. }
  729. func buildHost() string {
  730. if v := os.Getenv("BUILD_HOST"); v != "" {
  731. return v
  732. }
  733. h, err := os.Hostname()
  734. if err != nil {
  735. return "unknown-host"
  736. }
  737. return h
  738. }
  739. func buildArch() string {
  740. os := goos
  741. if os == "darwin" {
  742. os = "macosx"
  743. }
  744. return fmt.Sprintf("%s-%s", os, goarch)
  745. }
  746. func archiveName(target target) string {
  747. return fmt.Sprintf("%s-%s-%s", target.name, buildArch(), version)
  748. }
  749. func runError(cmd string, args ...string) ([]byte, error) {
  750. if debug {
  751. t0 := time.Now()
  752. log.Println("runError:", cmd, strings.Join(args, " "))
  753. defer func() {
  754. log.Println("... in", time.Since(t0))
  755. }()
  756. }
  757. ecmd := exec.Command(cmd, args...)
  758. bs, err := ecmd.CombinedOutput()
  759. return bytes.TrimSpace(bs), err
  760. }
  761. func runPrint(cmd string, args ...string) {
  762. if debug {
  763. t0 := time.Now()
  764. log.Println("runPrint:", cmd, strings.Join(args, " "))
  765. defer func() {
  766. log.Println("... in", time.Since(t0))
  767. }()
  768. }
  769. ecmd := exec.Command(cmd, args...)
  770. ecmd.Stdout = os.Stdout
  771. ecmd.Stderr = os.Stderr
  772. err := ecmd.Run()
  773. if err != nil {
  774. log.Fatal(err)
  775. }
  776. }
  777. func runPipe(file, cmd string, args ...string) {
  778. if debug {
  779. t0 := time.Now()
  780. log.Println("runPipe:", cmd, strings.Join(args, " "))
  781. defer func() {
  782. log.Println("... in", time.Since(t0))
  783. }()
  784. }
  785. fd, err := os.Create(file)
  786. if err != nil {
  787. log.Fatal(err)
  788. }
  789. ecmd := exec.Command(cmd, args...)
  790. ecmd.Stdout = fd
  791. ecmd.Stderr = os.Stderr
  792. err = ecmd.Run()
  793. if err != nil {
  794. log.Fatal(err)
  795. }
  796. fd.Close()
  797. }
  798. func tarGz(out string, files []archiveFile) {
  799. fd, err := os.Create(out)
  800. if err != nil {
  801. log.Fatal(err)
  802. }
  803. gw := gzip.NewWriter(fd)
  804. tw := tar.NewWriter(gw)
  805. for _, f := range files {
  806. sf, err := os.Open(f.src)
  807. if err != nil {
  808. log.Fatal(err)
  809. }
  810. info, err := sf.Stat()
  811. if err != nil {
  812. log.Fatal(err)
  813. }
  814. h := &tar.Header{
  815. Name: f.dst,
  816. Size: info.Size(),
  817. Mode: int64(info.Mode()),
  818. ModTime: info.ModTime(),
  819. }
  820. err = tw.WriteHeader(h)
  821. if err != nil {
  822. log.Fatal(err)
  823. }
  824. _, err = io.Copy(tw, sf)
  825. if err != nil {
  826. log.Fatal(err)
  827. }
  828. sf.Close()
  829. }
  830. err = tw.Close()
  831. if err != nil {
  832. log.Fatal(err)
  833. }
  834. err = gw.Close()
  835. if err != nil {
  836. log.Fatal(err)
  837. }
  838. err = fd.Close()
  839. if err != nil {
  840. log.Fatal(err)
  841. }
  842. }
  843. func zipFile(out string, files []archiveFile) {
  844. fd, err := os.Create(out)
  845. if err != nil {
  846. log.Fatal(err)
  847. }
  848. zw := zip.NewWriter(fd)
  849. for _, f := range files {
  850. sf, err := os.Open(f.src)
  851. if err != nil {
  852. log.Fatal(err)
  853. }
  854. info, err := sf.Stat()
  855. if err != nil {
  856. log.Fatal(err)
  857. }
  858. fh, err := zip.FileInfoHeader(info)
  859. if err != nil {
  860. log.Fatal(err)
  861. }
  862. fh.Name = filepath.ToSlash(f.dst)
  863. fh.Method = zip.Deflate
  864. if strings.HasSuffix(f.dst, ".txt") {
  865. // Text file. Read it and convert line endings.
  866. bs, err := ioutil.ReadAll(sf)
  867. if err != nil {
  868. log.Fatal(err)
  869. }
  870. bs = bytes.Replace(bs, []byte{'\n'}, []byte{'\n', '\r'}, -1)
  871. fh.UncompressedSize = uint32(len(bs))
  872. fh.UncompressedSize64 = uint64(len(bs))
  873. of, err := zw.CreateHeader(fh)
  874. if err != nil {
  875. log.Fatal(err)
  876. }
  877. of.Write(bs)
  878. } else {
  879. // Binary file. Copy verbatim.
  880. of, err := zw.CreateHeader(fh)
  881. if err != nil {
  882. log.Fatal(err)
  883. }
  884. _, err = io.Copy(of, sf)
  885. if err != nil {
  886. log.Fatal(err)
  887. }
  888. }
  889. }
  890. err = zw.Close()
  891. if err != nil {
  892. log.Fatal(err)
  893. }
  894. err = fd.Close()
  895. if err != nil {
  896. log.Fatal(err)
  897. }
  898. }
  899. func macosCodesign(file string) {
  900. if pass := os.Getenv("CODESIGN_KEYCHAIN_PASS"); pass != "" {
  901. bs, err := runError("security", "unlock-keychain", "-p", pass)
  902. if err != nil {
  903. log.Println("Codesign: unlocking keychain failed:", string(bs))
  904. return
  905. }
  906. }
  907. if id := os.Getenv("CODESIGN_IDENTITY"); id != "" {
  908. bs, err := runError("codesign", "-s", id, file)
  909. if err != nil {
  910. log.Println("Codesign: signing failed:", string(bs))
  911. return
  912. }
  913. log.Println("Codesign: successfully signed", file)
  914. }
  915. }
  916. func metalint(linters []string, dirs []string) {
  917. ok := true
  918. if isGometalinterInstalled() {
  919. if !gometalinter(linters, dirs, lintExcludes...) {
  920. ok = false
  921. }
  922. }
  923. if !ok {
  924. log.Fatal("Build succeeded, but there were lint warnings")
  925. }
  926. }
  927. func isGometalinterInstalled() bool {
  928. if _, err := runError("gometalinter", "--disable-all"); err != nil {
  929. log.Println("gometalinter is not installed")
  930. return false
  931. }
  932. return true
  933. }
  934. func gometalinter(linters []string, dirs []string, excludes ...string) bool {
  935. params := []string{"--disable-all", "--concurrency=2", "--deadline=300s"}
  936. for _, linter := range linters {
  937. params = append(params, "--enable="+linter)
  938. }
  939. for _, exclude := range excludes {
  940. params = append(params, "--exclude="+exclude)
  941. }
  942. for _, dir := range dirs {
  943. params = append(params, dir)
  944. }
  945. bs, _ := runError("gometalinter", params...)
  946. nerr := 0
  947. lines := make(map[string]struct{})
  948. for _, line := range strings.Split(string(bs), "\n") {
  949. if line == "" {
  950. continue
  951. }
  952. if _, ok := lines[line]; ok {
  953. continue
  954. }
  955. log.Println(line)
  956. if strings.Contains(line, "executable file not found") {
  957. log.Println(` - Try "go run build.go setup" to install missing tools`)
  958. }
  959. lines[line] = struct{}{}
  960. nerr++
  961. }
  962. return nerr == 0
  963. }