github.com/cloudcentricdev/golang-tutorials/03@v0.0.0-20231018054503-b24024842337/cli/cli.go (about)

     1  package cli
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/cloudcentricdev/golang-tutorials/03/skiplist"
    10  )
    11  
    12  type CLI struct {
    13  	scanner  *bufio.Scanner
    14  	skipList *skiplist.SkipList
    15  }
    16  
    17  func NewCLI(s *bufio.Scanner, sl *skiplist.SkipList) *CLI {
    18  	return &CLI{s, sl}
    19  }
    20  
    21  func (c *CLI) Start() {
    22  	c.printHelp()
    23  	c.printPrompt()
    24  	for {
    25  		if c.scanner.Scan() {
    26  			c.processInput(c.scanner.Text())
    27  		}
    28  	}
    29  }
    30  
    31  func (c *CLI) printHelp() {
    32  	fmt.Println(`
    33  SkipList CLI
    34  
    35  Available Commands:
    36    SET <key> <val> Insert a key-value pair into the SkipList
    37    DEL <key>       Remove a key-value pair from the SkipList
    38    GET <key>       Retrieve the value for key from the SkipList
    39    EXIT            Terminate this session
    40  `)
    41  }
    42  
    43  func (c *CLI) printPrompt() {
    44  	fmt.Print("> ")
    45  }
    46  
    47  func (c *CLI) processInput(line string) {
    48  	fields := strings.Fields(line)
    49  
    50  	if len(fields) < 1 {
    51  		return
    52  	}
    53  	command := strings.ToLower(fields[0])
    54  
    55  	switch command {
    56  	default:
    57  		fmt.Printf("Unknown command \"%s\"\n", command)
    58  	case "set":
    59  		c.processSetCommand(fields[1:])
    60  	case "del":
    61  		c.processDeleteCommand(fields[1:])
    62  	case "get":
    63  		c.processGetCommand(fields[1:])
    64  	case "exit":
    65  		os.Exit(0)
    66  	}
    67  	c.printPrompt()
    68  }
    69  
    70  func (c *CLI) processSetCommand(args []string) {
    71  	if len(args) != 2 {
    72  		fmt.Println("Usage: SET <key> <value>")
    73  		return
    74  	}
    75  	c.skipList.Insert([]byte(args[0]), []byte(args[1]))
    76  	fmt.Println(c.skipList)
    77  }
    78  
    79  func (c *CLI) processDeleteCommand(args []string) {
    80  	if len(args) != 1 {
    81  		fmt.Println("Usage: DEL <key>")
    82  		return
    83  	}
    84  	res := c.skipList.Delete([]byte(args[0]))
    85  
    86  	if !res {
    87  		fmt.Println("Key not found.")
    88  		return
    89  	}
    90  	fmt.Println(c.skipList)
    91  }
    92  
    93  func (c *CLI) processGetCommand(args []string) {
    94  	if len(args) != 1 {
    95  		fmt.Println("Usage: GET <key>")
    96  		return
    97  	}
    98  	val, err := c.skipList.Find([]byte(args[0]))
    99  
   100  	if err != nil {
   101  		fmt.Println("Key not found.")
   102  		return
   103  	}
   104  	fmt.Println(string(val))
   105  }