72 lines
1.6 KiB
Go
72 lines
1.6 KiB
Go
|
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)
|
||
|
}
|