gocomplete: improve package completion

This commit is contained in:
Eyal Posener 2017-05-19 11:59:51 +03:00
parent abde60c79d
commit 238b78ffd9
1 changed files with 23 additions and 39 deletions

View File

@ -3,64 +3,48 @@ package main
import ( import (
"go/build" "go/build"
"io/ioutil" "io/ioutil"
"os"
"path/filepath" "path/filepath"
"github.com/posener/complete" "github.com/posener/complete"
) )
// predictPackages completes packages in the directory pointed by a.Last
// and packages that are one level below that package.
func predictPackages(a complete.Args) (prediction []string) { func predictPackages(a complete.Args) (prediction []string) {
for { prediction = complete.PredictFilesSet(listPackages(a.Directory())).Predict(a)
prediction = complete.PredictFilesSet(listPackages(a)).Predict(a)
// if the number of prediction is not 1, we either have many results or
// have no results, so we return it.
if len(prediction) != 1 { if len(prediction) != 1 {
return return
} }
return complete.PredictFilesSet(listPackages(prediction[0])).Predict(a)
// if the result is only one item, we might want to recursively check
// for more accurate results.
if prediction[0] == a.Last {
return
} }
// only try deeper, if the one item is a directory // listPackages looks in current pointed dir and in all it's direct sub-packages
if stat, err := os.Stat(prediction[0]); err != nil || !stat.IsDir() { // and return a list of paths to go packages.
return func listPackages(dir string) (directories []string) {
} // add subdirectories
a.Last = prediction[0]
}
}
func listPackages(a complete.Args) (dirctories []string) {
dir := a.Directory()
complete.Log("listing packages in %s", dir)
// import current directory
pkg, err := build.ImportDir(dir, 0)
if err != nil {
complete.Log("failed importing directory %s: %s", dir, err)
return
}
dirctories = append(dirctories, pkg.Dir)
// import subdirectories
files, err := ioutil.ReadDir(dir) files, err := ioutil.ReadDir(dir)
if err != nil { if err != nil {
complete.Log("failed reading directory %s: %s", dir, err) complete.Log("failed reading directory %s: %s", dir, err)
return return
} }
// build paths array
paths := make([]string, 0, len(files)+1)
for _, f := range files { for _, f := range files {
if !f.IsDir() { if f.IsDir() {
continue paths = append(paths, filepath.Join(dir, f.Name()))
} }
pkg, err := build.ImportDir(filepath.Join(dir, f.Name()), 0) }
paths = append(paths, dir)
// import packages according to given paths
for _, p := range paths {
pkg, err := build.ImportDir(p, 0)
if err != nil { if err != nil {
complete.Log("failed importing subdirectory %s: %s", filepath.Join(dir, f.Name()), err) complete.Log("failed importing directory %s: %s", p, err)
continue continue
} }
dirctories = append(dirctories, pkg.Dir) directories = append(directories, pkg.Dir)
} }
return return
} }