This repository has been archived by the owner on Nov 19, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 390
/
archiver.go
317 lines (289 loc) · 10.3 KB
/
archiver.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package archiver
import (
"context"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"time"
)
// FileInfo is a virtualized, generalized file abstraction for interacting with archives.
type FileInfo struct {
fs.FileInfo
// The file header as used/provided by the archive format.
// Typically, you do not need to set this field when creating
// an archive.
Header any
// The path of the file as it appears in the archive.
// This is equivalent to Header.Name (for most Header
// types). We require it to be specified here because
// it is such a common field and we want to preserve
// format-agnosticism (no type assertions) for basic
// operations.
//
// When extracting, this name or path may not have
// been sanitized; it should not be trusted at face
// value. Consider using path.Clean() before using.
//
// EXPERIMENTAL: If inserting a file into an archive,
// and this is left blank, the implementation of the
// archive format can default to using the file's base
// name.
NameInArchive string
// For symbolic and hard links, the target of the link.
// Not supported by all archive formats.
LinkTarget string
// A callback function that opens the file to read its
// contents. The file must be closed when reading is
// complete.
Open func() (fs.File, error)
}
func (f FileInfo) Stat() (fs.FileInfo, error) { return f.FileInfo, nil }
// FilesFromDisk returns a list of files by walking the directories in the
// given filenames map. The keys are the names on disk, and the values are
// their associated names in the archive.
//
// Map keys that specify directories on disk will be walked and added to the
// archive recursively, rooted at the named directory. They should use the
// platform's path separator (backslash on Windows; slash on everything else).
// For convenience, map keys that end in a separator ('/', or '\' on Windows)
// will enumerate contents only without adding the folder itself to the archive.
//
// Map values should typically use slash ('/') as the separator regardless of
// the platform, as most archive formats standardize on that rune as the
// directory separator for filenames within an archive. For convenience, map
// values that are empty string are interpreted as the base name of the file
// (sans path) in the root of the archive; and map values that end in a slash
// will use the base name of the file in that folder of the archive.
//
// File gathering will adhere to the settings specified in options.
//
// This function is used primarily when preparing a list of files to add to
// an archive.
func FilesFromDisk(options *FromDiskOptions, filenames map[string]string) ([]FileInfo, error) {
var files []FileInfo
for rootOnDisk, rootInArchive := range filenames {
walkErr := filepath.WalkDir(rootOnDisk, func(filename string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
info, err := d.Info()
if err != nil {
return err
}
nameInArchive := nameOnDiskToNameInArchive(filename, rootOnDisk, rootInArchive)
// this is the root folder and we are adding its contents to target rootInArchive
if info.IsDir() && nameInArchive == "" {
return nil
}
// handle symbolic links
var linkTarget string
if isSymlink(info) {
if options != nil && options.FollowSymlinks {
// dereference symlinks
filename, err = os.Readlink(filename)
if err != nil {
return fmt.Errorf("%s: readlink: %w", filename, err)
}
info, err = os.Stat(filename)
if err != nil {
return fmt.Errorf("%s: statting dereferenced symlink: %w", filename, err)
}
} else {
// preserve symlinks
linkTarget, err = os.Readlink(filename)
if err != nil {
return fmt.Errorf("%s: readlink: %w", filename, err)
}
}
}
// handle file attributes
if options != nil && options.ClearAttributes {
info = noAttrFileInfo{info}
}
file := FileInfo{
FileInfo: info,
NameInArchive: nameInArchive,
LinkTarget: linkTarget,
Open: func() (fs.File, error) {
return os.Open(filename)
},
}
files = append(files, file)
return nil
})
if walkErr != nil {
return nil, walkErr
}
}
return files, nil
}
// nameOnDiskToNameInArchive converts a filename from disk to a name in an archive,
// respecting rules defined by FilesFromDisk. nameOnDisk is the full filename on disk
// which is expected to be prefixed by rootOnDisk (according to fs.WalkDirFunc godoc)
// and which will be placed into a folder rootInArchive in the archive.
func nameOnDiskToNameInArchive(nameOnDisk, rootOnDisk, rootInArchive string) string {
// These manipulations of rootInArchive could be done just once instead of on
// every walked file since they don't rely on nameOnDisk which is the only
// variable that changes during the walk, but combining all the logic into this
// one function is easier to reason about and test. I suspect the performance
// penalty is insignificant.
if strings.HasSuffix(rootOnDisk, string(filepath.Separator)) {
rootInArchive = trimTopDir(rootInArchive)
} else if rootInArchive == "" {
rootInArchive = filepath.Base(rootOnDisk)
}
if strings.HasSuffix(rootInArchive, "/") {
rootInArchive += filepath.Base(rootOnDisk)
}
truncPath := strings.TrimPrefix(nameOnDisk, rootOnDisk)
return path.Join(rootInArchive, filepath.ToSlash(truncPath))
}
// trimTopDir strips the top or first directory from the path.
// It expects a forward-slashed path.
//
// For example, "a/b/c" => "b/c".
func trimTopDir(dir string) string {
if len(dir) > 0 && dir[0] == '/' {
dir = dir[1:]
}
if pos := strings.Index(dir, "/"); pos >= 0 {
return dir[pos+1:]
}
return dir
}
// topDir returns the top or first directory in the path.
// It expects a forward-slashed path.
//
// For example, "a/b/c" => "a".
func topDir(dir string) string {
if len(dir) > 0 && dir[0] == '/' {
dir = dir[1:]
}
if pos := strings.Index(dir, "/"); pos >= 0 {
return dir[:pos]
}
return dir
}
// noAttrFileInfo is used to zero out some file attributes (issue #280).
type noAttrFileInfo struct{ fs.FileInfo }
// Mode preserves only the type and permission bits.
func (no noAttrFileInfo) Mode() fs.FileMode {
return no.FileInfo.Mode() & (fs.ModeType | fs.ModePerm)
}
func (noAttrFileInfo) ModTime() time.Time { return time.Time{} }
func (noAttrFileInfo) Sys() any { return nil }
// FromDiskOptions specifies various options for gathering files from disk.
type FromDiskOptions struct {
// If true, symbolic links will be dereferenced, meaning that
// the link will not be added as a link, but what the link
// points to will be added as a file.
FollowSymlinks bool
// If true, some file attributes will not be preserved.
// Name, size, type, and permissions will still be preserved.
ClearAttributes bool
}
// FileHandler is a callback function that is used to handle files as they are read
// from an archive; it is kind of like fs.WalkDirFunc. Handler functions that open
// their files must not overlap or run concurrently, as files may be read from the
// same sequential stream; always close the file before returning.
//
// If the special error value fs.SkipDir is returned, the directory of the file
// (or the file itself if it is a directory) will not be walked. Note that because
// archive contents are not necessarily ordered, skipping directories requires
// memory, and skipping lots of directories may run up your memory bill.
//
// Any other returned error will terminate a walk and be returned to the caller.
type FileHandler func(ctx context.Context, info FileInfo) error
// openAndCopyFile opens file for reading, copies its
// contents to w, then closes file.
func openAndCopyFile(file FileInfo, w io.Writer) error {
fileReader, err := file.Open()
if err != nil {
return err
}
defer fileReader.Close()
// When file is in use and size is being written to, creating the compressed
// file will fail with "archive/tar: write too long." Using CopyN gracefully
// handles this.
_, err = io.Copy(w, fileReader)
if err != nil && err != io.EOF {
return err
}
return nil
}
// fileIsIncluded returns true if filename is included according to
// filenameList; meaning it is in the list, its parent folder/path
// is in the list, or the list is nil.
func fileIsIncluded(filenameList []string, filename string) bool {
// include all files if there is no specific list
if filenameList == nil {
return true
}
for _, fn := range filenameList {
// exact matches are of course included
if filename == fn {
return true
}
// also consider the file included if its parent folder/path is in the list
if strings.HasPrefix(filename, strings.TrimSuffix(fn, "/")+"/") {
return true
}
}
return false
}
func isSymlink(info fs.FileInfo) bool {
return info.Mode()&os.ModeSymlink != 0
}
// streamSizeBySeeking determines the size of the stream by
// seeking to the end, then back again, so the resulting
// seek position upon returning is the same as when called
// (assuming no errors).
func streamSizeBySeeking(s io.Seeker) (int64, error) {
currentPosition, err := s.Seek(0, io.SeekCurrent)
if err != nil {
return 0, fmt.Errorf("getting current offset: %w", err)
}
maxPosition, err := s.Seek(0, io.SeekEnd)
if err != nil {
return 0, fmt.Errorf("fast-forwarding to end: %w", err)
}
_, err = s.Seek(currentPosition, io.SeekStart)
if err != nil {
return 0, fmt.Errorf("returning to prior offset %d: %w", currentPosition, err)
}
return maxPosition, nil
}
// skipList keeps a list of non-intersecting paths
// as long as its add method is used. Identical
// elements are rejected, more specific paths are
// replaced with broader ones, and more specific
// paths won't be added when a broader one already
// exists in the list. Trailing slashes are ignored.
type skipList []string
func (s *skipList) add(dir string) {
trimmedDir := strings.TrimSuffix(dir, "/")
var dontAdd bool
for i := 0; i < len(*s); i++ {
trimmedElem := strings.TrimSuffix((*s)[i], "/")
if trimmedDir == trimmedElem {
return
}
// don't add dir if a broader path already exists in the list
if strings.HasPrefix(trimmedDir, trimmedElem+"/") {
dontAdd = true
continue
}
// if dir is broader than a path in the list, remove more specific path in list
if strings.HasPrefix(trimmedElem, trimmedDir+"/") {
*s = append((*s)[:i], (*s)[i+1:]...)
i--
}
}
if !dontAdd {
*s = append(*s, dir)
}
}