Add embedded hourly report template assets
This commit is contained in:
60
internal/reporttemplate/reporttemplate.go
Normal file
60
internal/reporttemplate/reporttemplate.go
Normal file
@@ -0,0 +1,60 @@
|
||||
// Package reporttemplate provides embedded Markdown templates and schemas.
|
||||
package reporttemplate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"fmt"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
//go:embed templates/*.md.tmpl schemas/*.schema.json
|
||||
var assets embed.FS
|
||||
|
||||
var templates = map[string]string{
|
||||
"hourly": "templates/hourly.md.tmpl",
|
||||
}
|
||||
|
||||
var schemas = map[string]string{
|
||||
"hourly": "schemas/hourly.generated_text.schema.json",
|
||||
}
|
||||
|
||||
func Template(id string) (string, error) {
|
||||
path, ok := templates[id]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("unknown report template %q", id)
|
||||
}
|
||||
data, err := assets.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read report template %q: %w", id, err)
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func Schema(id string) ([]byte, error) {
|
||||
path, ok := schemas[id]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown generated text schema %q", id)
|
||||
}
|
||||
data, err := assets.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read generated text schema %q: %w", id, err)
|
||||
}
|
||||
return append([]byte(nil), data...), nil
|
||||
}
|
||||
|
||||
func Render(id string, data any) ([]byte, error) {
|
||||
source, err := Template(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tmpl, err := template.New(id).Option("missingkey=error").Parse(source)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse report template %q: %w", id, err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := tmpl.Execute(&out, data); err != nil {
|
||||
return nil, fmt.Errorf("render report template %q: %w", id, err)
|
||||
}
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
Reference in New Issue
Block a user