-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcompletions.go
More file actions
82 lines (64 loc) · 2.25 KB
/
completions.go
File metadata and controls
82 lines (64 loc) · 2.25 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
package exoskeleton
import (
"strings"
"github.com/square/exoskeleton/v2/pkg/shellcomp"
)
// CompleteCommands is a CompleteFunc that provides completions for command names.
// It is used by commands like 'help' and 'which' which expect their arguments
// to be command names.
func CompleteCommands(e *Entrypoint, args, env []string) ([]string, shellcomp.Directive, error) {
return e.completionsFor(args, env, false)
}
// CompleteFiles is a CompleteFunc that provides completions for files and paths.
func CompleteFiles(e *Entrypoint, args, env []string) ([]string, shellcomp.Directive, error) {
return nil, shellcomp.DirectiveDefault, nil
}
func (e *Entrypoint) completionsFor(args, env []string, completeArgs bool) ([]string, shellcomp.Directive, error) {
if len(args) == 0 {
return nil, shellcomp.DirectiveNoFileComp, nil
}
// The last argument, which is not completely typed by the user,
// should not be part of the list of arguments
toComplete := args[len(args)-1]
trimmedArgs := args[:len(args)-1]
// Find the real command for which completion must be performed
finalCmd, finalCmdArgs, err := e.Identify(trimmedArgs)
if err != nil {
return nil, shellcomp.DirectiveError, err
}
if subcmds, _ := finalCmd.Subcommands(); len(subcmds) == 0 && !completeArgs {
return nil, shellcomp.DirectiveNoFileComp, nil
}
return finalCmd.Complete(e, append(finalCmdArgs, toComplete), env)
}
func completionsForSubcommands(cmd Command, args []string) ([]string, shellcomp.Directive, error) {
cmds, err := cmd.Subcommands()
if err != nil {
return nil, shellcomp.DirectiveError, err
}
return cmds.completionsFor(args)
}
func (c Commands) completionsFor(args []string) ([]string, shellcomp.Directive, error) {
var completions []string
if len(args) > 0 {
toComplete := args[0]
seen := make(map[string]bool)
for _, subcmd := range c {
name := subcmd.Name()
if seen[name] {
continue
}
seen[name] = true
if strings.HasPrefix(name, toComplete) {
completions = append(completions, name)
}
for _, alias := range subcmd.Aliases() {
if !seen[alias] && strings.HasPrefix(alias, toComplete) {
completions = append(completions, alias)
seen[alias] = true
}
}
}
}
return completions, shellcomp.DirectiveNoFileComp, nil
}