github.com/coreos/mantle@v0.13.0/util/bunzip.go (about)

     1  // Copyright 2016 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"compress/bzip2"
    19  	"io"
    20  	"os"
    21  )
    22  
    23  // Bunzip2 does bunzip2 decompression from src to dst.
    24  //
    25  // It matches the signature of io.Copy.
    26  func Bunzip2(dst io.Writer, src io.Reader) (written int64, err error) {
    27  	bzr := bzip2.NewReader(src)
    28  	return io.Copy(dst, bzr)
    29  }
    30  
    31  // Bunzip2File does bunzip2 decompression from src file into dst file.
    32  func Bunzip2File(dst, src string) error {
    33  	in, err := os.Open(src)
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	defer in.Close()
    39  
    40  	out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
    41  	if err != nil {
    42  		return err
    43  	}
    44  
    45  	_, err = Bunzip2(out, in)
    46  	if err != nil {
    47  		os.Remove(dst)
    48  	}
    49  	return err
    50  }