github.com/tsuyoshiwada/git-prout@v0.0.0-20170402150409-5c51421d4bdb/git.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"io/ioutil"
     6  	"os/exec"
     7  	"regexp"
     8  	"strings"
     9  	"syscall"
    10  )
    11  
    12  // Check `git` command can be callable.
    13  func hasGitCommand() bool {
    14  	_, err := exec.LookPath("git")
    15  	return err == nil
    16  }
    17  
    18  // Check is inside work tree in git repository
    19  func isInsideGitWorkTree() bool {
    20  	_, err := git("rev-parse", "--is-inside-work-tree")
    21  	if err != nil {
    22  		return false
    23  	}
    24  	return true
    25  }
    26  
    27  // Git call `git` command, return standard output as a string.
    28  func git(subcmd string, args ...string) (string, error) {
    29  	gitArgs := append([]string{subcmd}, args...)
    30  
    31  	var out bytes.Buffer
    32  	cmd := exec.Command("git", gitArgs...)
    33  	cmd.Stdout = &out
    34  	cmd.Stderr = ioutil.Discard
    35  
    36  	err := cmd.Run()
    37  	if exitError, ok := err.(*exec.ExitError); ok {
    38  		if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); ok {
    39  			if waitStatus.ExitStatus() != 0 {
    40  				return "", err
    41  			}
    42  		}
    43  	}
    44  
    45  	return strings.TrimRight(strings.TrimSpace(out.String()), "\000"), nil
    46  }
    47  
    48  // GitRemotes get all remotes.
    49  func GitRemotes() ([]string, error) {
    50  	out, err := git("remote")
    51  	if err != nil {
    52  		return []string{}, err
    53  	}
    54  
    55  	return regexp.MustCompile("\r\n|\n\r|\n|\r").Split(out, -1), nil
    56  }
    57  
    58  // GitListRemotes get all remotes. In case of error, it returns an empty array.
    59  func GitListRemotes() []string {
    60  	remotes, err := GitRemotes()
    61  	if err != nil {
    62  		return []string{}
    63  	}
    64  	return remotes
    65  }
    66  
    67  // GitIsValidRemote check the exists of the specify remote.
    68  func GitIsValidRemote(remote string) bool {
    69  	remotes, err := GitRemotes()
    70  	if err != nil {
    71  		return false
    72  	}
    73  
    74  	for _, r := range remotes {
    75  		if r == remote {
    76  			return true
    77  		}
    78  	}
    79  
    80  	return false
    81  }
    82  
    83  // GitCurrentBranch get current branch name.
    84  func GitCurrentBranch() (string, error) {
    85  	return git("rev-parse", "--abbrev-ref", "HEAD")
    86  }