blob: 44ecc964011e49cdc13c4a92b4076a1f7ca14a90 [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2015 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package names
5
6import (
7 "fmt"
8 "regexp"
9 "strings"
10)
11
12const 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.
16var validFilesystem = regexp.MustCompile("^(" + MachineSnippet + "/)?" + NumberSnippet + "$")
17
18type FilesystemTag struct {
19 id string
20}
21
22func (t FilesystemTag) String() string { return t.Kind() + "-" + t.id }
23func (t FilesystemTag) Kind() string { return FilesystemTagKind }
24func (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.
28func 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.
37func 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.
50func 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.
57func 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
66func 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
74func filesystemTagSuffixToId(s string) string {
75 return strings.Replace(s, "-", "/", -1)
76}