github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/os/archive.go (about)

     1  package os
     2  
     3  import (
     4  	"archive/tar"
     5  	log "github.com/sirupsen/logrus"
     6  	"github.com/emc-advanced-dev/pkg/errors"
     7  	"io"
     8  	"os"
     9  	"os/exec"
    10  	"path"
    11  )
    12  
    13  func ExtractTar(tarArchive io.ReadCloser, localFolder string) error {
    14  	tr := tar.NewReader(tarArchive)
    15  	for {
    16  		hdr, err := tr.Next()
    17  		if err == io.EOF {
    18  			// end of tar archive
    19  			break
    20  		}
    21  		if err != nil {
    22  			return err
    23  		}
    24  		log.WithField("file", hdr.Name).Debug("Extracting file")
    25  		switch hdr.Typeflag {
    26  		case tar.TypeDir:
    27  			err = os.MkdirAll(path.Join(localFolder, hdr.Name), 0755)
    28  
    29  			if err != nil {
    30  				return err
    31  			}
    32  
    33  		case tar.TypeReg:
    34  			fallthrough
    35  		case tar.TypeRegA:
    36  			dir, _ := path.Split(hdr.Name)
    37  			if err := os.MkdirAll(path.Join(localFolder, dir), 0755); err != nil {
    38  				return err
    39  			}
    40  
    41  			outputFile, err := os.Create(path.Join(localFolder, hdr.Name))
    42  			if err != nil {
    43  				return err
    44  			}
    45  
    46  			if _, err := io.Copy(outputFile, tr); err != nil {
    47  				outputFile.Close()
    48  				return err
    49  			}
    50  			outputFile.Close()
    51  
    52  		default:
    53  			continue
    54  		}
    55  	}
    56  
    57  	return nil
    58  }
    59  
    60  ///http://blog.ralch.com/tutorial/golang-working-with-tar-and-gzip/
    61  func Compress(source, destination string) error {
    62  	tarCmd := exec.Command("tar", "cf", destination, "-C", source, ".")
    63  	if out, err := tarCmd.Output(); err != nil {
    64  		return errors.New("running tar command: "+string(out), err)
    65  	}
    66  	return nil
    67  }