-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrepo.go
94 lines (69 loc) · 1.67 KB
/
repo.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"strings"
)
type Repo struct {
Origin string
Branch string
}
func getDepRoot(repo string, gopath string, pkg string) (string, *Repo, error) {
var err error
pkgRoot := filepath.Join(gopath, "src", pkg)
root, err := getGitTopLevel(pkgRoot)
if err != nil {
return "", nil, err
}
rootRoot := root
for rootRoot != repo && strings.HasPrefix(rootRoot, repo) {
root = rootRoot
rootRoot, err = getGitTopLevel(filepath.Dir(root))
if err != nil {
return "", nil, err
}
}
if root == repo {
// non-git repo; point to package instead
return pkgRoot, nil, nil
}
pkgRepo := &Repo{}
gitOriginURL := exec.Command("git", "config", "--get", "remote.origin.url")
gitOriginURL.Dir = root
buf := new(bytes.Buffer)
gitOriginURL.Stdout = buf
gitOriginURL.Stderr = os.Stderr
err = gitOriginURL.Run()
if err != nil {
return "", nil, err
}
pkgRepo.Origin = strings.TrimRight(buf.String(), "\n")
gitRevParse := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
gitRevParse.Dir = root
buf = new(bytes.Buffer)
gitRevParse.Stdout = buf
gitRevParse.Stderr = os.Stderr
err = gitRevParse.Run()
if err != nil {
return "", nil, err
}
rev := strings.TrimRight(buf.String(), "\n")
if rev != "HEAD" {
pkgRepo.Branch = rev
}
return root, pkgRepo, nil
}
func getGitTopLevel(path string) (string, error) {
gitToplevel := exec.Command("git", "rev-parse", "--show-toplevel")
gitToplevel.Dir = path
buf := new(bytes.Buffer)
gitToplevel.Stdout = buf
gitToplevel.Stderr = os.Stderr
err := gitToplevel.Run()
if err != nil {
return "", err
}
return strings.TrimRight(buf.String(), "\n"), nil
}