//ExampleGetUnusedDefitions shows how to use gounexport package //to find all definition that not used in a package. As the result, //all unused definitions will be printed in console. func Example() { //package to check pkg := "github.com/dooman87/gounexport" //Regular expression to exclude //tests methods from the result. regex, _ := regexp.Compile("Test*") excludes := []*regexp.Regexp{regex} //Internal info structure that required for //ParsePackage call info := types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), } //Parsing package to fill info struct and //get file set. _, fset, err := gounexport.ParsePackage(pkg, &info) if err != nil { util.Err("error while parsing package %v", err) } //Analyze info and extract all definitions with usages. defs := gounexport.GetDefinitions(&info, fset) //Find all definitions that not used unusedDefs := gounexport.FindUnusedDefinitions(pkg, defs, excludes) //Print all unused definition to stdout. for _, d := range unusedDefs { util.Info("DEFINITION %s", d.Name) } }
func parsePackage(pkgStr string, t *testing.T) (*types.Package, *token.FileSet, *types.Info) { info := types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), } packag, fset, err := gounexport.ParsePackage(pkgStr, &info) if err != nil { t.Errorf("error while parsing package %v", err) } return packag, fset, &info }
func getUnusedDefinitions(pkg string, excludes []*regexp.Regexp) ( []*gounexport.Definition, map[string]*gounexport.Definition, error) { info := types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), } _, fset, err := gounexport.ParsePackage(pkg, &info) if err != nil { return nil, nil, err } defs := gounexport.GetDefinitions(&info, fset) return gounexport.FindUnusedDefinitions(pkg, defs, excludes), defs, nil }