-
Notifications
You must be signed in to change notification settings - Fork 39
/
filer.go
378 lines (345 loc) · 9.79 KB
/
filer.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
package filer
import (
"archive/zip"
"bytes"
"io/ioutil"
"os"
xpath "path"
"path/filepath"
"strings"
"github.com/pkg/errors"
sivafs "gopkg.in/src-d/go-billy-siva.v4"
"gopkg.in/src-d/go-billy.v4/memfs"
"gopkg.in/src-d/go-billy.v4/osfs"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/cache"
"gopkg.in/src-d/go-git.v4/plumbing/filemode"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
"gopkg.in/src-d/go-git.v4/storage/filesystem"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
// File represents a file in the virtual file system: every node is either a regular file
// or a directory. Symlinks are dereferenced in the implementations.
type File struct {
Name string
IsDir bool
}
// A Filer provides a list of files.
type Filer interface {
// ReadFile returns the contents of a file given it's path.
ReadFile(path string) (content []byte, err error)
// ReadDir lists a directory.
ReadDir(path string) ([]File, error)
// Close frees all the resources allocated by this Filer.
Close()
// PathsAreAlwaysSlash indicates whether the path separator is platform-independent ("/") or
// OS-specific.
PathsAreAlwaysSlash() bool
}
type localFiler struct {
root string
}
// FromDirectory returns a Filer that allows accessing over all the files contained in a directory.
func FromDirectory(path string) (Filer, error) {
fi, err := os.Stat(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot create Filer from %s", path)
}
if !fi.IsDir() {
return nil, errors.New("not a directory")
}
path, _ = filepath.Abs(path)
return &localFiler{root: path}, nil
}
func (filer *localFiler) resolvePath(path string) (string, error) {
path, err := filepath.Abs(filepath.Join(filer.root, path))
if err != nil {
return "", err
}
if !strings.HasPrefix(path, filer.root) {
return "", errors.New("path is out of scope")
}
return path, nil
}
func (filer *localFiler) ReadFile(path string) ([]byte, error) {
path, err := filer.resolvePath(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot read file %s", path)
}
buffer, err := ioutil.ReadFile(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot read file %s", path)
}
return buffer, nil
}
func (filer *localFiler) ReadDir(path string) ([]File, error) {
path, err := filer.resolvePath(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot read directory %s", path)
}
files, err := ioutil.ReadDir(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot read directory %s", path)
}
result := make([]File, 0, len(files))
for _, file := range files {
result = append(result, File{
Name: file.Name(),
IsDir: file.IsDir(),
})
}
return result, nil
}
func (filer *localFiler) Close() {}
func (filer *localFiler) PathsAreAlwaysSlash() bool {
return false
}
type gitFiler struct {
root *object.Tree
}
// FromGitURL returns a Filer that allows accessing all the files in a Git repository given its URL.
func FromGitURL(url string) (Filer, error) {
repo, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: url})
if err != nil {
return nil, errors.Wrapf(err, "could not clone repo from %s", url)
}
return FromGit(repo, "")
}
// FromGit returns a Filer that allows accessing all the files in a Git repository
func FromGit(repo *git.Repository, headRef plumbing.ReferenceName) (Filer, error) {
var head *plumbing.Reference
var err error
if headRef == "" {
head, err = repo.Head()
} else {
head, err = repo.Reference(headRef, true)
}
if err != nil {
return nil, errors.Wrap(err, "could not fetch HEAD from repo")
}
commit, err := repo.CommitObject(head.Hash())
if err != nil {
return nil, errors.Wrap(err, "could not fetch commit for HEAD")
}
tree, err := commit.Tree()
if err != nil {
return nil, errors.Wrap(err, "could not fetch root for HEAD commit")
}
return &gitFiler{root: tree}, nil
}
func (filer gitFiler) ReadFile(path string) ([]byte, error) {
entry, err := filer.root.FindEntry(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot find file %s", path)
}
if entry.Mode == filemode.Symlink {
file, err := filer.root.File(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot find file %s", path)
}
path, err = file.Contents()
if err != nil {
return nil, errors.Wrapf(err, "cannot read file %s", path)
}
}
file, err := filer.root.File(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot read file %s", path)
}
reader, err := file.Reader()
if err != nil {
return nil, errors.Wrapf(err, "cannot read file %s", path)
}
defer func() { err = reader.Close() }()
buf := new(bytes.Buffer)
if _, err = buf.ReadFrom(reader); err != nil {
return nil, errors.Wrapf(err, "cannot read file %s", path)
}
return buf.Bytes(), err
}
func (filer *gitFiler) ReadDir(path string) ([]File, error) {
var tree *object.Tree
if path != "" {
var err error
tree, err = filer.root.Tree(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot read directory %s", path)
}
} else {
tree = filer.root
}
result := make([]File, 0, len(tree.Entries))
for _, entry := range tree.Entries {
switch entry.Mode {
case filemode.Dir:
result = append(result, File{
Name: entry.Name,
IsDir: true,
})
case filemode.Regular, filemode.Executable, filemode.Deprecated, filemode.Symlink:
result = append(result, File{
Name: entry.Name,
IsDir: false,
})
}
}
return result, nil
}
func (filer *gitFiler) Close() {
filer.root = nil
}
func (filer *gitFiler) PathsAreAlwaysSlash() bool {
return true
}
// FromSiva returns a Filer that allows accessing all the files in a Git repository contained in a Siva file.
// See https://github.com/src-d/go-siva and https://github.com/src-d/go-billy-siva
func FromSiva(path string) (Filer, error) {
localFs := osfs.New(filepath.Dir(path))
tmpFs := memfs.New()
basePath := filepath.Base(path)
fs, err := sivafs.NewFilesystem(localFs, basePath, tmpFs)
if err != nil {
return nil, errors.Wrapf(err, "unable to create a Siva filesystem from %s", path)
}
sivaStorage := filesystem.NewStorage(fs, cache.NewObjectLRUDefault())
repo, err := git.Open(sivaStorage, tmpFs)
if err != nil {
return nil, errors.Wrapf(err, "unable to open the Git repository from Siva file %s", path)
}
refs, err := repo.References()
if err != nil {
return nil, errors.Wrapf(err, "unable to list Git references from Siva file %s", path)
}
var head plumbing.ReferenceName
err = refs.ForEach(func(ref *plumbing.Reference) error {
if strings.HasPrefix(ref.Name().String(), "refs/heads/HEAD/") {
head = ref.Name()
return storer.ErrStop
}
return nil
})
if err != nil {
return nil, errors.Wrapf(err, "failed to iterate over references in Siva file %s", path)
}
return FromGit(repo, head)
}
type zipNode struct {
children map[string]*zipNode
file *zip.File
}
type zipFiler struct {
arch *zip.ReadCloser
tree *zipNode
}
// FromZIP returns a Filer that allows accessing all the files in a ZIP archive given its path.
func FromZIP(path string) (Filer, error) {
arch, err := zip.OpenReader(path)
if err != nil {
return nil, errors.Wrapf(err, "cannot read ZIP archive %s", path)
}
root := &zipNode{children: map[string]*zipNode{}}
for _, f := range arch.File {
path := strings.Split(f.Name, "/") // zip always has "/"
node := root
for _, part := range path {
if part == "" {
continue
}
child := node.children[part]
if child == nil {
child = &zipNode{children: map[string]*zipNode{}}
node.children[part] = child
}
node = child
}
node.file = f
}
return &zipFiler{arch: arch, tree: root}, nil
}
func (filer *zipFiler) ReadFile(path string) ([]byte, error) {
parts := strings.Split(path, string("/"))
node := filer.tree
for _, part := range parts {
if part == "" {
continue
}
node = node.children[part]
if node == nil {
return nil, errors.Errorf("does not exist: %s", path)
}
}
reader, err := node.file.Open()
if err != nil {
return nil, errors.Wrapf(err, "cannot open %s", path)
}
defer reader.Close()
buffer, err := ioutil.ReadAll(reader)
if err != nil {
return nil, errors.Wrapf(err, "cannot read %s", path)
}
return buffer, nil
}
func (filer *zipFiler) ReadDir(path string) ([]File, error) {
parts := strings.Split(path, string("/"))
node := filer.tree
for _, part := range parts {
if part == "" {
continue
}
node = node.children[part]
if node == nil {
return nil, errors.Errorf("does not exist: %s", path)
}
}
if path != "" && !node.file.FileInfo().IsDir() {
return nil, errors.Errorf("not a directory: %s", path)
}
result := make([]File, 0, len(node.children))
for name, child := range node.children {
result = append(result, File{
Name: name,
IsDir: child.file.FileInfo().IsDir(),
})
}
return result, nil
}
func (filer *zipFiler) Close() {
filer.arch.Close()
}
func (filer *zipFiler) PathsAreAlwaysSlash() bool {
return true
}
type nestedFiler struct {
origin Filer
offset string
}
// NestFiler wraps an existing Filer. It prepends the specified prefix to every path.
func NestFiler(filer Filer, prefix string) Filer {
return &nestedFiler{origin: filer, offset: prefix}
}
func (filer *nestedFiler) ReadFile(path string) ([]byte, error) {
var fullPath string
if filer.origin.PathsAreAlwaysSlash() {
fullPath = xpath.Join(filer.offset, path)
} else {
fullPath = filepath.Join(filer.offset, path)
}
return filer.origin.ReadFile(fullPath)
}
func (filer *nestedFiler) ReadDir(path string) ([]File, error) {
var fullPath string
if filer.origin.PathsAreAlwaysSlash() {
fullPath = xpath.Join(filer.offset, path)
} else {
fullPath = filepath.Join(filer.offset, path)
}
return filer.origin.ReadDir(fullPath)
}
func (filer *nestedFiler) Close() {
filer.origin.Close()
}
func (filer *nestedFiler) PathsAreAlwaysSlash() bool {
return filer.origin.PathsAreAlwaysSlash()
}