syncfiles/gen/main.go
Dietrich Epp f2317d0ce7 Create build rules for generated data
Add flags to the generator code to specify the location of input and
output files.
2022-03-22 19:02:57 -04:00

113 lines
2.4 KiB
Go

package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"moria.us/macscript/charmap"
"moria.us/macscript/table"
)
const header = "/* This file is automatically generated. */\n"
var (
flagDest string
flagSrc string
flagQuiet bool
)
func getSrcdir() (string, error) {
if flagSrc != "" {
return flagSrc, nil
}
exe, err := os.Executable()
if err != nil {
return "", err
}
return filepath.Dir(filepath.Dir(exe)), nil
}
func mainE() error {
srcdir, err := getSrcdir()
if err != nil {
return fmt.Errorf("could not find source dir: %v", err)
}
destdir := flagDest
if destdir == "" {
destdir = filepath.Join(srcdir, "src")
}
// Read metadata.
d, err := readData(srcdir)
if err != nil {
return err
}
// Compile and emit charmap data.
cms := make([]string, len(d.charmaps))
var hascmap bool
for i, c := range d.charmaps {
if c.file == "" {
continue
}
cm, err := charmap.ReadFile(filepath.Join(srcdir, "charmap", c.file))
if err != nil {
return err
}
t, err := table.Create(cm)
if err != nil {
if e, ok := err.(*table.UnsupportedError); ok {
if !flagQuiet {
fmt.Fprintf(os.Stderr, "Warning: unsupported charmap %q: %s\n", c.file, e.Message)
}
continue
}
return fmt.Errorf("%s: %v", c.file, err)
}
data := t.Data()
name := "charmap_" + strings.ToLower(strings.TrimSuffix(c.file, ".TXT")) + ".dat"
fpath := filepath.Join(destdir, name)
if !flagQuiet {
fmt.Fprintln(os.Stderr, "Writing:", fpath)
}
if err := ioutil.WriteFile(fpath, data, 0666); err != nil {
return err
}
cms[i] = name
hascmap = true
}
if !hascmap {
return errors.New("could not compile any character map")
}
// Write generated output.
m := genMap(&d)
if err := writeMap(&d, m, filepath.Join(destdir, "charmap.c")); err != nil {
return err
}
if err := writeRez(&d, cms, filepath.Join(destdir, "charmap.r")); err != nil {
return err
}
return nil
}
func main() {
flag.StringVar(&flagDest, "dest", "", "output directory")
flag.StringVar(&flagSrc, "src", "", "source directory")
flag.BoolVar(&flagQuiet, "quiet", false, "only output error messages")
flag.Parse()
if args := flag.Args(); len(args) != 0 {
fmt.Fprintf(os.Stderr, "Error: unexpected argument: %q\n", args[0])
os.Exit(2)
}
if err := mainE(); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
}