forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote.go
70 lines (58 loc) · 1.29 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
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
}
func (remote *Remote) String() string {
return remote.Name
}
func (remote *Remote) Project() (*Project, error) {
return NewProjectFromURL(remote.URL)
}
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]string)
for _, r := range rs {
if re.MatchString(r) {
match := re.FindStringSubmatch(r)
name := strings.TrimSpace(match[1])
url := strings.TrimSpace(match[2])
remotesMap[name] = url
}
}
// construct remotes in priority order
names := OriginNamesInLookupOrder
for _, name := range names {
if u, ok := remotesMap[name]; ok {
url, e := git.ParseURL(u)
if e == nil {
remotes = append(remotes, Remote{Name: name, URL: url})
delete(remotesMap, name)
}
}
}
// the rest of the remotes
for n, u := range remotesMap {
url, e := git.ParseURL(u)
if e == nil {
remotes = append(remotes, Remote{Name: n, URL: url})
}
}
return
}