Files
go-zero/tools/goctl/util/zipx/zipx.go

70 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-02-21 10:19:33 +08:00
package zipx
import (
"archive/zip"
"fmt"
2022-02-21 10:19:33 +08:00
"io"
"os"
"path/filepath"
"strings"
2022-02-21 10:19:33 +08:00
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
func Unpacking(name, destPath string, mapper func(f *zip.File) bool) error {
r, err := zip.OpenReader(name)
if err != nil {
return err
}
defer r.Close()
2024-03-17 10:21:36 +08:00
destAbsPath, err := filepath.Abs(destPath)
if err != nil {
return err
}
2022-02-21 10:19:33 +08:00
for _, file := range r.File {
ok := mapper(file)
if ok {
2024-03-17 10:21:36 +08:00
err = fileCopy(file, destAbsPath)
2022-02-21 10:19:33 +08:00
if err != nil {
return err
}
}
}
return nil
}
func fileCopy(file *zip.File, destPath string) error {
rc, err := file.Open()
if err != nil {
return err
}
defer rc.Close()
// Ensure the file path does not contain directory traversal elements
if strings.Contains(file.Name, "..") {
return fmt.Errorf("invalid file path: %s", file.Name)
}
2024-03-17 10:21:36 +08:00
abs, err := filepath.Abs(file.Name)
if err != nil {
return err
}
filename := filepath.Join(destPath, filepath.Base(abs))
2022-02-21 10:19:33 +08:00
dir := filepath.Dir(filename)
err = pathx.MkdirIfNotExist(dir)
if err != nil {
return err
}
w, err := os.Create(filename)
if err != nil {
return err
}
defer w.Close()
_, err = io.Copy(w, rc)
return err
}