-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepo.go
67 lines (52 loc) · 1.58 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
package main
import (
"fmt"
"net/url"
"regexp"
"strings"
)
type RepoService struct {
cmd Commander
}
func (s RepoService) GetRepositoryURL(remote string) (string, error) {
remoteURL, err := s.getRemoteURL(remote)
if err != nil {
return "", err
}
if strings.HasPrefix(remoteURL, "http") && s.validURL(remoteURL) {
return s.handleHttpRemote(remoteURL)
}
if strings.HasPrefix(remoteURL, "ssh://git@") {
return s.handleSSHRemote(remoteURL)
}
return s.handleGitURLRemote(remoteURL)
}
func (s RepoService) getRemoteURL(remote string) (string, error) {
out, err := s.cmd.CommandOutput("git", "remote", "get-url", remote)
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
func (s RepoService) validURL(input string) bool {
_, err := url.ParseRequestURI(input)
return err == nil
}
func (s RepoService) handleHttpRemote(remoteURL string) (string, error) {
return strings.TrimSuffix(remoteURL, ".git"), nil
}
func (s RepoService) handleSSHRemote(remoteURL string) (string, error) {
parts := strings.Split(remoteURL, "ssh://git@")
if len(parts) < 2 {
return "", fmt.Errorf("failed to extract repository URL from %s", remoteURL)
}
return strings.TrimSuffix(fmt.Sprintf("https://%s", parts[1]), ".git"), nil
}
func (s RepoService) handleGitURLRemote(remoteURL string) (string, error) {
r := regexp.MustCompile(`^git@(.+):(.+\/.+).git$`)
matches := r.FindStringSubmatch(remoteURL)
if len(matches) < 3 {
return "", fmt.Errorf("failed to extract repository URL from %s", remoteURL)
}
return fmt.Sprintf("https://%s/%s", matches[1], matches[2]), nil
}