github.com/scaleoutsean/fusego@v0.0.0-20220224074057-4a6429e46bb8/fusetesting/readdir.go (about) 1 // Copyright 2015 Google Inc. All Rights Reserved. 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package fusetesting 16 17 import ( 18 "fmt" 19 "os" 20 "path" 21 "sort" 22 ) 23 24 type sortedEntries []os.FileInfo 25 26 func (f sortedEntries) Len() int { return len(f) } 27 func (f sortedEntries) Less(i, j int) bool { return f[i].Name() < f[j].Name() } 28 func (f sortedEntries) Swap(i, j int) { f[i], f[j] = f[j], f[i] } 29 30 // Read the directory with the given name and return a list of directory 31 // entries, sorted by name. 32 // 33 // Unlike ioutil.ReadDir (cf. http://goo.gl/i0nNP4), this function does not 34 // silently ignore "file not found" errors when stat'ing the names read from 35 // the directory. 36 func ReadDirPicky(dirname string) (entries []os.FileInfo, err error) { 37 // Open the directory. 38 f, err := os.Open(dirname) 39 if err != nil { 40 return nil, fmt.Errorf("Open: %v", err) 41 } 42 43 // Don't forget to close it later. 44 defer func() { 45 closeErr := f.Close() 46 if closeErr != nil && err == nil { 47 err = fmt.Errorf("Close: %v", closeErr) 48 } 49 }() 50 51 // Read all of the names from the directory. 52 names, err := f.Readdirnames(-1) 53 if err != nil { 54 return nil, fmt.Errorf("Readdirnames: %v", err) 55 } 56 57 // Stat each one. 58 for _, name := range names { 59 var fi os.FileInfo 60 61 fi, err = os.Lstat(path.Join(dirname, name)) 62 if err != nil { 63 return nil, fmt.Errorf("Lstat(%s): %v", name, err) 64 } 65 66 entries = append(entries, fi) 67 } 68 69 // Sort the entries by name. 70 sort.Sort(sortedEntries(entries)) 71 72 return entries, nil 73 }