fileutils.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package fileutils
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "github.com/Sirupsen/logrus"
  9. )
  10. // Matches returns true if relFilePath matches any of the patterns
  11. func Matches(relFilePath string, patterns []string) (bool, error) {
  12. for _, exclude := range patterns {
  13. matched, err := filepath.Match(exclude, relFilePath)
  14. if err != nil {
  15. logrus.Errorf("Error matching: %s (pattern: %s)", relFilePath, exclude)
  16. return false, err
  17. }
  18. if matched {
  19. if filepath.Clean(relFilePath) == "." {
  20. logrus.Errorf("Can't exclude whole path, excluding pattern: %s", exclude)
  21. continue
  22. }
  23. logrus.Debugf("Skipping excluded path: %s", relFilePath)
  24. return true, nil
  25. }
  26. }
  27. return false, nil
  28. }
  29. func CopyFile(src, dst string) (int64, error) {
  30. if src == dst {
  31. return 0, nil
  32. }
  33. sf, err := os.Open(src)
  34. if err != nil {
  35. return 0, err
  36. }
  37. defer sf.Close()
  38. if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
  39. return 0, err
  40. }
  41. df, err := os.Create(dst)
  42. if err != nil {
  43. return 0, err
  44. }
  45. defer df.Close()
  46. return io.Copy(df, sf)
  47. }
  48. func GetTotalUsedFds() int {
  49. if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
  50. logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
  51. } else {
  52. return len(fds)
  53. }
  54. return -1
  55. }
  56. // ReadSymlinkedDirectory returns the target directory of a symlink.
  57. // The target of the symbolic link may not be a file.
  58. func ReadSymlinkedDirectory(path string) (string, error) {
  59. var realPath string
  60. var err error
  61. if realPath, err = filepath.Abs(path); err != nil {
  62. return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
  63. }
  64. if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
  65. return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
  66. }
  67. realPathInfo, err := os.Stat(realPath)
  68. if err != nil {
  69. return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
  70. }
  71. if !realPathInfo.Mode().IsDir() {
  72. return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
  73. }
  74. return realPath, nil
  75. }