Implement func mapper for parser reflection
This commit is contained in:
71
api/funcmapper/funcmapper.go
Normal file
71
api/funcmapper/funcmapper.go
Normal file
@ -0,0 +1,71 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
// The package path you want to scan for functions
|
||||
const (
|
||||
packagePath = "api/" // Update this to your package path
|
||||
packageName = "eiaapi"
|
||||
mapperFile = "api/eiaapi_funcmap.gen.go"
|
||||
)
|
||||
|
||||
const tmplParseFuncs = `package ` + packageName + `
|
||||
|
||||
// Generated map of Parse functions to support
|
||||
// dynamic reflection upon parser functions
|
||||
var ParseFunctionsMap = map[string]interface{}{
|
||||
{{- range .}}
|
||||
"{{ . }}": {{ . }},
|
||||
{{- end}}
|
||||
}
|
||||
`
|
||||
|
||||
func main() {
|
||||
// Parse the package
|
||||
fset := token.NewFileSet()
|
||||
node, err := parser.ParseDir(fset, packagePath, nil, parser.ParseComments)
|
||||
if err != nil {
|
||||
fmt.Println("Error parsing package:", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Collect function names that start with "Parse"
|
||||
var functions []string
|
||||
for _, pkg := range node {
|
||||
for _, file := range pkg.Files {
|
||||
for _, decl := range file.Decls {
|
||||
if funcDecl, ok := decl.(*ast.FuncDecl); ok {
|
||||
if strings.HasPrefix(funcDecl.Name.Name, "Parse") {
|
||||
// Add function name to the list
|
||||
functions = append(functions, funcDecl.Name.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate Go code for the map
|
||||
mapFile, err := os.Create(mapperFile)
|
||||
if err != nil {
|
||||
fmt.Println("Error creating file:", err)
|
||||
return
|
||||
}
|
||||
defer mapFile.Close()
|
||||
|
||||
// Execute the template and write to the file
|
||||
t := template.Must(template.New("mapTemplate").Parse(tmplParseFuncs))
|
||||
if err := t.Execute(mapFile, functions); err != nil {
|
||||
fmt.Println("Error generating Go code:", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("%s has been generated successfully!\n", mapperFile)
|
||||
}
|
Reference in New Issue
Block a user