forked from redhat-developer/odo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
84 lines (71 loc) · 2.09 KB
/
main.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
package main
import (
"flag"
"github.com/posener/complete"
"github.com/redhat-developer/odo/cmd"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func main() {
// create the complete command
root := cmd.RootCmd()
rootCmp := createCompletion(root)
cmp := complete.New("odo", rootCmp)
// AddFlags adds the completion flags to the program flags, specifying custom names
cmp.CLI.InstallName = "complete"
cmp.CLI.UninstallName = "uncomplete"
cmp.AddFlags(nil)
// add the completion flags to the root command, though they won't appear in completions
root.Flags().AddGoFlagSet(flag.CommandLine)
// override usage so that flag.Parse uses root command's usage instead of default one when invoked with -h
flag.Usage = usage
// parse the flags - both the program's flags and the completion flags
flag.Parse()
// run the completion, in case that the completion was invoked
// and ran as a completion script or handled a flag that passed
// as argument, the Run method will return true,
// in that case, our program have nothing to do and should return.
if cmp.Complete() {
return
}
// Call commands
cmd.Execute()
}
func usage() {
_ = cmd.RootCmd().Usage()
}
func createCompletion(root *cobra.Command) complete.Command {
rootCmp := complete.Command{}
rootCmp.Flags = make(complete.Flags)
addFlags := func(flag *pflag.Flag) {
if flag.Hidden {
return
}
var handler complete.Predictor
handler, ok := cmd.Suggesters[cmd.GetFlagSuggesterName(root, flag.Name)]
if !ok {
handler = complete.PredictAnything
}
if len(flag.Shorthand) > 0 {
rootCmp.Flags["-"+flag.Shorthand] = handler
}
rootCmp.Flags["--"+flag.Name] = handler
}
root.LocalFlags().VisitAll(addFlags)
root.InheritedFlags().VisitAll(addFlags)
if root.HasAvailableSubCommands() {
rootCmp.Sub = make(complete.Commands)
for _, c := range root.Commands() {
if !c.Hidden {
rootCmp.Sub[c.Name()] = createCompletion(c)
}
}
}
var handler complete.Predictor
handler, ok := cmd.Suggesters[cmd.GetCommandSuggesterName(root)]
if !ok {
handler = complete.PredictNothing
}
rootCmp.Args = handler
return rootCmp
}