github.com/zsuzhengdu/helm@v3.0.0-beta.3+incompatible/pkg/chartutil/expand.go (about)

     1  /*
     2  Copyright The Helm 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      http://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 chartutil
    18  
    19  import (
    20  	"archive/tar"
    21  	"compress/gzip"
    22  	"io"
    23  	"os"
    24  	"path/filepath"
    25  )
    26  
    27  // Expand uncompresses and extracts a chart into the specified directory.
    28  func Expand(dir string, r io.Reader) error {
    29  	gr, err := gzip.NewReader(r)
    30  	if err != nil {
    31  		return err
    32  	}
    33  	defer gr.Close()
    34  	tr := tar.NewReader(gr)
    35  	for {
    36  		header, err := tr.Next()
    37  		if err == io.EOF {
    38  			break
    39  		} else if err != nil {
    40  			return err
    41  		}
    42  
    43  		// split header name and create missing directories
    44  		d := filepath.Dir(header.Name)
    45  		fullDir := filepath.Join(dir, d)
    46  		_, err = os.Stat(fullDir)
    47  		if err != nil && d != "" {
    48  			if err := os.MkdirAll(fullDir, 0700); err != nil {
    49  				return err
    50  			}
    51  		}
    52  
    53  		path := filepath.Clean(filepath.Join(dir, header.Name))
    54  		info := header.FileInfo()
    55  		if info.IsDir() {
    56  			if err = os.MkdirAll(path, info.Mode()); err != nil {
    57  				return err
    58  			}
    59  			continue
    60  		}
    61  
    62  		file, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode())
    63  		if err != nil {
    64  			return err
    65  		}
    66  		if _, err = io.Copy(file, tr); err != nil {
    67  			file.Close()
    68  			return err
    69  		}
    70  		file.Close()
    71  	}
    72  	return nil
    73  }
    74  
    75  // ExpandFile expands the src file into the dest directory.
    76  func ExpandFile(dest, src string) error {
    77  	h, err := os.Open(src)
    78  	if err != nil {
    79  		return err
    80  	}
    81  	defer h.Close()
    82  	return Expand(dest, h)
    83  }