-
Notifications
You must be signed in to change notification settings - Fork 40
/
tar.gz.go
56 lines (54 loc) · 1.07 KB
/
tar.gz.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
package main
import (
"archive/tar"
"compress/gzip"
"io"
"log"
"os"
"path/filepath"
)
func tarGz(w io.Writer, path string) error {
basePath := path
addFile := func(w *tar.Writer, path string, stat os.FileInfo) error {
if stat.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
header := new(tar.Header)
path, err = filepath.Rel(basePath, path)
if err != nil {
return err
}
header.Name = path
header.Size = stat.Size()
header.Mode = int64(stat.Mode())
header.ModTime = stat.ModTime()
if err := w.WriteHeader(header); err != nil {
return err
}
if _, err := io.Copy(w, file); err != nil {
return err
}
return w.Flush()
}
wGzip := gzip.NewWriter(w)
wTar := tar.NewWriter(wGzip)
defer func() {
if err := wTar.Close(); err != nil {
log.Println(err)
}
if err := wGzip.Close(); err != nil {
log.Println(err)
}
}()
return filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
return addFile(wTar, path, info)
})
}