-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo_config.go
99 lines (83 loc) · 1.98 KB
/
repo_config.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
95
96
97
98
99
package gitwrapper
import (
"errors"
"os"
"regexp"
"strings"
)
var (
ErrNoRemoteRepo = errors.New("no remote repository")
ErrNoDefaultBranch = errors.New("no default branch")
defaultBranches = []string{
"develop",
"master",
"main",
}
)
type RepoConfig struct {
RemoteHost string
Organization string
Repository string
Branches []string
CurrentBranch string
DefaultBranch string
CommitHash string
}
func NewRepoConfig(dir string) (*RepoConfig, error) {
if err := os.Chdir(dir); err != nil {
return nil, err
}
var repoConfig = new(RepoConfig)
var err error
if repoConfig.RemoteHost, repoConfig.Organization, repoConfig.Repository, err = getRemoteInfo(); err != nil {
return nil, err
}
if repoConfig.Branches, repoConfig.CurrentBranch, repoConfig.DefaultBranch, err = getBranchInfo(); err != nil {
return nil, err
}
if repoConfig.CommitHash, err = runGitCmd(false, "git rev-parse --short HEAD"); err != nil {
return nil, err
}
return repoConfig, nil
}
func getRemoteInfo() (string, string, string, error) {
o, err := runGitCmd(false, "git remote -v")
if err != nil {
return "", "", "", err
}
r, _ := regexp.Compile(`(?m)^origin\s+(?:ssh://)?(?:git@)?(github\.com|gitee\.com)(?:-.*)?(?::|/)(.*)/(.*|.*\.git)\s+\(fetch\)$`)
matches := r.FindStringSubmatch(o)
if len(matches) == 0 {
return "", "", "", ErrNoRemoteRepo
}
return matches[1], matches[2], strings.Split(matches[3], ".git")[0], nil
}
func getBranchInfo() (branches []string, curBranch string, defBranch string, err error) {
bb, err := getAllBranches()
if err != nil {
return
}
for _, b := range bb {
branches = append(branches, b.Name)
if b.IsCurrent {
curBranch = b.Name
}
if b.IsRemote && isDefaultBranch(b.Name) {
defBranch = b.Name
break
}
}
if defBranch == "" {
err = ErrNoDefaultBranch
return
}
return
}
func isDefaultBranch(name string) bool {
for _, branch := range defaultBranches {
if name == branch {
return true
}
}
return false
}