forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.go
52 lines (44 loc) · 1.19 KB
/
git.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
package git
import (
"bytes"
"fmt"
"os/exec"
"strings"
"github.com/pkg/errors"
)
func Clone(path, url, branch string) error {
return runcmd("git", "clone", "-b", branch, "--single-branch", url, path)
}
func Update(path, branch string) error {
if err := runcmd("git", "-C", path, "fetch"); err != nil {
return err
}
return runcmd("git", "-C", path, "checkout", fmt.Sprintf("origin/%s", branch))
}
func HeadCommit(path string) (string, error) {
cmd := exec.Command("git", "-C", path, "rev-parse", "HEAD")
output, err := cmd.Output()
return strings.Trim(string(output), "\n"), err
}
func RemoteBranchHeadCommit(url, branch string) (string, error) {
cmd := exec.Command("git", "ls-remote", url, branch)
output, err := cmd.CombinedOutput()
if err != nil {
return "", errors.Wrap(err, string(output))
}
parts := strings.Split(string(output), "\t")
return parts[0], nil
}
func IsValid(url string) bool {
err := runcmd("git", "ls-remote", url)
return err == nil
}
func runcmd(name string, arg ...string) error {
cmd := exec.Command(name, arg...)
bufErr := &bytes.Buffer{}
cmd.Stderr = bufErr
if err := cmd.Run(); err != nil {
return errors.Wrap(err, bufErr.String())
}
return nil
}