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