forked from juju/names
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unit.go
79 lines (67 loc) · 1.99 KB
/
unit.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright 2013 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package names
import (
"fmt"
"regexp"
"strings"
)
const UnitTagKind = "unit"
var validUnit = regexp.MustCompile("^(" + ServiceSnippet + ")/" + NumberSnippet + "$")
type UnitTag struct {
name string
}
func (t UnitTag) String() string { return t.Kind() + "-" + t.name }
func (t UnitTag) Kind() string { return UnitTagKind }
func (t UnitTag) Id() string { return unitTagSuffixToId(t.name) }
// NewUnitTag returns the tag for the unit with the given name.
// It will panic if the given unit name is not valid.
func NewUnitTag(unitName string) UnitTag {
tag, ok := tagFromUnitName(unitName)
if !ok {
panic(fmt.Sprintf("%q is not a valid unit name", unitName))
}
return tag
}
// ParseUnitTag parses a unit tag string.
func ParseUnitTag(unitTag string) (UnitTag, error) {
tag, err := ParseTag(unitTag)
if err != nil {
return UnitTag{}, err
}
ut, ok := tag.(UnitTag)
if !ok {
return UnitTag{}, invalidTagError(unitTag, UnitTagKind)
}
return ut, nil
}
// IsValidUnit returns whether name is a valid unit name.
func IsValidUnit(name string) bool {
return validUnit.MatchString(name)
}
// UnitService returns the name of the service that the unit is
// associated with. It panics if unitName is not a valid unit name.
func UnitService(unitName string) string {
s := validUnit.FindStringSubmatch(unitName)
if s == nil {
panic(fmt.Sprintf("%q is not a valid unit name", unitName))
}
return s[1]
}
func tagFromUnitName(unitName string) (UnitTag, bool) {
// Replace only the last "/" with "-".
i := strings.LastIndex(unitName, "/")
if i <= 0 || !IsValidUnit(unitName) {
return UnitTag{}, false
}
unitName = unitName[:i] + "-" + unitName[i+1:]
return UnitTag{name: unitName}, true
}
func unitTagSuffixToId(s string) string {
// Replace only the last "-" with "/", as it is valid for service
// names to contain hyphens.
if i := strings.LastIndex(s, "-"); i > 0 {
s = s[:i] + "/" + s[i+1:]
}
return s
}