/
treewalk.go
77 lines (66 loc) · 1.45 KB
/
treewalk.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
71
72
73
74
75
76
77
// MIT license · Daniel T. Gorski · dtg [at] lengo [dot] org · 06/2020
package internal
import (
"io/ioutil"
"strings"
"golang.org/x/tools/godoc/vfs/mapfs"
)
type (
// TreeWalk knows about Layout.
TreeWalk struct {
Layout
indent int
}
// The Layout interface shapes a type visitor.
Layout interface {
Enter(path string, last bool)
Print(line string, first, last bool)
Leave(path string, last bool)
}
// PathMap carries the mapping between the fully
// qualified import paths and their type projections.
PathMap map[string]string
)
// Walk traverses a PathMap according to the paths.
func (t *TreeWalk) Walk(m PathMap) error {
if len(m) == 0 {
return nil
}
mapFs := mapfs.New(m)
t.indent = -1
var walk func(dir string) error
walk = func(dir string) error {
t.indent++
defer func() { t.indent-- }()
finfo, err := mapFs.ReadDir(dir)
if err != nil {
return err
}
for i, n := 0, len(finfo); i < n; i++ {
path := dir + finfo[i].Name()
if finfo[i].IsDir() {
t.Enter(path, i == n-1)
err = walk(path + "/")
if err != nil {
return err
}
t.Leave(path, i == n-1)
continue
}
file, err := mapFs.Open(path)
if err != nil {
return err
}
data, err := ioutil.ReadAll(file)
if err != nil {
return err
}
lines := strings.Split(string(data), "\n")
for j, m := 0, len(lines); j < m; j++ {
t.Print(lines[j], j == 0, i == n-1)
}
}
return nil
}
return walk("/")
}