diff --git a/command_exit.go b/command_exit.go new file mode 100644 index 0000000..ca866ff --- /dev/null +++ b/command_exit.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "os" +) + +func commandExit() error { + fmt.Println("Closing the Pokedex... Goodbye!") + os.Exit(0) + return nil +} diff --git a/command_help.go b/command_help.go new file mode 100644 index 0000000..81807fe --- /dev/null +++ b/command_help.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +func commandHelp() error { + fmt.Println() + fmt.Println("Welcome to the Pokedex!") + fmt.Println("Usage:") + fmt.Println() + for _, c := range getCommands() { + fmt.Printf("\t%v\t\t%v\n", c.name, c.description) + } + fmt.Println() + return nil +} diff --git a/main.go b/main.go index e1bb917..cc05093 100644 --- a/main.go +++ b/main.go @@ -1,21 +1,7 @@ package main -import ( - "bufio" - "fmt" - "os" -) - const prompt = "Pokedex > " func main() { - dexScanner := bufio.NewScanner(os.Stdin) - for { - fmt.Print(prompt) - if !dexScanner.Scan() { - break - } - command := cleanInput(dexScanner.Text()) - fmt.Println("Your command was:", command[0]) - } + startRepl() } diff --git a/repl.go b/repl.go index e30843c..3c46349 100644 --- a/repl.go +++ b/repl.go @@ -1,6 +1,68 @@ package main -import "strings" +import ( + "bufio" + "fmt" + "os" + "strings" +) + +func getCommands() map[string]cliCommand { + return map[string]cliCommand{ + "exit": { + name: "exit", + description: "Exit the pokedex", + callback: commandExit, + }, + "help": { + name: "help", + description: "Displays a help message", + callback: commandHelp, + }, + "map": { + name: "map", + description: "Displays the names of the next 20 locations", + }, + "mapb": { + name: "mapb", + description: "Displays the names of the previous 20 locations", + }, + } +} + +func startRepl() { + reader := bufio.NewScanner(os.Stdin) + for { + fmt.Print(prompt) + reader.Scan() + + words := cleanInput(reader.Text()) + if len(words) == 0 { + continue + } + + inputCommand := words[0] + command, exists := getCommands()[inputCommand] + + if exists { + err := command.callback() + if err != nil { + fmt.Printf("%v error: %v", command.name, err.Error()) + } + } else { + + fmt.Println("Unknown command") + continue + } + + } +} + +type cliCommand struct { + name string + description string + callback func() error +} func cleanInput(text string) []string { input := strings.ToLower(text)