-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtar.go
67 lines (62 loc) · 1.04 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
package main
import (
"archive/tar"
"compress/gzip"
"io"
"os"
"sync"
)
type TarFile struct {
gw *gzip.Writer
tw *tar.Writer
destPath string
fw *os.File
mu sync.Mutex
}
func NewTar(dstPath string) (*TarFile, error) {
var res TarFile
var err error
res.fw, err = os.Create(dstPath)
if err != nil {
return nil, err
}
res.gw = gzip.NewWriter(res.fw)
res.tw = tar.NewWriter(res.gw)
res.destPath = dstPath
return &res, nil
}
func (tf *TarFile) AddFile(path, name string) error {
tf.mu.Lock()
defer tf.mu.Unlock()
fso, err := os.Open(path)
if err != nil {
return err
}
defer fso.Close()
stats, err := fso.Stat()
if err != nil {
return err
}
hdr, err := tar.FileInfoHeader(stats, "")
if err != nil {
return err
}
hdr.Name = name
err = tf.tw.WriteHeader(hdr)
if err != nil {
return err
}
_, err = io.Copy(tf.tw, fso)
return err
}
func (tf *TarFile) Finish() error {
err := tf.tw.Close()
if err != nil {
return err
}
err = tf.gw.Close()
if err != nil {
return err
}
return tf.fw.Close()
}