Skip to content

Commit 953d945

Browse files
author
en-ken
committed
refactor: chage my algo to filepath.Walk
1 parent 23e13bb commit 953d945

File tree

1 file changed

+23
-28
lines changed

1 file changed

+23
-28
lines changed

kadai2/en-ken/imgcnv/dirpath.go

Lines changed: 23 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,40 @@
11
package imgcnv
22

33
import (
4-
"io/ioutil"
4+
"os"
55
"path/filepath"
66
)
77

88
// IAllFilePaths is I/F of AllFilePaths
99
type IAllFilePaths func(path string, ext string) ([]string, error)
1010

11+
const allocSize = 100
12+
1113
// AllFilePaths returns
1214
// the paths of the files in the specified directory
1315
// filtered by the specified extension.
1416
func AllFilePaths(path string, ext string) ([]string, error) {
15-
absPath, err := filepath.Abs(path)
16-
if err != nil {
17-
return nil, err
18-
}
1917

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+
}
2223

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
4227
}
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
4540
}

0 commit comments

Comments
 (0)