github.com/rumpl/bof@v23.0.0-rc.2+incompatible/pkg/fileutils/fileutils.go (about) 1 package fileutils // import "github.com/docker/docker/pkg/fileutils" 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 "path/filepath" 8 ) 9 10 // CopyFile copies from src to dst until either EOF is reached 11 // on src or an error occurs. It verifies src exists and removes 12 // the dst if it exists. 13 func CopyFile(src, dst string) (int64, error) { 14 cleanSrc := filepath.Clean(src) 15 cleanDst := filepath.Clean(dst) 16 if cleanSrc == cleanDst { 17 return 0, nil 18 } 19 sf, err := os.Open(cleanSrc) 20 if err != nil { 21 return 0, err 22 } 23 defer sf.Close() 24 if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { 25 return 0, err 26 } 27 df, err := os.Create(cleanDst) 28 if err != nil { 29 return 0, err 30 } 31 defer df.Close() 32 return io.Copy(df, sf) 33 } 34 35 // ReadSymlinkedDirectory returns the target directory of a symlink. 36 // The target of the symbolic link may not be a file. 37 func ReadSymlinkedDirectory(path string) (string, error) { 38 var realPath string 39 var err error 40 if realPath, err = filepath.Abs(path); err != nil { 41 return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) 42 } 43 if realPath, err = filepath.EvalSymlinks(realPath); err != nil { 44 return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) 45 } 46 realPathInfo, err := os.Stat(realPath) 47 if err != nil { 48 return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) 49 } 50 if !realPathInfo.Mode().IsDir() { 51 return "", fmt.Errorf("canonical path points to a file '%s'", realPath) 52 } 53 return realPath, nil 54 } 55 56 // CreateIfNotExists creates a file or a directory only if it does not already exist. 57 func CreateIfNotExists(path string, isDir bool) error { 58 if _, err := os.Stat(path); err != nil { 59 if os.IsNotExist(err) { 60 if isDir { 61 return os.MkdirAll(path, 0755) 62 } 63 if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { 64 return err 65 } 66 f, err := os.OpenFile(path, os.O_CREATE, 0755) 67 if err != nil { 68 return err 69 } 70 f.Close() 71 } 72 } 73 return nil 74 }