build.go 27 KB

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