fileutil.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2015 CoreOS, Inc.
  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 fileutil
  15. import (
  16. "io/ioutil"
  17. "os"
  18. "path"
  19. "sort"
  20. )
  21. const (
  22. privateFileMode = 0600
  23. )
  24. // IsDirWriteable checks if dir is writable by writing and removing a file
  25. // to dir. It returns nil if dir is writable.
  26. func IsDirWriteable(dir string) error {
  27. f := path.Join(dir, ".touch")
  28. if err := ioutil.WriteFile(f, []byte(""), privateFileMode); err != nil {
  29. return err
  30. }
  31. return os.Remove(f)
  32. }
  33. // ReadDir returns the filenames in the given directory in sorted order.
  34. func ReadDir(dirpath string) ([]string, error) {
  35. dir, err := os.Open(dirpath)
  36. if err != nil {
  37. return nil, err
  38. }
  39. defer dir.Close()
  40. names, err := dir.Readdirnames(-1)
  41. if err != nil {
  42. return nil, err
  43. }
  44. sort.Strings(names)
  45. return names, nil
  46. }