gopp/main.go

68 lines
1.3 KiB
Go

package pp
import (
"strings"
"fmt"
)
type Preprocessor struct {
evaler Evaler
tags [2]string
}
// Get the new preprocessor with default options.
func NewPp(evaler Evaler) *Preprocessor {
pp := &Preprocessor{
tags: evaler.Tags(),
}
pp.evaler = evaler
return pp
}
func (pp *Preprocessor) Process(filePath string, data string) (string, error) {
var b strings.Builder
last := 0
texts := []string{}
codes := []string{}
for {
idxStart := strings.Index(data[last:], pp.tags[0])
idxEnd := strings.Index(data[last:], pp.tags[1])
//fmt.Printf("cock %d %d %d\n", last, idxStart, idxEnd)
if idxStart < 0 {
if idxEnd >= 0 {
return "", UnexpectedError{
What: "end tag",
}
}
texts = append(texts, data[last:])
break
} else if idxEnd < 0 {
return "", UnexpectedError{
What: "start tag",
}
}
text := data[last:idxStart]
texts = append(texts, text)
code := data[idxStart+len(pp.tags[0]):idxEnd]
codes = append(codes, code)
data = data[idxEnd + len(pp.tags[1]):]
/*if len(data) > 0 && data[0] == '\n' {
data = data[1:]
}*/
}
codeRets, err := pp.evaler.Eval(filePath, codes)
if err != nil {
return "", err
}
for i, codeRet := range codeRets {
fmt.Fprint(&b, texts[i])
fmt.Fprintf(&b, codeRet)
}
fmt.Fprint(&b, texts[len(codeRets)])
return b.String(), nil
}