David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame^] | 1 | // Copyright 2016 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package names |
| 5 | |
| 6 | import ( |
| 7 | "regexp" |
| 8 | ) |
| 9 | |
| 10 | const ModelTagKind = "model" |
| 11 | |
| 12 | // ModelTag represents a tag used to describe a model. |
| 13 | type ModelTag struct { |
| 14 | uuid string |
| 15 | } |
| 16 | |
| 17 | var validUUID = regexp.MustCompile(`[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}`) |
| 18 | |
| 19 | // Lowercase letters, digits and (non-leading) hyphens, as per LP:1568944 #5. |
| 20 | var validModelName = regexp.MustCompile(`^[a-z0-9]+[a-z0-9-]*$`) |
| 21 | |
| 22 | // NewModelTag returns the tag of an model with the given model UUID. |
| 23 | func NewModelTag(uuid string) ModelTag { |
| 24 | return ModelTag{uuid: uuid} |
| 25 | } |
| 26 | |
| 27 | // ParseModelTag parses an environ tag string. |
| 28 | func ParseModelTag(modelTag string) (ModelTag, error) { |
| 29 | tag, err := ParseTag(modelTag) |
| 30 | if err != nil { |
| 31 | return ModelTag{}, err |
| 32 | } |
| 33 | et, ok := tag.(ModelTag) |
| 34 | if !ok { |
| 35 | return ModelTag{}, invalidTagError(modelTag, ModelTagKind) |
| 36 | } |
| 37 | return et, nil |
| 38 | } |
| 39 | |
| 40 | func (t ModelTag) String() string { return t.Kind() + "-" + t.Id() } |
| 41 | func (t ModelTag) Kind() string { return ModelTagKind } |
| 42 | func (t ModelTag) Id() string { return t.uuid } |
| 43 | |
| 44 | // IsValidModel returns whether id is a valid model UUID. |
| 45 | func IsValidModel(id string) bool { |
| 46 | return validUUID.MatchString(id) |
| 47 | } |
| 48 | |
| 49 | // IsValidModelName returns whether name is a valid string safe for a model name. |
| 50 | func IsValidModelName(name string) bool { |
| 51 | return validModelName.MatchString(name) |
| 52 | } |