readdir.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. package fusetesting
  15. import (
  16. "fmt"
  17. "os"
  18. "path"
  19. "sort"
  20. )
  21. type sortedEntries []os.FileInfo
  22. func (f sortedEntries) Len() int { return len(f) }
  23. func (f sortedEntries) Less(i, j int) bool { return f[i].Name() < f[j].Name() }
  24. func (f sortedEntries) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
  25. // Read the directory with the given name and return a list of directory
  26. // entries, sorted by name.
  27. //
  28. // Unlike ioutil.ReadDir (cf. http://goo.gl/i0nNP4), this function does not
  29. // silently ignore "file not found" errors when stat'ing the names read from
  30. // the directory.
  31. func ReadDirPicky(dirname string) (entries []os.FileInfo, err error) {
  32. // Open the directory.
  33. f, err := os.Open(dirname)
  34. if err != nil {
  35. err = fmt.Errorf("Open: %v", err)
  36. return
  37. }
  38. // Don't forget to close it later.
  39. defer func() {
  40. closeErr := f.Close()
  41. if closeErr != nil && err == nil {
  42. err = fmt.Errorf("Close: %v", closeErr)
  43. }
  44. }()
  45. // Read all of the names from the directory.
  46. names, err := f.Readdirnames(-1)
  47. if err != nil {
  48. err = fmt.Errorf("Readdirnames: %v", err)
  49. return
  50. }
  51. // Stat each one.
  52. for _, name := range names {
  53. var fi os.FileInfo
  54. fi, err = os.Lstat(path.Join(dirname, name))
  55. if err != nil {
  56. err = fmt.Errorf("Lstat(%s): %v", name, err)
  57. return
  58. }
  59. entries = append(entries, fi)
  60. }
  61. // Sort the entries by name.
  62. sort.Sort(sortedEntries(entries))
  63. return
  64. }