github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/internal/build/util.go (about)

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