fix: malformed code pasted if reimplement is true

solution: replace go/ast with dst
This commit is contained in:
2025-02-16 14:35:50 +07:00
parent 86e4b9e977
commit e522f293c9
5 changed files with 128 additions and 95 deletions

View File

@@ -1,17 +1,21 @@
package internal
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
"github.com/dave/dst"
"github.com/dave/dst/decorator"
)
// GetStructNames reads all .go files from modelsDir and returns the names
// of all top-level struct types found, using the DST (dave/dst) library.
func GetStructNames(modelsDir string) ([]string, error) {
var structs []string
fset := token.NewFileSet()
fileSet := token.NewFileSet()
files, err := os.ReadDir(modelsDir)
if err != nil {
@@ -24,32 +28,37 @@ func GetStructNames(modelsDir string) ([]string, error) {
}
filePath := filepath.Join(modelsDir, file.Name())
fileAst, err := parser.ParseFile(fset, filePath, nil, parser.AllErrors)
// Using decorator.ParseFile from the DST library instead of parser.ParseFile
fileDst, err := decorator.ParseFile(fileSet, filePath, nil, parser.AllErrors)
if err != nil {
return nil, err
}
for _, decl := range fileAst.Decls {
genDecl, ok := decl.(*ast.GenDecl)
// Traverse the DST to find struct types
for _, decl := range fileDst.Decls {
genDecl, ok := decl.(*dst.GenDecl)
if !ok {
continue
}
// We only care about type declarations
if genDecl.Tok != token.TYPE {
continue
}
// Iterate over all type specs in the GenDecl
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
typeSpec, ok := spec.(*dst.TypeSpec)
if !ok {
continue
}
if _, ok := typeSpec.Type.(*ast.StructType); ok {
if typeSpec.Name != nil {
structs = append(structs, typeSpec.Name.Name)
}
// Check whether the type is a StructType
if _, ok := typeSpec.Type.(*dst.StructType); ok && typeSpec.Name != nil {
structs = append(structs, typeSpec.Name.Name)
}
}
}
}
return structs, nil
return structs, nil
}