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

     1  // Package gzip implements the Archive interface providing gz archiving
     2  // and compression.
     3  package gzip
     4  
     5  import (
     6  	"compress/gzip"
     7  	"fmt"
     8  	"io"
     9  	"os"
    10  )
    11  
    12  // Archive as gz.
    13  type Archive struct {
    14  	gw *gzip.Writer
    15  }
    16  
    17  // Close all closeables.
    18  func (a Archive) Close() error {
    19  	return a.gw.Close()
    20  }
    21  
    22  // New gz archive.
    23  func New(target io.Writer) Archive {
    24  	// the error will be nil since the compression level is valid
    25  	gw, _ := gzip.NewWriterLevel(target, gzip.BestCompression)
    26  	return Archive{
    27  		gw: gw,
    28  	}
    29  }
    30  
    31  // Add file to the archive.
    32  func (a Archive) Add(name, path string) error {
    33  	if a.gw.Header.Name != "" {
    34  		return fmt.Errorf("gzip: failed to add %s, only one file can be archived in gz format", name)
    35  	}
    36  	file, err := os.Open(path) // #nosec
    37  	if err != nil {
    38  		return err
    39  	}
    40  	defer file.Close()
    41  	info, err := file.Stat()
    42  	if err != nil {
    43  		return err
    44  	}
    45  	if info.IsDir() {
    46  		return nil
    47  	}
    48  	a.gw.Header.Name = name
    49  	a.gw.Header.ModTime = info.ModTime()
    50  	_, err = io.Copy(a.gw, file)
    51  	return err
    52  }