file.go 1.1 KB

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