forked from mholt/archiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
targz.go
60 lines (48 loc) · 1.4 KB
/
targz.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package archiver
import (
"archive/tar"
"compress/gzip"
"fmt"
"os"
"strings"
)
// TarGz is for TarGz format
var TarGz tarGzFormat
func init() {
RegisterFormat("TarGz", TarGz)
}
type tarGzFormat struct{}
func (tarGzFormat) Match(filename string) bool {
// TODO: read file header to identify the format
return strings.HasSuffix(strings.ToLower(filename), ".tar.gz") ||
strings.HasSuffix(strings.ToLower(filename), ".tgz")
}
// Make creates a .tar.gz file at targzPath containing
// the contents of files listed in filePaths. It works
// the same way Tar does, but with gzip compression.
func (tarGzFormat) Make(targzPath string, filePaths []string) error {
out, err := os.Create(targzPath)
if err != nil {
return fmt.Errorf("error creating %s: %v", targzPath, err)
}
defer out.Close()
gzWriter := gzip.NewWriter(out)
defer gzWriter.Close()
tarWriter := tar.NewWriter(gzWriter)
defer tarWriter.Close()
return tarball(filePaths, tarWriter, targzPath)
}
// Open untars source and decompresses the contents into destination.
func (tarGzFormat) Open(source, destination string) error {
f, err := os.Open(source)
if err != nil {
return fmt.Errorf("%s: failed to open archive: %v", source, err)
}
defer f.Close()
gzr, err := gzip.NewReader(f)
if err != nil {
return fmt.Errorf("%s: create new gzip reader: %v", source, err)
}
defer gzr.Close()
return untar(tar.NewReader(gzr), destination)
}