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