David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame^] | 1 | // Copyright 2015 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package names |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "regexp" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | const FilesystemTagKind = "filesystem" |
| 13 | |
| 14 | // Filesystems may be bound to a machine, meaning that the filesystem cannot |
| 15 | // exist without that machine. We encode this in the tag. |
| 16 | var validFilesystem = regexp.MustCompile("^(" + MachineSnippet + "/)?" + NumberSnippet + "$") |
| 17 | |
| 18 | type FilesystemTag struct { |
| 19 | id string |
| 20 | } |
| 21 | |
| 22 | func (t FilesystemTag) String() string { return t.Kind() + "-" + t.id } |
| 23 | func (t FilesystemTag) Kind() string { return FilesystemTagKind } |
| 24 | func (t FilesystemTag) Id() string { return filesystemTagSuffixToId(t.id) } |
| 25 | |
| 26 | // NewFilesystemTag returns the tag for the filesystem with the given name. |
| 27 | // It will panic if the given filesystem name is not valid. |
| 28 | func NewFilesystemTag(id string) FilesystemTag { |
| 29 | tag, ok := tagFromFilesystemId(id) |
| 30 | if !ok { |
| 31 | panic(fmt.Sprintf("%q is not a valid filesystem id", id)) |
| 32 | } |
| 33 | return tag |
| 34 | } |
| 35 | |
| 36 | // ParseFilesystemTag parses a filesystem tag string. |
| 37 | func ParseFilesystemTag(filesystemTag string) (FilesystemTag, error) { |
| 38 | tag, err := ParseTag(filesystemTag) |
| 39 | if err != nil { |
| 40 | return FilesystemTag{}, err |
| 41 | } |
| 42 | fstag, ok := tag.(FilesystemTag) |
| 43 | if !ok { |
| 44 | return FilesystemTag{}, invalidTagError(filesystemTag, FilesystemTagKind) |
| 45 | } |
| 46 | return fstag, nil |
| 47 | } |
| 48 | |
| 49 | // IsValidFilesystem returns whether id is a valid filesystem id. |
| 50 | func IsValidFilesystem(id string) bool { |
| 51 | return validFilesystem.MatchString(id) |
| 52 | } |
| 53 | |
| 54 | // FilesystemMachine returns the machine component of the filesystem |
| 55 | // tag, and a boolean indicating whether or not there is a |
| 56 | // machine component. |
| 57 | func FilesystemMachine(tag FilesystemTag) (MachineTag, bool) { |
| 58 | id := tag.Id() |
| 59 | pos := strings.LastIndex(id, "/") |
| 60 | if pos == -1 { |
| 61 | return MachineTag{}, false |
| 62 | } |
| 63 | return NewMachineTag(id[:pos]), true |
| 64 | } |
| 65 | |
| 66 | func tagFromFilesystemId(id string) (FilesystemTag, bool) { |
| 67 | if !IsValidFilesystem(id) { |
| 68 | return FilesystemTag{}, false |
| 69 | } |
| 70 | id = strings.Replace(id, "/", "-", -1) |
| 71 | return FilesystemTag{id}, true |
| 72 | } |
| 73 | |
| 74 | func filesystemTagSuffixToId(s string) string { |
| 75 | return strings.Replace(s, "-", "/", -1) |
| 76 | } |