-
Notifications
You must be signed in to change notification settings - Fork 7
/
spec.go
78 lines (70 loc) · 2.3 KB
/
spec.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
package catalog
import (
"fmt"
"net/url"
"os/exec"
"path"
"strings"
"github.com/anz-bank/sysl/pkg/sysl"
)
func IsOpenAPIFile(source *sysl.SourceContext) bool {
importPath := source.GetFile()
fileExt := path.Ext(importPath)
if fileExt == ".yaml" || fileExt == ".json" {
return true
}
return false
}
// BuildSpecURL takes a source context reference and builds an raw git URL for it
// It handles sourceContext paths which are from remote repos as well as in the same repo
func BuildSpecURL(source *sysl.SourceContext) string {
repoURL := GetRemoteFromGit()
rawRepoURL := BuildGithubRawURL(repoURL)
return rawRepoURL + source.GetFile()
}
// GetRemoteFromGit gets the URL to the git remote
// e.g github.com/myorg/somerepo/
func GetRemoteFromGit() string {
cmd := exec.Command("git", "config", "--get", "remote.origin.url")
out, err := cmd.CombinedOutput()
if err != nil {
panic(fmt.Errorf("error getting git remote: is sysl-catalog running in a git repo? %w", err))
}
return StripExtension(string(out))
}
// StripExtension removes spaces and suffixes
func StripExtension(input string) string {
noExt := strings.TrimSuffix(input, path.Ext(input))
noSpace := strings.TrimSpace(noExt)
return noSpace
}
// BuildGithubRawURL gets the base URL for raw content hosted on github.com or Github Enterprise
// For github.com it takes in https://github.com/anz-bank/sysl-catalog and returns https://raw.githubusercontent.com/anz-bank/sysl-catalog/master/
// For Github Enterprise it takes in https://github.myorg.com/anz-bank/sysl-catalog and returns https://github.myorg.com/raw/anz-bank/sysl-catalog/master/
func BuildGithubRawURL(repoURL string) (gitURL string) {
url, err := url.Parse(repoURL)
if err != nil {
panic(err)
}
switch url.Host {
case "github.com":
url.Host = "raw.githubusercontent.com"
url.Path = url.Path + "/master/"
gitURL = url.String()
default:
// Handles github enterprise which uses a different URL scheme for raw files
url.Path = "raw" + url.Path + "/master/"
gitURL = url.String()
}
return gitURL
}
// BuildGithubBlobURL creates a root URL for github blob
// it will not work for non github links.
func BuildGithubBlobURL(repoURL string) string {
url, err := url.Parse(repoURL)
if err != nil {
panic(err)
}
url.Path = path.Join(url.Path, "/blob/master/")
return url.String()
}