rickub/clipublic Fork 0
main
Commits
Clone
git clone https://git.rickub.com/rickub/cli.git
git clone ssh://git@rickub.com/rickub/cli.git
repospec.go · 57 lines · 1.7 KBGo Blame HistoryRaw
Initial import of the rickub CLI as a standalone public project 1a1d430 Olivier Girardot 9h ago1package cmd
2
3import (
4 "fmt"
5 "os/exec"
6 "regexp"
7 "strings"
8)
9
10// parseOwnerRepo splits "owner/repo" into its parts.
11func parseOwnerRepo(s string) (owner, repo string, err error) {
12 s = strings.TrimSuffix(strings.TrimSpace(s), ".git")
13 parts := strings.Split(s, "/")
14 if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
15 return "", "", fmt.Errorf("expected owner/repo, got %q", s)
16 }
17 return parts[0], parts[1], nil
18}
19
20// resolveRepo determines the target repo: an explicit --repo flag ("owner/repo")
21// wins; otherwise it infers "owner/repo" from the git "origin" remote of the
22// current directory.
23func resolveRepo(flagRepo string) (owner, repo string, err error) {
24 if flagRepo != "" {
25 return parseOwnerRepo(flagRepo)
26 }
27 url, err := gitOriginURL()
28 if err != nil {
29 return "", "", fmt.Errorf("no --repo given and could not infer from git remote: %w", err)
30 }
31 o, r, err := ownerRepoFromRemote(url)
32 if err != nil {
33 return "", "", fmt.Errorf("could not parse owner/repo from remote %q: %w", url, err)
34 }
35 return o, r, nil
36}
37
38func gitOriginURL() (string, error) {
39 out, err := exec.Command("git", "remote", "get-url", "origin").Output()
40 if err != nil {
41 return "", err
42 }
43 return strings.TrimSpace(string(out)), nil
44}
45
46// remotePathRe captures the trailing owner/repo of a git remote URL, whether
47// http(s)://host/owner/repo(.git), ssh://git@host:port/owner/repo(.git), or
48// git@host:owner/repo(.git).
49var remotePathRe = regexp.MustCompile(`[:/]([^/:]+)/([^/]+?)(?:\.git)?/?$`)
50
51func ownerRepoFromRemote(url string) (owner, repo string, err error) {
52 m := remotePathRe.FindStringSubmatch(url)
53 if m == nil {
54 return "", "", fmt.Errorf("unrecognized remote URL")
55 }
56 return m[1], m[2], nil
57}