-
Notifications
You must be signed in to change notification settings - Fork 115
/
tar.go
86 lines (78 loc) · 1.66 KB
/
tar.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package utils
import (
"archive/tar"
"compress/gzip"
"crypto/sha1"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
type TarWalker struct {
tw *tar.Writer
root string
}
func trimPathPrefix(s, prefix string) string {
return strings.TrimLeft(strings.TrimPrefix(s, prefix), "/")
}
func (t *TarWalker) Walk(path string, fi os.FileInfo, err error) error {
// If path == root we are adding only the contents of the directory
if path == t.root {
return nil
}
hdr, err := tar.FileInfoHeader(fi, "")
if err != nil {
return err
}
if fi.IsDir() {
hdr.Name = trimPathPrefix(path+string(filepath.Separator), t.root)
} else {
hdr.Name = trimPathPrefix(path, t.root)
}
if hdr.Name == "" {
return fmt.Errorf("invalid name: %q for root: %q", hdr.Name, t.root)
}
if err := t.tw.WriteHeader(hdr); err != nil {
return err
}
if !fi.IsDir() {
f, err := os.Open(path)
if err != nil {
return err
}
if _, err := io.Copy(t.tw, f); err != nil {
f.Close()
return err
}
f.Close()
}
return nil
}
// TarballDirectory - rootdir is equivalent to tar -C 'rootdir'
func TarballDirectory(dirname, rootdir, tarname string) (string, error) {
f, err := os.OpenFile(tarname, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
if err != nil {
return "", err
}
h := sha1.New()
gw := gzip.NewWriter(io.MultiWriter(f, h))
tw := tar.NewWriter(gw)
w := TarWalker{
tw: tw,
root: rootdir,
}
if err := filepath.Walk(dirname, w.Walk); err != nil {
return "", err
}
if err := tw.Close(); err != nil {
return "", err
}
if err := gw.Close(); err != nil {
return "", err
}
if err := f.Close(); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}