-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathremote.go
100 lines (85 loc) · 2.35 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
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"regexp"
)
type Remote struct {
Name, Url, Type string
}
func DetectRemote(dir string) ([]*Remote, error) {
git := exec.Command("git", "remote", "-v")
git.Dir = dir
stdout, err := git.StdoutPipe()
if err != nil {
return nil, err
}
git.Stderr = os.Stderr
err = git.Start()
if err != nil {
return nil, err
}
remotes := make([]*Remote, 0)
reader := bufio.NewReader(stdout)
re := regexp.MustCompile(`^(\S+)\s*(\S+)\s*\((\S+)\)`)
for {
line, err := reader.ReadString('\n')
if err != nil {
if err != io.EOF {
return nil, err
}
break
}
m := re.FindStringSubmatch(line)
if m != nil {
r := &Remote{m[1], m[2], m[3]}
remotes = append(remotes, r)
}
}
if err := git.Wait(); err != nil {
return nil, err
}
return remotes, nil
}
// Convert git remote url to github URL
//
// Supported types:
// - [email protected]:username/repo.git
// - https://github.com/username/repo.git
// - git://github.com/username/repo.git
// - [email protected]:username/repo.git //same github
// - https://[email protected]/username/repo.git //diffrent github
func MangleURL(url string) (string, error) {
ssh_re := regexp.MustCompile(`^git@(.*?):(.*?)/(.*?)\.git$`)
ssh2_re := regexp.MustCompile(`^ssh://git@(.*?)/(.*?)/(.*?)\.git$`)
https_re := regexp.MustCompile(`^https://(.*?)/(.*?)/(.*?)(?:.git)?$`)
https2_re := regexp.MustCompile(`^https://.*@(.*?)/(.*?)/(.*?)(?:.git)?$`)
git_re := regexp.MustCompile(`^git://(.*?)/(.*?)/(.*?).git$`)
var matches []string
if m := ssh_re.FindStringSubmatch(url); m != nil {
matches = m
} else if m := ssh2_re.FindStringSubmatch(url); m != nil {
matches = m
} else if m := https2_re.FindStringSubmatch(url); m != nil {
matches = m
} else if m := https_re.FindStringSubmatch(url); m != nil {
matches = m
} else if m := git_re.FindStringSubmatch(url); m != nil {
matches = m
} else {
return "", fmt.Errorf("unsupported remote url: %s", url)
}
return CreateURL(matches[1], matches[2], matches[3])
}
func CreateURL(host, user, repo string) (string, error) {
if host == "github.com" {
return fmt.Sprintf("https://%s/%s/%s", host, user, repo), nil
} else if host == "bitbucket.org" {
return fmt.Sprintf("https://%s/%s/%s", host, user, repo), nil
} else {
return "", fmt.Errorf("invalid github or bitbucket host: %s", host)
}
}