2023-10-16 16:34:15 +08:00
|
|
|
package files
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"path"
|
|
|
|
"strings"
|
|
|
|
"time"
|
2024-06-28 14:56:58 +08:00
|
|
|
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/cmd"
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/common"
|
2023-10-16 16:34:15 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type ZipArchiver struct {
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewZipArchiver() ShellArchiver {
|
|
|
|
return &ZipArchiver{}
|
|
|
|
}
|
|
|
|
|
2024-06-04 16:48:31 +08:00
|
|
|
func (z ZipArchiver) Extract(filePath, dstDir string, secret string) error {
|
2023-10-16 16:34:15 +08:00
|
|
|
if err := checkCmdAvailability("unzip"); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return cmd.ExecCmd(fmt.Sprintf("unzip -qo %s -d %s", filePath, dstDir))
|
|
|
|
}
|
|
|
|
|
2024-06-04 16:48:31 +08:00
|
|
|
func (z ZipArchiver) Compress(sourcePaths []string, dstFile string, _ string) error {
|
2023-12-27 11:40:09 +08:00
|
|
|
var err error
|
2024-06-28 14:04:08 +08:00
|
|
|
tmpFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("%s%s.zip", common.RandStr(50), time.Now().Format(constant.DateTimeSlimLayout)))
|
2023-10-16 16:34:15 +08:00
|
|
|
op := NewFileOp()
|
|
|
|
defer func() {
|
|
|
|
_ = op.DeleteFile(tmpFile)
|
2023-12-27 11:40:09 +08:00
|
|
|
if err != nil {
|
|
|
|
_ = op.DeleteFile(dstFile)
|
|
|
|
}
|
2023-10-16 16:34:15 +08:00
|
|
|
}()
|
|
|
|
baseDir := path.Dir(sourcePaths[0])
|
|
|
|
relativePaths := make([]string, len(sourcePaths))
|
|
|
|
for i, sp := range sourcePaths {
|
|
|
|
relativePaths[i] = path.Base(sp)
|
|
|
|
}
|
|
|
|
cmdStr := fmt.Sprintf("zip -qr %s %s", tmpFile, strings.Join(relativePaths, " "))
|
2023-12-27 11:40:09 +08:00
|
|
|
if err = cmd.ExecCmdWithDir(cmdStr, baseDir); err != nil {
|
2023-10-16 16:34:15 +08:00
|
|
|
return err
|
|
|
|
}
|
2023-12-27 11:40:09 +08:00
|
|
|
if err = op.Mv(tmpFile, dstFile); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
2023-10-16 16:34:15 +08:00
|
|
|
}
|