build.go 32 KB

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