2018-06-24 16:40:48 +03:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"archive/zip"
|
2021-10-13 17:38:07 +03:00
|
|
|
"fmt"
|
2018-06-24 16:40:48 +03:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2022-10-28 12:31:03 +03:00
|
|
|
|
|
|
|
"github.com/hasura/graphql-engine/cli/v2/internal/errors"
|
2018-06-24 16:40:48 +03:00
|
|
|
)
|
|
|
|
|
2018-06-28 11:36:25 +03:00
|
|
|
// from https://gist.github.com/svett/424e6784facc0ba907ae
|
2018-06-24 16:40:48 +03:00
|
|
|
|
2018-06-28 11:36:25 +03:00
|
|
|
// Unzip unzips the archive to target. Both archive and target should be paths
|
|
|
|
// in the filesystem. target is created if it doesn't exist already.
|
2018-06-24 16:40:48 +03:00
|
|
|
func Unzip(archive, target string) error {
|
2022-10-28 12:31:03 +03:00
|
|
|
var op errors.Op = "util.Unzip"
|
2018-06-24 16:40:48 +03:00
|
|
|
reader, err := zip.OpenReader(archive)
|
|
|
|
if err != nil {
|
2022-10-28 12:31:03 +03:00
|
|
|
return errors.E(op, err)
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := os.MkdirAll(target, 0755); err != nil {
|
2022-10-28 12:31:03 +03:00
|
|
|
return errors.E(op, err)
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, file := range reader.File {
|
|
|
|
path := filepath.Join(target, file.Name)
|
|
|
|
if file.FileInfo().IsDir() {
|
2021-10-13 17:38:07 +03:00
|
|
|
if err = os.MkdirAll(path, file.Mode()); err != nil {
|
2022-10-28 12:31:03 +03:00
|
|
|
return errors.E(op, fmt.Errorf("error while creating directory and it's parent directories: %w", err))
|
2021-10-13 17:38:07 +03:00
|
|
|
}
|
2018-06-24 16:40:48 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
fileReader, err := file.Open()
|
|
|
|
if err != nil {
|
|
|
|
|
|
|
|
if fileReader != nil {
|
|
|
|
fileReader.Close()
|
|
|
|
}
|
|
|
|
|
2022-10-28 12:31:03 +03:00
|
|
|
return errors.E(op, err)
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
|
|
|
|
if err != nil {
|
|
|
|
fileReader.Close()
|
|
|
|
|
|
|
|
if targetFile != nil {
|
|
|
|
targetFile.Close()
|
|
|
|
}
|
|
|
|
|
2022-10-28 12:31:03 +03:00
|
|
|
return errors.E(op, err)
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := io.Copy(targetFile, fileReader); err != nil {
|
|
|
|
fileReader.Close()
|
|
|
|
targetFile.Close()
|
|
|
|
|
2022-10-28 12:31:03 +03:00
|
|
|
return errors.E(op, err)
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fileReader.Close()
|
|
|
|
targetFile.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|