2020-01-12 14:00:56 +01:00
|
|
|
package fs
|
2019-12-05 19:21:35 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"archive/zip"
|
|
|
|
"io"
|
|
|
|
"os"
|
2020-01-06 14:32:15 +01:00
|
|
|
"strings"
|
2019-12-05 19:21:35 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// ZipFiles compresses one or many files into a single zip archive file.
|
|
|
|
// Param 1: filename is the output zip file's name.
|
|
|
|
// Param 2: files is a list of files to add to the zip.
|
2020-01-06 14:32:15 +01:00
|
|
|
func Zip(filename string, files []string) error {
|
2019-12-05 19:21:35 +01:00
|
|
|
newZipFile, err := os.Create(filename)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer newZipFile.Close()
|
|
|
|
|
|
|
|
zipWriter := zip.NewWriter(newZipFile)
|
|
|
|
defer zipWriter.Close()
|
|
|
|
|
|
|
|
// Add files to zip
|
|
|
|
for _, file := range files {
|
2020-01-06 14:32:15 +01:00
|
|
|
if err = AddToZip(zipWriter, file); err != nil {
|
2019-12-05 19:21:35 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-01-06 14:32:15 +01:00
|
|
|
func AddToZip(zipWriter *zip.Writer, filename string) error {
|
2019-12-05 19:21:35 +01:00
|
|
|
fileToZip, err := os.Open(filename)
|
2020-05-28 21:20:42 +02:00
|
|
|
|
2019-12-05 19:21:35 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-05-28 21:20:42 +02:00
|
|
|
|
2019-12-05 19:21:35 +01:00
|
|
|
defer fileToZip.Close()
|
|
|
|
|
|
|
|
// Get the file information
|
|
|
|
info, err := fileToZip.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
header, err := zip.FileInfoHeader(info)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Change to deflate to gain better compression
|
|
|
|
// see http://golang.org/pkg/archive/zip/#pkg-constants
|
|
|
|
header.Method = zip.Deflate
|
|
|
|
|
|
|
|
writer, err := zipWriter.CreateHeader(header)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, err = io.Copy(writer, fileToZip)
|
|
|
|
return err
|
|
|
|
}
|
2020-01-06 14:32:15 +01:00
|
|
|
|
|
|
|
// Extract Zip file in destination directory
|
|
|
|
func Unzip(src, dest string) (fileNames []string, err error) {
|
|
|
|
r, err := zip.OpenReader(src)
|
2020-05-28 21:20:42 +02:00
|
|
|
|
2020-01-06 14:32:15 +01:00
|
|
|
if err != nil {
|
|
|
|
return fileNames, err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer r.Close()
|
|
|
|
|
|
|
|
for _, f := range r.File {
|
2021-05-04 17:30:39 +02:00
|
|
|
// Skip directories like __OSX and potentially malicious file names containing "..".
|
|
|
|
if strings.HasPrefix(f.Name, "__") || strings.Contains(f.Name, "..") {
|
2020-01-06 14:32:15 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
fn, err := copyToFile(f, dest)
|
|
|
|
if err != nil {
|
|
|
|
return fileNames, err
|
|
|
|
}
|
|
|
|
|
|
|
|
fileNames = append(fileNames, fn)
|
|
|
|
}
|
|
|
|
|
|
|
|
return fileNames, nil
|
|
|
|
}
|