-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtarball.go
70 lines (57 loc) · 1.65 KB
/
tarball.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
package main
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
)
func CreateTarball(tarballFilePath string, filePaths []string) error {
file, err := os.Create(tarballFilePath)
if err != nil {
return fmt.Errorf("Could not create tarball file '%s', got error '%s'", tarballFilePath, err.Error())
}
defer file.Close()
gzipWriter := gzip.NewWriter(file)
defer gzipWriter.Close()
tarWriter := tar.NewWriter(gzipWriter)
defer tarWriter.Close()
for _, filePath := range filePaths {
err := addFileToTarWriter(filePath, tarWriter)
if err != nil {
return fmt.Errorf("Could not add file '%s', to tarball, got error '%s'", filePath, err.Error())
}
}
return nil
}
// Private methods
func addFileToTarWriter(filePath string, tarWriter *tar.Writer) error {
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("Could not open file '%s', got error '%s'", filePath, err.Error())
}
defer file.Close()
if err = file.Sync(); err != nil {
return err
}
stat, err := file.Stat()
if err != nil {
return fmt.Errorf("Could not get stat for file '%s', got error '%s'", filePath, err.Error())
}
header := &tar.Header{
Name: filepath.Join(filepath.Base(filepath.Dir(filePath)), filepath.Base(filePath)),
Size: stat.Size(),
Mode: int64(stat.Mode()),
ModTime: stat.ModTime(),
}
err = tarWriter.WriteHeader(header)
if err != nil {
return fmt.Errorf("Could not write header for file '%s', got error '%s'", filePath, err.Error())
}
_, err = io.Copy(tarWriter, file)
if err != nil {
return fmt.Errorf("Could not copy the file '%s' data to the tarball, got error '%s'", filePath, err.Error())
}
return nil
}