forked from juju/names
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine.go
60 lines (48 loc) · 1.55 KB
/
machine.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
// Copyright 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package names
import (
"regexp"
"strings"
)
const MachineTagKind = "machine"
const (
ContainerTypeSnippet = "[a-z]+"
ContainerSnippet = "/" + ContainerTypeSnippet + "/" + NumberSnippet + ""
MachineSnippet = NumberSnippet + "(?:" + ContainerSnippet + ")*"
)
var validMachine = regexp.MustCompile("^" + MachineSnippet + "$")
// IsValidMachine returns whether id is a valid machine id.
func IsValidMachine(id string) bool {
return validMachine.MatchString(id)
}
// IsContainerMachine returns whether id is a valid container machine id.
func IsContainerMachine(id string) bool {
return validMachine.MatchString(id) && strings.Contains(id, "/")
}
type MachineTag struct {
id string
}
func (t MachineTag) String() string { return t.Kind() + "-" + t.id }
func (t MachineTag) Kind() string { return MachineTagKind }
func (t MachineTag) Id() string { return machineTagSuffixToId(t.id) }
// NewMachineTag returns the tag for the machine with the given id.
func NewMachineTag(id string) MachineTag {
id = strings.Replace(id, "/", "-", -1)
return MachineTag{id: id}
}
// ParseMachineTag parses a machine tag string.
func ParseMachineTag(machineTag string) (MachineTag, error) {
tag, err := ParseTag(machineTag)
if err != nil {
return MachineTag{}, err
}
mt, ok := tag.(MachineTag)
if !ok {
return MachineTag{}, invalidTagError(machineTag, MachineTagKind)
}
return mt, nil
}
func machineTagSuffixToId(s string) string {
return strings.Replace(s, "-", "/", -1)
}