-
Notifications
You must be signed in to change notification settings - Fork 10
/
tar.go
54 lines (48 loc) · 898 Bytes
/
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
package main
import (
"archive/tar"
"fmt"
"io"
"os"
)
type Tar struct {
*tar.Writer
}
func CreateTar(filename string) (*Tar, error) {
file, err := os.Create(filename)
if err != nil {
return nil, err
}
return NewTarWriter(file), nil
}
func NewTarWriter(wr io.WriteCloser) *Tar {
writer := tar.NewWriter(wr)
return &Tar{Writer: writer}
}
func (t *Tar) Add(filename string) error {
info, rdc, err := statFile(filename)
if err != nil {
return err
}
defer rdc.Close()
link := ""
if info.Mode()&os.ModeSymlink != 0 {
link, _ = os.Readlink(filename)
}
// header
hdr, err := tar.FileInfoHeader(info, link)
if err != nil {
return err
}
hdr.Name = sanitizedName(filename)
if info.IsDir() {
hdr.Name += "/"
}
if err = t.WriteHeader(hdr); err != nil {
return fmt.Errorf("header: %v", err)
}
if info.Mode().IsRegular() {
_, err = io.Copy(t, rdc)
}
return err
}