file.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package utils
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "github.com/mholt/archiver/v4"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. )
  12. func IsExist(path string) bool {
  13. _, err := os.Stat(path)
  14. if os.IsNotExist(err) {
  15. return false
  16. }
  17. return true
  18. }
  19. func TarXz(dst string, src string) error {
  20. src = filepath.Clean(src)
  21. dst = filepath.Clean(dst)
  22. if !strings.HasSuffix(src, string(os.PathSeparator)) {
  23. src += string(os.PathSeparator)
  24. }
  25. files, err := archiver.FilesFromDisk(nil, map[string]string{
  26. src: "",
  27. })
  28. if err != nil {
  29. return err
  30. }
  31. out, err := os.Create(dst)
  32. if err != nil {
  33. return err
  34. }
  35. defer out.Close()
  36. var compression archiver.Compression
  37. if strings.HasSuffix(dst, "gz") {
  38. compression = archiver.Gz{}
  39. } else if strings.HasSuffix(dst, "xz") {
  40. compression = archiver.Xz{}
  41. } else {
  42. compression = archiver.Gz{}
  43. }
  44. format := archiver.CompressedArchive{
  45. Compression: compression,
  46. Archival: archiver.Tar{},
  47. }
  48. err = format.Archive(context.Background(), out, files)
  49. if err != nil {
  50. return err
  51. }
  52. return nil
  53. }
  54. func CalcMd5(content string) string {
  55. pass := md5.Sum([]byte(content))
  56. return hex.EncodeToString(pass[:])
  57. }
  58. func CopyFile(src, dst string) (err error) {
  59. in, err := os.Open(src)
  60. if err != nil {
  61. return
  62. }
  63. defer in.Close()
  64. out, err := os.Create(dst)
  65. if err != nil {
  66. return
  67. }
  68. defer out.Close()
  69. _, err = io.Copy(out, in)
  70. return
  71. }