build.go 33 KB

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