fileutil.go 2.0 KB

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