github.com/cloudfoundry/libcfbuildpack@v1.91.23/helper/extract_zip.go (about)

     1  /*
     2   * Copyright 2018-2020 the original author or authors.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      https://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package helper
    18  
    19  import (
    20  	"archive/zip"
    21  	"os"
    22  )
    23  
    24  // ExtractZip extracts source ZIP file to a destination directory.  An arbitrary number of top-level directory
    25  // components can be stripped from each path.
    26  func ExtractZip(source string, destination string, stripComponents int) error {
    27  	z, err := zip.OpenReader(source)
    28  	if err != nil {
    29  		return err
    30  	}
    31  	defer z.Close()
    32  
    33  	for _, f := range z.File {
    34  		target := strippedPath(f.Name, destination, stripComponents)
    35  		if target == "" {
    36  			continue
    37  		}
    38  
    39  		if f.FileInfo().IsDir() {
    40  			if err := os.MkdirAll(target, 0755); err != nil {
    41  				return err
    42  			}
    43  		} else {
    44  			if err := writeFile(f, target); err != nil {
    45  				return err
    46  			}
    47  		}
    48  	}
    49  
    50  	return nil
    51  }
    52  
    53  func writeFile(file *zip.File, target string) error {
    54  	in, err := file.Open()
    55  	if err != nil {
    56  		return err
    57  	}
    58  	defer in.Close()
    59  
    60  	return WriteFileFromReader(target, file.Mode(), in)
    61  }