ucl/cmd/gendocs/main.go

72 lines
1.3 KiB
Go
Raw Normal View History

2025-01-18 05:02:35 +00:00
package main
import (
"bytes"
"embed"
"flag"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/parser"
"go.abhg.dev/goldmark/frontmatter"
"html/template"
"log"
"os"
2025-01-18 23:11:55 +00:00
"path/filepath"
2025-01-18 05:02:35 +00:00
)
//go:embed frame.tmpl
var frameTmpl embed.FS
func main() {
flag.Parse()
2025-01-18 23:11:55 +00:00
if flag.NArg() != 2 {
log.Fatalln("usage: gendocs MARKDOWN OUTFILE")
2025-01-18 05:02:35 +00:00
}
2025-01-18 23:11:55 +00:00
srcFile := flag.Arg(0)
dstFile := flag.Arg(1)
2025-01-18 05:02:35 +00:00
md := goldmark.New(goldmark.WithExtensions(&frontmatter.Extender{}))
2025-01-18 23:11:55 +00:00
mdData, err := os.ReadFile(srcFile)
2025-01-18 05:02:35 +00:00
if err != nil {
log.Fatal(err)
}
ctx := parser.NewContext()
var buf bytes.Buffer
if err := md.Convert(mdData, &buf, parser.WithContext(ctx)); err != nil {
log.Fatal(err)
}
var frontMatter struct {
Title string `yaml:"title"`
}
if fm := frontmatter.Get(ctx); fm != nil {
if err := fm.Decode(&frontMatter); err != nil {
log.Fatal(err)
}
}
frameTmpls, err := template.ParseFS(frameTmpl, "*.tmpl")
if err != nil {
log.Fatal(err)
}
var res bytes.Buffer
if err := frameTmpls.ExecuteTemplate(&res, "frame.tmpl", map[string]interface{}{
"Title": frontMatter.Title,
"Body": template.HTML(buf.Bytes()),
}); err != nil {
log.Fatal(err)
}
2025-01-18 23:11:55 +00:00
destDir := filepath.Dir(dstFile)
if err := os.MkdirAll(destDir, 0755); err != nil {
log.Fatal(err)
}
if err := os.WriteFile(dstFile, res.Bytes(), 0644); err != nil {
log.Fatal(err)
}
2025-01-18 05:02:35 +00:00
}