Created
October 3, 2019 10:21
-
-
Save yowcow/fac906be4396fe1ec4138b6a231501b4 to your computer and use it in GitHub Desktop.
Struct scanner
This file contains hidden or 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 ( | |
"flag" | |
"fmt" | |
"go/ast" | |
"go/parser" | |
"go/token" | |
"io" | |
"os" | |
) | |
var file string | |
var help bool | |
func init() { | |
flag.StringVar(&file, "i", "", "input file") | |
flag.BoolVar(&help, "h", false, "show this help") | |
flag.Parse() | |
if help { | |
flag.Usage() | |
os.Exit(0) | |
} | |
} | |
type Summary map[string][]string | |
func newSummary() Summary { | |
return Summary{} | |
} | |
func (s Summary) Add(key, value string) { | |
if _, ok := s[key]; ok { | |
s[key] = append(s[key], value) | |
} else { | |
s[key] = []string{value} | |
} | |
} | |
func (s Summary) Write(w io.Writer) { | |
for k, names := range s { | |
fmt.Fprintf(w, "%s:\n", k) | |
for _, name := range names { | |
fmt.Fprintf(w, "\t%s\n", name) | |
} | |
} | |
} | |
func main() { | |
fset := token.NewFileSet() | |
f, err := parser.ParseFile(fset, file, nil, 0) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("~~ Hi!! ~~") | |
summary := newSummary() | |
for _, decl := range f.Decls { | |
dec, ok := decl.(*ast.GenDecl) | |
if !ok || dec.Tok != token.TYPE { | |
continue | |
} | |
for _, spec := range dec.Specs { | |
ty, ok := spec.(*ast.TypeSpec) | |
if !ok { | |
continue | |
} | |
structName := ty.Name.Name | |
st, ok := ty.Type.(*ast.StructType) | |
if !ok { | |
continue | |
} | |
for _, field := range st.Fields.List { | |
for _, name := range field.Names { | |
summary.Add(structName, name.Name) | |
} | |
} | |
} | |
} | |
summary.Write(os.Stdout) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment