github.com/divan/complete@v0.0.0-20170515130636-337e95201af7/gocomplete/tests.go (about)

     1  package main
     2  
     3  import (
     4  	"go/ast"
     5  	"go/parser"
     6  	"go/token"
     7  	"os"
     8  	"path/filepath"
     9  	"strings"
    10  
    11  	"github.com/posener/complete"
    12  	"github.com/posener/complete/match"
    13  )
    14  
    15  // predictTest predict test names.
    16  // it searches in the current directory for all the go test files
    17  // and then all the relevant function names.
    18  // for test names use prefix of 'Test' or 'Example', and for benchmark
    19  // test names use 'Benchmark'
    20  func predictTest(funcPrefix ...string) complete.Predictor {
    21  	return complete.PredictFunc(func(a complete.Args) (prediction []string) {
    22  		tests := testNames(funcPrefix)
    23  		for _, t := range tests {
    24  			if match.Prefix(t, a.Last) {
    25  				prediction = append(prediction, t)
    26  			}
    27  		}
    28  		return
    29  	})
    30  }
    31  
    32  // get all test names in current directory
    33  func testNames(funcPrefix []string) (tests []string) {
    34  	filepath.Walk("./", func(path string, info os.FileInfo, err error) error {
    35  		// if not a test file, skip
    36  		if !strings.HasSuffix(path, "_test.go") {
    37  			return nil
    38  		}
    39  		// inspect test file and append all the test names
    40  		tests = append(tests, testsInFile(funcPrefix, path)...)
    41  		return nil
    42  	})
    43  	return
    44  }
    45  
    46  func testsInFile(funcPrefix []string, path string) (tests []string) {
    47  	fset := token.NewFileSet()
    48  	f, err := parser.ParseFile(fset, path, nil, 0)
    49  	if err != nil {
    50  		complete.Log("Failed parsing %s: %s", path, err)
    51  		return nil
    52  	}
    53  	for _, d := range f.Decls {
    54  		if f, ok := d.(*ast.FuncDecl); ok {
    55  			name := f.Name.String()
    56  			for _, prefix := range funcPrefix {
    57  				if strings.HasPrefix(name, prefix) {
    58  					tests = append(tests, name)
    59  					break
    60  				}
    61  			}
    62  		}
    63  	}
    64  	return
    65  }