gopp/main.go

84 lines
1.4 KiB
Go
Raw Normal View History

package tpp
2024-02-26 00:22:09 +03:00
import (
//"fmt"
"bytes"
"context"
2024-02-26 00:22:09 +03:00
)
2024-02-26 00:22:09 +03:00
type Preprocessor struct {
tengo *Tengo
tags [2][]byte
2024-02-26 00:22:09 +03:00
}
// Get the new preprocessor with default options.
func New(tengo *Tengo ) *Preprocessor {
pp := &Preprocessor{}
pp.tengo = tengo
pp.tags = [2][]byte{
[]byte("{{"),
[]byte("}}"),
2024-02-26 00:22:09 +03:00
}
return pp
}
func (pp *Preprocessor) Process(
ctx context.Context,
recompile bool,
filePath string,
data []byte,
) ([]byte, error) {
var b bytes.Buffer
2024-02-26 00:22:09 +03:00
last := 0
texts := [][]byte{}
codes := [][]byte{}
2024-02-26 00:22:09 +03:00
for {
idxStart := bytes.Index(data[last:], pp.tags[0])
idxEnd := bytes.Index(data[last:], pp.tags[1])
2024-02-26 00:22:09 +03:00
//fmt.Printf("cock %d %d %d\n", last, idxStart, idxEnd)
if idxStart < 0 {
if idxEnd >= 0 {
return nil, UnexpectedError{
2024-02-26 00:22:09 +03:00
What: "end tag",
}
}
texts = append(texts, data[last:])
2024-02-26 00:22:09 +03:00
break
} else if idxEnd < 0 {
return nil, UnexpectedError{
2024-02-26 00:22:09 +03:00
What: "start tag",
}
}
text := data[last:idxStart]
texts = append(texts, text)
2024-02-26 00:22:09 +03:00
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.tengo.Eval(
ctx,
recompile,
filePath,
codes,
)
if err != nil {
return nil, err
}
for i, codeRet := range codeRets {
b.Write(texts[i])
b.Write(codeRet)
2024-02-26 00:22:09 +03:00
}
b.Write(texts[len(codeRets)])
2024-02-26 00:22:09 +03:00
return b.Bytes(), nil
2024-02-26 00:22:09 +03:00
}