package main
import (
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"os"
"path/filepath"
"sort"
"strings"
)
func main() {
dir := "."
if len (os .Args ) > 1 {
dir = os .Args [1 ]
}
files , err := filepath .Glob (filepath .Join (dir , "*_test.go" ))
if err != nil {
panic (err )
}
fset := token .NewFileSet ()
type method struct {
name string
res string
}
type strct struct {
name string
embeds []string
methods []method
}
strcts := map [string ]*strct {}
var order []string
for _ , file := range files {
if strings .HasPrefix (filepath .Base (file ), "mach_handlers" ) {
continue
}
f , err := parser .ParseFile (fset , file , nil , 0 )
if err != nil {
panic (err )
}
for _ , decl := range f .Decls {
switch d := decl .(type ) {
case *ast .GenDecl :
if d .Tok != token .TYPE {
continue
}
for _ , spec := range d .Specs {
ts , ok := spec .(*ast .TypeSpec )
if !ok {
continue
}
st , ok := ts .Type .(*ast .StructType )
if !ok {
continue
}
name := ts .Name .Name
s := &strct {name : name }
for _ , field := range st .Fields .List {
if len (field .Names ) == 0 {
s .embeds = append (s .embeds , exprString (field .Type ))
}
}
if _ , ok := strcts [name ]; !ok {
order = append (order , name )
}
strcts [name ] = s
}
case *ast .FuncDecl :
if d .Recv == nil || d .Name == nil || len (d .Recv .List ) != 1 {
continue
}
recv := exprString (d .Recv .List [0 ].Type )
if !strings .HasPrefix (recv , "*" ) {
continue
}
s , ok := strcts [strings .TrimPrefix (recv , "*" )]
if !ok {
continue
}
res := ""
if d .Type .Results != nil && len (d .Type .Results .List ) == 1 {
res = exprString (d .Type .Results .List [0 ].Type )
}
s .methods = append (s .methods , method {name : d .Name .Name , res : res })
}
}
}
states := map [string ]bool {}
for _ , s := range strcts {
for _ , m := range s .methods {
for _ , suf := range []string {"Enter" , "Exit" , "State" , "End" } {
if strings .HasSuffix (m .name , suf ) && len (m .name ) > len (suf ) {
if st := strings .TrimSuffix (m .name , suf ); st != "Any" {
states [st ] = true
}
}
}
if strings .HasPrefix (m .name , "Any" ) && len (m .name ) > len ("Any" ) {
switch st := strings .TrimPrefix (m .name , "Any" ); st {
case "Enter" , "State" :
default :
states [st ] = true
}
}
}
}
isHandler := func (name string ) (final bool , ok bool ) {
if !ast .IsExported (name ) {
return false , false
}
for _ , suf := range []string {"State" , "End" } {
if strings .HasSuffix (name , suf ) && len (name ) > len (suf ) {
return true , true
}
}
if name == "AnyState" {
return true , true
}
for _ , suf := range []string {"Enter" , "Exit" } {
if strings .HasSuffix (name , suf ) && len (name ) > len (suf ) {
return false , true
}
}
if name == "AnyEnter" {
return false , true
}
if strings .HasPrefix (name , "Any" ) && len (name ) > len ("Any" ) {
return false , true
}
for s1 := range states {
if !strings .HasPrefix (name , s1 ) {
continue
}
for s2 := range states {
if s1 +s2 == name {
return false , true
}
}
}
return false , false
}
buf := &strings .Builder {}
buf .WriteString ("// Code generated by go generate; DO NOT EDIT.\n\n" )
buf .WriteString ("package machine\n\n" )
buf .WriteString ("// testHandlerMaps provides map-based handler bindings " +
"for the test suite.\n" )
buf .WriteString ("type testHandlerMaps interface {\n" )
buf .WriteString ("\tnegotiations() map[string]HandlerNegotiation\n" )
buf .WriteString ("\tpartials() map[string]HandlerNegotiationPartial\n" )
buf .WriteString ("\tfinals() map[string]HandlerFinal\n" )
buf .WriteString ("}\n\n" )
buf .WriteString ("func bindHandlerMaps(\n" )
buf .WriteString ("\tm *Machine, h testHandlerMaps, opts ...BindOpts,\n" )
buf .WriteString (") (string, error) {\n" )
buf .WriteString ("\treturn m.HandlersBindMapsPartial(\n" )
buf .WriteString ("\t\th.negotiations(), h.partials(), h.finals(), opts...)\n" )
buf .WriteString ("}\n\n" )
sort .Strings (order )
for _ , name := range order {
if name == "ExceptionHandler" {
continue
}
s := strcts [name ]
var negs , partials , finals []string
for _ , m := range s .methods {
final , ok := isHandler (m .name )
if !ok {
continue
}
if final {
finals = append (finals , fmt .Sprintf ("%q: h.%s," , m .name , m .name ))
continue
}
switch m .res {
case "bool" :
negs = append (negs , fmt .Sprintf ("%q: h.%s," , m .name , m .name ))
case "S" :
partials = append (partials , fmt .Sprintf ("%q: h.%s," , m .name , m .name ))
default :
negs = append (negs , fmt .Sprintf (
"%q: func(e *Event) bool { h.%s(e); return true }," ,
m .name , m .name ))
}
}
for _ , e := range s .embeds {
if strings .HasSuffix (e , "ExceptionHandler" ) {
finals = append (finals , `"ExceptionState": h.ExceptionState,` )
}
}
if len (negs ) == 0 && len (partials ) == 0 && len (finals ) == 0 {
continue
}
sort .Strings (negs )
sort .Strings (partials )
sort .Strings (finals )
buf .WriteString (fmt .Sprintf (
"func (h *%s) negotiations() map[string]HandlerNegotiation {\n" , name ))
writeMap (buf , "HandlerNegotiation" , negs )
buf .WriteString ("}\n\n" )
buf .WriteString (fmt .Sprintf (
"func (h *%s) partials() map[string]HandlerNegotiationPartial {\n" , name ))
writeMap (buf , "HandlerNegotiationPartial" , partials )
buf .WriteString ("}\n\n" )
buf .WriteString (fmt .Sprintf (
"func (h *%s) finals() map[string]HandlerFinal {\n" , name ))
writeMap (buf , "HandlerFinal" , finals )
buf .WriteString ("}\n\n" )
}
src , err := format .Source ([]byte (buf .String ()))
if err != nil {
panic (err )
}
out := filepath .Join (dir , "mach_handlers_test.go" )
if err := os .WriteFile (out , src , 0644 ); err != nil {
panic (err )
}
}
func writeMap(buf *strings .Builder , typ string , entries []string ) {
if len (entries ) == 0 {
buf .WriteString ("\treturn nil\n" )
return
}
buf .WriteString (fmt .Sprintf ("\treturn map[string]%s{\n" , typ ))
for _ , e := range entries {
buf .WriteString ("\t\t" + e + "\n" )
}
buf .WriteString ("\t}\n" )
}
func exprString(e ast .Expr ) string {
switch t := e .(type ) {
case *ast .Ident :
return t .Name
case *ast .StarExpr :
return "*" + exprString (t .X )
case *ast .SelectorExpr :
return exprString (t .X ) + "." + t .Sel .Name
default :
return ""
}
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .