blob: 867aa721da5fb05bf4ecc1f2750e008a3c085b77 [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2013 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package names
5
6import (
7 "regexp"
8 "strings"
9)
10
11const MachineTagKind = "machine"
12
13const (
14 ContainerTypeSnippet = "[a-z]+"
15 ContainerSnippet = "/" + ContainerTypeSnippet + "/" + NumberSnippet + ""
16 MachineSnippet = NumberSnippet + "(?:" + ContainerSnippet + ")*"
17)
18
19var validMachine = regexp.MustCompile("^" + MachineSnippet + "$")
20
21// IsValidMachine returns whether id is a valid machine id.
22func IsValidMachine(id string) bool {
23 return validMachine.MatchString(id)
24}
25
26// IsContainerMachine returns whether id is a valid container machine id.
27func IsContainerMachine(id string) bool {
28 return validMachine.MatchString(id) && strings.Contains(id, "/")
29}
30
31type MachineTag struct {
32 id string
33}
34
35func (t MachineTag) String() string { return t.Kind() + "-" + t.id }
36func (t MachineTag) Kind() string { return MachineTagKind }
37func (t MachineTag) Id() string { return machineTagSuffixToId(t.id) }
38
39// NewMachineTag returns the tag for the machine with the given id.
40func NewMachineTag(id string) MachineTag {
41 id = strings.Replace(id, "/", "-", -1)
42 return MachineTag{id: id}
43}
44
45// ParseMachineTag parses a machine tag string.
46func 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
58func machineTagSuffixToId(s string) string {
59 return strings.Replace(s, "-", "/", -1)
60}