forked from imjerrybao/apex
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocomplete.go
112 lines (96 loc) · 2.02 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
100
101
102
103
104
105
106
107
108
109
110
111
112
// Package autocomplete generates bash auto-completion words.
package autocomplete
import (
"fmt"
"io/ioutil"
"github.com/tj/cobra"
flag "github.com/tj/pflag"
"github.com/apex/apex/cmd/apex/root"
"github.com/apex/apex/utils"
)
// funcCommands is a list of commands which
// accept function names as arguments.
var funcCommands = map[string]bool{
"build": true,
"delete": true,
"deploy": true,
"invoke": true,
"list": true,
"logs": true,
"metrics": true,
"rollback": true,
}
// Command config.
var Command = &cobra.Command{
Use: "autocomplete",
Short: "Generate bash auto-completion words",
PersistentPreRun: root.PreRunNoop,
Hidden: true,
Run: run,
}
// Initialize.
func init() {
root.Register(Command)
}
// Run command.
func run(c *cobra.Command, args []string) {
// TODO: works with flags inbetween?
if len(args) == 0 {
rootCommands()
flags(root.Command)
return
}
// find command, on error assume it's in-complete
// or missing and all root commands are shown
cmd := find(args[0])
if cmd == nil {
rootCommands()
flags(root.Command)
return
}
// command flags
flags(cmd)
// always show root flags
flags(root.Command)
// command accepts functions
if ok := funcCommands[cmd.Name()]; ok {
functions(args)
}
}
// find command by `name`.
func find(name string) *cobra.Command {
for _, cmd := range root.Command.Commands() {
if cmd.Name() == name {
return cmd
}
}
return nil
}
// output root commands.
func rootCommands() {
for _, cmd := range root.Command.Commands() {
if !cmd.Hidden {
fmt.Printf("%s ", cmd.Name())
}
}
}
// output flags.
func flags(cmd *cobra.Command) {
cmd.Flags().VisitAll(func(f *flag.Flag) {
if !f.Hidden {
fmt.Printf("--%s ", f.Name)
}
})
}
// output (deduped) functions.
func functions(args []string) {
files, err := ioutil.ReadDir("functions")
if err != nil {
return
}
for _, file := range files {
if !utils.ContainsString(args, file.Name()) {
fmt.Printf("%s ", file.Name())
}
}
}