-
Notifications
You must be signed in to change notification settings - Fork 12
/
autocomplete.go
99 lines (83 loc) · 2.03 KB
/
autocomplete.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package input_autocomplete
import (
"runtime"
"strings"
)
type autocomplete struct {
cmd DirListChecker
}
func Autocomplete(path string) []string {
os := runtime.GOOS
a := autocomplete{
cmd: Cmd{},
}
switch os {
case "linux", "darwin":
return a.unixAutocomplete(path)
case "windows":
return a.windowsAutocomplete(path)
default:
return []string{path}
}
}
func invalidPath(path string) bool {
if path == "" || strings.TrimSpace(path) == "" {
return true
}
return false
}
// Return if the string starts with prefix, case insensitive
func hasInsensitivePrefix(s string, prefix string) bool {
return len(s) >= len(prefix) && strings.EqualFold(s[0:len(prefix)], prefix)
}
func (a autocomplete) unixAutocomplete(path string) []string {
if invalidPath(path) {
return []string{path}
}
lastSlash := strings.LastIndex(path, "/")
if lastSlash == -1 || (path[0] != '/' && path[:2] != "./") {
path = "./" + path
if !strings.Contains(path, "/") {
lastSlash = 1
} else {
lastSlash = strings.LastIndex(path, "/")
}
}
return a.findFromPrefix(path, lastSlash, "/")
}
func (a autocomplete) windowsAutocomplete(path string) []string {
if invalidPath(path) {
return []string{path}
}
lastSlash := strings.LastIndex(path, "\\")
if !strings.Contains(path, ":") && !strings.Contains(path, ".\\") {
path = ".\\" + path
if !strings.Contains(path, "\\") {
lastSlash = 1
} else {
lastSlash = strings.LastIndex(path, "\\")
}
}
return a.findFromPrefix(path, lastSlash, "\\")
}
func (a autocomplete) findFromPrefix(prefix string, lastSlash int, sep string) []string {
contents, err := a.cmd.ListContent(prefix[:lastSlash+1])
if err != nil {
return []string{prefix}
}
var matches []string
for _, content := range contents {
if hasInsensitivePrefix(content, prefix[lastSlash+1:]) {
p := prefix[:lastSlash+1] + content
ok, err := a.cmd.IsDir(p)
if ok && err == nil {
p = p + sep
}
matches = append(matches, p)
}
}
if len(matches) == 0 {
matches = append(matches, prefix)
}
return matches
}