Skip to content

Commit

Permalink
Add repository.ParseWithHost
Browse files Browse the repository at this point in the history
  • Loading branch information
samcoe committed May 16, 2022
1 parent 8d34617 commit d31612c
Showing 1 changed file with 41 additions and 4 deletions.
45 changes: 41 additions & 4 deletions pkg/repository/repository.go
Expand Up @@ -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"
)
Expand All @@ -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)
Expand All @@ -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)
Expand Down

0 comments on commit d31612c

Please sign in to comment.