1package getter
2
3import (
4	"fmt"
5	"net/url"
6	"strings"
7)
8
9// GitHubDetector implements Detector to detect GitHub URLs and turn
10// them into URLs that the Git Getter can understand.
11type GitHubDetector struct{}
12
13func (d *GitHubDetector) Detect(src, _ string) (string, bool, error) {
14	if len(src) == 0 {
15		return "", false, nil
16	}
17
18	if strings.HasPrefix(src, "github.com/") {
19		return d.detectHTTP(src)
20	}
21
22	return "", false, nil
23}
24
25func (d *GitHubDetector) detectHTTP(src string) (string, bool, error) {
26	parts := strings.Split(src, "/")
27	if len(parts) < 3 {
28		return "", false, fmt.Errorf(
29			"GitHub URLs should be github.com/username/repo")
30	}
31
32	urlStr := fmt.Sprintf("https://%s", strings.Join(parts[:3], "/"))
33	url, err := url.Parse(urlStr)
34	if err != nil {
35		return "", true, fmt.Errorf("error parsing GitHub URL: %s", err)
36	}
37
38	if !strings.HasSuffix(url.Path, ".git") {
39		url.Path += ".git"
40	}
41
42	if len(parts) > 3 {
43		url.Path += "//" + strings.Join(parts[3:], "/")
44	}
45
46	return "git::" + url.String(), true, nil
47}
48