utils.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package backup
  2. import (
  3. "io"
  4. "os"
  5. "path/filepath"
  6. "github.com/uozi-tech/cosy"
  7. )
  8. // copyFile copies a file from src to dst
  9. func copyFile(src, dst string) error {
  10. // Open source file
  11. source, err := os.Open(src)
  12. if err != nil {
  13. return err
  14. }
  15. defer source.Close()
  16. // Create destination file
  17. destination, err := os.Create(dst)
  18. if err != nil {
  19. return err
  20. }
  21. defer destination.Close()
  22. // Copy content
  23. _, err = io.Copy(destination, source)
  24. return err
  25. }
  26. // copyDirectory copies a directory recursively from src to dst
  27. func copyDirectory(src, dst string) error {
  28. // Check if source is a directory
  29. srcInfo, err := os.Stat(src)
  30. if err != nil {
  31. return err
  32. }
  33. if !srcInfo.IsDir() {
  34. return cosy.WrapErrorWithParams(ErrCopyNginxConfigDir, "%s is not a directory", src)
  35. }
  36. // Create destination directory
  37. if err := os.MkdirAll(dst, srcInfo.Mode()); err != nil {
  38. return err
  39. }
  40. // Walk through source directory
  41. return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
  42. if err != nil {
  43. return err
  44. }
  45. // Calculate relative path
  46. relPath, err := filepath.Rel(src, path)
  47. if err != nil {
  48. return err
  49. }
  50. if relPath == "." {
  51. return nil
  52. }
  53. // Create target path
  54. targetPath := filepath.Join(dst, relPath)
  55. // Check if it's a symlink
  56. if info.Mode()&os.ModeSymlink != 0 {
  57. // Read the link
  58. linkTarget, err := os.Readlink(path)
  59. if err != nil {
  60. return err
  61. }
  62. // Create symlink at target path
  63. return os.Symlink(linkTarget, targetPath)
  64. }
  65. // If it's a directory, create it
  66. if info.IsDir() {
  67. return os.MkdirAll(targetPath, info.Mode())
  68. }
  69. // If it's a file, copy it
  70. return copyFile(path, targetPath)
  71. })
  72. }