-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl.go
97 lines (88 loc) · 1.85 KB
/
repl.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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func startRepl(cfg *config) {
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print(" > ")
scanner.Scan()
text := scanner.Text()
cleaned := cleanInput(text)
if len(cleaned) == 0 {
continue
}
commandName := cleaned[0]
args := []string{}
if len(cleaned) > 1 {
args = cleaned[1:]
}
availableCommands := getCommands()
command, ok := availableCommands[commandName]
if !ok {
fmt.Println("invalid command")
continue
}
err := command.callback(cfg, args...)
if err != nil {
fmt.Println(err)
}
}
}
type cliCommand struct {
name string
description string
callback func(*config, ...string) error
}
func getCommands() map[string]cliCommand {
return map[string]cliCommand{
"help": {
name: "help",
description: "Displays a help message",
callback: callbackHelp,
},
"exit": {
name: "exit",
description: "Exit the Pokedex",
callback: callbackExit,
},
"map": {
name: "map",
description: "List some location areas",
callback: callbackMap,
},
"mapb": {
name: "mapb",
description: "List previous location areas",
callback: callbackMapb,
},
"explore": {
name: "explore",
description: "List every pokemon in a provided area",
callback: callbackExplore,
},
"catch": {
name: "catch",
description: "Try to catch a provided pokemon",
callback: callbackCatch,
},
"inspect": {
name: "inspect",
description: "Try to inspect a provided pokemon",
callback: callbackInspect,
},
"pokedex": {
name: "pokedex",
description: "Show the list of your pokemon",
callback: callbackPokedex,
},
}
}
func cleanInput(str string) []string {
lowered := strings.ToLower(str)
words := strings.Fields(lowered)
return words
}