github.com/joselitofilho/goreleaser@v0.155.1-0.20210123221854-e4891856c593/pkg/archive/tarxz/tarxz.go (about)

     1  // Package tarxz implements the Archive interface providing tar.xz archiving
     2  // and compression.
     3  package tarxz
     4  
     5  import (
     6  	"archive/tar"
     7  	"io"
     8  	"os"
     9  
    10  	"github.com/ulikunitz/xz"
    11  )
    12  
    13  // Archive as tar.xz.
    14  type Archive struct {
    15  	xzw *xz.Writer
    16  	tw  *tar.Writer
    17  }
    18  
    19  // Close all closeables.
    20  func (a Archive) Close() error {
    21  	if err := a.tw.Close(); err != nil {
    22  		return err
    23  	}
    24  	return a.xzw.Close()
    25  }
    26  
    27  // New tar.xz archive.
    28  func New(target io.Writer) Archive {
    29  	xzw, _ := xz.WriterConfig{DictCap: 16 * 1024 * 1024}.NewWriter(target)
    30  	tw := tar.NewWriter(xzw)
    31  	return Archive{
    32  		xzw: xzw,
    33  		tw:  tw,
    34  	}
    35  }
    36  
    37  // Add file to the archive.
    38  func (a Archive) Add(name, path string) error {
    39  	file, err := os.Open(path) // #nosec
    40  	if err != nil {
    41  		return err
    42  	}
    43  	defer file.Close()
    44  	info, err := file.Stat()
    45  	if err != nil {
    46  		return err
    47  	}
    48  	header, err := tar.FileInfoHeader(info, name)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	header.Name = name
    53  	if err = a.tw.WriteHeader(header); err != nil {
    54  		return err
    55  	}
    56  	if info.IsDir() {
    57  		return nil
    58  	}
    59  	_, err = io.Copy(a.tw, file)
    60  	return err
    61  }