zip.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package fileutil
  2. import (
  3. "archive/zip"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. )
  10. /*
  11. UnzipFile extracts a given zip file into a given output folder.
  12. */
  13. func UnzipFile(name string, dest string, overwrite bool) error {
  14. var f *os.File
  15. stat, err := os.Stat(name)
  16. if err == nil {
  17. if f, err = os.Open(name); err == nil {
  18. defer f.Close()
  19. err = UnzipReader(f, stat.Size(), dest, overwrite)
  20. }
  21. }
  22. return err
  23. }
  24. /*
  25. UnzipReader extracts a given zip archive into a given output folder.
  26. Size is the size of the archive.
  27. */
  28. func UnzipReader(reader io.ReaderAt, size int64, dest string, overwrite bool) error {
  29. var rc io.ReadCloser
  30. r, err := zip.NewReader(reader, size)
  31. if err == nil {
  32. for _, f := range r.File {
  33. if rc, err = f.Open(); err == nil {
  34. var e bool
  35. fpath := filepath.Join(dest, f.Name)
  36. if e, _ = PathExists(fpath); e && !overwrite {
  37. err = fmt.Errorf("Path already exists: %v", fpath)
  38. } else if f.FileInfo().IsDir() {
  39. // Create folder
  40. err = os.MkdirAll(fpath, os.ModePerm)
  41. } else {
  42. var fdir string
  43. // Create File
  44. if lastIndex := strings.LastIndex(fpath, string(os.PathSeparator)); lastIndex > -1 {
  45. fdir = fpath[:lastIndex]
  46. }
  47. if err = os.MkdirAll(fdir, os.ModePerm); err == nil {
  48. var file *os.File
  49. file, err = os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  50. if err == nil {
  51. _, err = io.Copy(file, rc)
  52. file.Close()
  53. }
  54. }
  55. }
  56. rc.Close()
  57. }
  58. if err != nil {
  59. break
  60. }
  61. }
  62. }
  63. return err
  64. }