github.com/crowdsecurity/crowdsec@v1.6.1/cmd/crowdsec-cli/copyfile.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 "path/filepath" 8 9 log "github.com/sirupsen/logrus" 10 ) 11 12 13 /*help to copy the file, ioutil doesn't offer the feature*/ 14 15 func copyFileContents(src, dst string) (err error) { 16 in, err := os.Open(src) 17 if err != nil { 18 return 19 } 20 defer in.Close() 21 22 out, err := os.Create(dst) 23 if err != nil { 24 return 25 } 26 27 defer func() { 28 cerr := out.Close() 29 if err == nil { 30 err = cerr 31 } 32 }() 33 34 if _, err = io.Copy(out, in); err != nil { 35 return 36 } 37 38 err = out.Sync() 39 40 return 41 } 42 43 /*copy the file, ioutile doesn't offer the feature*/ 44 func CopyFile(sourceSymLink, destinationFile string) error { 45 sourceFile, err := filepath.EvalSymlinks(sourceSymLink) 46 if err != nil { 47 log.Infof("Not a symlink : %s", err) 48 49 sourceFile = sourceSymLink 50 } 51 52 sourceFileStat, err := os.Stat(sourceFile) 53 if err != nil { 54 return err 55 } 56 57 if !sourceFileStat.Mode().IsRegular() { 58 // cannot copy non-regular files (e.g., directories, 59 // symlinks, devices, etc.) 60 return fmt.Errorf("copyFile: non-regular source file %s (%q)", sourceFileStat.Name(), sourceFileStat.Mode().String()) 61 } 62 63 destinationFileStat, err := os.Stat(destinationFile) 64 if err != nil { 65 if !os.IsNotExist(err) { 66 return err 67 } 68 } else { 69 if !(destinationFileStat.Mode().IsRegular()) { 70 return fmt.Errorf("copyFile: non-regular destination file %s (%q)", destinationFileStat.Name(), destinationFileStat.Mode().String()) 71 } 72 if os.SameFile(sourceFileStat, destinationFileStat) { 73 return err 74 } 75 } 76 77 if err = os.Link(sourceFile, destinationFile); err != nil { 78 err = copyFileContents(sourceFile, destinationFile) 79 } 80 81 return err 82 } 83