github.com/pankona/gometalinter@v2.0.11+incompatible/_linters/src/4d63.com/gochecknoinits/check_no_init.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"go/ast"
     6  	"go/parser"
     7  	"go/token"
     8  	"os"
     9  	"path/filepath"
    10  	"strings"
    11  )
    12  
    13  func checkNoInits(rootPath string) ([]string, error) {
    14  	const recursiveSuffix = string(filepath.Separator) + "..."
    15  	recursive := false
    16  	if strings.HasSuffix(rootPath, recursiveSuffix) {
    17  		recursive = true
    18  		rootPath = rootPath[:len(rootPath)-len(recursiveSuffix)]
    19  	}
    20  
    21  	messages := []string{}
    22  
    23  	err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
    24  		if err != nil {
    25  			return err
    26  		}
    27  		if info.IsDir() {
    28  			if !recursive && path != rootPath {
    29  				return filepath.SkipDir
    30  			}
    31  			return nil
    32  		}
    33  		if !strings.HasSuffix(path, ".go") {
    34  			return nil
    35  		}
    36  
    37  		fset := token.NewFileSet()
    38  		file, err := parser.ParseFile(fset, path, nil, 0)
    39  		if err != nil {
    40  			return err
    41  		}
    42  
    43  		for _, decl := range file.Decls {
    44  			funcDecl, ok := decl.(*ast.FuncDecl)
    45  			if !ok {
    46  				continue
    47  			}
    48  			filename := fset.Position(funcDecl.Pos()).Filename
    49  			line := fset.Position(funcDecl.Pos()).Line
    50  			name := funcDecl.Name.Name
    51  			if name == "init" && funcDecl.Recv.NumFields() == 0 {
    52  				message := fmt.Sprintf("%s:%d %s function", filename, line, name)
    53  				messages = append(messages, message)
    54  			}
    55  		}
    56  		return nil
    57  	})
    58  
    59  	return messages, err
    60  }