...
1 package utils
2
3 import (
4 "fmt"
5
6 "io/ioutil"
7 "sort"
8 "strings"
9 )
10
11 type dirwalker struct {
12 root string
13
17 fn func(root string, relative_filename string) error
18 }
19
20
21 func DirWalkAllFiles(dir string) ([]string, error) {
22 var res []string
23 err := DirWalk(dir, func(root, rel string) error {
24 if strings.HasSuffix(rel, ".goeasyops-dir") {
25 return nil
26 }
27 res = append(res, rel)
28 return nil
29 })
30 if err != nil {
31 return nil, err
32 }
33 return res, nil
34 }
35
36
37 func DirWalk(dir string, fn func(root string, relative_filename string) error) error {
38 dw := &dirwalker{root: dir, fn: fn}
39 return dw.Walk("")
40 }
41 func (dw *dirwalker) Walk(relative_path string) error {
42 path := strings.TrimPrefix(relative_path, "/")
43 fpath := fmt.Sprintf("%s/%s", dw.root, path)
44 entries, err := ioutil.ReadDir(fpath)
45 if err != nil {
46 return err
47 }
48 sort.Slice(entries, func(i, j int) bool {
49 return entries[i].Name() < entries[j].Name()
50 })
51
52
53 for _, e := range entries {
54 m := e.Mode()
55 if !m.IsRegular() {
56 continue
57 }
58 s := path + "/" + e.Name()
59 if path == "" {
60 s = e.Name()
61 }
62 err := dw.fn(dw.root, s)
63 if err != nil {
64 return err
65 }
66 }
67
68 for _, e := range entries {
69 if !e.IsDir() {
70
71 continue
72 }
73 fname := e.Name()
74 err := dw.Walk(path + "/" + fname)
75 if err != nil {
76 return err
77 }
78 }
79 return nil
80 }
81
View as plain text