github.com/coreos/mantle@v0.13.0/update/generator/bzip2.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 generator
    16  
    17  import (
    18  	"bytes"
    19  	"io"
    20  	"os"
    21  	"os/exec"
    22  )
    23  
    24  type bzip2Writer struct {
    25  	cmd *exec.Cmd
    26  	in  io.WriteCloser
    27  }
    28  
    29  // NewBzip2Writer wraps a writer, compressing all data written to it.
    30  func NewBzip2Writer(w io.Writer) (io.WriteCloser, error) {
    31  	zipper, err := exec.LookPath("lbzip2")
    32  	if err != nil {
    33  		zipper = "bzip2"
    34  	}
    35  
    36  	cmd := exec.Command(zipper, "-c")
    37  	cmd.Stdout = w
    38  	cmd.Stderr = os.Stderr
    39  	in, err := cmd.StdinPipe()
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	return &bzip2Writer{cmd, in}, cmd.Start()
    45  }
    46  
    47  func (bz *bzip2Writer) Write(p []byte) (n int, err error) {
    48  	return bz.in.Write(p)
    49  }
    50  
    51  // Close stops the compressor, flushing out any remaining data.
    52  // The underlying writer is not closed.
    53  func (bz *bzip2Writer) Close() error {
    54  	if err := bz.in.Close(); err != nil {
    55  		return err
    56  	}
    57  	return bz.cmd.Wait()
    58  }
    59  
    60  // Bzip2 simplifies using a Bzip2Writer when working with in-memory buffers.
    61  func Bzip2(data []byte) ([]byte, error) {
    62  	buf := bytes.Buffer{}
    63  	zip, err := NewBzip2Writer(&buf)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  
    68  	if _, err := zip.Write(data); err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	if err := zip.Close(); err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	return buf.Bytes(), nil
    77  }