utils.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. Copyright The containerd Authors.
  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. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package driver
  14. import (
  15. "io"
  16. "os"
  17. "sort"
  18. )
  19. // ReadFile works the same as os.ReadFile with the Driver abstraction
  20. func ReadFile(r Driver, filename string) ([]byte, error) {
  21. f, err := r.Open(filename)
  22. if err != nil {
  23. return nil, err
  24. }
  25. defer f.Close()
  26. data, err := io.ReadAll(f)
  27. if err != nil {
  28. return nil, err
  29. }
  30. return data, nil
  31. }
  32. // WriteFile works the same as os.WriteFile with the Driver abstraction
  33. func WriteFile(r Driver, filename string, data []byte, perm os.FileMode) error {
  34. f, err := r.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
  35. if err != nil {
  36. return err
  37. }
  38. defer f.Close()
  39. n, err := f.Write(data)
  40. if err != nil {
  41. return err
  42. } else if n != len(data) {
  43. return io.ErrShortWrite
  44. }
  45. return nil
  46. }
  47. // ReadDir works the same as os.ReadDir with the Driver abstraction
  48. func ReadDir(r Driver, dirname string) ([]os.FileInfo, error) {
  49. f, err := r.Open(dirname)
  50. if err != nil {
  51. return nil, err
  52. }
  53. defer f.Close()
  54. dirs, err := f.Readdir(-1)
  55. if err != nil {
  56. return nil, err
  57. }
  58. sort.Sort(fileInfos(dirs))
  59. return dirs, nil
  60. }
  61. // Simple implementation of the sort.Interface for os.FileInfo
  62. type fileInfos []os.FileInfo
  63. func (fis fileInfos) Len() int {
  64. return len(fis)
  65. }
  66. func (fis fileInfos) Less(i, j int) bool {
  67. return fis[i].Name() < fis[j].Name()
  68. }
  69. func (fis fileInfos) Swap(i, j int) {
  70. fis[i], fis[j] = fis[j], fis[i]
  71. }