-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl.go
112 lines (101 loc) · 2.22 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
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: commandHelp,
},
"exit": {
name: "exit",
description: "Exit the Pokedex",
callback: commandExit,
},
"map": {
name: "map",
description: "Get next 20 locations",
callback: commandMap,
},
"mapb": {
name: "mapb",
description: "Get previous 20 locations",
callback: commandMapb,
},
"explore": {
name: "explore {location_area}",
description: "get pokemon for a region",
callback: commandExplore,
},
"catch": {
name: "catch {pokemon_name}",
description: "try to catch a pokemon!",
callback: commandCatch,
},
"inspect": {
name: "inspect {pokemon_name}",
description: "inspect a pokemon you've caught",
callback: commandInspect,
},
"pokedex": {
name: "pokedex",
description: "list pokemon you've caught",
callback: commandPokedex,
},
"reap": {
name: "reap",
description: "invalidate cache",
callback: commandReap,
},
}
}
func startRepl(cfg *config) {
quit := false
for !quit {
// print prompt
fmt.Print("pokedex > ")
// read text
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
}
cleanedInput := cleanInput(line)
if len(cleanedInput) == 0 {
continue
}
// we don't yet use the rest of cleanedInput
command := cleanedInput[0]
args := []string{}
if len(cleanedInput) > 1 {
args = cleanedInput[1:]
}
// get commands and check if input is in commands
commands := getCommands()
_, cmdInMap := commands[command]
if !cmdInMap {
fmt.Println("Invalid command:", command)
continue
}
err = commands[command].callback(cfg, args...)
if err != nil {
fmt.Println(err)
}
}
}
func cleanInput(input string) []string {
lowered := strings.ToLower(input)
stripped := strings.TrimSpace(lowered)
words := strings.Fields(stripped)
return words
}