utils.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. "io/ioutil"
  17. "os"
  18. "sort"
  19. )
  20. // ReadFile works the same as ioutil.ReadFile with the Driver abstraction
  21. func ReadFile(r Driver, filename string) ([]byte, error) {
  22. f, err := r.Open(filename)
  23. if err != nil {
  24. return nil, err
  25. }
  26. defer f.Close()
  27. data, err := ioutil.ReadAll(f)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return data, nil
  32. }
  33. // WriteFile works the same as ioutil.WriteFile with the Driver abstraction
  34. func WriteFile(r Driver, filename string, data []byte, perm os.FileMode) error {
  35. f, err := r.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
  36. if err != nil {
  37. return err
  38. }
  39. defer f.Close()
  40. n, err := f.Write(data)
  41. if err != nil {
  42. return err
  43. } else if n != len(data) {
  44. return io.ErrShortWrite
  45. }
  46. return nil
  47. }
  48. // ReadDir works the same as ioutil.ReadDir with the Driver abstraction
  49. func ReadDir(r Driver, dirname string) ([]os.FileInfo, error) {
  50. f, err := r.Open(dirname)
  51. if err != nil {
  52. return nil, err
  53. }
  54. defer f.Close()
  55. dirs, err := f.Readdir(-1)
  56. if err != nil {
  57. return nil, err
  58. }
  59. sort.Sort(fileInfos(dirs))
  60. return dirs, nil
  61. }
  62. // Simple implementation of the sort.Interface for os.FileInfo
  63. type fileInfos []os.FileInfo
  64. func (fis fileInfos) Len() int {
  65. return len(fis)
  66. }
  67. func (fis fileInfos) Less(i, j int) bool {
  68. return fis[i].Name() < fis[j].Name()
  69. }
  70. func (fis fileInfos) Swap(i, j int) {
  71. fis[i], fis[j] = fis[j], fis[i]
  72. }