tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/engine/fs/memfs/dir.go (about) 1 // Copyright © 2014 Steve Francia <spf@spf13.com>. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package memfs 15 16 import ( 17 "io/fs" 18 "sort" 19 ) 20 21 type Dir interface { 22 Len() int 23 Names() []string 24 Files() []*FileData 25 Add(*FileData) 26 Remove(*FileData) 27 } 28 29 type dirEntry struct { 30 name string 31 isDir bool 32 typ fs.FileMode 33 info fs.FileInfo 34 } 35 36 func (e dirEntry) Name() string { 37 return e.name 38 } 39 40 func (e dirEntry) IsDir() bool { 41 return e.isDir 42 } 43 44 func (e dirEntry) Type() fs.FileMode { 45 return e.typ 46 } 47 48 func (e dirEntry) Info() (fs.FileInfo, error) { 49 return e.info, nil 50 } 51 52 func RemoveFromMemDir(dir *FileData, f *FileData) { 53 dir.memDir.Remove(f) 54 } 55 56 func AddToMemDir(dir *FileData, f *FileData) { 57 dir.memDir.Add(f) 58 } 59 60 func InitializeDir(d *FileData) { 61 if d.memDir == nil { 62 d.dir = true 63 d.memDir = &DirMap{} 64 } 65 } 66 67 type DirMap map[string]*FileData 68 69 func (m DirMap) Len() int { return len(m) } 70 func (m DirMap) Add(f *FileData) { m[f.name] = f } 71 func (m DirMap) Remove(f *FileData) { delete(m, f.name) } 72 func (m DirMap) Files() (files []*FileData) { 73 for _, f := range m { 74 files = append(files, f) 75 } 76 sort.Sort(filesSorter(files)) 77 return files 78 } 79 80 // implement sort.Interface for []*FileData 81 type filesSorter []*FileData 82 83 func (s filesSorter) Len() int { return len(s) } 84 func (s filesSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 85 func (s filesSorter) Less(i, j int) bool { return s[i].name < s[j].name } 86 87 func (m DirMap) Names() (names []string) { 88 for x := range m { 89 names = append(names, x) 90 } 91 return names 92 }