github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/build/util/zip/zip.go (about)

     1  // Package zip is a wrapper around archive/zip, it's used for archiving and unarchiving source from
     2  // and into folders on the host. Because runtime has many cases where it streams source via RPC,
     3  // this package encapsulates the shared logic.
     4  package zip
     5  
     6  import (
     7  	"archive/zip"
     8  	"bytes"
     9  	"io"
    10  	"io/ioutil"
    11  	"os"
    12  	"path/filepath"
    13  )
    14  
    15  // Unarchive decodes the source in a zip and writes it to a directory
    16  func Unarchive(src io.Reader, dir string) error {
    17  	// create a new buffer with the source, this is required because zip.NewReader takes a io.ReaderAt
    18  	// and not an io.Reader
    19  	buff := bytes.NewBuffer([]byte{})
    20  	size, err := io.Copy(buff, src)
    21  	if err != nil {
    22  		return err
    23  	}
    24  
    25  	// create the zip
    26  	reader := bytes.NewReader(buff.Bytes())
    27  	zip, err := zip.NewReader(reader, size)
    28  	if err != nil {
    29  		return err
    30  	}
    31  
    32  	// write the files in the zip to our tmp dir
    33  	for _, f := range zip.File {
    34  		rc, err := f.Open()
    35  		if err != nil {
    36  			return err
    37  		}
    38  
    39  		bytes, err := ioutil.ReadAll(rc)
    40  		if err != nil {
    41  			return err
    42  		}
    43  
    44  		path := filepath.Join(dir, f.Name)
    45  		if err := ioutil.WriteFile(path, bytes, os.ModePerm); err != nil {
    46  			return err
    47  		}
    48  
    49  		if err := rc.Close(); err != nil {
    50  			return err
    51  		}
    52  	}
    53  
    54  	return nil
    55  }