128 lines
2.3 KiB
Go
128 lines
2.3 KiB
Go
package extractertool
|
|
|
|
import (
|
|
"archive/tar"
|
|
"archive/zip"
|
|
"compress/gzip"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func unTarGz(src string, dest string) ([]string, error) {
|
|
|
|
var filenames []string
|
|
|
|
gzipStream, err := os.Open(src)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
uncompressedStream, err := gzip.NewReader(gzipStream)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
tarReader := tar.NewReader(uncompressedStream)
|
|
|
|
for true {
|
|
|
|
header, err := tarReader.Next()
|
|
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
}
|
|
|
|
switch header.Typeflag {
|
|
case tar.TypeDir:
|
|
if err := os.Mkdir(filepath.Join(dest, header.Name), 0755); err != nil {
|
|
println(err.Error())
|
|
return nil, err
|
|
}
|
|
case tar.TypeReg:
|
|
|
|
outFile, err := os.Create(filepath.Join(dest, header.Name))
|
|
if err != nil {
|
|
println(err.Error())
|
|
return nil, err
|
|
}
|
|
if _, err := io.Copy(outFile, tarReader); err != nil {
|
|
println(err.Error())
|
|
return nil, err
|
|
}
|
|
filenames = append(filenames, outFile.Name())
|
|
outFile.Close()
|
|
|
|
default:
|
|
continue
|
|
}
|
|
|
|
}
|
|
return filenames, nil
|
|
}
|
|
|
|
func Unzip(src string, dest string) ([]string, error) {
|
|
|
|
var filenames []string
|
|
|
|
r, err := zip.OpenReader(src)
|
|
if err != nil {
|
|
return filenames, err
|
|
}
|
|
defer r.Close()
|
|
|
|
for _, f := range r.File {
|
|
|
|
// Store filename/path for returning and using later on
|
|
fpath := filepath.Join(dest, f.Name)
|
|
|
|
// Check for ZipSlip. More Info: http://bit.ly/2MsjAWE
|
|
if !strings.HasPrefix(fpath, filepath.Clean(dest)+string(os.PathSeparator)) {
|
|
return nil, fmt.Errorf("%s: illegal file path", fpath)
|
|
}
|
|
|
|
filenames = append(filenames, fpath)
|
|
|
|
if f.FileInfo().IsDir() {
|
|
// Make Folder
|
|
err := os.MkdirAll(fpath, os.ModePerm)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
continue
|
|
}
|
|
|
|
// Make File
|
|
if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
rc, err := f.Open()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
_, err = io.Copy(outFile, rc)
|
|
|
|
// Close the file without defer to close before next iteration of loop
|
|
outFile.Close()
|
|
rc.Close()
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return filenames, nil
|
|
}
|