gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/internal/build/util.go (about)

     1  // Copyright 2018 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package build
    18  
    19  import (
    20  	"bytes"
    21  	"flag"
    22  	"fmt"
    23  	"io"
    24  	"io/ioutil"
    25  	"log"
    26  	"os"
    27  	"os/exec"
    28  	"path"
    29  	"path/filepath"
    30  	"runtime"
    31  	"strings"
    32  	"text/template"
    33  )
    34  
    35  var DryRunFlag = flag.Bool("n", false, "dry run, don't execute commands")
    36  
    37  // MustRun executes the given command and exits the host process for
    38  // any error.
    39  func MustRun(cmd *exec.Cmd) {
    40  	fmt.Println(">>>", strings.Join(cmd.Args, " "))
    41  	if !*DryRunFlag {
    42  		cmd.Stderr = os.Stderr
    43  		cmd.Stdout = os.Stdout
    44  		if err := cmd.Run(); err != nil {
    45  			log.Fatal(err)
    46  		}
    47  	}
    48  }
    49  
    50  // ShouldRun executes the given command and doesnt exit the host process for
    51  // any error.
    52  func ShouldRun(cmd *exec.Cmd, msg string) {
    53  	fmt.Println(">>>", strings.Join(cmd.Args, " "))
    54  	if !*DryRunFlag {
    55  		cmd.Stderr = os.Stderr
    56  		cmd.Stdout = os.Stdout
    57  		if err := cmd.Run(); err != nil {
    58  			log.Printf("[WARN %s] %v", msg, err)
    59  		}
    60  	}
    61  }
    62  
    63  func MustRunCommand(cmd string, args ...string) {
    64  	MustRun(exec.Command(cmd, args...))
    65  }
    66  
    67  // GOPATH returns the value that the GOPATH environment
    68  // variable should be set to.
    69  func GOPATH() string {
    70  	if os.Getenv("GOPATH") == "" {
    71  		return "unset"
    72  	}
    73  	return os.Getenv("GOPATH")
    74  }
    75  
    76  // VERSION returns the content of the VERSION file.
    77  func VERSION() string {
    78  	version, err := ioutil.ReadFile("VERSION")
    79  	if err != nil {
    80  		log.Fatal(err)
    81  	}
    82  	return string(bytes.TrimSpace(version))
    83  }
    84  
    85  var warnedAboutGit bool
    86  
    87  // RunGit runs a git subcommand and returns its output.
    88  // The command must complete successfully.
    89  func RunGit(args ...string) string {
    90  	cmd := exec.Command("git", args...)
    91  	var stdout, stderr bytes.Buffer
    92  	cmd.Stdout, cmd.Stderr = &stdout, &stderr
    93  	if err := cmd.Run(); err == exec.ErrNotFound {
    94  		if !warnedAboutGit {
    95  			log.Println("Warning: can't find 'git' in PATH")
    96  			warnedAboutGit = true
    97  		}
    98  		return ""
    99  	} else if err != nil {
   100  		log.Fatal(strings.Join(cmd.Args, " "), ": ", err, "\n", stderr.String())
   101  	}
   102  	return strings.TrimSpace(stdout.String())
   103  }
   104  
   105  // readGitFile returns content of file in .git directory.
   106  func readGitFile(file string) string {
   107  	content, err := ioutil.ReadFile(path.Join(".git", file))
   108  	if err != nil {
   109  		return ""
   110  	}
   111  	return strings.TrimSpace(string(content))
   112  }
   113  
   114  // Render renders the given template file into outputFile.
   115  func Render(templateFile, outputFile string, outputPerm os.FileMode, x interface{}) {
   116  	tpl := template.Must(template.ParseFiles(templateFile))
   117  	render(tpl, outputFile, outputPerm, x)
   118  }
   119  
   120  // RenderString renders the given template string into outputFile.
   121  func RenderString(templateContent, outputFile string, outputPerm os.FileMode, x interface{}) {
   122  	tpl := template.Must(template.New("").Parse(templateContent))
   123  	render(tpl, outputFile, outputPerm, x)
   124  }
   125  
   126  func render(tpl *template.Template, outputFile string, outputPerm os.FileMode, x interface{}) {
   127  	if err := os.MkdirAll(filepath.Dir(outputFile), 0755); err != nil {
   128  		log.Fatal(err)
   129  	}
   130  	out, err := os.OpenFile(outputFile, os.O_CREATE|os.O_WRONLY|os.O_EXCL, outputPerm)
   131  	if err != nil {
   132  		log.Fatal(err)
   133  	}
   134  	if err := tpl.Execute(out, x); err != nil {
   135  		log.Fatal(err)
   136  	}
   137  	if err := out.Close(); err != nil {
   138  		log.Fatal(err)
   139  	}
   140  }
   141  
   142  // CopyFile copies a file.
   143  func CopyFile(dst, src string, mode os.FileMode) {
   144  	if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
   145  		log.Fatal(err)
   146  	}
   147  	destFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
   148  	if err != nil {
   149  		log.Fatal(err)
   150  	}
   151  	defer destFile.Close()
   152  
   153  	srcFile, err := os.Open(src)
   154  	if err != nil {
   155  		log.Fatal(err)
   156  	}
   157  	defer srcFile.Close()
   158  
   159  	if _, err := io.Copy(destFile, srcFile); err != nil {
   160  		log.Fatal(err)
   161  	}
   162  }
   163  
   164  // GoTool returns the command that runs a go tool. This uses go from GOROOT instead of PATH
   165  // so that go commands executed by build use the same version of Go as the 'host' that runs
   166  // build code. e.g.
   167  //
   168  //     /usr/lib/go-1.8/bin/go run build/ci.go ...
   169  //
   170  // runs using go 1.8 and invokes go 1.8 tools from the same GOROOT. This is also important
   171  // because runtime.Version checks on the host should match the tools that are run.
   172  func GoTool(tool string, args ...string) *exec.Cmd {
   173  	args = append([]string{tool}, args...)
   174  	return exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
   175  }
   176  
   177  // ExpandPackagesNoVendor expands a cmd/go import path pattern, skipping
   178  // vendored packages.
   179  func ExpandPackagesNoVendor(patterns []string) (all, short, long []string) {
   180  	expand := false
   181  	for _, pkg := range patterns {
   182  		if strings.Contains(pkg, "...") {
   183  			expand = true
   184  		}
   185  	}
   186  	if !expand {
   187  		log.Println("not expanding")
   188  		return patterns, short, long
   189  	}
   190  
   191  	log.Println("listing")
   192  	cmd := GoTool("list", patterns...)
   193  	out, err := cmd.Output()
   194  	if err != nil {
   195  		log.Fatalf("package listing failed: %v\n%s", err, string(out))
   196  	}
   197  	for _, line := range strings.Split(string(out), "\n") {
   198  		if strings.Contains(line, "/vendor/") {
   199  			continue
   200  		}
   201  		if strings.Contains(line, ":") {
   202  			log.Println("Skipping invalid package (FIXME):", line)
   203  			continue
   204  		}
   205  		line = strings.TrimSpace(line)
   206  		all = append(all, line)
   207  		if strings.HasSuffix(line, "aqua/downloader") ||
   208  			strings.HasSuffix(line, "aqua/fetcher") {
   209  			long = append(long, line)
   210  		} else {
   211  			short = append(short, line)
   212  		}
   213  	}
   214  	return
   215  }