forked from jehiah/git-open-pull
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git_commands.go
59 lines (52 loc) · 1.75 KB
/
git_commands.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
import (
"context"
"fmt"
"os/exec"
"strings"
)
func RunGit(ctx context.Context, arg ...string) ([]byte, error) {
// log.Printf("run git %s", strings.Join(arg, " "))
cmd := exec.CommandContext(ctx, "git", arg...)
body, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("%s running \"git %s\"", err, strings.Join(arg, " "))
}
return body, nil
}
func GitFeatureBranch(ctx context.Context) (string, error) {
body, err := RunGit(ctx, "rev-parse", "--abbrev-ref", "HEAD")
return strings.TrimSpace(string(body)), err
}
func MergeBase(ctx context.Context, settings *Settings) (string, error) {
_, err := RunGit(ctx, "fetch", settings.BaseAccount, fmt.Sprintf("+refs/heads/%s", settings.BaseBranch))
if err != nil {
return "", err
}
base, err := RunGit(ctx, "merge-base", "FETCH_HEAD", "HEAD")
return strings.TrimSpace(string(base)), err
}
// reverse an array of strings
func reverse(ss []string) {
last := len(ss) - 1
for i := 0; i < len(ss)/2; i++ {
ss[i], ss[last-i] = ss[last-i], ss[i]
}
}
// Commits returns a list of all commit sha's since merge base
// the oldest commit (first) is returned first
func Commits(ctx context.Context, base string) ([]string, error) {
output, err := RunGit(ctx, "log", "--format=%H", fmt.Sprintf("%s...HEAD", base))
commits := strings.Split(strings.TrimSpace(string(output)), "\n")
reverse(commits)
return commits, err
}
// CommitDetails gets the subject and body for a commit
func CommitDetails(ctx context.Context, hash string) (string, string, error) {
title, err := RunGit(ctx, "show", "-s", "--format=%s", hash)
if err != nil {
return "", "", err
}
body, err := RunGit(ctx, "show", "-s", "--format=%b", hash)
return strings.TrimSpace(string(title)), strings.TrimSpace(string(body)), err
}