forked from philpearl/scratchbuild
/
tar.go
56 lines (47 loc) · 1.26 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
package scratchbuild
import (
"archive/tar"
"io"
"os"
"path/filepath"
"github.com/pkg/errors"
)
// TarDirectory builds a directory into a tar file. At the moment it does not support
// subdirectories. dir is the name of the directory to copy into the tar file. The tar file
// is written into w.
func TarDirectory(dir string, w io.Writer) error {
tw := tar.NewWriter(w)
defer tw.Close()
d, err := os.Open(dir)
if err != nil {
return errors.Wrap(err, "failed to open directory")
}
defer d.Close()
fis, err := d.Readdir(0)
if err != nil {
return errors.Wrap(err, "failed to read directory")
}
for _, fi := range fis {
if fi.IsDir() {
return errors.Errorf("directories (%s) are not currently supported", fi.Name())
}
h, err := tar.FileInfoHeader(fi, "")
if err != nil {
return errors.Wrapf(err, "failed building tar header for %s", fi.Name())
}
h.Name = filepath.Join(".", h.Name)
if err := tw.WriteHeader(h); err != nil {
return errors.Wrapf(err, "failed writing header for %s", fi.Name())
}
f, err := os.Open(filepath.Join(dir, fi.Name()))
if err != nil {
return err
}
if _, err := io.Copy(tw, f); err != nil {
f.Close()
return errors.Wrapf(err, "failed copying %s into tar file", fi.Name())
}
f.Close()
}
return nil
}