/
get_source.go
96 lines (80 loc) · 2.35 KB
/
get_source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package httptransport
import (
"bytes"
"fmt"
"reflect"
"runtime"
"strings"
"go/ast"
"go/parser"
"go/printer"
"go/token"
)
// FuncSourceCode returns a string representing the source code of the function
// provided to it.
func FuncSourceCode(val interface{}) (string, error) {
ptr := reflect.ValueOf(val).Pointer()
fpath, _ := runtime.FuncForPC(ptr).FileLine(ptr)
funcName := runtime.FuncForPC(ptr).Name()
parts := strings.Split(funcName, ".")
funcName = parts[len(parts)-1]
// Parse the go file into the ast
fset := token.NewFileSet()
fileAst, err := parser.ParseFile(fset, fpath, nil, parser.ParseComments)
if err != nil {
return "", fmt.Errorf("ERROR: go parser couldn't parse file '%v'\n", fpath)
}
// Search ast for function declaration with name of function passed
var fAst *ast.FuncDecl
for _, decs := range fileAst.Decls {
switch decs.(type) {
case *ast.FuncDecl:
f := decs.(*ast.FuncDecl)
if f.Name.String() == funcName {
fAst = f
}
}
}
code := bytes.NewBuffer(nil)
err = printer.Fprint(code, fset, fAst)
if err != nil {
return "", fmt.Errorf("couldn't print code for func '%v': %v\n", funcName, err)
}
return code.String(), nil
}
// AllFuncSourceCode returns the the source code for all the functions defined
// in the same file as the one provided, including the source of the function
// provided.
func AllFuncSourceCode(val interface{}) (string, error) {
ptr := reflect.ValueOf(val).Pointer()
fpath, _ := runtime.FuncForPC(ptr).FileLine(ptr)
funcName := runtime.FuncForPC(ptr).Name()
parts := strings.Split(funcName, ".")
funcName = parts[len(parts)-1]
// Parse the go file into the ast
fset := token.NewFileSet()
fileAst, err := parser.ParseFile(fset, fpath, nil, parser.ParseComments)
if err != nil {
return "", fmt.Errorf("ERROR: go parser couldn't parse file '%v'\n", fpath)
}
// Search ast for all function declarations
fncSlc := []*ast.FuncDecl{}
for _, decs := range fileAst.Decls {
switch decs.(type) {
case *ast.FuncDecl:
f := decs.(*ast.FuncDecl)
fncSlc = append(fncSlc, f)
}
}
rv := ""
// Append source of each function to rv
for _, fnc := range fncSlc {
code := bytes.NewBuffer(nil)
err = printer.Fprint(code, fset, fnc)
if err != nil {
return "", fmt.Errorf("couldn't print code for func '%v': %v\n", fnc.Name.String(), err)
}
rv += code.String() + "\n"
}
return rv, nil
}