forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fs.go
70 lines (66 loc) · 1.64 KB
/
fs.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
package helpers
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// ReadDir finds files according to extensions in the dir
func ReadDir(dir string, extensions []string) ([]string, error) {
confs, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
files := make([]string, 0)
for _, f := range confs {
ext := filepath.Ext(f.Name())
for _, e := range extensions {
if strings.EqualFold(ext, e) {
files = append(files, filepath.Join(dir, f.Name()))
break
}
}
}
return files, nil
}
// ReadDirRecursively finds files according to extensions in the dir recursively
func ReadDirRecursively(dir string, extensions []string) ([]string, error) {
files := make([]string, 0)
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
ext := filepath.Ext(path)
for _, e := range extensions {
if strings.EqualFold(ext, e) {
files = append(files, path)
break
}
}
return nil
})
if err != nil {
return nil, err
}
return files, nil
}
// ResolveFolderToFiles expands folder path (if any and it exists) to file paths.
// Any other paths, like file, even URL, it returns them as is.
func ResolveFolderToFiles(paths []string, extensions []string, recursively bool) ([]string, error) {
dirReader := ReadDir
if recursively {
dirReader = ReadDirRecursively
}
files := make([]string, 0)
for _, p := range paths {
i, err := os.Stat(p)
if err == nil && i.IsDir() {
fs, err := dirReader(p, extensions)
if err != nil {
return nil, fmt.Errorf("failed to read dir %s: %s", p, err)
}
files = append(files, fs...)
continue
}
files = append(files, p)
}
return files, nil
}