2017-05-12 16:17:48 -05:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/posener/complete"
|
|
|
|
)
|
|
|
|
|
2017-05-15 14:44:19 -05:00
|
|
|
const goListFormat = `{"Name": "{{.Name}}", "Path": "{{.Dir}}", "FilesString": "{{.GoFiles}}"}`
|
2017-05-12 16:17:48 -05:00
|
|
|
|
2017-05-15 14:44:19 -05:00
|
|
|
func predictPackages(a complete.Args) (prediction []string) {
|
|
|
|
dir := a.Directory()
|
|
|
|
pkgs := listPackages(dir)
|
2017-05-12 16:17:48 -05:00
|
|
|
|
2017-05-15 14:44:19 -05:00
|
|
|
files := make([]string, 0, len(pkgs))
|
|
|
|
for _, p := range pkgs {
|
|
|
|
files = append(files, p.Path)
|
|
|
|
}
|
|
|
|
return complete.PredictFilesSet(files).Predict(a)
|
|
|
|
}
|
|
|
|
|
2017-05-12 16:17:48 -05:00
|
|
|
type pack struct {
|
2017-05-15 14:44:19 -05:00
|
|
|
Name string
|
|
|
|
Path string
|
|
|
|
FilesString string
|
|
|
|
Files []string
|
2017-05-12 16:17:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func listPackages(dir string) (pkgs []pack) {
|
2017-05-15 14:44:19 -05:00
|
|
|
dir = strings.TrimRight(dir, "/") + "/..."
|
2017-05-12 16:17:48 -05:00
|
|
|
out, err := exec.Command("go", "list", "-f", goListFormat, dir).Output()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
lines := bytes.Split(out, []byte("\n"))
|
|
|
|
for _, line := range lines {
|
|
|
|
var p pack
|
2017-05-15 14:44:19 -05:00
|
|
|
err := json.Unmarshal(line, &p)
|
|
|
|
if err != nil {
|
|
|
|
continue
|
2017-05-12 16:17:48 -05:00
|
|
|
}
|
2017-05-15 14:44:19 -05:00
|
|
|
// parse the FileString from a string "[file1 file2 file3]" to a list of files
|
|
|
|
p.Files = strings.Split(strings.Trim(p.FilesString, "[]"), " ")
|
|
|
|
pkgs = append(pkgs, p)
|
2017-05-12 16:17:48 -05:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|