Added option to compress and archive multiple generated files
This commit is contained in:
parent
cb73258a84
commit
84e27d622a
2 changed files with 84 additions and 0 deletions
|
|
@ -1,8 +1,10 @@
|
|||
package util
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"cmp"
|
||||
"compress/gzip"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
|
|
@ -97,3 +99,64 @@ func CopyIf[T comparable](s []T, condition func(t T) bool) []T {
|
|||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func CreateArchive(files []string, buf io.Writer) error {
|
||||
// Create new Writers for gzip and tar
|
||||
// These writers are chained. Writing to the tar writer will
|
||||
// write to the gzip writer which in turn will write to
|
||||
// the "buf" writer
|
||||
gw := gzip.NewWriter(buf)
|
||||
defer gw.Close()
|
||||
tw := tar.NewWriter(gw)
|
||||
defer tw.Close()
|
||||
|
||||
// Iterate over files and add them to the tar archive
|
||||
for _, file := range files {
|
||||
err := addToArchive(tw, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func addToArchive(tw *tar.Writer, filename string) error {
|
||||
// open file to write to archive
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// get FileInfo for file size, mode, etc.
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// create a tar Header from the FileInfo data
|
||||
header, err := tar.FileInfoHeader(info, info.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// use full path as name (FileInfoHeader only takes the basename) to
|
||||
// preserve directory structure
|
||||
// see for more info: https://golang.org/src/archive/tar/common.go?#L626
|
||||
header.Name = filename
|
||||
|
||||
// Write file header to the tar archive
|
||||
err = tw.WriteHeader(header)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// copy file content to tar archive
|
||||
_, err = io.Copy(tw, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue