2019-02-07 12:12:20 -02:00
|
|
|
// Package targz implements the Archive interface providing tar.gz archiving
|
2018-08-05 10:23:39 -03:00
|
|
|
// and compression.
|
2019-02-07 12:12:20 -02:00
|
|
|
package targz
|
2018-08-05 10:23:39 -03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"archive/tar"
|
|
|
|
"compress/gzip"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Archive as tar.gz
|
|
|
|
type Archive struct {
|
|
|
|
gw *gzip.Writer
|
|
|
|
tw *tar.Writer
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close all closeables
|
|
|
|
func (a Archive) Close() error {
|
|
|
|
if err := a.tw.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return a.gw.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
// New tar.gz archive
|
|
|
|
func New(target io.Writer) Archive {
|
2020-04-01 15:05:20 -04:00
|
|
|
// the error will be nil since the compression level is valid
|
|
|
|
gw, _ := gzip.NewWriterLevel(target, gzip.BestCompression)
|
2018-08-05 10:23:39 -03:00
|
|
|
tw := tar.NewWriter(gw)
|
|
|
|
return Archive{
|
|
|
|
gw: gw,
|
|
|
|
tw: tw,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add file to the archive
|
|
|
|
func (a Archive) Add(name, path string) error {
|
2018-09-04 09:48:22 -03:00
|
|
|
file, err := os.Open(path) // #nosec
|
2018-08-05 10:23:39 -03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer file.Close() // nolint: errcheck
|
|
|
|
info, err := file.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
header, err := tar.FileInfoHeader(info, name)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
header.Name = name
|
|
|
|
if err = a.tw.WriteHeader(header); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if info.IsDir() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
_, err = io.Copy(a.tw, file)
|
|
|
|
return err
|
|
|
|
}
|