-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugins.go
65 lines (57 loc) · 1.86 KB
/
plugins.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package golib
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strings"
)
const gopathPluginDir = "bin"
// PluginSearchPath returns a list of directories that can be used to search for plugins.
// It contains all directories from the PATH environment variable, all bin/ subdirectories of
// the GOPATH environment variable, the current working directory and the directory of the
// current executable. The result is sorted and does not contain duplicates.
func PluginSearchPath() ([]string, error) {
// Search all PATH directories
paths := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator))
// Search all bin/ directories in GOPATH
for _, gopath := range strings.Split(os.Getenv("GOPATH"), string(os.PathListSeparator)) {
paths = append(paths, path.Join(gopath, gopathPluginDir))
}
// Search the current working directory
wd, err := os.Getwd()
if err != nil {
return nil, err
}
paths = append(paths, wd)
// Search the directory of the current executable
executableDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return nil, err
}
paths = append(paths, executableDir)
return RemoveDuplicates(paths), nil
}
// FindPrefixedFiles reads the contents of all given directories and returns a list of
// files with a basename that matches the given regex. It is intended to find
// plugin executables. All directories are processed, and a list of all encountered errors is returned.
func FindMatchingFiles(regex *regexp.Regexp, directories []string) (result []string, errs []error) {
for _, dir := range directories {
files, readErr := ioutil.ReadDir(dir)
if readErr != nil {
errs = append(errs, readErr)
continue
}
for _, file := range files {
if file.IsDir() {
continue
}
baseName := file.Name()
if regex.MatchString(baseName) {
result = append(result, path.Join(dir, baseName))
}
}
}
return
}