github.com/creativeprojects/go-selfupdate@v1.2.0/cmd/source.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "net/url" 6 "strings" 7 8 "github.com/creativeprojects/go-selfupdate" 9 ) 10 11 // SplitDomainSlug tries to make sense of the repository string 12 // and returns a domain name (if present) and a slug. 13 // 14 // Example of valid entries: 15 // 16 // - "owner/name" 17 // - "github.com/owner/name" 18 // - "http://github.com/owner/name" 19 func SplitDomainSlug(repo string) (domain, slug string, err error) { 20 // simple case first => only a slug 21 parts := strings.Split(repo, "/") 22 if len(parts) == 2 { 23 if parts[0] == "" || parts[1] == "" { 24 return "", "", fmt.Errorf("invalid slug or URL %q", repo) 25 } 26 return "", repo, nil 27 } 28 // trim trailing / 29 repo = strings.TrimSuffix(repo, "/") 30 31 if !strings.HasPrefix(repo, "http") && !strings.Contains(repo, "://") && !strings.HasPrefix(repo, "/") { 32 // add missing scheme 33 repo = "https://" + repo 34 } 35 36 repoURL, err := url.Parse(repo) 37 if err != nil { 38 return "", "", err 39 } 40 41 // make sure hostname looks like a real domain name 42 if !strings.Contains(repoURL.Hostname(), ".") { 43 return "", "", fmt.Errorf("invalid domain name %q", repoURL.Hostname()) 44 } 45 domain = repoURL.Scheme + "://" + repoURL.Host 46 slug = strings.TrimPrefix(repoURL.Path, "/") 47 48 if slug == "" { 49 return "", "", fmt.Errorf("invalid URL %q", repo) 50 } 51 return domain, slug, nil 52 } 53 54 func GetSource(cvsType, domain string) (selfupdate.Source, error) { 55 if cvsType != "auto" && cvsType != "" { 56 source, err := getSourceFromName(cvsType, domain) 57 if err != nil { 58 return nil, err 59 } 60 return source, nil 61 } 62 63 source, err := getSourceFromURL(domain) 64 if err != nil { 65 return nil, err 66 } 67 return source, nil 68 } 69 70 func getSourceFromName(name, domain string) (selfupdate.Source, error) { 71 switch name { 72 case "gitea": 73 return selfupdate.NewGiteaSource(selfupdate.GiteaConfig{BaseURL: domain}) 74 75 case "gitlab": 76 return selfupdate.NewGitLabSource(selfupdate.GitLabConfig{BaseURL: domain}) 77 78 default: 79 return newGitHubSource(domain) 80 } 81 } 82 83 func getSourceFromURL(domain string) (selfupdate.Source, error) { 84 if strings.Contains(domain, "gitea") { 85 return selfupdate.NewGiteaSource(selfupdate.GiteaConfig{BaseURL: domain}) 86 } 87 if strings.Contains(domain, "gitlab") { 88 return selfupdate.NewGitLabSource(selfupdate.GitLabConfig{BaseURL: domain}) 89 } 90 return newGitHubSource(domain) 91 } 92 93 func newGitHubSource(domain string) (*selfupdate.GitHubSource, error) { 94 config := selfupdate.GitHubConfig{} 95 if domain != "" && !strings.HasSuffix(domain, "://github.com") { 96 config.EnterpriseBaseURL = domain 97 } 98 return selfupdate.NewGitHubSource(config) 99 }