From d31612c722e061f781e08027417c3a320ecf3abf Mon Sep 17 00:00:00 2001 From: Sam Coe Date: Mon, 16 May 2022 13:59:12 +0200 Subject: [PATCH] Add repository.ParseWithHost --- pkg/repository/repository.go | 45 ++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/pkg/repository/repository.go b/pkg/repository/repository.go index 044ab94..90e6c8b 100644 --- a/pkg/repository/repository.go +++ b/pkg/repository/repository.go @@ -4,9 +4,9 @@ package repository import ( "fmt" - "os" "strings" + "github.com/cli/go-gh/internal/config" "github.com/cli/go-gh/internal/git" irepo "github.com/cli/go-gh/internal/repository" ) @@ -20,6 +20,7 @@ type Repository interface { // Parse extracts the repository information from the following // string formats: "OWNER/REPO", "HOST/OWNER/REPO", and a full URL. +// If the format does not specify a host, use the config to determine a host. func Parse(s string) (Repository, error) { if git.IsURL(s) { u, err := git.ParseURL(s) @@ -46,10 +47,46 @@ func Parse(s string) (Repository, error) { case 3: return irepo.New(parts[0], parts[1], parts[2]), nil case 2: - host := os.Getenv("GH_HOST") - if host == "" { - host = "github.com" + host := "github.com" + cfg, err := config.Load() + if err != nil { + host = cfg.Host() + } + return irepo.New(host, parts[0], parts[1]), nil + default: + return nil, fmt.Errorf(`expected the "[HOST/]OWNER/REPO" format, got %q`, s) + } +} + +// Parse extracts the repository information from the following +// string formats: "OWNER/REPO", "HOST/OWNER/REPO", and a full URL. +// If the format does not specify a host, use the host provided. +func ParseWithHost(s, host string) (Repository, error) { + if git.IsURL(s) { + u, err := git.ParseURL(s) + if err != nil { + return nil, err + } + + host, owner, name, err := git.RepoInfoFromURL(u) + if err != nil { + return nil, err } + + return irepo.New(host, owner, name), nil + } + + parts := strings.SplitN(s, "/", 4) + for _, p := range parts { + if len(p) == 0 { + return nil, fmt.Errorf(`expected the "[HOST/]OWNER/REPO" format, got %q`, s) + } + } + + switch len(parts) { + case 3: + return irepo.New(parts[0], parts[1], parts[2]), nil + case 2: return irepo.New(host, parts[0], parts[1]), nil default: return nil, fmt.Errorf(`expected the "[HOST/]OWNER/REPO" format, got %q`, s)