-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
static.go
74 lines (63 loc) · 1.26 KB
/
static.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
package staticfs
import (
"bytes"
"context"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/tonistiigi/fsutil"
"github.com/tonistiigi/fsutil/types"
)
type File struct {
Stat types.Stat
Data []byte
}
type FS struct {
files map[string]File
}
var _ fsutil.FS = &FS{}
func NewFS() *FS {
return &FS{
files: map[string]File{},
}
}
func (fs *FS) Add(p string, stat types.Stat, data []byte) {
stat.Size_ = int64(len(data))
if stat.Mode == 0 {
stat.Mode = 0644
}
stat.Path = p
fs.files[p] = File{
Stat: stat,
Data: data,
}
}
func (fs *FS) Walk(ctx context.Context, fn filepath.WalkFunc) error {
keys := make([]string, 0, len(fs.files))
for k := range fs.files {
keys = append(keys, convertPathToKey(k))
}
sort.Strings(keys)
for _, k := range keys {
p := convertKeyToPath(k)
st := fs.files[p].Stat
if err := fn(p, &fsutil.StatInfo{Stat: &st}, nil); err != nil {
return err
}
}
return nil
}
func (fs *FS) Open(p string) (io.ReadCloser, error) {
if f, ok := fs.files[p]; ok {
return io.NopCloser(bytes.NewReader(f.Data)), nil
}
return nil, os.ErrNotExist
}
func convertPathToKey(p string) string {
return strings.Replace(p, "/", "\x00", -1)
}
func convertKeyToPath(p string) string {
return strings.Replace(p, "\x00", "/", -1)
}