feat: add help and exit commands
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
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
|
||||
}
|
||||
|
||||
err = command.callback(context)
|
||||
|
||||
if err != nil {
|
||||
fmt.Fprintf(w, "Pokedex > Error occurred executing command: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user