David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2013 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package names |
| 5 | |
| 6 | import ( |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | const MachineTagKind = "machine" |
| 12 | |
| 13 | const ( |
| 14 | ContainerTypeSnippet = "[a-z]+" |
| 15 | ContainerSnippet = "/" + ContainerTypeSnippet + "/" + NumberSnippet + "" |
| 16 | MachineSnippet = NumberSnippet + "(?:" + ContainerSnippet + ")*" |
| 17 | ) |
| 18 | |
| 19 | var validMachine = regexp.MustCompile("^" + MachineSnippet + "$") |
| 20 | |
| 21 | // IsValidMachine returns whether id is a valid machine id. |
| 22 | func IsValidMachine(id string) bool { |
| 23 | return validMachine.MatchString(id) |
| 24 | } |
| 25 | |
| 26 | // IsContainerMachine returns whether id is a valid container machine id. |
| 27 | func IsContainerMachine(id string) bool { |
| 28 | return validMachine.MatchString(id) && strings.Contains(id, "/") |
| 29 | } |
| 30 | |
| 31 | type MachineTag struct { |
| 32 | id string |
| 33 | } |
| 34 | |
| 35 | func (t MachineTag) String() string { return t.Kind() + "-" + t.id } |
| 36 | func (t MachineTag) Kind() string { return MachineTagKind } |
| 37 | func (t MachineTag) Id() string { return machineTagSuffixToId(t.id) } |
| 38 | |
| 39 | // NewMachineTag returns the tag for the machine with the given id. |
| 40 | func NewMachineTag(id string) MachineTag { |
| 41 | id = strings.Replace(id, "/", "-", -1) |
| 42 | return MachineTag{id: id} |
| 43 | } |
| 44 | |
| 45 | // ParseMachineTag parses a machine tag string. |
| 46 | func ParseMachineTag(machineTag string) (MachineTag, error) { |
| 47 | tag, err := ParseTag(machineTag) |
| 48 | if err != nil { |
| 49 | return MachineTag{}, err |
| 50 | } |
| 51 | mt, ok := tag.(MachineTag) |
| 52 | if !ok { |
| 53 | return MachineTag{}, invalidTagError(machineTag, MachineTagKind) |
| 54 | } |
| 55 | return mt, nil |
| 56 | } |
| 57 | |
| 58 | func machineTagSuffixToId(s string) string { |
| 59 | return strings.Replace(s, "-", "/", -1) |
| 60 | } |