-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathautocomplete.go
More file actions
101 lines (84 loc) · 1.55 KB
/
Copy pathautocomplete.go
File metadata and controls
101 lines (84 loc) · 1.55 KB
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
100
101
package sh
import (
"path"
"strings"
"github.com/icexin/eggos/app"
"github.com/spf13/afero"
)
func autocompleteWrapper(ctx *app.Context) func(line string) []string {
return func(line string) []string {
return autocomplete(ctx, line)
}
}
func autocomplete(ctx *app.Context, line string) []string {
line = strings.TrimLeft(line, " ")
list := strings.Split(line, " ")
var (
last = ""
hascmd bool
l []string
)
if len(list) != 0 && list[0] == "go" {
list = list[1:]
}
switch len(list) {
case 0:
case 1:
last = list[0]
default:
hascmd = true
last = list[len(list)-1]
}
if !hascmd {
l = app.AppNames()
} else {
l = completeFile(ctx, last)
}
var r []string
for _, s := range l {
if strings.HasPrefix(s, last) {
r = append(r, line+strings.TrimPrefix(s, last))
}
}
return r
}
func completeFile(fs afero.Fs, prefix string) []string {
if prefix == "" {
prefix = "."
}
joinPrefix := func(dir string, l []string) []string {
for i := range l {
l[i] = path.Join(dir, l[i])
}
return l
}
f, err := fs.Open(prefix)
// user input a complete file name
if err == nil {
defer f.Close()
stat, err := f.Stat()
if err != nil {
return nil
}
if !stat.IsDir() {
return nil
}
names, err := f.Readdirnames(-1)
if err != nil {
return nil
}
return joinPrefix(prefix, names)
}
// complete dir entries
dir := path.Dir(prefix)
f, err = fs.Open(dir)
if err != nil {
return nil
}
defer f.Close()
names, err := f.Readdirnames(-1)
if err != nil {
return nil
}
return joinPrefix(dir, names)
}