pokedex_cli/repl.go

88 lines
1.7 KiB
Go
Raw Normal View History

2025-09-28 20:15:55 +00:00
package main
import (
"fmt"
"strings"
"bufio"
"os"
2025-10-04 17:29:20 +00:00
"k3gtpi.jumpingcrab.com/go-learning/pokedexcli/internal/pokecache"
"time"
2025-09-28 20:15:55 +00:00
)
type cliCommand struct {
name string
description string
2025-10-04 17:29:20 +00:00
callback func(*PokedexConfig, *pokecache.Cache) error
}
type PokedexConfig struct {
Next *string
Previous *string
Results []map[string]string
2025-09-28 20:15:55 +00:00
}
var supportedCommands map[string]cliCommand
func startRepl() {
reader := bufio.NewScanner(os.Stdin)
fmt.Println("Welcome to the Pokedex!")
2025-10-04 17:29:20 +00:00
pokedexConfig := PokedexConfig{}
cache := pokecache.NewCache(5 * time.Second)
2025-09-28 20:15:55 +00:00
for {
// Print prompt
fmt.Printf("Pokedex > ")
reader.Scan()
words := cleanInput(reader.Text())
if len(words) == 0 {
continue
}
commandName := words[0]
command, valid := getCommands()[commandName]
if !valid {
fmt.Println("Unknown command.")
continue
}
2025-10-04 17:29:20 +00:00
if err := command.callback(&pokedexConfig, cache); err != nil {
fmt.Printf("Encountered error running command: %v\nErr: %v", command.name, err)
2025-09-28 20:15:55 +00:00
}
}
}
func cleanInput(text string) []string {
if len(text) == 0 {
fmt.Println("Input is empty!")
return []string{}
}
output := strings.ToLower(text)
words := strings.Fields(output)
return words
}
func getCommands() map[string]cliCommand{
return map[string]cliCommand{
"help": {
name: "help",
description: "Prints this help menu.",
callback: commandHelp,
},
"exit": {
name: "exit",
description: "Exits the Pokedex",
callback: commandExit,
},
2025-09-28 20:57:48 +00:00
"map": {
name: "map",
description: "Print Pokemon world locations.",
callback: commandMap,
},
2025-10-04 17:29:20 +00:00
"mapb": {
name: "mapb",
description: "Print previoud Pokemon locationsi.",
callback: commandMapb,
},
2025-09-28 20:15:55 +00:00
}
}