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

     1  // Copyright 2018 Red Hat.
     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  	"io"
    19  	"os"
    20  
    21  	"github.com/ulikunitz/xz"
    22  )
    23  
    24  // XZ2File does xz decompression from src file into dst file
    25  func XZ2File(dst, src string) error {
    26  	in, err := os.Open(src)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	defer in.Close()
    31  
    32  	out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
    33  	if err != nil {
    34  		return err
    35  	}
    36  	defer out.Close()
    37  
    38  	reader, err := xz.NewReader(in)
    39  	if err != nil {
    40  		os.Remove(dst)
    41  		return err
    42  	}
    43  
    44  	_, err = io.Copy(out, reader)
    45  	if err != nil {
    46  		os.Remove(dst)
    47  		return err
    48  	}
    49  	return nil
    50  }