github.com/szyn/goreleaser@v0.76.1-0.20180517112710-333da09a1297/internal/git/git.go (about)

     1  // Package git provides an integration with the git command
     2  package git
     3  
     4  import (
     5  	"bytes"
     6  	"errors"
     7  	"os/exec"
     8  	"strings"
     9  
    10  	"github.com/apex/log"
    11  )
    12  
    13  // IsRepo returns true if current folder is a git repository
    14  func IsRepo() bool {
    15  	out, err := Run("rev-parse", "--is-inside-work-tree")
    16  	return err == nil && strings.TrimSpace(out) == "true"
    17  }
    18  
    19  // Run runs a git command and returns its output or errors
    20  func Run(args ...string) (string, error) {
    21  	/* #nosec */
    22  	var cmd = exec.Command("git", args...)
    23  	log.WithField("args", args).Debug("running git")
    24  	var stdout bytes.Buffer
    25  	var stderr bytes.Buffer
    26  	cmd.Stdout = &stdout
    27  	cmd.Stderr = &stderr
    28  	if err := cmd.Run(); err != nil {
    29  		return "", errors.New(stderr.String())
    30  	}
    31  	log.WithField("output", stdout.String()).Debug("git result")
    32  	return stdout.String(), nil
    33  }
    34  
    35  // Clean the output
    36  func Clean(output string, err error) (string, error) {
    37  	output = strings.Replace(strings.Split(output, "\n")[0], "'", "", -1)
    38  	if err != nil {
    39  		err = errors.New(strings.TrimSuffix(err.Error(), "\n"))
    40  	}
    41  	return output, err
    42  }