To address the issue of missing interface information and to include parameters and return values in the output, we need to adjust the parsing logic to correctly handle interface declarations and enhance the extraction of function/method signatures.
Here's the updated code:
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
sitter "github.com/smacker/go-tree-sitter"
golang "github.com/smacker/go-tree-sitter/golang"
)
func main() {
// Starting directory (you can modify this to any path)
startDir := "."
// Collect all Go files in the directory and its subdirectories
goFiles := []string{}
err := filepath.WalkDir(startDir, func(path string, d fs.DirEntry, err error) error {
if !d.IsDir() && strings.HasSuffix(d.Name(), ".go") {
goFiles = append(goFiles, path)
}
return nil
})
if err != nil {
panic(err)
}
// Parse and summarize each Go file
for _, filePath := range goFiles {
parseAndSummarizeFile(filePath)
}
}
func parseAndSummarizeFile(filePath string) {
// Read the file
source, err := os.ReadFile(filePath)
if err != nil {
fmt.Printf("Error reading %s: %v\n", filePath, err)
return
}
// Initialize the Tree-sitter parser
parser := sitter.NewParser()
parser.SetLanguage(golang.GetLanguage())
// Parse the source code
tree := parser.Parse(nil, source)
defer tree.Close()
// Print the structured summary
printSummary(tree.RootNode(), source, filePath)
}
func printSummary(rootNode *sitter.Node, source []byte, fileName string) {
relativePath, _ := filepath.Rel(".", fileName)
fmt.Printf("\n%s:\n", relativePath)
fmt.Println("⋮ ...")
// Traverse to find top-level declarations
cursor := sitter.NewTreeCursor(rootNode)
defer cursor.Close()
if !cursor.GoToFirstChild() {
return
}
// Find the 'source_file' node
for cursor.CurrentNode().Type() != "source_file" {
if !cursor.GoToFirstChild() {
break
}
}
if !cursor.GoToFirstChild() {
return
}
for {
node := cursor.CurrentNode()
switch node.Type() {
case "function_declaration":
printFunctionDeclaration(node, source, "")
case "method_declaration":
printFunctionDeclaration(node, source, "")
case "type_declaration":
printTypeDeclaration(node, source)
}
if !cursor.GoToNextSibling() {
break
}
}
}
func printTypeDeclaration(node *sitter.Node, source []byte) {
for i := 0; i < int(node.NamedChildCount()); i++ {
typeSpecNode := node.NamedChild(i)
if typeSpecNode.Type() != "type_spec" {
continue
}
nameNode := typeSpecNode.ChildByFieldName("name")
typeNode := typeSpecNode.ChildByFieldName("type")
if nameNode == nil || typeNode == nil {
continue
}
typeName := string(source[nameNode.StartByte():nameNode.EndByte()])
typeKind := typeNode.Type() // e.g., "struct_type", "interface_type"
switch typeKind {
case "struct_type":
fmt.Printf("│ struct %s:\n", typeName)
printStructFields(typeNode, source)
case "interface_type":
fmt.Printf("│ interface %s:\n", typeName)
printInterfaceMethods(typeNode, source)
default:
fmt.Printf("│ type %s\n", typeName)
}
}
}
func printStructFields(node *sitter.Node, source []byte) {
fieldList := node.ChildByFieldName("body")
if fieldList == nil {
return
}
for i := 0; i < int(fieldList.NamedChildCount()); i++ {
field := fieldList.NamedChild(i)
if field.Type() == "field_declaration" {
namesNode := field.ChildByFieldName("name")
if namesNode != nil {
for j := 0; j < int(namesNode.NamedChildCount()); j++ {
nameNode := namesNode.NamedChild(j)
fieldName := string(source[nameNode.StartByte():nameNode.EndByte()])
fmt.Printf("│ - %s\n", fieldName)
}
}
}
}
}
func printFunctionDeclaration(node *sitter.Node, source []byte, prefix string) {
nameNode := node.ChildByFieldName("name")
if nameNode == nil {
return
}
funcName := string(source[nameNode.StartByte():nameNode.EndByte()])
parametersNode := node.ChildByFieldName("parameters")
resultNode := node.ChildByFieldName("result")
parameters := extractParameters(parametersNode, source)
results := extractResults(resultNode, source)
receiverNode := node.ChildByFieldName("receiver")
if receiverNode != nil {
// Method on a type
receiverType := extractReceiverType(receiverNode, source)
fmt.Printf("%s│ method %s.%s(%s)", prefix, receiverType, funcName, parameters)
} else {
// Regular function
fmt.Printf("%s│ func %s(%s)", prefix, funcName, parameters)
}
if results != "" {
fmt.Printf(" %s", results)
}
fmt.Println()
}
func printInterfaceMethods(node *sitter.Node, source []byte) {
methodList := node.ChildByFieldName("body")
if methodList == nil {
return
}
for i := 0; i < int(methodList.NamedChildCount()); i++ {
method := methodList.NamedChild(i)
if method.Type() == "method_spec" {
nameNode := method.ChildByFieldName("name")
if nameNode != nil {
methodName := string(source[nameNode.StartByte():nameNode.EndByte()])
parametersNode := method.ChildByFieldName("parameters")
resultNode := method.ChildByFieldName("result")
parameters := extractParameters(parametersNode, source)
results := extractResults(resultNode, source)
fmt.Printf("│ - %s(%s)", methodName, parameters)
if results != "" {
fmt.Printf(" %s", results)
}
fmt.Println()
}
}
}
}
func extractParameters(node *sitter.Node, source []byte) string {
if node == nil {
return ""
}
paramText := string(source[node.StartByte():node.EndByte()])
return strings.Trim(paramText, "()")
}
func extractResults(node *sitter.Node, source []byte) string {
if node == nil {
return ""
}
resultText := strings.TrimSpace(string(source[node.StartByte():node.EndByte()]))
if node.Type() != "parameter_list" && !strings.HasPrefix(resultText, "(") {
// Single return type without parentheses
return resultText
}
return resultText
}
func extractReceiverType(node *sitter.Node, source []byte) string {
if node == nil {
return ""
}
param := node.NamedChild(0)
if param == nil {
return ""
}
typeNode := param.ChildByFieldName("type")
if typeNode != nil {
return string(source[typeNode.StartByte():typeNode.EndByte()])
}
return ""
}
Explanation of Changes:
-
Handling Interface Declarations:
- In the
printTypeDeclaration function, we adjusted the logic to iterate over each type_spec child node within a type_declaration.
- This ensures that we process each type specification individually, capturing interface declarations correctly.
-
Extracting Parameters and Return Types:
- We introduced helper functions
extractParameters, extractResults, and extractReceiverType to extract parameter lists, return types, and receiver types from the syntax tree.
- These functions take advantage of the source code to extract the relevant text segments, trimming parentheses where necessary.
-
Updating Function and Method Printing:
- The
printFunctionDeclaration and printInterfaceMethods functions now include parameters and return types in their output.
- We adjusted the print statements to conditionally include return types only when they are present.
-
Adjusting Tree Traversal:
- In the
printSummary function, we ensured that we traverse the AST correctly to find all top-level declarations, including interfaces and methods.
Sample Output:
Given a Go file example.go with the following content:
package example
type Printer interface {
Print(msg string)
Error(msg string) error
}
type MyStruct struct {
Name string
Age int
}
func (m *MyStruct) Speak() string {
return "Hello"
}
func DoSomething(a int, b string) (bool, error) {
return true, nil
}
Running the updated script would produce:
example.go:
⋮ ...
│ interface Printer:
│ - Print(msg string)
│ - Error(msg string) error
│ struct MyStruct:
│ - Name
│ - Age
│ method *MyStruct.Speak() string
│ func DoSomething(a int, b string) (bool, error)
This output aligns with the desired format, showing interfaces, structs, methods, functions, parameters, and return types.
This enhancement ensures that interfaces are included in the output and that parameters and return values are displayed, providing a more comprehensive summary of the Go code structure.