Skip to content
Snippets Groups Projects
prompt.go 7.23 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 (
    	"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
    
    
    // PromptCompleter provides completion for a device
    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
    }
    
    
    // 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() {
    
    	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)
    	}
    
    }
    
    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(createContextWithAuthorization(), 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(createContextWithAuthorization(), 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)
    }