-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
92 lines (72 loc) · 1.37 KB
/
parse.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package tpl
import (
"bufio"
"bytes"
"io"
"os"
"path"
"path/filepath"
"regexp"
"strings"
)
type tplFile struct {
abspath string
path string
parent *string
content []byte
}
var re = regexp.MustCompile(`(?m)\{\{(\s*)extends\s+["'](.+)["'](\s*)\}\}`)
func parseDir(dir string, exts ...string) (map[string]*tplFile, error) {
e := make(map[string]struct{}, len(exts))
for i := range exts {
e[exts[i]] = struct{}{}
}
files := make(map[string]*tplFile)
err := filepath.Walk(dir, func(file string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if _, ok := e[path.Ext(file)]; !ok {
return nil
}
f, err := parseFile(dir, file)
if err != nil {
return err
}
if f != nil {
files[f.path] = f
}
return nil
})
if err != nil {
return nil, err
}
return files, nil
}
func parseFile(dir string, file string) (*tplFile, error) {
body, err := os.ReadFile(file)
if err != nil {
return nil, err
}
f := &tplFile{
abspath: file,
path: strings.TrimPrefix(filepath.ToSlash(file), dir),
}
r := bufio.NewReader(bytes.NewReader(body))
line, _, err := r.ReadLine()
if err != nil && err != io.EOF {
return nil, err
}
m := re.FindSubmatch(line)
if m != nil {
s := string(m[2])
f.parent = &s
f.content = body[len(line):]
return f, nil
}
f.content = body
return f, nil
}