copyfile.go 1.6 KB

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