fileutil.go 1.3 KB

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