fileutil.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  21. )
  22. const (
  23. privateFileMode = 0600
  24. )
  25. var (
  26. plog = capnslog.NewPackageLogger("github.com/coreos/etcd/pkg", "fileutil")
  27. )
  28. // IsDirWriteable checks if dir is writable by writing and removing a file
  29. // to dir. It returns nil if dir is writable.
  30. func IsDirWriteable(dir string) error {
  31. f := path.Join(dir, ".touch")
  32. if err := ioutil.WriteFile(f, []byte(""), privateFileMode); err != nil {
  33. return err
  34. }
  35. return os.Remove(f)
  36. }
  37. // ReadDir returns the filenames in the given directory in sorted order.
  38. func ReadDir(dirpath string) ([]string, error) {
  39. dir, err := os.Open(dirpath)
  40. if err != nil {
  41. return nil, err
  42. }
  43. defer dir.Close()
  44. names, err := dir.Readdirnames(-1)
  45. if err != nil {
  46. return nil, err
  47. }
  48. sort.Strings(names)
  49. return names, nil
  50. }