github.com/ethereum/go-ethereum@v1.14.3/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/filepath"
    31  	"strconv"
    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(">>>", printArgs(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 printArgs(args []string) string {
    53  	var s strings.Builder
    54  	for i, arg := range args {
    55  		if i > 0 {
    56  			s.WriteByte(' ')
    57  		}
    58  		if strings.IndexByte(arg, ' ') >= 0 {
    59  			arg = strconv.QuoteToASCII(arg)
    60  		}
    61  		s.WriteString(arg)
    62  	}
    63  	return s.String()
    64  }
    65  
    66  func MustRunCommand(cmd string, args ...string) {
    67  	MustRun(exec.Command(cmd, args...))
    68  }
    69  
    70  // MustRunCommandWithOutput runs the given command, and ensures that some output will be
    71  // printed while it runs. This is useful for CI builds where the process will be stopped
    72  // when there is no output.
    73  func MustRunCommandWithOutput(cmd string, args ...string) {
    74  	interval := time.NewTicker(time.Minute)
    75  	done := make(chan struct{})
    76  	defer interval.Stop()
    77  	defer close(done)
    78  	go func() {
    79  		for {
    80  			select {
    81  			case <-interval.C:
    82  				fmt.Printf("Waiting for command %q\n", cmd)
    83  			case <-done:
    84  				return
    85  			}
    86  		}
    87  	}()
    88  	MustRun(exec.Command(cmd, args...))
    89  }
    90  
    91  var warnedAboutGit bool
    92  
    93  // RunGit runs a git subcommand and returns its output.
    94  // The command must complete successfully.
    95  func RunGit(args ...string) string {
    96  	cmd := exec.Command("git", args...)
    97  	var stdout, stderr bytes.Buffer
    98  	cmd.Stdout, cmd.Stderr = &stdout, &stderr
    99  	if err := cmd.Run(); err != nil {
   100  		if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound {
   101  			if !warnedAboutGit {
   102  				log.Println("Warning: can't find 'git' in PATH")
   103  				warnedAboutGit = true
   104  			}
   105  			return ""
   106  		}
   107  		log.Fatal(strings.Join(cmd.Args, " "), ": ", err, "\n", stderr.String())
   108  	}
   109  	return strings.TrimSpace(stdout.String())
   110  }
   111  
   112  // readGitFile returns content of file in .git directory.
   113  func readGitFile(file string) string {
   114  	content, err := os.ReadFile(filepath.Join(".git", file))
   115  	if err != nil {
   116  		return ""
   117  	}
   118  	return strings.TrimSpace(string(content))
   119  }
   120  
   121  // Render renders the given template file into outputFile.
   122  func Render(templateFile, outputFile string, outputPerm os.FileMode, x interface{}) {
   123  	tpl := template.Must(template.ParseFiles(templateFile))
   124  	render(tpl, outputFile, outputPerm, x)
   125  }
   126  
   127  // RenderString renders the given template string into outputFile.
   128  func RenderString(templateContent, outputFile string, outputPerm os.FileMode, x interface{}) {
   129  	tpl := template.Must(template.New("").Parse(templateContent))
   130  	render(tpl, outputFile, outputPerm, x)
   131  }
   132  
   133  func render(tpl *template.Template, outputFile string, outputPerm os.FileMode, x interface{}) {
   134  	if err := os.MkdirAll(filepath.Dir(outputFile), 0755); err != nil {
   135  		log.Fatal(err)
   136  	}
   137  	out, err := os.OpenFile(outputFile, os.O_CREATE|os.O_WRONLY|os.O_EXCL, outputPerm)
   138  	if err != nil {
   139  		log.Fatal(err)
   140  	}
   141  	if err := tpl.Execute(out, x); err != nil {
   142  		log.Fatal(err)
   143  	}
   144  	if err := out.Close(); err != nil {
   145  		log.Fatal(err)
   146  	}
   147  }
   148  
   149  // UploadSFTP uploads files to a remote host using the sftp command line tool.
   150  // The destination host may be specified either as [user@]host: or as a URI in
   151  // the form sftp://[user@]host[:port].
   152  func UploadSFTP(identityFile, host, dir string, files []string) error {
   153  	sftp := exec.Command("sftp")
   154  	sftp.Stderr = os.Stderr
   155  	if identityFile != "" {
   156  		sftp.Args = append(sftp.Args, "-i", identityFile)
   157  	}
   158  	sftp.Args = append(sftp.Args, host)
   159  	fmt.Println(">>>", printArgs(sftp.Args))
   160  	if *DryRunFlag {
   161  		return nil
   162  	}
   163  
   164  	stdin, err := sftp.StdinPipe()
   165  	if err != nil {
   166  		return fmt.Errorf("can't create stdin pipe for sftp: %v", err)
   167  	}
   168  	stdout, err := sftp.StdoutPipe()
   169  	if err != nil {
   170  		return fmt.Errorf("can't create stdout pipe for sftp: %v", err)
   171  	}
   172  	if err := sftp.Start(); err != nil {
   173  		return err
   174  	}
   175  	in := io.MultiWriter(stdin, os.Stdout)
   176  	for _, f := range files {
   177  		fmt.Fprintln(in, "put", f, filepath.Join(dir, filepath.Base(f)))
   178  	}
   179  	fmt.Fprintln(in, "exit")
   180  	// Some issue with the PPA sftp server makes it so the server does not
   181  	// respond properly to a 'bye', 'exit' or 'quit' from the client.
   182  	// To work around that, we check the output, and when we see the client
   183  	// exit command, we do a hard exit.
   184  	// See
   185  	// https://github.com/kolban-google/sftp-gcs/issues/23
   186  	// https://github.com/mscdex/ssh2/pull/1111
   187  	aborted := false
   188  	go func() {
   189  		scanner := bufio.NewScanner(stdout)
   190  		for scanner.Scan() {
   191  			txt := scanner.Text()
   192  			fmt.Println(txt)
   193  			if txt == "sftp> exit" {
   194  				// Give it .5 seconds to exit (server might be fixed), then
   195  				// hard kill it from the outside
   196  				time.Sleep(500 * time.Millisecond)
   197  				aborted = true
   198  				sftp.Process.Kill()
   199  			}
   200  		}
   201  	}()
   202  	stdin.Close()
   203  	err = sftp.Wait()
   204  	if aborted {
   205  		return nil
   206  	}
   207  	return err
   208  }
   209  
   210  // FindMainPackages finds all 'main' packages in the given directory and returns their
   211  // package paths.
   212  func FindMainPackages(dir string) []string {
   213  	var commands []string
   214  	cmds, err := os.ReadDir(dir)
   215  	if err != nil {
   216  		log.Fatal(err)
   217  	}
   218  	for _, cmd := range cmds {
   219  		pkgdir := filepath.Join(dir, cmd.Name())
   220  		if !cmd.IsDir() {
   221  			continue
   222  		}
   223  		pkgs, err := parser.ParseDir(token.NewFileSet(), pkgdir, nil, parser.PackageClauseOnly)
   224  		if err != nil {
   225  			log.Fatal(err)
   226  		}
   227  		for name := range pkgs {
   228  			if name == "main" {
   229  				path := "./" + filepath.ToSlash(pkgdir)
   230  				commands = append(commands, path)
   231  				break
   232  			}
   233  		}
   234  	}
   235  	return commands
   236  }