gopp/main.go

89 lines
1.6 KiB
Go
Raw Permalink Normal View History

package tpp
2024-02-26 00:22:09 +03:00
import (
"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
preTag 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
}
pp.preTag = '#'
2024-02-26 00:22:09 +03:00
return pp
}
func (pp *Preprocessor) Process(
ctx context.Context,
filePath string,
data []byte,
) (*Compiled, []byte, error) {
2024-06-09 14:51:03 +03:00
//var b bytes.Buffer
2024-05-22 13:16:07 +03:00
preCode := []byte(nil)
texts := [][]byte{}
codes := [][]byte{}
2024-05-22 13:16:07 +03:00
pref := append(pp.tags[0], pp.preTag)
if bytes.HasPrefix(data, pref) {
idxEnd := bytes.Index(data, pp.tags[1])
if idxEnd < 0 {
return nil, nil, UnexpectedError{
2024-05-22 13:16:07 +03:00
What: "pre-code start tag",
}
}
preCode = data[len(pref):idxEnd]
2024-06-09 15:51:45 +03:00
//texts = append(texts, []byte{})
2024-05-22 13:16:07 +03:00
data = data[idxEnd+len(pp.tags[1]):]
}
2024-02-26 00:22:09 +03:00
for {
idxStart := bytes.Index(data, pp.tags[0])
idxEnd := bytes.Index(data, 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, nil, UnexpectedError{
2024-02-26 00:22:09 +03:00
What: "end tag",
}
}
texts = append(texts, data)
2024-02-26 00:22:09 +03:00
break
} else if idxEnd < 0 {
return nil, nil, UnexpectedError{
2024-02-26 00:22:09 +03:00
What: "start tag",
}
}
text := data[:idxStart]
texts = append(texts, text)
2024-02-26 00:22:09 +03:00
code := data[idxStart+len(pp.tags[0]):idxEnd]
2024-05-22 13:16:07 +03:00
codes = append(codes, code)
data = data[idxEnd + len(pp.tags[1]):]
}
2024-05-22 13:16:07 +03:00
compiled, ret, err := pp.tengo.Eval(
ctx,
filePath,
2024-06-09 14:51:03 +03:00
texts,
2024-05-22 13:16:07 +03:00
preCode,
codes,
)
if err != nil {
return nil, nil, err
}
return compiled, ret, nil
2024-02-26 00:22:09 +03:00
}