-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_spec.go
116 lines (96 loc) · 2.18 KB
/
model_spec.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package gogh
import (
"net/url"
"path"
"regexp"
)
// Spec describes which project is in a root.
type Spec struct {
host string
owner string
name string
}
func (s Spec) Host() string { return s.host }
func (s Spec) Owner() string { return s.owner }
func (s Spec) Name() string { return s.name }
func (s Spec) RelLevels() []string {
return []string{s.host, s.owner, s.name}
}
func (s Spec) URL() string {
return "https://" + path.Join(s.RelLevels()...)
}
func (s Spec) String() string {
return path.Join(s.RelLevels()...)
}
var (
ErrEmptyHost = ErrInvalidHost("empty host")
ErrEmptyOwner = ErrInvalidOwner("empty owner")
ErrEmptyName = ErrInvalidName("empty name")
)
type ErrInvalidHost string
func (e ErrInvalidHost) Error() string {
return string(e)
}
func ValidateHost(h string) error {
if h == "" {
return ErrEmptyHost
}
u, err := url.ParseRequestURI("https://" + h)
if err != nil {
return ErrInvalidHost("invalid host: " + h)
}
if u.Host != h {
return ErrInvalidHost("invalid host: " + h)
}
return nil
}
type ErrInvalidName string
func (e ErrInvalidName) Error() string {
return string(e)
}
var invalidNameRegexp = regexp.MustCompile(`[^\w\-\.]`)
func ValidateName(name string) error {
if name == "" {
return ErrEmptyName
}
if name == "." {
return ErrInvalidName("'.' is reserved name")
}
if name == ".." {
return ErrInvalidName("'..' is reserved name")
}
if invalidNameRegexp.MatchString(name) {
return ErrInvalidName("invalid name: " + name)
}
return nil
}
type ErrInvalidOwner string
func (e ErrInvalidOwner) Error() string {
return string(e)
}
var validOwnerRegexp = regexp.MustCompile(`^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$`)
func ValidateOwner(owner string) error {
if owner == "" {
return ErrEmptyOwner
}
if !validOwnerRegexp.MatchString(owner) {
return ErrInvalidOwner("invalid owner: " + owner)
}
return nil
}
func NewSpec(host, owner, name string) (Spec, error) {
if err := ValidateName(name); err != nil {
return Spec{}, err
}
if err := ValidateOwner(owner); err != nil {
return Spec{}, err
}
if err := ValidateHost(host); err != nil {
return Spec{}, err
}
return Spec{
host: host,
owner: owner,
name: name,
}, nil
}