2014-09-30 06:21:41 +00:00
|
|
|
package fileutils
|
|
|
|
|
|
|
|
import (
|
2015-03-29 21:17:23 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2014-09-30 06:21:41 +00:00
|
|
|
"path/filepath"
|
2015-03-29 19:48:52 +00:00
|
|
|
|
|
|
|
"github.com/Sirupsen/logrus"
|
2014-09-30 06:21:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Matches returns true if relFilePath matches any of the patterns
|
|
|
|
func Matches(relFilePath string, patterns []string) (bool, error) {
|
|
|
|
for _, exclude := range patterns {
|
|
|
|
matched, err := filepath.Match(exclude, relFilePath)
|
|
|
|
if err != nil {
|
2015-03-26 22:22:04 +00:00
|
|
|
logrus.Errorf("Error matching: %s (pattern: %s)", relFilePath, exclude)
|
2014-09-30 06:21:41 +00:00
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
if matched {
|
|
|
|
if filepath.Clean(relFilePath) == "." {
|
2015-03-26 22:22:04 +00:00
|
|
|
logrus.Errorf("Can't exclude whole path, excluding pattern: %s", exclude)
|
2014-09-30 06:21:41 +00:00
|
|
|
continue
|
|
|
|
}
|
2015-03-26 22:22:04 +00:00
|
|
|
logrus.Debugf("Skipping excluded path: %s", relFilePath)
|
2014-09-30 06:21:41 +00:00
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false, nil
|
|
|
|
}
|
2015-03-29 21:17:23 +00:00
|
|
|
|
|
|
|
func CopyFile(src, dst string) (int64, error) {
|
|
|
|
if src == dst {
|
|
|
|
return 0, nil
|
|
|
|
}
|
|
|
|
sf, err := os.Open(src)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
defer sf.Close()
|
|
|
|
if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
df, err := os.Create(dst)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
defer df.Close()
|
|
|
|
return io.Copy(df, sf)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetTotalUsedFds() int {
|
|
|
|
if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil {
|
|
|
|
logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err)
|
|
|
|
} else {
|
|
|
|
return len(fds)
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReadSymlinkedDirectory returns the target directory of a symlink.
|
|
|
|
// The target of the symbolic link may not be a file.
|
|
|
|
func ReadSymlinkedDirectory(path string) (string, error) {
|
|
|
|
var realPath string
|
|
|
|
var err error
|
|
|
|
if realPath, err = filepath.Abs(path); err != nil {
|
|
|
|
return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
|
|
|
|
}
|
|
|
|
if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
|
|
|
|
return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
|
|
|
|
}
|
|
|
|
realPathInfo, err := os.Stat(realPath)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
|
|
|
|
}
|
|
|
|
if !realPathInfo.Mode().IsDir() {
|
|
|
|
return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
|
|
|
|
}
|
|
|
|
return realPath, nil
|
|
|
|
}
|