-
Notifications
You must be signed in to change notification settings - Fork 17
/
hostdevice.go
68 lines (57 loc) · 1.56 KB
/
hostdevice.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
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
type HostDevice struct {
HostPath string `json:"hostPath"`
ContainerPath string `json:"containerPath"`
Permission string `json:"permission"`
}
func (d *HostDevice) validate() error {
numGlobHostPath := strings.Count(d.HostPath, "*")
if numGlobHostPath > 1 {
return fmt.Errorf("HostPath can container only one '*' character: %s", d.HostPath)
}
if numGlobHostPath == 1 {
if !strings.HasSuffix(d.ContainerPath, "*") {
return fmt.Errorf("ContainerPath should ends with '*' character when HostPath container '*': %s", d.ContainerPath)
}
return nil
}
if strings.Contains(d.ContainerPath, "*") {
return fmt.Errorf("ContainerPath must not contain '*' when HostPath does not contain '*': %s", d.ContainerPath)
}
return nil
}
type ExpandedHostDevice struct {
HostPath string
ContainerPath string
Permission string
}
func (d HostDevice) Expand() ([]*ExpandedHostDevice, error) {
if err := d.validate(); err != nil {
return nil, err
}
matchedHostPath, err := filepath.Glob(d.HostPath)
if err != nil {
return nil, err
}
expanded := []*ExpandedHostDevice{}
baseHostPath := strings.Split(d.HostPath, "*")[0]
baseContainerPath := strings.Split(d.ContainerPath, "*")[0]
for _, hp := range matchedHostPath {
fInfo, _ := os.Stat(hp)
if fInfo.IsDir() {
continue
}
expanded = append(expanded, &ExpandedHostDevice{
HostPath: hp,
ContainerPath: strings.Replace(hp, baseHostPath, baseContainerPath, 1),
Permission: d.Permission,
})
}
return expanded, nil
}