github.com/remind101/go-getter@v0.0.0-20180809191950-4bda8fa99001/decompress_xz.go (about)

     1  package getter
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/ulikunitz/xz"
    10  )
    11  
    12  // XzDecompressor is an implementation of Decompressor that can
    13  // decompress xz files.
    14  type XzDecompressor struct{}
    15  
    16  func (d *XzDecompressor) Decompress(dst, src string, dir bool) error {
    17  	// Directory isn't supported at all
    18  	if dir {
    19  		return fmt.Errorf("xz-compressed files can only unarchive to a single file")
    20  	}
    21  
    22  	// If we're going into a directory we should make that first
    23  	if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
    24  		return err
    25  	}
    26  
    27  	// File first
    28  	f, err := os.Open(src)
    29  	if err != nil {
    30  		return err
    31  	}
    32  	defer f.Close()
    33  
    34  	// xz compression is second
    35  	xzR, err := xz.NewReader(f)
    36  	if err != nil {
    37  		return err
    38  	}
    39  
    40  	// Copy it out
    41  	dstF, err := os.Create(dst)
    42  	if err != nil {
    43  		return err
    44  	}
    45  	defer dstF.Close()
    46  
    47  	_, err = io.Copy(dstF, xzR)
    48  	return err
    49  }