github.com/LGUG2Z/story@v0.4.1/git/push.go (about)

     1  package git
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"strings"
     7  )
     8  
     9  type PushOpts struct {
    10  	Project string
    11  	Remote  string
    12  	Branch  string
    13  }
    14  
    15  func hasUnpushedCommits(project string) (bool, error) {
    16  	command := exec.Command("git", "log", "--branches", "--not", "--remotes")
    17  	if project != "" {
    18  		command.Dir = project
    19  	}
    20  
    21  	combinedOutput, err := command.CombinedOutput()
    22  	if err != nil {
    23  		return false, err
    24  	}
    25  
    26  	trimmed := strings.TrimSpace(string(combinedOutput))
    27  
    28  	return len(trimmed) > 0, nil
    29  }
    30  
    31  func Push(opts PushOpts) (string, error) {
    32  	changes, err := hasUnpushedCommits(opts.Project)
    33  	if err != nil {
    34  		return "", err
    35  	}
    36  
    37  	if !changes {
    38  		return "no unpushed commits", err
    39  	}
    40  
    41  	var args []string
    42  	args = append(args, "push", "-u", opts.Remote, opts.Branch)
    43  
    44  	command := exec.Command("git", args...)
    45  	if opts.Project != "" {
    46  		command.Dir = opts.Project
    47  	}
    48  
    49  	combinedOutput, err := command.CombinedOutput()
    50  	if err != nil {
    51  		return "", fmt.Errorf("%s: %s", err, combinedOutput)
    52  	}
    53  
    54  	return strings.TrimSpace(string(combinedOutput)), nil
    55  }