-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathimage.go
98 lines (82 loc) · 2.14 KB
/
image.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package sabakan
import (
"regexp"
"time"
)
const (
// MaxImages is the maximum number of images that an index can hold.
MaxImages = 5
// ImageKernelFilename is a filename appear in TAR archive of an image.
ImageKernelFilename = "kernel"
// ImageInitrdFilename is a filename appear in TAR archive of an image.
ImageInitrdFilename = "initrd.gz"
)
var (
reValidImageID = regexp.MustCompile(`^[0-9a-zA-Z.-]+$`)
reValidImageOS = regexp.MustCompile(`^[a-z0-9.]+$`)
)
// IsValidImageID returns true if id is valid as an image ID.
func IsValidImageID(id string) bool {
return reValidImageID.MatchString(id)
}
// IsValidImageOS returns true if id is valid as OS.
func IsValidImageOS(os string) bool {
return reValidImageOS.MatchString(os)
}
// Image represents a set of image files for iPXE boot.
type Image struct {
ID string `json:"id"`
Date time.Time `json:"date"`
Size int64 `json:"size"`
URLs []string `json:"urls"`
Exists bool `json:"exists"`
}
// ImageIndex is a list of *Image.
type ImageIndex []*Image
// Append appends a new *Image to the index.
//
// If the index has MaxImages images, the oldest image will be discarded.
// ID of discarded images are returned in the second return value.
func (i ImageIndex) Append(img *Image) (ImageIndex, []string) {
for idx, entry := range i {
if entry.ID == img.ID {
ret := i[:idx]
ret = append(ret, i[idx+1:]...)
ret = append(ret, entry)
return ret, nil
}
}
if len(i) < MaxImages {
return append(i, img), nil
}
ndels := len(i) - MaxImages + 1
dels := make([]string, ndels)
for j := 0; j < ndels; j++ {
dels[j] = i[j].ID
}
copy(i, i[ndels:])
i[MaxImages-1] = img
return i[0:MaxImages], dels
}
// Remove removes an image entry from the index.
func (i ImageIndex) Remove(id string) ImageIndex {
newIndex := make(ImageIndex, 0, len(i))
for _, img := range i {
if img.ID == id {
continue
}
newIndex = append(newIndex, img)
}
return newIndex
}
// Find an image whose ID is id.
//
// If no image can be found, this returns nil.
func (i ImageIndex) Find(id string) *Image {
for _, img := range i {
if img.ID == id {
return img
}
}
return nil
}