Skip to content
Snippets Groups Projects
prompt.go 12.2 KiB
Newer Older
  • Learn to ignore specific revisions
  • /*
    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 (
    	"os"
    	"strings"
    
    	"code.fbi.h-da.de/danet/gosdn/cli/completer"
    
    	"code.fbi.h-da.de/danet/gosdn/controller/api"
    
    	"github.com/c-bata/go-prompt"
    	"github.com/google/uuid"
    
    	"github.com/openconfig/goyang/pkg/yang"
    	"github.com/pterm/pterm"
    
    	"github.com/spf13/cobra"
    	"github.com/spf13/pflag"
    
    	"github.com/spf13/viper"
    
    // PromptCompleter provides completion for a device
    type PromptCompleter struct {
    
    	yangSchemaCompleterMap map[uuid.UUID]*completer.YangSchemaCompleter
    
    	currentSuggestions     []prompt.Suggest
    	document               *prompt.Document
    	history                []string
    
    // 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.OptionCompletionOnDown(),
    		prompt.OptionHistory(pc.history),
    		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 {
    
    		pterm.Error.Println("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 {
    
    	return completionBasedOnCmd(pc, currCmd, inputSplitFiltered, 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 {
    
    	switch inputLen := len(inputSplit); inputLen {
    	case 2:
    		return c.updateSuggestionsThroughFunc(d, getDevices)
    	case 3:
    		id, err := uuid.Parse(inputSplit[inputLen-1])
    		if err != nil {
    			return c.updateSuggestionsThroughFunc(d, getDevices)
    		}
    		if c, ok := c.yangSchemaCompleterMap[id]; ok {
    			return c.Complete(d)
    		}
    		schemaTree, err := getSchemaTreeForDeviceID(id.String())
    		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)
    		}
    	case 4:
    		if d.GetWordBeforeCursor() == "" || d.GetWordAfterCursor() != "" {
    			return []prompt.Suggest{}
    		}
    		id, err := uuid.Parse(inputSplit[inputLen-2])
    		if err != nil {
    			return c.updateSuggestionsThroughFunc(d, getDevices)
    
    		if yc, ok := c.yangSchemaCompleterMap[id]; ok {
    
    		return []prompt.Suggest{}
    	}
    	return []prompt.Suggest{}
    }
    
    
    func (pc *PromptCompleter) updateSuggestionsThroughFunc(d prompt.Document, fn func() ([]prompt.Suggest, error)) []prompt.Suggest {
    	if pc.currentSuggestions == nil {
    		var err error
    		pc.currentSuggestions, err = fn()
    		if err != nil {
    			return prompt.FilterHasPrefix(pc.currentSuggestions, d.GetWordBeforeCursor(), true)
    		}
    
    	return prompt.FilterHasPrefix(pc.currentSuggestions, d.GetWordBeforeCursor(), true)
    }
    
    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)
    
    //nolint
    func completionBasedOnCmd(c *PromptCompleter, cmd *cobra.Command, inputSplit []string, inputFlags []string, d prompt.Document) []prompt.Suggest {
    
    	case pndUseCmd, pndGetCmd, pndRemoveCmd:
    		if len(inputSplit) < 3 || (len(inputSplit) == 3 && d.GetWordBeforeCursor() != "") {
    			suggestions := c.updateSuggestionsThroughFunc(d, getPnds)
    			return cobraCommandCompletion(cmd, d, inputFlags, suggestions)
    		}
    
    		if len(inputSplit) < 3 || (len(inputSplit) == 3 && d.GetWordBeforeCursor() != "") {
    			return c.updateSuggestionsThroughFunc(d, getCommitedChanges)
    		}
    
    		if len(inputSplit) < 3 || (len(inputSplit) == 3 && d.GetWordBeforeCursor() != "") {
    			return c.updateSuggestionsThroughFunc(d, getConfirmedChanges)
    		}
    	case deviceRemoveCmd:
    		if len(inputSplit) < 3 || (len(inputSplit) == 3 && d.GetWordBeforeCursor() != "") {
    			return c.updateSuggestionsThroughFunc(d, getDevices)
    		}
    
    	case deviceGetCmd, deviceSetCmd:
    		return deviceGetCompletion(c, d, inputSplit)
    	case deviceShowCmd:
    
    		devices, err := getDevices()
    		if err != nil {
    			return []prompt.Suggest{}
    		}
    		return devices
    	case deviceCmd, pndCmd, changeCmd:
    		c.currentSuggestions = nil
    		return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
    
    		return cobraCommandCompletion(cmd, d, inputFlags, []prompt.Suggest{})
    	}
    
    	return []prompt.Suggest{}
    }
    
    // getDevices is a helper function which requests devices from the controller
    // and gives feedback about the current pulling status with the help of pterm
    // the result is converted into a prompt.Suggest slice.
    func getDevices() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching devices from controller.")
    	resp, err := pndAdapter.GetDevices(createContextWithAuthorization())
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    	for _, ond := range resp.Ond {
    		s = append(s, prompt.Suggest{Text: ond.GetId(), Description: ond.GetName()})
    	}
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    }
    
    // getSchemaTreeForDeviceID is a helper function which requests the SBI's
    // schema tree of a specific device. The function gives feedback about the
    // current pulling status with the help of pterm.
    func getSchemaTreeForDeviceID(id string) (map[string]*yang.Entry, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching schema tree for Device with ID: ", id)
    	dev, err := pndAdapter.GetDevice(createContextWithAuthorization(), id)
    	if err != nil {
    		spinner.Fail(err)
    		return nil, err
    	}
    
    	sid, err := uuid.Parse(dev.GetOnd().GetSbi().GetId())
    
    	if err != nil {
    		spinner.Fail(err)
    		return nil, err
    	}
    	spinner.Success()
    	return pndAdapter.GetSbiSchemaTree(createContextWithAuthorization(), sid)
    }
    
    // getPnds is a helper function which requests pnds from the controller and
    // gives feedback about the current pulling status with the help of pterm the
    // result is converted into a prompt.Suggest slice.
    func getPnds() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching PNDs from controller.")
    	resp, err := api.GetIds(createContextWithAuthorization(), viper.GetString("controllerAPIEndpoint"))
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    	for _, pnd := range resp {
    		s = append(s, prompt.Suggest{Text: pnd.GetId(), Description: pnd.GetDescription()})
    	}
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    }
    
    // getCommitedChanges is a helper function which requests all the commited
    // changes from the controller and gives feedback about the current pulling
    // status with the help of pterm the result is converted into a prompt.Suggest
    // slice.
    func getCommitedChanges() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching commited changes.")
    
    	resp, err := pndAdapter.CommittedChanges(createContextWithAuthorization())
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    	for _, change := range resp {
    		s = append(s, prompt.Suggest{Text: change.GetId(), Description: change.State.String()})
    	}
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    }
    
    // getConfirmedChanges is a helper function which requests all the confirmed
    // changes from the controller and gives feedback about the current pulling
    // status with the help of pterm the result is converted into a prompt.Suggest
    // slice.
    func getConfirmedChanges() ([]prompt.Suggest, error) {
    	spinner, _ := pterm.DefaultSpinner.Start("Fetching confirmed changes.")
    
    	resp, err := pndAdapter.ConfirmedChanges(createContextWithAuthorization())
    	if err != nil {
    		spinner.Fail(err)
    		return []prompt.Suggest{}, err
    	}
    
    	s := []prompt.Suggest{}
    	for _, change := range resp {
    		s = append(s, prompt.Suggest{Text: change.GetId(), Description: change.State.String()})
    
    	spinner.Success()
    	return completer.SortSuggestionByText(s), nil
    
    }
    
    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)
    }