-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfile_system.go
419 lines (366 loc) · 8.88 KB
/
file_system.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package zipfs
import (
"archive/zip"
"errors"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"sort"
"strings"
"sync"
"time"
)
var (
errFileClosed = errors.New("file closed")
errFileSystemClosed = errors.New("filesystem closed")
errNotDirectory = errors.New("not a directory")
errDirectory = errors.New("is a directory")
)
// FileSystem is a file system based on a ZIP file.
// It implements the http.FileSystem interface.
type FileSystem struct {
readerAt io.ReaderAt
closer io.Closer
reader *zip.Reader
fileInfos fileInfoMap
}
// New will open the Zip file specified by name and
// return a new FileSystem based on that Zip file.
func New(name string) (*FileSystem, error) {
file, err := os.Open(name)
if err != nil {
return nil, err
}
fi, err := file.Stat()
if err != nil {
return nil, err
}
return NewFromReaderAt(file, fi.Size(), file)
}
// NewFromReaderAt will open the Zip file accessible by readerAt with the given size.
// The closer, if not nil, will be called when the file system is closed.
func NewFromReaderAt(readerAt io.ReaderAt, size int64, closer io.Closer) (*FileSystem, error) {
zipReader, err := zip.NewReader(readerAt, size)
if err != nil {
return nil, err
}
// Separate the file into an io.ReaderAt and an io.Closer.
// Earlier versions of the code allowed for opening a filesystem
// just with an io.ReaderAt. Not also that thw zip.Reader is
// not actually used outside of this function so it probably
// does not need to be in the FileSystem structure. Keeping it
// there for now but may remove it in future.
fs := &FileSystem{
closer: closer,
readerAt: readerAt,
reader: zipReader,
fileInfos: fileInfoMap{},
}
// Build a map of file paths to speed lookup.
// Note that this assumes that there are not a very
// large number of files in the ZIP file.
//
// Because we iterate through the map it seems reasonable
// to attach each fileInfo to it's parent directory. Once again,
// reasonable if the ZIP file does not contain a very large number
// of entries.
for _, zf := range fs.reader.File {
fi := fs.fileInfos.FindOrCreate(zf.Name)
fi.zipFile = zf
fiParent := fs.fileInfos.FindOrCreateParent(zf.Name)
fiParent.fileInfos = append(fiParent.fileInfos, fi)
}
// Sort all of the list of fileInfos in each directory.
for _, fi := range fs.fileInfos {
if len(fi.fileInfos) > 1 {
sort.Sort(fi.fileInfos)
}
}
return fs, nil
}
// Open implements the http.FileSystem interface.
// A http.File is returned, which can be served by
// the http.FileServer implementation.
func (fs *FileSystem) Open(name string) (http.File, error) {
fi, err := fs.openFileInfo(name)
if err != nil {
return nil, err
}
return fi.openReader(name), nil
}
// Close closes the file system's underlying ZIP file and
// releases all memory allocated to internal data structures.
func (fs *FileSystem) Close() error {
fs.reader = nil
fs.readerAt = nil
var err error
if fs.closer != nil {
err = fs.closer.Close()
fs.closer = nil
}
fs.fileInfos = nil
return err
}
type fileInfoList []*fileInfo
func (fl fileInfoList) Len() int {
return len(fl)
}
func (fl fileInfoList) Less(i, j int) bool {
name1 := fl[i].Name()
name2 := fl[j].Name()
return name1 < name2
}
func (fl fileInfoList) Swap(i, j int) {
fi := fl[i]
fl[i] = fl[j]
fl[j] = fi
}
func (fs *FileSystem) openFileInfo(name string) (*fileInfo, error) {
if fs.readerAt == nil {
return nil, errFileSystemClosed
}
name = path.Clean(name)
trimmedName := strings.TrimLeft(name, "/")
fi := fs.fileInfos[trimmedName]
if fi == nil {
return nil, &os.PathError{Op: "Open", Path: name, Err: os.ErrNotExist}
}
return fi, nil
}
// fileMap keeps track of fileInfos
type fileInfoMap map[string]*fileInfo
func (fm fileInfoMap) FindOrCreate(name string) *fileInfo {
strippedName := strings.TrimRight(name, "/")
fi := fm[name]
if fi == nil {
fi = &fileInfo{
name: name,
}
fm[name] = fi
if strippedName != name {
// directories get two entries: with and without trailing slash
fm[strippedName] = fi
}
}
return fi
}
func (fm fileInfoMap) FindOrCreateParent(name string) *fileInfo {
strippedName := strings.TrimRight(name, "/")
dirName := path.Dir(strippedName)
if dirName == "." {
dirName = "/"
} else if !strings.HasSuffix(dirName, "/") {
dirName = dirName + "/"
}
return fm.FindOrCreate(dirName)
}
// fileInfo implements the os.FileInfo interface.
type fileInfo struct {
name string
fs *FileSystem
zipFile *zip.File
fileInfos fileInfoList
tempPath string
mutex sync.Mutex
}
func (fi *fileInfo) Name() string {
return path.Base(fi.name)
}
func (fi *fileInfo) Size() int64 {
if fi.zipFile == nil {
return 0
}
if fi.zipFile.UncompressedSize64 == 0 {
return int64(fi.zipFile.UncompressedSize)
}
return int64(fi.zipFile.UncompressedSize64)
}
func (fi *fileInfo) Mode() os.FileMode {
if fi.zipFile == nil || fi.IsDir() {
return 0555 | os.ModeDir
}
return 0444
}
var dirTime = time.Date(2001, 1, 1, 0, 0, 0, 0, time.UTC)
func (fi *fileInfo) ModTime() time.Time {
if fi.zipFile == nil {
return dirTime
}
return fi.zipFile.ModTime()
}
func (fi *fileInfo) IsDir() bool {
if fi.zipFile == nil {
return true
}
return fi.zipFile.Mode().IsDir()
}
func (fi *fileInfo) Sys() interface{} {
return fi.zipFile
}
func (fi *fileInfo) openReader(name string) *fileReader {
return &fileReader{
fileInfo: fi,
name: name,
}
}
func (fi *fileInfo) readdir() ([]os.FileInfo, error) {
if !fi.Mode().IsDir() {
return nil, errNotDirectory
}
v := make([]os.FileInfo, len(fi.fileInfos))
for i, fi := range fi.fileInfos {
v[i] = fi
}
return v, nil
}
type fileReader struct {
name string // the name used to open
fileInfo *fileInfo
reader io.ReadCloser
file *os.File
closed bool
readdir []os.FileInfo
}
func (f *fileReader) Close() error {
var errs []error
if f.reader != nil {
err := f.reader.Close()
errs = append(errs, err)
}
var tempFile string
if f.file != nil {
tempFile = f.file.Name()
err := f.file.Close()
errs = append(errs, err)
}
if tempFile != "" {
err := os.Remove(tempFile)
errs = append(errs, err)
}
f.closed = true
for _, err := range errs {
if err != nil {
return f.pathError("Close", err)
}
}
return nil
}
func (f *fileReader) Read(p []byte) (n int, err error) {
if f.closed {
return 0, f.pathError("Read", errFileClosed)
}
if f.file != nil {
return f.file.Read(p)
}
if f.reader == nil {
f.reader, err = f.fileInfo.zipFile.Open()
if err != nil {
return 0, err
}
}
return f.reader.Read(p)
}
func (f *fileReader) Seek(offset int64, whence int) (int64, error) {
if f.closed {
return 0, f.pathError("Seek", errFileClosed)
}
// The reader cannot seek, so close it.
if f.reader != nil {
if err := f.reader.Close(); err != nil {
return 0, err
}
}
// A special case for when there is no file created and the seek is
// to the beginning of the file. Just open (or re-open) the reader
// at the beginning of the file.
if f.file == nil && offset == 0 && whence == 0 {
var err error
f.reader, err = f.fileInfo.zipFile.Open()
return 0, err
}
if err := f.createTempFile(); err != nil {
return 0, err
}
return f.file.Seek(offset, whence)
}
func (f *fileReader) Readdir(count int) ([]os.FileInfo, error) {
var err error
var osFileInfos []os.FileInfo
if count > 0 {
if f.readdir == nil {
f.readdir, err = f.fileInfo.readdir()
if err != nil {
return nil, f.pathError("Readdir", err)
}
}
if len(f.readdir) >= count {
osFileInfos = f.readdir[0:count]
f.readdir = f.readdir[count:]
} else {
osFileInfos = f.readdir
f.readdir = nil
err = io.EOF
}
} else {
osFileInfos, err = f.fileInfo.readdir()
if err != nil {
return nil, f.pathError("Readdir", err)
}
}
return osFileInfos, err
}
func (f *fileReader) Stat() (os.FileInfo, error) {
return f.fileInfo, nil
}
func (f *fileReader) createTempFile() error {
if f.reader != nil {
if err := f.reader.Close(); err != nil {
return err
}
f.reader = nil
}
if f.file == nil {
// Open a file that contains the contents of the zip file.
osFile, err := createTempFile(f.fileInfo.zipFile)
if err != nil {
return err
}
f.file = osFile
}
return nil
}
func (f *fileReader) pathError(op string, err error) error {
return &os.PathError{
Op: op,
Path: f.name,
Err: err,
}
}
// createTempFile creates a temporary file with the contents of the
// zip file. Used to implement io.Seeker interface.
func createTempFile(f *zip.File) (*os.File, error) {
reader, err := f.Open()
if err != nil {
return nil, err
}
defer reader.Close()
tempFile, err := ioutil.TempFile("", "zipfs")
if err != nil {
return nil, err
}
_, err = io.Copy(tempFile, reader)
if err != nil {
tempFile.Close()
os.Remove(tempFile.Name())
return nil, err
}
_, err = tempFile.Seek(0, os.SEEK_SET)
if err != nil {
tempFile.Close()
os.Remove(tempFile.Name())
return nil, err
}
return tempFile, nil
}