build.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. // +build ignore
  5. package main
  6. import (
  7. "archive/tar"
  8. "archive/zip"
  9. "bytes"
  10. "compress/gzip"
  11. "flag"
  12. "fmt"
  13. "io"
  14. "io/ioutil"
  15. "log"
  16. "os"
  17. "os/exec"
  18. "os/user"
  19. "path/filepath"
  20. "regexp"
  21. "runtime"
  22. "strconv"
  23. "strings"
  24. )
  25. var (
  26. versionRe = regexp.MustCompile(`-[0-9]{1,3}-g[0-9a-f]{5,10}`)
  27. goarch string
  28. goos string
  29. noupgrade bool
  30. )
  31. const minGoVersion = 1.3
  32. func main() {
  33. log.SetOutput(os.Stdout)
  34. log.SetFlags(0)
  35. if os.Getenv("GOPATH") == "" {
  36. cwd, err := os.Getwd()
  37. if err != nil {
  38. log.Fatal(err)
  39. }
  40. gopath := filepath.Clean(filepath.Join(cwd, "../../../../"))
  41. log.Println("GOPATH is", gopath)
  42. os.Setenv("GOPATH", gopath)
  43. }
  44. os.Setenv("PATH", fmt.Sprintf("%s%cbin%c%s", os.Getenv("GOPATH"), os.PathSeparator, os.PathListSeparator, os.Getenv("PATH")))
  45. flag.StringVar(&goarch, "goarch", runtime.GOARCH, "GOARCH")
  46. flag.StringVar(&goos, "goos", runtime.GOOS, "GOOS")
  47. flag.BoolVar(&noupgrade, "no-upgrade", false, "Disable upgrade functionality")
  48. flag.Parse()
  49. checkRequiredGoVersion()
  50. if check() != nil {
  51. setup()
  52. }
  53. if flag.NArg() == 0 {
  54. install("./cmd/...")
  55. return
  56. }
  57. switch flag.Arg(0) {
  58. case "install":
  59. pkg := "./cmd/..."
  60. if flag.NArg() > 2 {
  61. pkg = flag.Arg(1)
  62. }
  63. install(pkg)
  64. case "build":
  65. pkg := "./cmd/syncthing"
  66. if flag.NArg() > 2 {
  67. pkg = flag.Arg(1)
  68. }
  69. var tags []string
  70. if noupgrade {
  71. tags = []string{"noupgrade"}
  72. }
  73. build(pkg, tags)
  74. case "test":
  75. pkg := "./..."
  76. if flag.NArg() > 2 {
  77. pkg = flag.Arg(1)
  78. }
  79. test(pkg)
  80. case "assets":
  81. assets()
  82. case "xdr":
  83. xdr()
  84. case "translate":
  85. translate()
  86. case "transifex":
  87. transifex()
  88. case "deps":
  89. deps()
  90. case "tar":
  91. buildTar()
  92. case "zip":
  93. buildZip()
  94. case "clean":
  95. clean()
  96. default:
  97. log.Fatalf("Unknown command %q", flag.Arg(0))
  98. }
  99. }
  100. func check() error {
  101. _, err := exec.LookPath("godep")
  102. return err
  103. }
  104. func checkRequiredGoVersion() {
  105. ver := run("go", "version")
  106. re := regexp.MustCompile(`go version go(\d+\.\d+)`)
  107. if m := re.FindSubmatch(ver); len(m) == 2 {
  108. vs := string(m[1])
  109. // This is a standard go build. Verify that it's new enough.
  110. f, err := strconv.ParseFloat(vs, 64)
  111. if err != nil {
  112. log.Printf("*** Could parse Go version out of %q.\n*** This isn't known to work, proceed on your own risk.", vs)
  113. return
  114. }
  115. if f < minGoVersion {
  116. log.Fatalf("*** Go version %.01f is less than required %.01f.\n*** This is known not to work, not proceeding.", f, minGoVersion)
  117. }
  118. } else {
  119. log.Printf("*** Unknown Go version %q.\n*** This isn't known to work, proceed on your own risk.", ver)
  120. }
  121. }
  122. func setup() {
  123. runPrint("go", "get", "-v", "code.google.com/p/go.tools/cmd/cover")
  124. runPrint("go", "get", "-v", "code.google.com/p/go.tools/cmd/vet")
  125. runPrint("go", "get", "-v", "code.google.com/p/go.net/html")
  126. runPrint("go", "get", "-v", "github.com/tools/godep")
  127. }
  128. func test(pkg string) {
  129. runPrint("godep", "go", "test", pkg)
  130. }
  131. func install(pkg string) {
  132. os.Setenv("GOBIN", "./bin")
  133. setBuildEnv()
  134. runPrint("godep", "go", "install", "-ldflags", ldflags(), pkg)
  135. }
  136. func build(pkg string, tags []string) {
  137. rmr("syncthing", "syncthing.exe")
  138. args := []string{"go", "build", "-ldflags", ldflags()}
  139. if len(tags) > 0 {
  140. args = append(args, "-tags", strings.Join(tags, ","))
  141. }
  142. args = append(args, pkg)
  143. setBuildEnv()
  144. runPrint("godep", args...)
  145. }
  146. func buildTar() {
  147. name := archiveName()
  148. var tags []string
  149. if noupgrade {
  150. tags = []string{"noupgrade"}
  151. name += "-noupgrade"
  152. }
  153. build("./cmd/syncthing", tags)
  154. filename := name + ".tar.gz"
  155. tarGz(filename, []archiveFile{
  156. {"README.md", name + "/README.txt"},
  157. {"LICENSE", name + "/LICENSE.txt"},
  158. {"CONTRIBUTORS", name + "/CONTRIBUTORS.txt"},
  159. {"syncthing", name + "/syncthing"},
  160. })
  161. log.Println(filename)
  162. }
  163. func buildZip() {
  164. name := archiveName()
  165. var tags []string
  166. if noupgrade {
  167. tags = []string{"noupgrade"}
  168. name += "-noupgrade"
  169. }
  170. build("./cmd/syncthing", tags)
  171. filename := name + ".zip"
  172. zipFile(filename, []archiveFile{
  173. {"README.md", name + "/README.txt"},
  174. {"LICENSE", name + "/LICENSE.txt"},
  175. {"CONTRIBUTORS", name + "/CONTRIBUTORS.txt"},
  176. {"syncthing.exe", name + "/syncthing.exe"},
  177. })
  178. log.Println(filename)
  179. }
  180. func setBuildEnv() {
  181. os.Setenv("GOOS", goos)
  182. if strings.HasPrefix(goarch, "arm") {
  183. os.Setenv("GOARCH", "arm")
  184. os.Setenv("GOARM", goarch[4:])
  185. } else {
  186. os.Setenv("GOARCH", goarch)
  187. }
  188. if goarch == "386" {
  189. os.Setenv("GO386", "387")
  190. }
  191. }
  192. func assets() {
  193. runPipe("auto/gui.files.go", "godep", "go", "run", "cmd/genassets/main.go", "gui")
  194. }
  195. func xdr() {
  196. for _, f := range []string{"discover/packets", "files/leveldb", "protocol/message"} {
  197. runPipe(f+"_xdr.go", "go", "run", "./Godeps/_workspace/src/github.com/calmh/xdr/cmd/genxdr/main.go", "--", f+".go")
  198. }
  199. }
  200. func translate() {
  201. os.Chdir("gui")
  202. runPipe("lang-en-new.json", "go", "run", "../cmd/translate/main.go", "lang-en.json", "index.html")
  203. os.Remove("lang-en.json")
  204. err := os.Rename("lang-en-new.json", "lang-en.json")
  205. if err != nil {
  206. log.Fatal(err)
  207. }
  208. os.Chdir("..")
  209. }
  210. func transifex() {
  211. os.Chdir("gui")
  212. runPrint("go", "run", "../cmd/transifexdl/main.go")
  213. os.Chdir("..")
  214. assets()
  215. }
  216. func deps() {
  217. rmr("Godeps")
  218. runPrint("godep", "save", "./cmd/...")
  219. }
  220. func clean() {
  221. rmr("bin", "Godeps/_workspace/pkg", "Godeps/_workspace/bin")
  222. rmr(filepath.Join(os.Getenv("GOPATH"), fmt.Sprintf("pkg/%s_%s/github.com/syncthing", goos, goarch)))
  223. }
  224. func ldflags() string {
  225. var b bytes.Buffer
  226. b.WriteString("-w")
  227. b.WriteString(fmt.Sprintf(" -X main.Version %s", version()))
  228. b.WriteString(fmt.Sprintf(" -X main.BuildStamp %d", buildStamp()))
  229. b.WriteString(fmt.Sprintf(" -X main.BuildUser %s", buildUser()))
  230. b.WriteString(fmt.Sprintf(" -X main.BuildHost %s", buildHost()))
  231. b.WriteString(fmt.Sprintf(" -X main.BuildEnv %s", buildEnvironment()))
  232. if strings.HasPrefix(goarch, "arm") {
  233. b.WriteString(fmt.Sprintf(" -X main.GoArchExtra %s", goarch[3:]))
  234. }
  235. return b.String()
  236. }
  237. func rmr(paths ...string) {
  238. for _, path := range paths {
  239. log.Println("rm -r", path)
  240. os.RemoveAll(path)
  241. }
  242. }
  243. func version() string {
  244. v := run("git", "describe", "--always", "--dirty")
  245. v = versionRe.ReplaceAllFunc(v, func(s []byte) []byte {
  246. s[0] = '+'
  247. return s
  248. })
  249. return string(v)
  250. }
  251. func buildStamp() int64 {
  252. bs := run("git", "show", "-s", "--format=%ct")
  253. s, _ := strconv.ParseInt(string(bs), 10, 64)
  254. return s
  255. }
  256. func buildUser() string {
  257. u, err := user.Current()
  258. if err != nil {
  259. return "unknown-user"
  260. }
  261. return strings.Replace(u.Username, " ", "-", -1)
  262. }
  263. func buildHost() string {
  264. h, err := os.Hostname()
  265. if err != nil {
  266. return "unknown-host"
  267. }
  268. return h
  269. }
  270. func buildEnvironment() string {
  271. if v := os.Getenv("ENVIRONMENT"); len(v) > 0 {
  272. return v
  273. }
  274. return "default"
  275. }
  276. func buildArch() string {
  277. os := goos
  278. if os == "darwin" {
  279. os = "macosx"
  280. }
  281. return fmt.Sprintf("%s-%s", os, goarch)
  282. }
  283. func archiveName() string {
  284. return fmt.Sprintf("syncthing-%s-%s", buildArch(), version())
  285. }
  286. func run(cmd string, args ...string) []byte {
  287. ecmd := exec.Command(cmd, args...)
  288. bs, err := ecmd.CombinedOutput()
  289. if err != nil {
  290. log.Println(cmd, strings.Join(args, " "))
  291. log.Println(string(bs))
  292. log.Fatal(err)
  293. }
  294. return bytes.TrimSpace(bs)
  295. }
  296. func runPrint(cmd string, args ...string) {
  297. log.Println(cmd, strings.Join(args, " "))
  298. ecmd := exec.Command(cmd, args...)
  299. ecmd.Stdout = os.Stdout
  300. ecmd.Stderr = os.Stderr
  301. err := ecmd.Run()
  302. if err != nil {
  303. log.Fatal(err)
  304. }
  305. }
  306. func runPipe(file, cmd string, args ...string) {
  307. log.Println(cmd, strings.Join(args, " "), ">", file)
  308. fd, err := os.Create(file)
  309. if err != nil {
  310. log.Fatal(err)
  311. }
  312. ecmd := exec.Command(cmd, args...)
  313. ecmd.Stdout = fd
  314. ecmd.Stderr = os.Stderr
  315. err = ecmd.Run()
  316. if err != nil {
  317. log.Fatal(err)
  318. }
  319. fd.Close()
  320. }
  321. type archiveFile struct {
  322. src string
  323. dst string
  324. }
  325. func tarGz(out string, files []archiveFile) {
  326. fd, err := os.Create(out)
  327. if err != nil {
  328. log.Fatal(err)
  329. }
  330. gw := gzip.NewWriter(fd)
  331. tw := tar.NewWriter(gw)
  332. for _, f := range files {
  333. sf, err := os.Open(f.src)
  334. if err != nil {
  335. log.Fatal(err)
  336. }
  337. info, err := sf.Stat()
  338. if err != nil {
  339. log.Fatal(err)
  340. }
  341. h := &tar.Header{
  342. Name: f.dst,
  343. Size: info.Size(),
  344. Mode: int64(info.Mode()),
  345. ModTime: info.ModTime(),
  346. }
  347. err = tw.WriteHeader(h)
  348. if err != nil {
  349. log.Fatal(err)
  350. }
  351. _, err = io.Copy(tw, sf)
  352. if err != nil {
  353. log.Fatal(err)
  354. }
  355. sf.Close()
  356. }
  357. err = tw.Close()
  358. if err != nil {
  359. log.Fatal(err)
  360. }
  361. err = gw.Close()
  362. if err != nil {
  363. log.Fatal(err)
  364. }
  365. err = fd.Close()
  366. if err != nil {
  367. log.Fatal(err)
  368. }
  369. }
  370. func zipFile(out string, files []archiveFile) {
  371. fd, err := os.Create(out)
  372. if err != nil {
  373. log.Fatal(err)
  374. }
  375. zw := zip.NewWriter(fd)
  376. for _, f := range files {
  377. sf, err := os.Open(f.src)
  378. if err != nil {
  379. log.Fatal(err)
  380. }
  381. info, err := sf.Stat()
  382. if err != nil {
  383. log.Fatal(err)
  384. }
  385. fh, err := zip.FileInfoHeader(info)
  386. if err != nil {
  387. log.Fatal(err)
  388. }
  389. fh.Name = f.dst
  390. fh.Method = zip.Deflate
  391. if strings.HasSuffix(f.dst, ".txt") {
  392. // Text file. Read it and convert line endings.
  393. bs, err := ioutil.ReadAll(sf)
  394. if err != nil {
  395. log.Fatal(err)
  396. }
  397. bs = bytes.Replace(bs, []byte{'\n'}, []byte{'\n', '\r'}, -1)
  398. fh.UncompressedSize = uint32(len(bs))
  399. fh.UncompressedSize64 = uint64(len(bs))
  400. of, err := zw.CreateHeader(fh)
  401. if err != nil {
  402. log.Fatal(err)
  403. }
  404. of.Write(bs)
  405. } else {
  406. // Binary file. Copy verbatim.
  407. of, err := zw.CreateHeader(fh)
  408. if err != nil {
  409. log.Fatal(err)
  410. }
  411. _, err = io.Copy(of, sf)
  412. if err != nil {
  413. log.Fatal(err)
  414. }
  415. }
  416. }
  417. err = zw.Close()
  418. if err != nil {
  419. log.Fatal(err)
  420. }
  421. err = fd.Close()
  422. if err != nil {
  423. log.Fatal(err)
  424. }
  425. }