package app import ( "errors" "fmt" "os" "regexp" "strings" "cnb.cool/cnb/go-cnb/cnb" "cnb.cool/looc/git-cnb/git" "cnb.cool/looc/git-cnb/ui" ) var Client *cnb.Client var Repo string func init() { gitRemoteURL, err := git.Remote() if err != nil { ui.ErrorWithExit(err.Error()) } scheme, domain, repo, err := parseGitRemoteUrl(gitRemoteURL) if err != nil { ui.ErrorWithExit(err.Error()) } baseURL := fmt.Sprintf("%s://api.%s/", scheme, domain) Repo = repo Client, err = cnb.NewClient(nil).WithAuthToken(getToken(domain)).WithURLs(baseURL) if err != nil { ui.ErrorWithExit(err.Error()) } } func parseGitRemoteUrl(gitRemoteURL string) (string, string, string, error) { re := regexp.MustCompile(`^(https?)://([^/]+)/(.+?)(?:\.git)?$`) matches := re.FindStringSubmatch(gitRemoteURL) var scheme, domain, repo string if len(matches) == 4 { scheme = matches[1] d := strings.Split(matches[2], "@") if len(d) == 2 { domain = d[1] } else { domain = d[0] } repo = matches[3] return scheme, domain, repo, nil } return "", "", "", errors.New("git remote url is not a valid cnb url") } func getToken(domain string) string { tokenWithDomainKey := fmt.Sprintf( "CNB_TOKEN_%s", strings.ReplaceAll(domain, ".", "")) token := os.Getenv(tokenWithDomainKey) if token == "" { return os.Getenv("CNB_TOKEN") } return token }