hatmill/internal/elementgen/main.go

94 lines
1.9 KiB
Go

package main
import (
"bufio"
"bytes"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
"strings"
)
const (
inputPath = "elements.txt"
outputPath = "elements.go"
packageName = "hatmill"
parentType = "parent"
emptyType = "empty"
parentTemplate = `func %s(attribs ...Attrib) func(children ...Term) *ParentElement {
return func(children ...Term) *ParentElement {
return &ParentElement{
EmptyElement: EmptyElement{
TagName: "%s",
Attribs: attribs,
},
Children: children,
}
}
}
`
emptyTemplate = `func %s(attribs ...Attrib) EmptyElement {
return EmptyElement{
TagName: "%s",
Attribs: attribs,
}
}
`
)
func main() {
inputFile, err := os.Open(inputPath)
if err != nil {
log.Fatal(err)
}
defer inputFile.Close()
var output bytes.Buffer
fmt.Fprintln(&output, "// GENERATED BY gitlab.codemonkeysoftware.net/b/hatmill/internal/elementgen")
fmt.Fprintln(&output, "// DO NOT EDIT!\n")
fmt.Fprintln(&output, "package ", packageName, "\n")
scanner := bufio.NewScanner(inputFile)
for scanner.Scan() {
line := scanner.Text()
if line == "" {
continue
}
var tagName, elemType string
_, err = fmt.Sscanf(line, "%s %s", &tagName, &elemType)
if err != nil {
log.Fatalf("error parsing input line: %s", err)
}
var template string
switch elemType {
case parentType:
template = parentTemplate
case emptyType:
template = emptyTemplate
default:
log.Fatal("unknown element type: ", elemType)
}
fmt.Fprintf(&output, template, strings.Title(tagName), tagName)
}
if err := scanner.Err(); err != nil {
log.Fatalf("error scanning input: %s", err)
}
formatted, err := format.Source(output.Bytes())
if err != nil {
log.Fatalf("error formatting output: %s", err)
}
err = ioutil.WriteFile(outputPath, formatted, 0644)
if err != nil {
log.Fatalf("error writing output: %s", err)
}
}