Last active
April 28, 2022 17:29
-
-
Save louisbuchbinder/1a1912d7f8226c75366019c7f5c19c41 to your computer and use it in GitHub Desktop.
Parse Function Comments From Source in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"go/ast" | |
"go/parser" | |
"go/token" | |
"log" | |
) | |
func main() { | |
fset := token.NewFileSet() | |
filename := "" | |
src := ` | |
package example | |
var a int = 3 | |
// This is a function comment | |
// and it is continued on this line | |
func doThing() {} | |
` | |
f, err := parser.ParseFile(fset, filename, src, parser.ParseComments) | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
var fv funcVisitor | |
ast.Walk(&fv, f) | |
fmt.Println(fv) | |
} | |
type funcData struct { | |
identity string | |
comment string | |
} | |
type funcVisitor struct { | |
data []funcData | |
} | |
func (fv *funcVisitor) Visit(n ast.Node) ast.Visitor { | |
if val, ok := n.(*ast.FuncDecl); ok { | |
fv.data = append(fv.data, funcData{ | |
identity: val.Name.String(), | |
comment: val.Doc.Text(), | |
}) | |
} | |
return fv | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment