forked from k1LoW/runn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath.go
338 lines (317 loc) · 7.3 KB
/
path.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
package runn
import (
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/bmatcuk/doublestar/v4"
"github.com/k1LoW/ghfs"
"github.com/k1LoW/urlfilepath"
)
const (
schemeHttps = "https"
schemeGitHub = "github"
)
const (
prefixHttps = schemeHttps + "://"
prefixGitHub = schemeGitHub + "://"
)
// ShortenPath shorten path.
func ShortenPath(p string) string {
flags := strings.Split(p, string(filepath.Separator))
abs := false
if flags[0] == "" {
abs = true
}
var s []string
for _, f := range flags[:len(flags)-1] {
if len(f) > 0 {
s = append(s, string(f[0]))
}
}
s = append(s, flags[len(flags)-1])
if abs {
return string(filepath.Separator) + filepath.Join(s...)
}
return filepath.Join(s...)
}
// fetchPaths retrieves readable file paths from path list ( like `path/to/a.yml;path/to/b/**/*.yml` ) .
// If the file paths are remote files, it fetches them and returns their local cache paths.
func fetchPaths(pathp string) ([]string, error) {
paths := []string{}
listp := splitList(pathp)
for _, pp := range listp {
base, pattern := doublestar.SplitPattern(filepath.ToSlash(pp))
switch {
case strings.HasPrefix(base, prefixHttps):
// https://
if strings.Contains(pattern, "*") {
return nil, fmt.Errorf("https scheme does not support wildcard: %s", pp)
}
p, err := fetchPathViaHTTPS(pp)
if err != nil {
return nil, err
}
paths = append(paths, p)
case strings.HasPrefix(base, prefixGitHub):
// github://
splitted := strings.Split(strings.TrimPrefix(base, prefixGitHub), "/")
if len(splitted) < 2 {
return nil, fmt.Errorf("invalid path: %s", pp)
}
owner := splitted[0]
repo := splitted[1]
sub := splitted[2:]
gfs, err := ghfs.New(owner, repo)
if err != nil {
return nil, err
}
var fsys fs.FS
if len(sub) > 0 {
fsys, err = gfs.Sub(strings.Join(sub, "/"))
if err != nil {
return nil, err
}
} else {
fsys = gfs
}
ps, err := fetchPathsViaGitHub(fsys, base, pattern)
if err != nil {
return nil, err
}
paths = append(paths, ps...)
default:
// Local file or cache
// Local single file
if !strings.Contains(pattern, "*") {
if _, err := readFile(pp); err == nil {
paths = append(paths, pp)
} // skip if file not found
continue
}
// Local multiple files
abs, err := filepath.Abs(base)
if err != nil {
return nil, err
}
fsys := os.DirFS(abs)
if err := doublestar.GlobWalk(fsys, pattern, func(p string, d fs.DirEntry) error {
if d.IsDir() {
return nil
}
paths = append(paths, filepath.Join(base, p))
return nil
}); err != nil {
return nil, err
}
}
}
return unique(paths), nil
}
// fetchPath retrieves readable file path.
func fetchPath(path string) (string, error) {
paths, err := fetchPaths(path)
if err != nil {
return "", err
}
if len(paths) > 1 {
return "", errors.New("multiple paths found")
}
if len(paths) == 0 {
return "", errors.New("path not found")
}
return paths[0], nil
}
// readFile reads single file from local or cache.
// When retrieving a cache file, if the cache file does not exist, re-fetch it.
func readFile(p string) ([]byte, error) {
_, err := os.Stat(p)
if err == nil {
// Read local file or cache
return os.ReadFile(p)
}
if globalCacheDir == "" || !strings.HasPrefix(p, globalCacheDir) {
// Not cache file
return nil, err
}
// Re-fetch remote file and create cache
pathstr, err := filepath.Rel(globalCacheDir, p)
if err != nil {
return nil, err
}
u, err := urlfilepath.Decode(pathstr)
if err != nil {
return nil, err
}
switch u.Scheme {
case schemeHttps:
b, err := readFileViaHTTPS(u.String())
if err != nil {
return nil, err
}
// Write cache
if err := os.WriteFile(p, b, os.ModePerm); err != nil {
return nil, err
}
return b, err
case schemeGitHub:
b, err := readFileViaGitHub(u.String())
if err != nil {
return nil, err
}
// Write cache
if err := os.WriteFile(p, b, os.ModePerm); err != nil {
return nil, err
}
return b, err
default:
return nil, fmt.Errorf("unsupported scheme: %s", u.String())
}
}
func fetchPathViaHTTPS(urlstr string) (string, error) {
u, err := url.Parse(urlstr)
if err != nil {
return "", err
}
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return "", err
}
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
cd, err := cacheDir()
if err != nil {
return "", err
}
ep, err := urlfilepath.Encode(u)
if err != nil {
return "", err
}
p := filepath.Join(cd, ep)
if err := os.MkdirAll(filepath.Dir(p), os.ModePerm); err != nil {
return "", err
}
n, err := os.Create(p)
if err != nil {
return "", err
}
defer n.Close()
if _, err = io.Copy(n, res.Body); err != nil {
return "", err
}
return p, nil
}
func fetchPathsViaGitHub(fsys fs.FS, base, pattern string) ([]string, error) {
paths := []string{}
cd, err := cacheDir()
if err != nil {
return nil, err
}
u, err := url.Parse(base)
if err != nil {
return nil, err
}
ep, err := urlfilepath.Encode(u)
if err != nil {
return nil, err
}
fetchDir := filepath.Join(cd, ep)
if err := doublestar.GlobWalk(fsys, pattern, func(p string, d fs.DirEntry) error {
if d.IsDir() {
return nil
}
cp := filepath.Join(fetchDir, p)
paths = append(paths, cp)
// Write cache
f, err := fsys.Open(p)
if err != nil {
return err
}
defer f.Close()
if err := os.MkdirAll(filepath.Dir(cp), os.ModePerm); err != nil {
return err
}
n, err := os.Create(cp)
if err != nil {
return err
}
defer n.Close()
if _, err := io.Copy(n, f); err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
return paths, nil
}
func readFileViaHTTPS(urlstr string) ([]byte, error) {
u, err := url.Parse(urlstr)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
return io.ReadAll(res.Body)
}
func readFileViaGitHub(urlstr string) ([]byte, error) {
splitted := strings.Split(strings.TrimPrefix(urlstr, prefixGitHub), "/")
if len(splitted) < 2 {
return nil, fmt.Errorf("invalid url: %s", urlstr)
}
owner := splitted[0]
repo := splitted[1]
p := strings.Join(splitted[2:], "/")
gfs, err := ghfs.New(owner, repo)
if err != nil {
return nil, err
}
f, err := gfs.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
}
// splitList splits the path list by os.PathListSeparator while keeping schemes.
func splitList(pathp string) []string {
rep := strings.NewReplacer(prefixHttps, repKey(prefixHttps), prefixGitHub, repKey(prefixGitHub))
per := strings.NewReplacer(repKey(prefixHttps), prefixHttps, repKey(prefixGitHub), prefixGitHub)
listp := []string{}
for _, p := range filepath.SplitList(rep.Replace(pathp)) {
listp = append(listp, per.Replace(p))
}
return listp
}
func repKey(in string) string {
return fmt.Sprintf("RUNN_%s_SCHEME", strings.TrimSuffix(strings.ToUpper(in), "://"))
}
func unique(in []string) []string {
u := []string{}
m := map[string]struct{}{}
for _, s := range in {
if _, ok := m[s]; ok {
continue
}
u = append(u, s)
m[s] = struct{}{}
}
return u
}