-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver.go
72 lines (64 loc) · 1.71 KB
/
resolver.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
package htmlr
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
)
var includeExpressionReg = regexp.MustCompile(`(?mi)\{% *include *["'](.*)["'] *%\}`)
func Resolve(input, output string) {
er := ioutil.WriteFile(output, resolve(input), 0765)
if er != nil {
panic(fmt.Sprintf("couldn't write resolved template to '%s'", output))
}
}
func resolve(input string) []byte {
return resolveIncludes(loadFile(input), filepath.Dir(input))
}
func resolveIncludes(src []byte, currentDir string) []byte {
return includeExpressionReg.ReplaceAllFunc(src, func(b []byte) []byte {
fpath := resolveFilePath(currentDir, extractPath(b))
return resolveIncludes(loadFile(fpath), filepath.Dir(fpath))
})
}
func resolveFilePath(dir, fpath string) string {
np := fpath
var err error
if _, err = os.Stat(np); errors.Is(err, os.ErrNotExist) {
np = filepath.Join(dir, np)
if _, err = os.Stat(np); errors.Is(err, os.ErrNotExist) {
np, err = filepath.Abs(fpath)
if err != nil {
np = filepath.Join(dir, fpath)
np, err = filepath.Abs(np)
if err != nil {
panic(fmt.Sprintf("couldn't find template '%s'", fpath))
}
}
if _, err = os.Stat(np); errors.Is(err, os.ErrNotExist) {
panic(fmt.Sprintf("couldn't find template '%s'", fpath))
}
}
}
return np
}
func loadFile(fpath string) []byte {
if fpath == "" {
panic(fmt.Sprintf("template file path cannot be empty '%s'", fpath))
}
src, er := fileToBytes(fpath)
if er != nil {
panic(fmt.Sprintf("couldn't find template '%s'", fpath))
}
return src
}
func extractPath(inclExpr []byte) string {
for _, match := range includeExpressionReg.FindAllSubmatch(inclExpr, -1) {
if len(match) >= 2 {
return string(match[1])
}
}
return ""
}