-
Notifications
You must be signed in to change notification settings - Fork 51
/
archive_write_unix.go
106 lines (90 loc) · 1.75 KB
/
archive_write_unix.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//go:build !windows
package main
import (
"archive/tar"
"fmt"
"io"
"os"
"path/filepath"
"syscall"
"github.com/reconquest/hierr-go"
)
func writeFileToArchive(
fileName string,
stream io.Writer,
archive *tar.Writer,
workDir string,
preserveUID, preserveGID bool,
) error {
fileInfo, err := os.Stat(fileName)
if err != nil {
return hierr.Errorf(
err,
`can't stat file for archiving: '%s`, fileName,
)
}
// avoid tar warnings about leading slash
tarFileName := fileName
if tarFileName[0] == '/' {
tarFileName = tarFileName[1:]
fileName, err = filepath.Rel(workDir, fileName)
if err != nil {
return hierr.Errorf(
err,
`can't make relative path from: '%s'`,
fileName,
)
}
}
header := &tar.Header{
Name: tarFileName,
Mode: int64(fileInfo.Sys().(*syscall.Stat_t).Mode),
Size: fileInfo.Size(),
ModTime: fileInfo.ModTime(),
}
if preserveUID {
header.Uid = int(fileInfo.Sys().(*syscall.Stat_t).Uid)
}
if preserveGID {
header.Gid = int(fileInfo.Sys().(*syscall.Stat_t).Gid)
}
tracef(
hierr.Errorf(
fmt.Sprintf(
"size: %d bytes; mode: %o; uid/gid: %d/%d; modtime: %s",
header.Size,
header.Mode,
header.Uid,
header.Gid,
header.ModTime,
),
`local file: %s; remote file: %s`,
fileName,
tarFileName,
).Error(),
)
err = archive.WriteHeader(header)
if err != nil {
return hierr.Errorf(
err,
`can't write tar header for fileName: '%s'`, fileName,
)
}
fileToArchive, err := os.Open(fileName)
if err != nil {
return hierr.Errorf(
err,
`can't open fileName for reading: '%s'`,
fileName,
)
}
_, err = io.Copy(stream, fileToArchive)
if err != nil {
return hierr.Errorf(
err,
`can't copy file to the archive: '%s'`,
fileName,
)
}
return nil
}