-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.go
105 lines (89 loc) · 1.85 KB
/
cli.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package cli
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/cloudcentricdev/golang-tutorials/03/skiplist"
)
type CLI struct {
scanner *bufio.Scanner
skipList *skiplist.SkipList
}
func NewCLI(s *bufio.Scanner, sl *skiplist.SkipList) *CLI {
return &CLI{s, sl}
}
func (c *CLI) Start() {
c.printHelp()
c.printPrompt()
for {
if c.scanner.Scan() {
c.processInput(c.scanner.Text())
}
}
}
func (c *CLI) printHelp() {
fmt.Println(`
SkipList CLI
Available Commands:
SET <key> <val> Insert a key-value pair into the SkipList
DEL <key> Remove a key-value pair from the SkipList
GET <key> Retrieve the value for key from the SkipList
EXIT Terminate this session
`)
}
func (c *CLI) printPrompt() {
fmt.Print("> ")
}
func (c *CLI) processInput(line string) {
fields := strings.Fields(line)
if len(fields) < 1 {
return
}
command := strings.ToLower(fields[0])
switch command {
default:
fmt.Printf("Unknown command \"%s\"\n", command)
case "set":
c.processSetCommand(fields[1:])
case "del":
c.processDeleteCommand(fields[1:])
case "get":
c.processGetCommand(fields[1:])
case "exit":
os.Exit(0)
}
c.printPrompt()
}
func (c *CLI) processSetCommand(args []string) {
if len(args) != 2 {
fmt.Println("Usage: SET <key> <value>")
return
}
c.skipList.Insert([]byte(args[0]), []byte(args[1]))
fmt.Println(c.skipList)
}
func (c *CLI) processDeleteCommand(args []string) {
if len(args) != 1 {
fmt.Println("Usage: DEL <key>")
return
}
res := c.skipList.Delete([]byte(args[0]))
if !res {
fmt.Println("Key not found.")
return
}
fmt.Println(c.skipList)
}
func (c *CLI) processGetCommand(args []string) {
if len(args) != 1 {
fmt.Println("Usage: GET <key>")
return
}
val, err := c.skipList.Find([]byte(args[0]))
if err != nil {
fmt.Println("Key not found.")
return
}
fmt.Println(string(val))
}