Example #1
0
func getSourceFiles(pkgPath string, deep bool) ([]string, error) {
	pkgDir, err := os.Open(pkgPath)
	if err != nil {
		util.Err("error while opening package at path [%s]\n%v", pkgPath, err)
		return nil, err
	}

	filesInfos, err := pkgDir.Readdir(0)
	if err != nil {
		util.Err("error reading opening package at path [%s]\n%v", pkgPath, err)
		return nil, err
	}

	var files []string
	for _, f := range filesInfos {
		if f.IsDir() && deep && isValidSourceDir(f.Name()) {
			util.Debug("append folder [%s]", f.Name())
			dirFiles, err := getSourceFiles(pkgPath+"/"+f.Name(), true)
			if err != nil {
				return dirFiles, err
			}
			files = append(files, dirFiles...)
		} else if isValidSourceFile(f.Name()) {
			util.Debug("append file [%s]", f.Name())
			if strings.HasSuffix(f.Name(), "_test.go") {
				files = append(files, pkgPath+"/"+f.Name())
			} else {
				files = append([]string{pkgPath + "/" + f.Name()}, files...)
			}
		}
	}
	util.Info("FILES [%v]", files)

	return files, nil
}
Example #2
0
//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)
	}
}