github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/internal/build/util.go (about)

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