examples/cmd/gen_examples/gen_examples.go

117 lines
2.6 KiB
Go

package main
import (
"fmt"
"os"
"strings"
"git.kotmisia.pl/Mm2PL/examples"
)
var currentFile *os.File
var sourceFiles = []string{
"irc.md",
"pubsub.md",
}
func main() {
var err error
currentFile, err = os.OpenFile("examples.go", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o744)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open output file for writing: %s\n", err)
return
}
currentFile.WriteString(
`package examples
// WARNING: this file was auto generated with cmd/gen_examples
import (
"math/rand"
)
// dummy keeps go from complaining about math/rand being unused
func dummy() int {
return rand.Intn(0)
}
`,
)
for _, file := range sourceFiles {
// fmt.Printf("Starting file #%d: %s\n", i, file)
f, err := os.Open(file)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open %s for reading: %s\n", file, err)
continue
}
exs, err := examples.ReadFile(f)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse %s: %s\n", file, err)
continue
}
var fnames []string
for i, example := range exs {
if i >= 1 {
lastEx := exs[i-1]
if lastEx.Path[len(lastEx.Path)-1] != example.Path[len(example.Path)-1] {
// changed header
currentFile.WriteString(genRandomFunction(fnames, lastEx.Path))
fnames = nil
}
}
code, fname := generateFunction(example)
_, err := currentFile.WriteString(code)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to write to output file: %s\n", err)
return
}
fnames = append(fnames, fname)
}
currentFile.WriteString(genRandomFunction(fnames, exs[len(exs)-1].Path))
}
}
func genPathName(input []string) string {
path := ""
for _, elem := range strings.Split(strings.Join(input, " "), " ") { // account for spaces
if elem == "" {
continue
}
temp := []rune(elem)
path += strings.ToUpper(string(temp[0])) + strings.ToLower(string(temp[1:]))
}
return path
}
func generateFunction(example examples.Example) (code string, fname string) {
fname = genPathName(example.Path) + example.Name
return fmt.Sprintf(
`
// %[2]s returns %[1]s
func %[2]s() string {
return %[3]q
}
`,
example.Comment,
fname,
example.Data,
), fname
}
func genRandomFunction(fnames []string, path []string) (code string) {
return fmt.Sprintf(
`
// Random%[1]s returns a random example from %[2]s
func Random%[1]s() string {
values := Examples%[1]s()
return values[rand.Intn(len(values))]
}
// Examples%[1]s returns all examples from %[2]s
func Examples%[1]s() []string {
return []string{
%[3]s(),
}
}
`,
genPathName(path),
strings.Join(path, " -> "),
strings.Join(fnames, "(),\n\t\t"),
)
}