fileutil.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 implements utility functions related to files and paths.
  15. package fileutil
  16. import (
  17. "io/ioutil"
  18. "os"
  19. "path"
  20. "sort"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  22. )
  23. const (
  24. privateFileMode = 0600
  25. // owner can make/remove files inside the directory
  26. privateDirMode = 0700
  27. )
  28. var (
  29. plog = capnslog.NewPackageLogger("github.com/coreos/etcd/pkg", "fileutil")
  30. )
  31. // IsDirWriteable checks if dir is writable by writing and removing a file
  32. // to dir. It returns nil if dir is writable.
  33. func IsDirWriteable(dir string) error {
  34. f := path.Join(dir, ".touch")
  35. if err := ioutil.WriteFile(f, []byte(""), privateFileMode); err != nil {
  36. return err
  37. }
  38. return os.Remove(f)
  39. }
  40. // ReadDir returns the filenames in the given directory in sorted order.
  41. func ReadDir(dirpath string) ([]string, error) {
  42. dir, err := os.Open(dirpath)
  43. if err != nil {
  44. return nil, err
  45. }
  46. defer dir.Close()
  47. names, err := dir.Readdirnames(-1)
  48. if err != nil {
  49. return nil, err
  50. }
  51. sort.Strings(names)
  52. return names, nil
  53. }
  54. // TouchDirAll is similar to os.MkdirAll. It creates directories with 0700 permission if any directory
  55. // does not exists. TouchDirAll also ensures the given directory is writable.
  56. func TouchDirAll(dir string) error {
  57. err := os.MkdirAll(dir, privateDirMode)
  58. if err != nil && err != os.ErrExist {
  59. return err
  60. }
  61. return IsDirWriteable(dir)
  62. }
  63. func Exist(name string) bool {
  64. _, err := os.Stat(name)
  65. return err == nil
  66. }