build.go 40 KB

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