file.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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 path
  14. import (
  15. "errors"
  16. "os"
  17. )
  18. // LinkTreatment is the base type for constants used by Exists that indicate
  19. // how symlinks are treated for existence checks.
  20. type LinkTreatment int
  21. const (
  22. // CheckFollowSymlink follows the symlink and verifies that the target of
  23. // the symlink exists.
  24. CheckFollowSymlink LinkTreatment = iota
  25. // CheckSymlinkOnly does not follow the symlink and verfies only that they
  26. // symlink itself exists.
  27. CheckSymlinkOnly
  28. )
  29. // ErrInvalidLinkTreatment indicates that the link treatment behavior requested
  30. // is not a valid behavior.
  31. var ErrInvalidLinkTreatment = errors.New("unknown link behavior")
  32. // Exists checks if specified file, directory, or symlink exists. The behavior
  33. // of the test depends on the linkBehaviour argument. See LinkTreatment for
  34. // more details.
  35. func Exists(linkBehavior LinkTreatment, filename string) (bool, error) {
  36. var err error
  37. if linkBehavior == CheckFollowSymlink {
  38. _, err = os.Stat(filename)
  39. } else if linkBehavior == CheckSymlinkOnly {
  40. _, err = os.Lstat(filename)
  41. } else {
  42. return false, ErrInvalidLinkTreatment
  43. }
  44. if os.IsNotExist(err) {
  45. return false, nil
  46. } else if err != nil {
  47. return false, err
  48. }
  49. return true, nil
  50. }
  51. // ReadDirNoStat returns a string of files/directories contained
  52. // in dirname without calling lstat on them.
  53. func ReadDirNoStat(dirname string) ([]string, error) {
  54. if dirname == "" {
  55. dirname = "."
  56. }
  57. f, err := os.Open(dirname)
  58. if err != nil {
  59. return nil, err
  60. }
  61. defer f.Close()
  62. return f.Readdirnames(-1)
  63. }