forked from msf/go-minipypi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
localfilefetcher.go
77 lines (68 loc) · 1.61 KB
/
localfilefetcher.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
package main
import (
"os"
"path"
"path/filepath"
"strings"
)
var _ FileFetcher = (*localFileFetcher)(nil)
type localFileFetcher struct {
localDirectory string
}
// NewLocalFileFetcher returns a FileFetcher that serves a local directory.
func NewLocalFileFetcher(localPath string) FileFetcher {
newFileFetcher := localFileFetcher{
localDirectory: localPath,
}
return newFileFetcher
}
func (fetcher localFileFetcher) GetFile(path string) (*FetchedFile, error) {
fullPath := filepath.Join(fetcher.localDirectory, path)
f, err := os.Open(fullPath)
if err != nil {
return nil, err
}
file := &FetchedFile{
Payload: f,
BucketName: fetcher.localDirectory,
Key: path,
Etag: fullPath,
}
return file, nil
}
func (fetcher localFileFetcher) ListDir(prefix string) ([]ListDirEntry, error) {
searchDir := searchDir{
rootPath: fetcher.localDirectory,
prefix: path.Join(fetcher.localDirectory, prefix),
}
if err := filepath.Walk(fetcher.localDirectory, searchDir.processFile); err != nil {
return nil, err
}
return searchDir.fList, nil
}
type searchDir struct {
rootPath string
prefix string
fList []ListDirEntry
}
func (searchDir *searchDir) processFile(filePath string, info os.FileInfo, err error) error {
if filePath == searchDir.rootPath {
return nil
}
if info == nil {
return nil
}
if info.IsDir() {
return nil
}
if !strings.HasPrefix(filePath, searchDir.prefix) {
return nil
}
entry := ListDirEntry{
Name: info.Name(),
LastModified: info.ModTime(),
SizeKb: info.Size() / 1024,
}
searchDir.fList = append(searchDir.fList, entry)
return nil
}