From c892caeb0a89fbaacb76526c49726ab26d65ef06 Mon Sep 17 00:00:00 2001 From: zijiren233 Date: Sun, 27 Nov 2022 20:47:14 +0800 Subject: [PATCH] Fix: linux os zip prefix --- utils/unzip.go | 12 +++++------- utils/zip.go | 30 +++++++++++------------------- 2 files changed, 16 insertions(+), 26 deletions(-) diff --git a/utils/unzip.go b/utils/unzip.go index 824d5c3..94979af 100644 --- a/utils/unzip.go +++ b/utils/unzip.go @@ -62,29 +62,27 @@ func decode(files []*zip.File, targetPath string, types string) error { } func handleFile(f *zip.File, targetPath, decodeName string) error { - var err error fpath := filepath.Join(targetPath, decodeName) if f.FileInfo().IsDir() { - os.MkdirAll(fpath, os.ModePerm) + return os.MkdirAll(fpath, os.ModePerm) } else { - if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil { + if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil { return err } inFile, err := f.Open() if err != nil { return err } + defer inFile.Close() outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return err } + defer outFile.Close() buf := bufio.NewWriter(outFile) if _, err = io.Copy(buf, inFile); err != nil { return err } - buf.Flush() - inFile.Close() - outFile.Close() + return buf.Flush() } - return err } diff --git a/utils/zip.go b/utils/zip.go index 8d9e3ca..045f7b2 100644 --- a/utils/zip.go +++ b/utils/zip.go @@ -11,8 +11,8 @@ import ( // 示例 zip.Zip("MCSManager 9.4.5_win64_x86", "./test.zip") 可使用相对路径和绝对路径 func Zip(filePath []string, zipPath string) error { - var err error - if zipPath, err = filepath.Abs(zipPath); err != nil { + zipPath, err := filepath.Abs(zipPath) + if err != nil { return err } if strings.ToLower(filepath.Ext(zipPath)) != ".zip" { @@ -24,6 +24,7 @@ func Zip(filePath []string, zipPath string) error { } defer zipfile.Close() buf := bufio.NewWriter(zipfile) + defer buf.Flush() zw := zip.NewWriter(buf) defer zw.Close() for _, fPath := range filePath { @@ -35,34 +36,25 @@ func Zip(filePath []string, zipPath string) error { if err != nil { return err } - var zipfile io.Writer - if !strings.HasSuffix(filepath.Dir(fPath), `\`) { - fPath = filepath.Dir(fPath) + `\` - } if info.IsDir() { - if !strings.HasSuffix(path, `\`) && !strings.HasSuffix(path, `/`) { - path = path + `/` - } - _, err = zw.Create(strings.TrimPrefix(path, fPath)) + _, err = zw.Create(strings.TrimPrefix(strings.TrimPrefix(path, filepath.Dir(fPath)), string(os.PathSeparator)) + `/`) + return err + } + zipfile, err := zw.Create(strings.TrimPrefix(strings.TrimPrefix(path, filepath.Dir(fPath)), string(os.PathSeparator))) + if err != nil { return err - } else { - zipfile, err = zw.Create(strings.TrimPrefix(path, fPath)) - if err != nil { - return err - } } f1, err := os.Open(path) if err != nil { return err } - io.Copy(zipfile, f1) - f1.Close() - return nil + defer f1.Close() + _, err = io.Copy(zipfile, f1) + return err }) if err != nil { return err } } - buf.Flush() return err }