gigaparsec/internal/bindgen/bindgen.go

130 lines
2.1 KiB
Go
Raw Normal View History

// SPDX-License-Identifier: Unlicense
2024-09-14 00:28:38 +00:00
package main
import (
2024-09-14 03:03:10 +00:00
"bytes"
2024-09-14 00:28:38 +00:00
_ "embed"
"errors"
"flag"
"fmt"
2024-09-14 03:03:10 +00:00
"go/format"
2024-09-14 00:28:38 +00:00
"os"
"strconv"
"text/template"
)
//go:embed bind.go.tmpl
var bind string
2024-09-14 02:48:33 +00:00
//go:embed seq.go.tmpl
var seq string
var bindTmpl, seqTmpl *template.Template
2024-09-14 00:28:38 +00:00
func main() {
err := run()
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
2024-09-14 02:48:33 +00:00
bindPath := flag.String("bindpath", "", "bind file path")
seqPath := flag.String("seqpath", "", "seq file path")
2024-09-14 00:28:38 +00:00
maxBindLen := flag.Int("max", 0, "max bind length")
pkg := flag.String("pkg", "", "output package")
flag.Parse()
2024-09-14 02:48:33 +00:00
if *bindPath == "" {
return errors.New("bindpath required")
}
if *seqPath == "" {
return errors.New("seqpath required")
2024-09-14 00:28:38 +00:00
}
if *maxBindLen == 0 {
return errors.New("maxbind required")
}
if *pkg == "" {
return errors.New("pkg required")
}
2024-09-14 02:48:33 +00:00
bindTmpl = template.Must(template.New("bind").Parse(bind))
seqTmpl = template.Must(template.New("seq").Parse(seq))
2024-09-14 00:28:38 +00:00
data := File{
Package: *pkg,
Counter: Counter(*maxBindLen),
}
2024-09-14 03:03:10 +00:00
err := genCodeFile(*bindPath, bindTmpl, data)
2024-09-14 02:48:33 +00:00
if err != nil {
return err
}
2024-09-14 03:03:10 +00:00
return genCodeFile(*seqPath, seqTmpl, data)
}
2024-09-14 02:48:33 +00:00
2024-09-14 03:03:10 +00:00
func genCodeFile(path string, tmpl *template.Template, data any) error {
var buf bytes.Buffer
err := tmpl.Execute(&buf, data)
2024-09-14 02:48:33 +00:00
if err != nil {
return err
}
2024-09-14 03:03:10 +00:00
src, err := format.Source(buf.Bytes())
if err != nil {
return err
}
return os.WriteFile(path, src, 0777)
2024-09-14 00:28:38 +00:00
}
type File struct {
Package string
Counter
}
// func (f File) Funcs() []Func {
// counters := f.Max.Count()
// funcs := make([]Func, len(counters))
// for i, counter := range counters {
// funcs[i] = Func{
// Max: f.Max,
// Length: counter,
// }
// }
// return funcs
// }
type Func struct {
Max Counter
Length Counter
}
type Counter int
func (c Counter) String() string {
if c == 1 {
return ""
}
return strconv.Itoa(int(c))
}
func (c Counter) Int() int {
return int(c)
}
func (c Counter) Next() Counter {
return c + 1
}
func (c Counter) Prev() Counter {
return c - 1
}
func (c Counter) Count() []Counter {
a := make([]Counter, c)
for i := range a {
a[i] = Counter(i + 1)
}
return a
}