File compression utils.

This commit is contained in:
Andrey Smirnov
2013-12-24 12:25:39 +04:00
parent 634bfa7b94
commit 7fe48d8d86
2 changed files with 68 additions and 0 deletions

33
utils/compress.go Normal file
View File

@@ -0,0 +1,33 @@
package utils
import (
"compress/gzip"
"io"
"os"
"os/exec"
)
// CompressFile compresses file specified by source to .gz & .bz2
//
// It uses internal gzip and external bzip2, see:
// https://code.google.com/p/go/issues/detail?id=4828
func CompressFile(source *os.File) error {
gzPath := source.Name() + ".gz"
gzFile, err := os.Create(gzPath)
if err != nil {
return err
}
defer gzFile.Close()
gzWriter := gzip.NewWriter(gzFile)
defer gzWriter.Close()
source.Seek(0, 0)
_, err = io.Copy(gzWriter, source)
if err != nil {
return err
}
cmd := exec.Command("bzip2", source.Name())
return cmd.Run()
}

35
utils/compress_test.go Normal file
View File

@@ -0,0 +1,35 @@
package utils
import (
"io/ioutil"
. "launchpad.net/gocheck"
"os"
)
type CompressSuite struct {
tempfile *os.File
}
var _ = Suite(&CompressSuite{})
func (s *CompressSuite) SetUpTest(c *C) {
s.tempfile, _ = ioutil.TempFile(c.MkDir(), "aptly-test")
s.tempfile.WriteString("Quick brown fox jumps over black dog and runs away... Really far away... who knows?")
}
func (s *CompressSuite) TearDownTest(c *C) {
s.tempfile.Close()
}
func (s *CompressSuite) TestCompress(c *C) {
err := CompressFile(s.tempfile)
c.Assert(err, IsNil)
st, err := os.Stat(s.tempfile.Name() + ".gz")
c.Assert(err, IsNil)
c.Assert(st.Size() < 100, Equals, true)
st, err = os.Stat(s.tempfile.Name() + ".bz2")
c.Assert(err, IsNil)
c.Assert(st.Size() < 120, Equals, true)
}