github.com/authcall/reference-optimistic-geth@v0.0.0-20220816224302-06313bfeb8d2/internal/build/util.go (about) 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 17 package build 18 19 import ( 20 "bufio" 21 "bytes" 22 "flag" 23 "fmt" 24 "go/parser" 25 "go/token" 26 "io" 27 "log" 28 "os" 29 "os/exec" 30 "path" 31 "path/filepath" 32 "strings" 33 "text/template" 34 "time" 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 := os.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 // 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.Stderr = os.Stderr 120 if identityFile != "" { 121 sftp.Args = append(sftp.Args, "-i", identityFile) 122 } 123 sftp.Args = append(sftp.Args, host) 124 fmt.Println(">>>", strings.Join(sftp.Args, " ")) 125 if *DryRunFlag { 126 return nil 127 } 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 stdout, err := sftp.StdoutPipe() 134 if err != nil { 135 return fmt.Errorf("can't create stdout pipe for sftp: %v", err) 136 } 137 if err := sftp.Start(); err != nil { 138 return err 139 } 140 in := io.MultiWriter(stdin, os.Stdout) 141 for _, f := range files { 142 fmt.Fprintln(in, "put", f, path.Join(dir, filepath.Base(f))) 143 } 144 fmt.Fprintln(in, "exit") 145 // Some issue with the PPA sftp server makes it so the server does not 146 // respond properly to a 'bye', 'exit' or 'quit' from the client. 147 // To work around that, we check the output, and when we see the client 148 // exit command, we do a hard exit. 149 // See 150 // https://github.com/kolban-google/sftp-gcs/issues/23 151 // https://github.com/mscdex/ssh2/pull/1111 152 aborted := false 153 go func() { 154 scanner := bufio.NewScanner(stdout) 155 for scanner.Scan() { 156 txt := scanner.Text() 157 fmt.Println(txt) 158 if txt == "sftp> exit" { 159 // Give it .5 seconds to exit (server might be fixed), then 160 // hard kill it from the outside 161 time.Sleep(500 * time.Millisecond) 162 aborted = true 163 sftp.Process.Kill() 164 } 165 } 166 }() 167 stdin.Close() 168 err = sftp.Wait() 169 if aborted { 170 return nil 171 } 172 return err 173 } 174 175 // FindMainPackages finds all 'main' packages in the given directory and returns their 176 // package paths. 177 func FindMainPackages(dir string) []string { 178 var commands []string 179 cmds, err := os.ReadDir(dir) 180 if err != nil { 181 log.Fatal(err) 182 } 183 for _, cmd := range cmds { 184 pkgdir := filepath.Join(dir, cmd.Name()) 185 pkgs, err := parser.ParseDir(token.NewFileSet(), pkgdir, nil, parser.PackageClauseOnly) 186 if err != nil { 187 log.Fatal(err) 188 } 189 for name := range pkgs { 190 if name == "main" { 191 path := "./" + filepath.ToSlash(pkgdir) 192 commands = append(commands, path) 193 break 194 } 195 } 196 } 197 return commands 198 }