build.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. // +build ignore
  16. package main
  17. import (
  18. "archive/tar"
  19. "archive/zip"
  20. "bytes"
  21. "compress/gzip"
  22. "flag"
  23. "fmt"
  24. "io"
  25. "io/ioutil"
  26. "log"
  27. "os"
  28. "os/exec"
  29. "os/user"
  30. "path/filepath"
  31. "regexp"
  32. "runtime"
  33. "strconv"
  34. "strings"
  35. "time"
  36. )
  37. var (
  38. versionRe = regexp.MustCompile(`-[0-9]{1,3}-g[0-9a-f]{5,10}`)
  39. goarch string
  40. goos string
  41. noupgrade bool
  42. version string
  43. race bool
  44. )
  45. const minGoVersion = 1.3
  46. func main() {
  47. log.SetOutput(os.Stdout)
  48. log.SetFlags(0)
  49. if os.Getenv("GOPATH") == "" {
  50. cwd, err := os.Getwd()
  51. if err != nil {
  52. log.Fatal(err)
  53. }
  54. gopath := filepath.Clean(filepath.Join(cwd, "../../../../"))
  55. log.Println("GOPATH is", gopath)
  56. os.Setenv("GOPATH", gopath)
  57. }
  58. os.Setenv("PATH", fmt.Sprintf("%s%cbin%c%s", os.Getenv("GOPATH"), os.PathSeparator, os.PathListSeparator, os.Getenv("PATH")))
  59. flag.StringVar(&goarch, "goarch", runtime.GOARCH, "GOARCH")
  60. flag.StringVar(&goos, "goos", runtime.GOOS, "GOOS")
  61. flag.BoolVar(&noupgrade, "no-upgrade", noupgrade, "Disable upgrade functionality")
  62. flag.StringVar(&version, "version", getVersion(), "Set compiled in version string")
  63. flag.BoolVar(&race, "race", race, "Use race detector")
  64. flag.Parse()
  65. switch goarch {
  66. case "386", "amd64", "armv5", "armv6", "armv7":
  67. break
  68. case "arm":
  69. switch os.Getenv("GOARM") {
  70. case "5", "6", "7":
  71. goarch += "v" + os.Getenv("GOARM")
  72. break
  73. default:
  74. log.Println("Invalid goarch \"arm\". Use one of \"armv5\", \"armv6\", \"armv7\".")
  75. log.Fatalln("Note that producing a correct \"armv5\" binary requires a rebuilt stdlib.")
  76. }
  77. default:
  78. log.Printf("Unknown goarch %q; proceed with caution!", goarch)
  79. }
  80. checkRequiredGoVersion()
  81. if flag.NArg() == 0 {
  82. var tags []string
  83. if noupgrade {
  84. tags = []string{"noupgrade"}
  85. }
  86. install("./cmd/...", tags)
  87. return
  88. }
  89. for _, cmd := range flag.Args() {
  90. switch cmd {
  91. case "setup":
  92. setup()
  93. case "install":
  94. pkg := "./cmd/..."
  95. var tags []string
  96. if noupgrade {
  97. tags = []string{"noupgrade"}
  98. }
  99. install(pkg, tags)
  100. case "build":
  101. pkg := "./cmd/syncthing"
  102. var tags []string
  103. if noupgrade {
  104. tags = []string{"noupgrade"}
  105. }
  106. build(pkg, tags)
  107. case "test":
  108. pkg := "./..."
  109. test(pkg)
  110. case "assets":
  111. assets()
  112. case "xdr":
  113. xdr()
  114. case "translate":
  115. translate()
  116. case "transifex":
  117. transifex()
  118. case "deps":
  119. deps()
  120. case "tar":
  121. buildTar()
  122. case "zip":
  123. buildZip()
  124. case "clean":
  125. clean()
  126. default:
  127. log.Fatalf("Unknown command %q", cmd)
  128. }
  129. }
  130. }
  131. func checkRequiredGoVersion() {
  132. ver := run("go", "version")
  133. re := regexp.MustCompile(`go version go(\d+\.\d+)`)
  134. if m := re.FindSubmatch(ver); len(m) == 2 {
  135. vs := string(m[1])
  136. // This is a standard go build. Verify that it's new enough.
  137. f, err := strconv.ParseFloat(vs, 64)
  138. if err != nil {
  139. log.Printf("*** Could parse Go version out of %q.\n*** This isn't known to work, proceed on your own risk.", vs)
  140. return
  141. }
  142. if f < minGoVersion {
  143. log.Fatalf("*** Go version %.01f is less than required %.01f.\n*** This is known not to work, not proceeding.", f, minGoVersion)
  144. }
  145. } else {
  146. log.Printf("*** Unknown Go version %q.\n*** This isn't known to work, proceed on your own risk.", ver)
  147. }
  148. }
  149. func setup() {
  150. runPrint("go", "get", "-v", "golang.org/x/tools/cmd/cover")
  151. runPrint("go", "get", "-v", "golang.org/x/tools/cmd/vet")
  152. runPrint("go", "get", "-v", "golang.org/x/net/html")
  153. runPrint("go", "get", "-v", "github.com/tools/godep")
  154. }
  155. func test(pkg string) {
  156. setBuildEnv()
  157. runPrint("go", "test", "-short", "-timeout", "10s", pkg)
  158. }
  159. func install(pkg string, tags []string) {
  160. os.Setenv("GOBIN", "./bin")
  161. args := []string{"install", "-v", "-ldflags", ldflags()}
  162. if len(tags) > 0 {
  163. args = append(args, "-tags", strings.Join(tags, ","))
  164. }
  165. if race {
  166. args = append(args, "-race")
  167. }
  168. args = append(args, pkg)
  169. setBuildEnv()
  170. runPrint("go", args...)
  171. }
  172. func build(pkg string, tags []string) {
  173. rmr("syncthing", "syncthing.exe")
  174. args := []string{"build", "-ldflags", ldflags()}
  175. if len(tags) > 0 {
  176. args = append(args, "-tags", strings.Join(tags, ","))
  177. }
  178. if race {
  179. args = append(args, "-race")
  180. }
  181. args = append(args, pkg)
  182. setBuildEnv()
  183. runPrint("go", args...)
  184. }
  185. func buildTar() {
  186. name := archiveName()
  187. var tags []string
  188. if noupgrade {
  189. tags = []string{"noupgrade"}
  190. name += "-noupgrade"
  191. }
  192. build("./cmd/syncthing", tags)
  193. filename := name + ".tar.gz"
  194. files := []archiveFile{
  195. {"README.md", name + "/README.txt"},
  196. {"LICENSE", name + "/LICENSE.txt"},
  197. {"AUTHORS", name + "/AUTHORS.txt"},
  198. {"syncthing", name + "/syncthing"},
  199. }
  200. for _, file := range listFiles("etc") {
  201. files = append(files, archiveFile{file, name + "/" + file})
  202. }
  203. tarGz(filename, files)
  204. log.Println(filename)
  205. }
  206. func buildZip() {
  207. name := archiveName()
  208. var tags []string
  209. if noupgrade {
  210. tags = []string{"noupgrade"}
  211. name += "-noupgrade"
  212. }
  213. build("./cmd/syncthing", tags)
  214. filename := name + ".zip"
  215. files := []archiveFile{
  216. {"README.md", name + "/README.txt"},
  217. {"LICENSE", name + "/LICENSE.txt"},
  218. {"AUTHORS", name + "/AUTHORS.txt"},
  219. {"syncthing.exe", name + "/syncthing.exe"},
  220. }
  221. zipFile(filename, files)
  222. log.Println(filename)
  223. }
  224. func listFiles(dir string) []string {
  225. var res []string
  226. filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error {
  227. if err != nil {
  228. return err
  229. }
  230. if fi.Mode().IsRegular() {
  231. res = append(res, path)
  232. }
  233. return nil
  234. })
  235. return res
  236. }
  237. func setBuildEnv() {
  238. os.Setenv("GOOS", goos)
  239. if strings.HasPrefix(goarch, "arm") {
  240. os.Setenv("GOARCH", "arm")
  241. os.Setenv("GOARM", goarch[4:])
  242. } else {
  243. os.Setenv("GOARCH", goarch)
  244. }
  245. if goarch == "386" {
  246. os.Setenv("GO386", "387")
  247. }
  248. wd, err := os.Getwd()
  249. if err != nil {
  250. log.Println("Warning: can't determine current dir:", err)
  251. log.Println("Build might not work as expected")
  252. }
  253. os.Setenv("GOPATH", fmt.Sprintf("%s%c%s", filepath.Join(wd, "Godeps", "_workspace"), os.PathListSeparator, os.Getenv("GOPATH")))
  254. log.Println("GOPATH=" + os.Getenv("GOPATH"))
  255. }
  256. func assets() {
  257. setBuildEnv()
  258. runPipe("internal/auto/gui.files.go", "go", "run", "cmd/genassets/main.go", "gui")
  259. }
  260. func xdr() {
  261. for _, f := range []string{"internal/discover/packets", "internal/files/leveldb", "internal/protocol/message"} {
  262. runPipe(f+"_xdr.go", "go", "run", "./Godeps/_workspace/src/github.com/calmh/xdr/cmd/genxdr/main.go", "--", f+".go")
  263. }
  264. }
  265. func translate() {
  266. os.Chdir("gui/assets/lang")
  267. runPipe("lang-en-new.json", "go", "run", "../../../cmd/translate/main.go", "lang-en.json", "../../index.html")
  268. os.Remove("lang-en.json")
  269. err := os.Rename("lang-en-new.json", "lang-en.json")
  270. if err != nil {
  271. log.Fatal(err)
  272. }
  273. os.Chdir("../../..")
  274. }
  275. func transifex() {
  276. os.Chdir("gui/assets/lang")
  277. runPrint("go", "run", "../../../cmd/transifexdl/main.go")
  278. os.Chdir("../../..")
  279. assets()
  280. }
  281. func deps() {
  282. rmr("Godeps")
  283. runPrint("godep", "save", "./cmd/...")
  284. }
  285. func clean() {
  286. rmr("bin", "Godeps/_workspace/pkg", "Godeps/_workspace/bin")
  287. rmr(filepath.Join(os.Getenv("GOPATH"), fmt.Sprintf("pkg/%s_%s/github.com/syncthing", goos, goarch)))
  288. }
  289. func ldflags() string {
  290. var b bytes.Buffer
  291. b.WriteString("-w")
  292. b.WriteString(fmt.Sprintf(" -X main.Version %s", version))
  293. b.WriteString(fmt.Sprintf(" -X main.BuildStamp %d", buildStamp()))
  294. b.WriteString(fmt.Sprintf(" -X main.BuildUser %s", buildUser()))
  295. b.WriteString(fmt.Sprintf(" -X main.BuildHost %s", buildHost()))
  296. b.WriteString(fmt.Sprintf(" -X main.BuildEnv %s", buildEnvironment()))
  297. if strings.HasPrefix(goarch, "arm") {
  298. b.WriteString(fmt.Sprintf(" -X main.GoArchExtra %s", goarch[3:]))
  299. }
  300. return b.String()
  301. }
  302. func rmr(paths ...string) {
  303. for _, path := range paths {
  304. log.Println("rm -r", path)
  305. os.RemoveAll(path)
  306. }
  307. }
  308. func getVersion() string {
  309. v, err := runError("git", "describe", "--always", "--dirty")
  310. if err != nil {
  311. return "unknown-dev"
  312. }
  313. v = versionRe.ReplaceAllFunc(v, func(s []byte) []byte {
  314. s[0] = '+'
  315. return s
  316. })
  317. return string(v)
  318. }
  319. func buildStamp() int64 {
  320. bs, err := runError("git", "show", "-s", "--format=%ct")
  321. if err != nil {
  322. return time.Now().Unix()
  323. }
  324. s, _ := strconv.ParseInt(string(bs), 10, 64)
  325. return s
  326. }
  327. func buildUser() string {
  328. u, err := user.Current()
  329. if err != nil {
  330. return "unknown-user"
  331. }
  332. return strings.Replace(u.Username, " ", "-", -1)
  333. }
  334. func buildHost() string {
  335. h, err := os.Hostname()
  336. if err != nil {
  337. return "unknown-host"
  338. }
  339. return h
  340. }
  341. func buildEnvironment() string {
  342. if v := os.Getenv("ENVIRONMENT"); len(v) > 0 {
  343. return v
  344. }
  345. return "default"
  346. }
  347. func buildArch() string {
  348. os := goos
  349. if os == "darwin" {
  350. os = "macosx"
  351. }
  352. return fmt.Sprintf("%s-%s", os, goarch)
  353. }
  354. func archiveName() string {
  355. return fmt.Sprintf("syncthing-%s-%s", buildArch(), version)
  356. }
  357. func run(cmd string, args ...string) []byte {
  358. bs, err := runError(cmd, args...)
  359. if err != nil {
  360. log.Println(cmd, strings.Join(args, " "))
  361. log.Println(string(bs))
  362. log.Fatal(err)
  363. }
  364. return bytes.TrimSpace(bs)
  365. }
  366. func runError(cmd string, args ...string) ([]byte, error) {
  367. ecmd := exec.Command(cmd, args...)
  368. bs, err := ecmd.CombinedOutput()
  369. if err != nil {
  370. return nil, err
  371. }
  372. return bytes.TrimSpace(bs), nil
  373. }
  374. func runPrint(cmd string, args ...string) {
  375. log.Println(cmd, strings.Join(args, " "))
  376. ecmd := exec.Command(cmd, args...)
  377. ecmd.Stdout = os.Stdout
  378. ecmd.Stderr = os.Stderr
  379. err := ecmd.Run()
  380. if err != nil {
  381. log.Fatal(err)
  382. }
  383. }
  384. func runPipe(file, cmd string, args ...string) {
  385. log.Println(cmd, strings.Join(args, " "), ">", file)
  386. fd, err := os.Create(file)
  387. if err != nil {
  388. log.Fatal(err)
  389. }
  390. ecmd := exec.Command(cmd, args...)
  391. ecmd.Stdout = fd
  392. ecmd.Stderr = os.Stderr
  393. err = ecmd.Run()
  394. if err != nil {
  395. log.Fatal(err)
  396. }
  397. fd.Close()
  398. }
  399. type archiveFile struct {
  400. src string
  401. dst string
  402. }
  403. func tarGz(out string, files []archiveFile) {
  404. fd, err := os.Create(out)
  405. if err != nil {
  406. log.Fatal(err)
  407. }
  408. gw := gzip.NewWriter(fd)
  409. tw := tar.NewWriter(gw)
  410. for _, f := range files {
  411. sf, err := os.Open(f.src)
  412. if err != nil {
  413. log.Fatal(err)
  414. }
  415. info, err := sf.Stat()
  416. if err != nil {
  417. log.Fatal(err)
  418. }
  419. h := &tar.Header{
  420. Name: f.dst,
  421. Size: info.Size(),
  422. Mode: int64(info.Mode()),
  423. ModTime: info.ModTime(),
  424. }
  425. err = tw.WriteHeader(h)
  426. if err != nil {
  427. log.Fatal(err)
  428. }
  429. _, err = io.Copy(tw, sf)
  430. if err != nil {
  431. log.Fatal(err)
  432. }
  433. sf.Close()
  434. }
  435. err = tw.Close()
  436. if err != nil {
  437. log.Fatal(err)
  438. }
  439. err = gw.Close()
  440. if err != nil {
  441. log.Fatal(err)
  442. }
  443. err = fd.Close()
  444. if err != nil {
  445. log.Fatal(err)
  446. }
  447. }
  448. func zipFile(out string, files []archiveFile) {
  449. fd, err := os.Create(out)
  450. if err != nil {
  451. log.Fatal(err)
  452. }
  453. zw := zip.NewWriter(fd)
  454. for _, f := range files {
  455. sf, err := os.Open(f.src)
  456. if err != nil {
  457. log.Fatal(err)
  458. }
  459. info, err := sf.Stat()
  460. if err != nil {
  461. log.Fatal(err)
  462. }
  463. fh, err := zip.FileInfoHeader(info)
  464. if err != nil {
  465. log.Fatal(err)
  466. }
  467. fh.Name = f.dst
  468. fh.Method = zip.Deflate
  469. if strings.HasSuffix(f.dst, ".txt") {
  470. // Text file. Read it and convert line endings.
  471. bs, err := ioutil.ReadAll(sf)
  472. if err != nil {
  473. log.Fatal(err)
  474. }
  475. bs = bytes.Replace(bs, []byte{'\n'}, []byte{'\n', '\r'}, -1)
  476. fh.UncompressedSize = uint32(len(bs))
  477. fh.UncompressedSize64 = uint64(len(bs))
  478. of, err := zw.CreateHeader(fh)
  479. if err != nil {
  480. log.Fatal(err)
  481. }
  482. of.Write(bs)
  483. } else {
  484. // Binary file. Copy verbatim.
  485. of, err := zw.CreateHeader(fh)
  486. if err != nil {
  487. log.Fatal(err)
  488. }
  489. _, err = io.Copy(of, sf)
  490. if err != nil {
  491. log.Fatal(err)
  492. }
  493. }
  494. }
  495. err = zw.Close()
  496. if err != nil {
  497. log.Fatal(err)
  498. }
  499. err = fd.Close()
  500. if err != nil {
  501. log.Fatal(err)
  502. }
  503. }