Skip to content

Instantly share code, notes, and snippets.

@aaronlifton3
Created November 2, 2012 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronlifton3/91207c4e461de312391a to your computer and use it in GitHub Desktop.
Save aaronlifton3/91207c4e461de312391a to your computer and use it in GitHub Desktop.
inspect.go
package main
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"strings"
)
func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
fset = token.NewFileSet()
if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
for _, d := range file.Decls {
if f, ok := d.(*ast.FuncDecl); ok && f.Name.Name == functionname {
fun = f
return
}
}
}
panic("function not found")
}
func ExampleFprint() {
// Parse source file and extract the AST without comments for
// this function, with position information referring to the
// file set fset.
funcAST, fset := parseFunc("../gooo.go", "Test")
// Print the function body into buffer buf.
// The file set is provided to the printer so that it knows
// about the original source formatting and can add additional
// line breaks where they were present in the source.
var buf bytes.Buffer
printer.Fprint(&buf, fset, funcAST.Body)
// Remove braces {} enclosing the function body, unindent,
// and trim leading and trailing white space.
s := buf.String()
s = s[1 : len(s)-1]
s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1))
// Print the cleaned-up body text to stdout.
fmt.Println(s)
// output:
// funcAST, fset := parseFunc("example_test.go", "ExampleFprint")
//
// var buf bytes.Buffer
// printer.Fprint(&buf, fset, funcAST.Body)
//
// s := buf.String()
// s = s[1 : len(s)-1]
// s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1))
//
// fmt.Println(s)
}
func main() {
ExampleFprint()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment