David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2015 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package names |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "regexp" |
| 9 | ) |
| 10 | |
| 11 | const ( |
| 12 | SpaceTagKind = "space" |
| 13 | SpaceSnippet = "(?:[a-z0-9]+(?:-[a-z0-9]+)*)" |
| 14 | ) |
| 15 | |
| 16 | var validSpace = regexp.MustCompile("^" + SpaceSnippet + "$") |
| 17 | |
| 18 | // IsValidSpace reports whether name is a valid space name. |
| 19 | func IsValidSpace(name string) bool { |
| 20 | return validSpace.MatchString(name) |
| 21 | } |
| 22 | |
| 23 | type SpaceTag struct { |
| 24 | name string |
| 25 | } |
| 26 | |
| 27 | func (t SpaceTag) String() string { return t.Kind() + "-" + t.Id() } |
| 28 | func (t SpaceTag) Kind() string { return SpaceTagKind } |
| 29 | func (t SpaceTag) Id() string { return t.name } |
| 30 | |
| 31 | // NewSpaceTag returns the tag of a space with the given name. |
| 32 | func NewSpaceTag(name string) SpaceTag { |
| 33 | if !IsValidSpace(name) { |
| 34 | panic(fmt.Sprintf("%q is not a valid space name", name)) |
| 35 | } |
| 36 | return SpaceTag{name: name} |
| 37 | } |
| 38 | |
| 39 | // ParseSpaceTag parses a space tag string. |
| 40 | func ParseSpaceTag(spaceTag string) (SpaceTag, error) { |
| 41 | tag, err := ParseTag(spaceTag) |
| 42 | if err != nil { |
| 43 | return SpaceTag{}, err |
| 44 | } |
| 45 | nt, ok := tag.(SpaceTag) |
| 46 | if !ok { |
| 47 | return SpaceTag{}, invalidTagError(spaceTag, SpaceTagKind) |
| 48 | } |
| 49 | return nt, nil |
| 50 | } |