gitee.com/h79/goutils@v1.22.10/common/archive/targz/targz.go (about) 1 // Package targz implements the Archive interface providing tar.gz archiving 2 // and compression. 3 package targz 4 5 import ( 6 "compress/gzip" 7 "gitee.com/h79/goutils/common/archive/tar" 8 fileconfig "gitee.com/h79/goutils/common/file/config" 9 "io" 10 ) 11 12 // Archive as tar.gz. 13 type Archive struct { 14 gw *gzip.Writer 15 tw *tar.Archive 16 } 17 18 // New tar.gz archive. 19 func New(target io.Writer) Archive { 20 // the error will be nil since the compression level is valid 21 writer, _ := gzip.NewWriterLevel(target, gzip.BestCompression) 22 tw := tar.New(writer) 23 return Archive{ 24 gw: writer, 25 tw: &tw, 26 } 27 } 28 29 func Copying(source io.Reader, target io.Writer) (Archive, error) { 30 // the error will be nil since the compression level is valid 31 writer, _ := gzip.NewWriterLevel(target, gzip.BestCompression) 32 src, err := gzip.NewReader(source) 33 if err != nil { 34 return Archive{}, err 35 } 36 tw, err := tar.Copying(src, writer) 37 return Archive{ 38 gw: writer, 39 tw: &tw, 40 }, err 41 } 42 43 // Close all closeables. 44 func (a Archive) Close() error { 45 if a.tw != nil { 46 err := a.tw.Close() 47 a.tw = nil 48 if err != nil { 49 return err 50 } 51 } 52 if a.gw != nil { 53 err := a.gw.Close() 54 a.gw = nil 55 return err 56 } 57 return nil 58 } 59 60 // Add file to the archive. 61 func (a Archive) Add(f fileconfig.File, stream ...fileconfig.ReaderStream) error { 62 return a.tw.Add(f, stream...) 63 }