Newer
Older
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
/*
Copyright © 2021 da/net Research Group <danet@h-da.de>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package cmd
import (
"fmt"
"os"
"strings"
"code.fbi.h-da.de/danet/gosdn/api/go/gosdn/pnd"
"code.fbi.h-da.de/danet/gosdn/cli/completer"
"github.com/c-bata/go-prompt"
"github.com/google/uuid"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
var suggestions []prompt.Suggest
type promptCompleter struct {
//NOTE: not too sure about this but for now it should be sufficient
deviceId uuid.UUID
yangSchemaCompleterMap map[uuid.UUID]*completer.YangSchemaCompleter
}
func NewPromptCompleter() *promptCompleter {
return &promptCompleter{
yangSchemaCompleterMap: make(map[uuid.UUID]*completer.YangSchemaCompleter),
}
}
func (pc *promptCompleter) Run() {
fmt.Println("Welcome to the interactive mode of gosdnc.")
defer fmt.Println("Bye!")
p := prompt.New(
executeFunc,
pc.cstmCompleter,
prompt.OptionTitle("gosdnc-prompt: interactive gosdn CLI"),
prompt.OptionPrefix(">>> "),
prompt.OptionCompletionWordSeparator(completer.YangSchemaCompletionSeperator),
prompt.OptionShowCompletionAtStart(),
prompt.OptionSuggestionBGColor(prompt.DarkBlue),
prompt.OptionSuggestionTextColor(prompt.DarkGray),
prompt.OptionDescriptionTextColor(prompt.White),
prompt.OptionDescriptionBGColor(prompt.DarkGray),
prompt.OptionSelectedSuggestionBGColor(prompt.DarkRed),
prompt.OptionSelectedSuggestionTextColor(prompt.DarkGray),
prompt.OptionSelectedDescriptionBGColor(prompt.DarkGray),
prompt.OptionSelectedDescriptionTextColor(prompt.White),
)
p.Run()
}
func executeFunc(s string) {
if s := strings.TrimSpace(s); s == "" {
return
}
rootCmd.SetArgs(strings.Fields(s))
err := rootCmd.Execute()
if err != nil {
fmt.Fprintln(os.Stderr, "Could not execute:", err)
}
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
}
func flagVisitor(f *pflag.Flag) {
if !f.Hidden {
suggestions = append(suggestions, prompt.Suggest{Text: "--" + f.Name, Description: f.Usage})
}
}
func (pc *promptCompleter) cstmCompleter(d prompt.Document) []prompt.Suggest {
// Start with the cobra 'rootCmd' and walk through it
// Reference: https://github.com/stromland/cobra-prompt
currCmd := rootCmd
inputSplit := removeFlagsFromInputSlice(strings.Fields(d.CurrentLine()))
if c, _, err := currCmd.Find(inputSplit); err == nil {
currCmd = c
}
return completionBasedOnCmd(pc, currCmd, inputSplit, d)
}
func removeFlagsFromInputSlice(input []string) []string {
r := []string{}
for _, in := range input {
if !strings.HasPrefix(in, "--") {
r = append(r, in)
}
}
return r
}
func deviceGetCompletion(c *promptCompleter, d prompt.Document, inputSplit []string) []prompt.Suggest {
inputLen := len(inputSplit)
if inputLen == 2 || inputLen == 3 {
if id, err := uuid.Parse(inputSplit[inputLen-1]); err == nil {
if c, ok := c.yangSchemaCompleterMap[id]; ok {
return c.Complete(d)
}
dev, err := pndAdapter.GetDevice(id.String())
if err != nil {
return []prompt.Suggest{}
}
sid, err := uuid.Parse(dev[0].GetSbi().GetId())
if err != nil {
return []prompt.Suggest{}
}
schemaTree, err := pndAdapter.GetSbiSchemaTree(sid)
if err != nil {
return []prompt.Suggest{}
}
c.yangSchemaCompleterMap[id] = completer.NewYangSchemaCompleter(schemaTree["Device"], true)
if yc, ok := c.yangSchemaCompleterMap[id]; ok {
c.deviceId = id
return yc.Complete(d)
}
return []prompt.Suggest{}
}
if inputLen == 2 || (inputLen == 3 && !(d.GetWordBeforeCursor() == "")) {
return prompt.FilterHasPrefix(getDevices(), d.GetWordBeforeCursor(), true)
}
} else {
if yc, ok := c.yangSchemaCompleterMap[c.deviceId]; ok {
return yc.Complete(d)
}
return []prompt.Suggest{}
}
return []prompt.Suggest{}
}
func cobraCommandCompletion(currCmd *cobra.Command, d prompt.Document, loaded []prompt.Suggest) []prompt.Suggest {
suggestions = []prompt.Suggest{}
if len(loaded) > 0 {
suggestions = append(suggestions, loaded...)
}
if currCmd.HasAvailableFlags() {
// it would be possible to always show the inherited flags, but i think
// this is currently not necessary.
// currCmd.InheritedFlags().VisitAll(flagVisitor)
currCmd.LocalFlags().VisitAll(flagVisitor)
}
for _, cmd := range currCmd.Commands() {
suggestions = append(suggestions, prompt.Suggest{Text: cmd.Name(), Description: cmd.Short})
}
return prompt.FilterHasPrefix(suggestions, d.GetWordBeforeCursor(), true)
}
func completionBasedOnCmd(c *promptCompleter, cmd *cobra.Command, inputSplit []string, d prompt.Document) []prompt.Suggest {
switch cmd {
case pndUseCmd, pndGetCmd:
return cobraCommandCompletion(cmd, d, getPnds())
case commitCmd:
return getChangesByType(pnd.ChangeState_CHANGE_STATE_PENDING)
case confirmCmd:
return getChangesByType(pnd.ChangeState_CHANGE_STATE_COMMITTED)
case deviceGetCmd, deviceSetCmd:
return deviceGetCompletion(c, d, inputSplit)
case deviceShowCmd:
return getDevices()
default:
return cobraCommandCompletion(cmd, d, []prompt.Suggest{})
}
}
var exitCmd = &cobra.Command{
Use: "exit",
Short: "The exit command exits the interactive prompt mode.",
Long: `The exit command exits the interactive prompt mode.`,
RunE: func(cmd *cobra.Command, args []string) error {
os.Exit(0)
return nil
},
}
// deviceListCmd represents the listDevice command
var promptCmd = &cobra.Command{
Use: "prompt",
Short: "The prompt command runs the CLI in an interactive shell.",
Long: `The prompt command rund the CLI in an interactive shell and
provides the user with autocompletion and more...`,
RunE: func(cmd *cobra.Command, args []string) error {
c := NewPromptCompleter()
c.Run()
return nil
},
}
func init() {
rootCmd.AddCommand(promptCmd)
rootCmd.AddCommand(exitCmd)
}