-
Notifications
You must be signed in to change notification settings - Fork 46
/
repository.go
94 lines (81 loc) · 2.26 KB
/
repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Package repository is a set of types and functions for modeling and
// interacting with GitHub repositories.
package repository
import (
"fmt"
"strings"
"github.com/cli/go-gh/internal/config"
"github.com/cli/go-gh/internal/git"
irepo "github.com/cli/go-gh/internal/repository"
)
// Repository is the interface that wraps repository information methods.
type Repository interface {
Host() string
Name() string
Owner() string
}
// 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)
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:
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)
}
}