file.go 1.1 KB

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