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
/*
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"
)
// PromptCompleter provides completion for a device
type PromptCompleter struct {
//NOTE: not too sure about this but for now it should be sufficient
yangSchemaCompleterMap map[uuid.UUID]*completer.YangSchemaCompleter
}
// NewPromptCompleter returns a new promptCompleter
func NewPromptCompleter() *PromptCompleter {
return &PromptCompleter{
yangSchemaCompleterMap: make(map[uuid.UUID]*completer.YangSchemaCompleter),
}
}
// Run starts the interactive completion
func (pc *PromptCompleter) Run() {
title, _ := pterm.DefaultBigText.WithLetters(
pterm.NewLettersFromString("go"),
pterm.NewLettersFromStringWithStyle("SDN", pterm.NewStyle(pterm.FgCyan)),
pterm.NewLettersFromString("c"),
).Srender()
description := pterm.DefaultBasicText.Sprint("Control your goSDN controller like you've never done it before!")
pterm.DefaultCenter.Println(title)
pterm.DefaultCenter.Println(description)
p := prompt.New(
executeFunc,
pc.cstmCompleter,
prompt.OptionTitle("gosdnc-prompt: interactive gosdn CLI"),
prompt.OptionPrefix(">>> "),
prompt.OptionPrefixTextColor(prompt.Cyan),
prompt.OptionCompletionWordSeparator(completer.YangSchemaCompletionSeperator),
prompt.OptionShowCompletionAtStart(),
prompt.OptionSuggestionBGColor(prompt.DarkGray),
prompt.OptionSuggestionTextColor(prompt.LightGray),
prompt.OptionDescriptionTextColor(prompt.DarkGray),
prompt.OptionDescriptionBGColor(prompt.LightGray),
prompt.OptionSelectedSuggestionBGColor(prompt.Cyan),
prompt.OptionSelectedSuggestionTextColor(prompt.DarkGray),
prompt.OptionSelectedDescriptionBGColor(prompt.LightGray),
prompt.OptionSelectedDescriptionTextColor(prompt.DarkGray),
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)
}
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 := strings.Fields(d.CurrentLine())
inputSplitFiltered, inputFlags := filterFlagSlice(inputSplit)
if c, _, err := currCmd.Find(inputSplitFiltered); err == nil {
currCmd = c
}
return completionBasedOnCmd(pc, currCmd, inputSplit, inputFlags, d)
func filterFlagSlice(input []string) (commandSlice []string, flagSlice []string) {
for _, in := range input {
if !strings.HasPrefix(in, "--") {
commandSlice = append(commandSlice, in)
} else {
flagSlice = append(flagSlice, strings.Split(in, "=")[0])
return commandSlice, flagSlice
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 {
return yc.Complete(d)
}
return []prompt.Suggest{}
}
if inputLen == 2 || (inputLen == 3 && !(d.GetWordBeforeCursor() == "")) {
spinner, _ := pterm.DefaultSpinner.Start("Requesting devices from controller.")
devices, err := getDevices()
if err != nil {
spinner.Fail(err)
return prompt.FilterHasPrefix(devices, d.GetWordBeforeCursor(), true)
}
spinner.Success()
return prompt.FilterHasPrefix(devices, d.GetWordBeforeCursor(), true)
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, inputFlags []string, loaded []prompt.Suggest) []prompt.Suggest {
if currCmd.HasAvailableFlags() {
currCmd.LocalFlags().VisitAll(
func(f *pflag.Flag) {
if !f.Hidden && !sliceContains(inputFlags, "--"+f.Name) {
loaded = append(loaded, prompt.Suggest{Text: "--" + f.Name, Description: f.Usage})
}
},
)
}
for _, cmd := range currCmd.Commands() {
loaded = append(loaded, prompt.Suggest{Text: cmd.Name(), Description: cmd.Short})
return prompt.FilterHasPrefix(loaded, d.GetWordBeforeCursor(), true)
func completionBasedOnCmd(c *PromptCompleter, cmd *cobra.Command, inputSplit []string, inputFlags []string, d prompt.Document) []prompt.Suggest {
switch cmd {
case pndUseCmd, pndGetCmd:
return cobraCommandCompletion(cmd, d, inputFlags, 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:
devices, _ := getDevices()
return devices
return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
}
}
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)
}