util.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package build
  17. import (
  18. "bytes"
  19. "flag"
  20. "fmt"
  21. "go/parser"
  22. "go/token"
  23. "io"
  24. "io/ioutil"
  25. "log"
  26. "os"
  27. "os/exec"
  28. "path"
  29. "path/filepath"
  30. "runtime"
  31. "strings"
  32. "text/template"
  33. )
  34. var DryRunFlag = flag.Bool("n", false, "dry run, don't execute commands")
  35. // MustRun executes the given command and exits the host process for
  36. // any error.
  37. func MustRun(cmd *exec.Cmd) {
  38. fmt.Println(">>>", strings.Join(cmd.Args, " "))
  39. if !*DryRunFlag {
  40. cmd.Stderr = os.Stderr
  41. cmd.Stdout = os.Stdout
  42. if err := cmd.Run(); err != nil {
  43. log.Fatal(err)
  44. }
  45. }
  46. }
  47. func MustRunCommand(cmd string, args ...string) {
  48. MustRun(exec.Command(cmd, args...))
  49. }
  50. var warnedAboutGit bool
  51. // RunGit runs a git subcommand and returns its output.
  52. // The command must complete successfully.
  53. func RunGit(args ...string) string {
  54. cmd := exec.Command("git", args...)
  55. var stdout, stderr bytes.Buffer
  56. cmd.Stdout, cmd.Stderr = &stdout, &stderr
  57. if err := cmd.Run(); err != nil {
  58. if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound {
  59. if !warnedAboutGit {
  60. log.Println("Warning: can't find 'git' in PATH")
  61. warnedAboutGit = true
  62. }
  63. return ""
  64. }
  65. log.Fatal(strings.Join(cmd.Args, " "), ": ", err, "\n", stderr.String())
  66. }
  67. return strings.TrimSpace(stdout.String())
  68. }
  69. // readGitFile returns content of file in .git directory.
  70. func readGitFile(file string) string {
  71. content, err := ioutil.ReadFile(path.Join(".git", file))
  72. if err != nil {
  73. return ""
  74. }
  75. return strings.TrimSpace(string(content))
  76. }
  77. // Render renders the given template file into outputFile.
  78. func Render(templateFile, outputFile string, outputPerm os.FileMode, x interface{}) {
  79. tpl := template.Must(template.ParseFiles(templateFile))
  80. render(tpl, outputFile, outputPerm, x)
  81. }
  82. // RenderString renders the given template string into outputFile.
  83. func RenderString(templateContent, outputFile string, outputPerm os.FileMode, x interface{}) {
  84. tpl := template.Must(template.New("").Parse(templateContent))
  85. render(tpl, outputFile, outputPerm, x)
  86. }
  87. func render(tpl *template.Template, outputFile string, outputPerm os.FileMode, x interface{}) {
  88. if err := os.MkdirAll(filepath.Dir(outputFile), 0755); err != nil {
  89. log.Fatal(err)
  90. }
  91. out, err := os.OpenFile(outputFile, os.O_CREATE|os.O_WRONLY|os.O_EXCL, outputPerm)
  92. if err != nil {
  93. log.Fatal(err)
  94. }
  95. if err := tpl.Execute(out, x); err != nil {
  96. log.Fatal(err)
  97. }
  98. if err := out.Close(); err != nil {
  99. log.Fatal(err)
  100. }
  101. }
  102. // GoTool returns the command that runs a go tool. This uses go from GOROOT instead of PATH
  103. // so that go commands executed by build use the same version of Go as the 'host' that runs
  104. // build code. e.g.
  105. //
  106. // /usr/lib/go-1.12.1/bin/go run build/ci.go ...
  107. //
  108. // runs using go 1.12.1 and invokes go 1.12.1 tools from the same GOROOT. This is also important
  109. // because runtime.Version checks on the host should match the tools that are run.
  110. func GoTool(tool string, args ...string) *exec.Cmd {
  111. args = append([]string{tool}, args...)
  112. return exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
  113. }
  114. // UploadSFTP uploads files to a remote host using the sftp command line tool.
  115. // The destination host may be specified either as [user@]host[: or as a URI in
  116. // the form sftp://[user@]host[:port].
  117. func UploadSFTP(identityFile, host, dir string, files []string) error {
  118. sftp := exec.Command("sftp")
  119. sftp.Stdout = nil
  120. sftp.Stderr = os.Stderr
  121. if identityFile != "" {
  122. sftp.Args = append(sftp.Args, "-i", identityFile)
  123. }
  124. sftp.Args = append(sftp.Args, host)
  125. fmt.Println(">>>", strings.Join(sftp.Args, " "))
  126. if *DryRunFlag {
  127. return nil
  128. }
  129. stdin, err := sftp.StdinPipe()
  130. if err != nil {
  131. return fmt.Errorf("can't create stdin pipe for sftp: %v", err)
  132. }
  133. if err := sftp.Start(); err != nil {
  134. return err
  135. }
  136. in := io.MultiWriter(stdin, os.Stdout)
  137. for _, f := range files {
  138. fmt.Fprintln(in, "put", f, path.Join(dir, filepath.Base(f)))
  139. }
  140. stdin.Close()
  141. return sftp.Wait()
  142. }
  143. // FindMainPackages finds all 'main' packages in the given directory and returns their
  144. // package paths.
  145. func FindMainPackages(dir string) []string {
  146. var commands []string
  147. cmds, err := ioutil.ReadDir(dir)
  148. if err != nil {
  149. log.Fatal(err)
  150. }
  151. for _, cmd := range cmds {
  152. pkgdir := filepath.Join(dir, cmd.Name())
  153. pkgs, err := parser.ParseDir(token.NewFileSet(), pkgdir, nil, parser.PackageClauseOnly)
  154. if err != nil {
  155. log.Fatal(err)
  156. }
  157. for name := range pkgs {
  158. if name == "main" {
  159. path := "./" + filepath.ToSlash(pkgdir)
  160. commands = append(commands, path)
  161. break
  162. }
  163. }
  164. }
  165. return commands
  166. }