-
Notifications
You must be signed in to change notification settings - Fork 0
/
retrieve.go
129 lines (101 loc) · 2.19 KB
/
retrieve.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
package assets
import (
"errors"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
var (
// ErrNoMatch is returned when the glob does not match any file.
ErrNoMatch = errors.New("no match")
)
func retrieve(loc string) ([]*file, error) {
if strings.HasPrefix(loc, "http://") || strings.HasPrefix(loc, "https://") {
return retrieveHTTP(loc)
}
if hasMeta(loc) {
return retrieveGlob(loc)
}
return retrieveFile(loc)
}
func retrieveHTTP(url string) ([]*file, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New("http status: " + string(resp.StatusCode))
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
modTime, err := http.ParseTime(resp.Header.Get("Last-Modified"))
if err != nil {
modTime = time.Now()
}
return []*file{&file{url, data, modTime}}, nil
}
func retrieveFile(loc string) ([]*file, error) {
f, err := os.Open(filepath.FromSlash(loc))
if err != nil {
return nil, err
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
modTime := time.Now()
info, err := f.Stat()
if err == nil {
modTime = info.ModTime()
}
return []*file{&file{loc, data, modTime}}, nil
}
func retrieveGlob(loc string) ([]*file, error) {
// find longest prefix not containing globs
dirs := strings.Split(loc, "/")
i := 0
for ; i < len(dirs); i++ {
if hasMeta(dirs[i]) {
break
}
}
root := strings.Join(dirs[:i], "/") + "/"
matches, err := filepath.Glob(filepath.FromSlash(loc))
if err != nil {
return nil, err
}
if len(matches) == 0 {
return nil, ErrNoMatch
}
files := []*file{}
for _, match := range matches {
path := strings.TrimPrefix(filepath.ToSlash(match), root)
f, err := os.Open(match)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(f)
if err != nil {
f.Close()
return nil, err
}
modTime := time.Now()
info, err := f.Stat()
if err == nil {
modTime = info.ModTime()
}
f.Close()
files = append(files, &file{path, data, modTime})
}
return files, nil
}
func hasMeta(path string) bool {
return strings.ContainsAny(path, "*?[")
}