Files
pokedexcli/repl.go
T

69 lines
1.1 KiB
Go

package main
import (
"fmt"
"io"
"regexp"
"strings"
)
func cleanInput(input string) []string {
normalized := strings.ToLower(input)
trimmed := strings.TrimSpace(normalized)
re := regexp.MustCompile(`[\s]+`)
words := re.Split(trimmed, -1)
return words
}
type inputScanner interface {
Scan() bool
Err() error
Text() string
}
func runREPL(s inputScanner, w io.Writer, sanitizer func(string) []string) {
context := NewContext()
for {
fmt.Fprint(w, "Pokedex > ")
s.Scan()
err := s.Err()
if err != nil {
fmt.Fprintf(w, "Pokedex > Sorry I didn't get that.\n")
continue
}
input := s.Text()
if input == "" {
break
}
cleanedInput := sanitizer(input)
if len(cleanedInput) < 1 {
fmt.Fprintf(w, "Pokedex > Sorry I couldn't understand that.\n")
continue
}
requestedCommand := cleanedInput[0]
command, exists := context.commands[requestedCommand]
if !exists {
fmt.Fprintln(w, "Unknown command")
continue
}
context.args = cleanedInput[1:]
err = command.callback(context)
if err != nil {
fmt.Fprintf(w, "Pokedex > Error occurred executing command: %s", err)
}
}
}