build.go 33 KB

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