|
1 | 1 | package imgcnv
|
2 | 2 |
|
3 | 3 | import (
|
4 |
| - "io/ioutil" |
| 4 | + "os" |
5 | 5 | "path/filepath"
|
6 | 6 | )
|
7 | 7 |
|
8 | 8 | // IAllFilePaths is I/F of AllFilePaths
|
9 | 9 | type IAllFilePaths func(path string, ext string) ([]string, error)
|
10 | 10 |
|
| 11 | +const allocSize = 100 |
| 12 | + |
11 | 13 | // AllFilePaths returns
|
12 | 14 | // the paths of the files in the specified directory
|
13 | 15 | // filtered by the specified extension.
|
14 | 16 | func AllFilePaths(path string, ext string) ([]string, error) {
|
15 |
| - absPath, err := filepath.Abs(path) |
16 |
| - if err != nil { |
17 |
| - return nil, err |
18 |
| - } |
19 | 17 |
|
20 |
| - return searchFiles(absPath, ext) |
21 |
| -} |
| 18 | + result := make([]string, 0, allocSize) |
| 19 | + err := filepath.Walk(path, func(filePath string, info os.FileInfo, err error) error { |
| 20 | + if err != nil { |
| 21 | + return err |
| 22 | + } |
22 | 23 |
|
23 |
| -func searchFiles(dirPath string, ext string) ([]string, error) { |
24 |
| - |
25 |
| - files, err := ioutil.ReadDir(dirPath) |
26 |
| - if err != nil { |
27 |
| - return nil, err |
28 |
| - } |
29 |
| - |
30 |
| - result := make([]string, 0) // allocate 0 items to merge 2 slices |
31 |
| - for _, file := range files { |
32 |
| - path := filepath.Join(dirPath, file.Name()) |
33 |
| - if file.IsDir() { |
34 |
| - paths, _ := searchFiles(path, ext) |
35 |
| - result = append(result, paths...) |
36 |
| - } else { |
37 |
| - // ignore error |
38 |
| - isMatch, _ := filepath.Match("*."+ext, file.Name()) |
39 |
| - if isMatch { |
40 |
| - result = append(result, path) |
41 |
| - } |
| 24 | + if info.IsDir() { |
| 25 | + // Skip |
| 26 | + return nil |
42 | 27 | }
|
43 |
| - } |
44 |
| - return result, nil |
| 28 | + |
| 29 | + // Find by extension |
| 30 | + isMatch, _ := filepath.Match("*."+ext, info.Name()) |
| 31 | + if isMatch { |
| 32 | + absPath, err := filepath.Abs(filePath) |
| 33 | + result = append(result, absPath) |
| 34 | + return err |
| 35 | + } |
| 36 | + return nil |
| 37 | + }) |
| 38 | + |
| 39 | + return result, err |
45 | 40 | }
|
0 commit comments