forked from robertkrimen/otto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (68 loc) · 1.74 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Command gen-tokens generates go representations of JavaScript tokens.
package main
import (
"embed"
"flag"
"fmt"
"log"
"os"
"os/exec"
"strings"
"text/template"
"gopkg.in/yaml.v3"
)
//go:embed .gen-tokens.yaml
var configData []byte
//go:embed templates/*
var templates embed.FS
// token represents a JavaScript token.
type token struct {
Group string `yaml:"group"`
Name string `yaml:"name"`
Symbol string `yaml:"symbol"`
Future bool `yaml:"future"`
Strict bool `yaml:"strict"`
}
// config represents our configuration.
type config struct {
Tokens []token `yaml:"tokens"`
}
// generate generates the context file writing the output to filename.
func generate(filename string) (err error) {
var cfg config
if err := yaml.Unmarshal(configData, &cfg); err != nil {
return fmt.Errorf("decode config: %w", err)
}
tmpl := template.New("base").Funcs(template.FuncMap{
"toLower": strings.ToLower,
})
tmpl, err = tmpl.ParseFS(templates, "templates/*.tmpl")
if err != nil {
return fmt.Errorf("parse templates: %w", err)
}
output, err := os.Create(filename) //nolint: gosec
if err != nil {
return fmt.Errorf("open output: %w", err)
}
defer func() {
if errc := output.Close(); err == nil && errc != nil {
err = errc
}
}()
if err := tmpl.ExecuteTemplate(output, "root.tmpl", cfg); err != nil {
return fmt.Errorf("execute template: %w", err)
}
cmd := exec.Command("gofmt", "-w", filename)
buf, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("format output %q: %w", string(buf), err)
}
return nil
}
func main() {
var filename string
flag.StringVar(&filename, "output", "token_const.go", "the filename to write the generated code to")
if err := generate(filename); err != nil {
log.Fatal(err)
}
}