-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwalking.go
49 lines (42 loc) · 1.49 KB
/
walking.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
package main
import (
"fmt"
"os"
"strings"
)
// callbackHandler is the function signature of the function to be called when a match
// is found during recursion
type callbackHandler func(currentDirectory string)
// skipHandler is the function signature of the function to be called to determine if a directory should be skipped
type skipHandler func(currentDirectory string) bool
func recurseDirectories(directory, targetDirectory string, searchString string, skip skipHandler, callback callbackHandler) {
directoryHandle, error := os.Open(directory)
if error != nil {
fmt.Printf(errorRecursingDirectories, error)
os.Exit(1)
}
files, error := directoryHandle.Readdir(-1)
if error != nil {
fmt.Printf(errorRecursingDirectories, error)
os.Exit(1)
}
searchStringFound := false
directoryParts := strings.Split(directory, string(os.PathSeparator))
directoryName := directoryParts[len(directoryParts)-1]
for _, file := range files {
if file.IsDir() && directoryName != targetDirectory {
if skip(file.Name()) {
continue
}
recurseDirectories(fmt.Sprintf("%s/%s", directory, file.Name()), targetDirectory, searchString, skip, callback)
} else {
if searchStringFound == false && strings.Contains(file.Name(), searchString) {
searchStringFound = true
}
}
}
if (searchStringFound && (targetDirectory == "" || targetDirectory == "all")) || (searchStringFound && directoryName == targetDirectory) {
// We found our search string, call the handler
callback(directory)
}
}