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
|
package main
import (
"bytes"
"flag"
"go/parser"
"go/printer"
"go/ast"
"go/token"
"log"
"template"
"os"
)
var (
srcFn = flag.String("src", "", "source filename")
getName = flag.String("name", "", "func/type name to output")
html = flag.Bool("html", true, "output HTML")
showPkg = flag.Bool("pkg", false, "show package in output")
)
func main() {
// handle input
flag.Parse()
if *srcFn == "" || *getName == "" {
flag.Usage()
os.Exit(2)
}
// load file
fs := token.NewFileSet()
file, err := parser.ParseFile(fs, *srcFn, nil, 0)
if err != nil {
log.Fatal(err)
}
// create filter
filter := func(name string) bool {
return name == *getName
}
// filter
if !ast.FilterFile(file, filter) {
os.Exit(1)
}
// print the AST
var b bytes.Buffer
printer.Fprint(&b, fs, file)
// drop package declaration
if !*showPkg {
for {
c, err := b.ReadByte()
if c == '\n' || err != nil {
break
}
}
}
// drop leading newlines
for {
b, err := b.ReadByte()
if err != nil {
break
}
if b != '\n' {
os.Stdout.Write([]byte{b})
break
}
}
// output
if *html {
template.HTMLEscape(os.Stdout, b.Bytes())
} else {
b.WriteTo(os.Stdout)
}
}
|