forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote.go
101 lines (85 loc) · 1.9 KB
/
remote.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
100
101
package github
import (
"fmt"
"net/url"
"regexp"
"strings"
"github.com/github/hub/git"
)
var (
OriginNamesInLookupOrder = []string{"upstream", "github", "origin"}
)
type Remote struct {
Name string
URL *url.URL
PushURL *url.URL
}
func (remote *Remote) String() string {
return remote.Name
}
func (remote *Remote) Project() (*Project, error) {
p, err := NewProjectFromURL(remote.URL)
if _, ok := err.(*GithubHostError); ok {
return NewProjectFromURL(remote.PushURL)
}
return p, err
}
func Remotes() (remotes []Remote, err error) {
re := regexp.MustCompile(`(.+)\s+(.+)\s+\((push|fetch)\)`)
rs, err := git.Remotes()
if err != nil {
err = fmt.Errorf("Can't load git remote")
return
}
// build the remotes map
remotesMap := make(map[string]map[string]string)
for _, r := range rs {
if re.MatchString(r) {
match := re.FindStringSubmatch(r)
name := strings.TrimSpace(match[1])
url := strings.TrimSpace(match[2])
urlType := strings.TrimSpace(match[3])
utm, ok := remotesMap[name]
if !ok {
utm = make(map[string]string)
remotesMap[name] = utm
}
utm[urlType] = url
}
}
// construct remotes in priority order
names := OriginNamesInLookupOrder
for _, name := range names {
if u, ok := remotesMap[name]; ok {
r, err := newRemote(name, u)
if err == nil {
remotes = append(remotes, r)
delete(remotesMap, name)
}
}
}
// the rest of the remotes
for n, u := range remotesMap {
r, err := newRemote(n, u)
if err == nil {
remotes = append(remotes, r)
}
}
return
}
func newRemote(name string, urlMap map[string]string) (Remote, error) {
r := Remote{}
fetchURL, ferr := git.ParseURL(urlMap["fetch"])
pushURL, perr := git.ParseURL(urlMap["push"])
if ferr != nil && perr != nil {
return r, fmt.Errorf("No valid remote URLs")
}
r.Name = name
if ferr == nil {
r.URL = fetchURL
}
if perr == nil {
r.PushURL = pushURL
}
return r, nil
}