util.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. "io"
  22. "io/ioutil"
  23. "log"
  24. "os"
  25. "os/exec"
  26. "path"
  27. "path/filepath"
  28. "runtime"
  29. "strings"
  30. "text/template"
  31. )
  32. var DryRunFlag = flag.Bool("n", false, "dry run, don't execute commands")
  33. // MustRun executes the given command and exits the host process for
  34. // any error.
  35. func MustRun(cmd *exec.Cmd) {
  36. fmt.Println(">>>", strings.Join(cmd.Args, " "))
  37. if !*DryRunFlag {
  38. cmd.Stderr = os.Stderr
  39. cmd.Stdout = os.Stdout
  40. if err := cmd.Run(); err != nil {
  41. log.Fatal(err)
  42. }
  43. }
  44. }
  45. func MustRunCommand(cmd string, args ...string) {
  46. MustRun(exec.Command(cmd, args...))
  47. }
  48. // GOPATH returns the value that the GOPATH environment
  49. // variable should be set to.
  50. func GOPATH() string {
  51. if os.Getenv("GOPATH") == "" {
  52. log.Fatal("GOPATH is not set")
  53. }
  54. return os.Getenv("GOPATH")
  55. }
  56. var warnedAboutGit bool
  57. // RunGit runs a git subcommand and returns its output.
  58. // The command must complete successfully.
  59. func RunGit(args ...string) string {
  60. cmd := exec.Command("git", args...)
  61. var stdout, stderr bytes.Buffer
  62. cmd.Stdout, cmd.Stderr = &stdout, &stderr
  63. if err := cmd.Run(); err != nil {
  64. if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound {
  65. if !warnedAboutGit {
  66. log.Println("Warning: can't find 'git' in PATH")
  67. warnedAboutGit = true
  68. }
  69. return ""
  70. }
  71. log.Fatal(strings.Join(cmd.Args, " "), ": ", err, "\n", stderr.String())
  72. }
  73. return strings.TrimSpace(stdout.String())
  74. }
  75. // readGitFile returns content of file in .git directory.
  76. func readGitFile(file string) string {
  77. content, err := ioutil.ReadFile(path.Join(".git", file))
  78. if err != nil {
  79. return ""
  80. }
  81. return strings.TrimSpace(string(content))
  82. }
  83. // Render renders the given template file into outputFile.
  84. func Render(templateFile, outputFile string, outputPerm os.FileMode, x interface{}) {
  85. tpl := template.Must(template.ParseFiles(templateFile))
  86. render(tpl, outputFile, outputPerm, x)
  87. }
  88. // RenderString renders the given template string into outputFile.
  89. func RenderString(templateContent, outputFile string, outputPerm os.FileMode, x interface{}) {
  90. tpl := template.Must(template.New("").Parse(templateContent))
  91. render(tpl, outputFile, outputPerm, x)
  92. }
  93. func render(tpl *template.Template, outputFile string, outputPerm os.FileMode, x interface{}) {
  94. if err := os.MkdirAll(filepath.Dir(outputFile), 0755); err != nil {
  95. log.Fatal(err)
  96. }
  97. out, err := os.OpenFile(outputFile, os.O_CREATE|os.O_WRONLY|os.O_EXCL, outputPerm)
  98. if err != nil {
  99. log.Fatal(err)
  100. }
  101. if err := tpl.Execute(out, x); err != nil {
  102. log.Fatal(err)
  103. }
  104. if err := out.Close(); err != nil {
  105. log.Fatal(err)
  106. }
  107. }
  108. // CopyFile copies a file.
  109. func CopyFile(dst, src string, mode os.FileMode) {
  110. if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
  111. log.Fatal(err)
  112. }
  113. destFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
  114. if err != nil {
  115. log.Fatal(err)
  116. }
  117. defer destFile.Close()
  118. srcFile, err := os.Open(src)
  119. if err != nil {
  120. log.Fatal(err)
  121. }
  122. defer srcFile.Close()
  123. if _, err := io.Copy(destFile, srcFile); err != nil {
  124. log.Fatal(err)
  125. }
  126. }
  127. // CopyFolder copies a folder.
  128. func CopyFolder(dst, src string, mode os.FileMode) {
  129. if err := os.MkdirAll(dst, mode); err != nil {
  130. log.Fatal(err)
  131. }
  132. dir, _ := os.Open(src)
  133. objects, err := dir.Readdir(-1)
  134. if err != nil {
  135. log.Fatal(err)
  136. }
  137. for _, obj := range objects {
  138. srcPath := filepath.Join(src, obj.Name())
  139. dstPath := filepath.Join(dst, obj.Name())
  140. if obj.IsDir() {
  141. CopyFolder(dstPath, srcPath, mode)
  142. } else {
  143. CopyFile(dstPath, srcPath, mode)
  144. }
  145. }
  146. }
  147. // GoTool returns the command that runs a go tool. This uses go from GOROOT instead of PATH
  148. // so that go commands executed by build use the same version of Go as the 'host' that runs
  149. // build code. e.g.
  150. //
  151. // /usr/lib/go-1.12.1/bin/go run build/ci.go ...
  152. //
  153. // runs using go 1.12.1 and invokes go 1.12.1 tools from the same GOROOT. This is also important
  154. // because runtime.Version checks on the host should match the tools that are run.
  155. func GoTool(tool string, args ...string) *exec.Cmd {
  156. args = append([]string{tool}, args...)
  157. return exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
  158. }
  159. // UploadSFTP uploads files to a remote host using the sftp command line tool.
  160. // The destination host may be specified either as [user@]host[: or as a URI in
  161. // the form sftp://[user@]host[:port].
  162. func UploadSFTP(identityFile, host, dir string, files []string) error {
  163. sftp := exec.Command("sftp")
  164. sftp.Stdout = nil
  165. sftp.Stderr = os.Stderr
  166. if identityFile != "" {
  167. sftp.Args = append(sftp.Args, "-i", identityFile)
  168. }
  169. sftp.Args = append(sftp.Args, host)
  170. fmt.Println(">>>", strings.Join(sftp.Args, " "))
  171. if *DryRunFlag {
  172. return nil
  173. }
  174. stdin, err := sftp.StdinPipe()
  175. if err != nil {
  176. return fmt.Errorf("can't create stdin pipe for sftp: %v", err)
  177. }
  178. if err := sftp.Start(); err != nil {
  179. return err
  180. }
  181. in := io.MultiWriter(stdin, os.Stdout)
  182. for _, f := range files {
  183. fmt.Fprintln(in, "put", f, path.Join(dir, filepath.Base(f)))
  184. }
  185. stdin.Close()
  186. return sftp.Wait()
  187. }