1package mk2rbc 2 3import ( 4 "io/fs" 5 "os" 6 "path/filepath" 7 "time" 8) 9 10// Mock FS. Maps a directory name to an array of entries. 11// An entry implements fs.DirEntry, fs.FIleInfo and fs.File interface 12type FindMockFS struct { 13 dirs map[string][]myFileInfo 14} 15 16func (m FindMockFS) locate(name string) (myFileInfo, bool) { 17 if name == "." { 18 return myFileInfo{".", true}, true 19 } 20 dir := filepath.Dir(name) 21 base := filepath.Base(name) 22 if entries, ok := m.dirs[dir]; ok { 23 for _, e := range entries { 24 if e.name == base { 25 return e, true 26 } 27 } 28 } 29 return myFileInfo{}, false 30} 31 32func (m FindMockFS) create(name string, isDir bool) { 33 dir := filepath.Dir(name) 34 m.dirs[dir] = append(m.dirs[dir], myFileInfo{filepath.Base(name), isDir}) 35} 36 37func (m FindMockFS) Stat(name string) (fs.FileInfo, error) { 38 if fi, ok := m.locate(name); ok { 39 return fi, nil 40 } 41 return nil, os.ErrNotExist 42} 43 44type myFileInfo struct { 45 name string 46 isDir bool 47} 48 49func (m myFileInfo) Info() (fs.FileInfo, error) { 50 panic("implement me") 51} 52 53func (m myFileInfo) Size() int64 { 54 panic("implement me") 55} 56 57func (m myFileInfo) Mode() fs.FileMode { 58 panic("implement me") 59} 60 61func (m myFileInfo) ModTime() time.Time { 62 panic("implement me") 63} 64 65func (m myFileInfo) Sys() interface{} { 66 return nil 67} 68 69func (m myFileInfo) Stat() (fs.FileInfo, error) { 70 return m, nil 71} 72 73func (m myFileInfo) Read(bytes []byte) (int, error) { 74 panic("implement me") 75} 76 77func (m myFileInfo) Close() error { 78 panic("implement me") 79} 80 81func (m myFileInfo) Name() string { 82 return m.name 83} 84 85func (m myFileInfo) IsDir() bool { 86 return m.isDir 87} 88 89func (m myFileInfo) Type() fs.FileMode { 90 return m.Mode() 91} 92 93func (m FindMockFS) Open(name string) (fs.File, error) { 94 panic("implement me") 95} 96 97func (m FindMockFS) ReadDir(name string) ([]fs.DirEntry, error) { 98 if d, ok := m.dirs[name]; ok { 99 var res []fs.DirEntry 100 for _, e := range d { 101 res = append(res, e) 102 } 103 return res, nil 104 } 105 return nil, os.ErrNotExist 106} 107 108func NewFindMockFS(files []string) FindMockFS { 109 myfs := FindMockFS{make(map[string][]myFileInfo)} 110 for _, f := range files { 111 isDir := false 112 for f != "." { 113 if _, ok := myfs.locate(f); !ok { 114 myfs.create(f, isDir) 115 } 116 isDir = true 117 f = filepath.Dir(f) 118 } 119 } 120 return myfs 121} 122