76 lines
1.2 KiB
Go
76 lines
1.2 KiB
Go
package main
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
"sort"
|
||
|
|
)
|
||
|
|
|
||
|
|
type context struct {
|
||
|
|
commands map[string]cliCommand
|
||
|
|
}
|
||
|
|
|
||
|
|
func (r *context) register(c cliCommand) {
|
||
|
|
if c.name != "" {
|
||
|
|
r.commands[c.name] = c
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewContext() *context {
|
||
|
|
var exitCommand = cliCommand{
|
||
|
|
name: "exit",
|
||
|
|
description: "Exit the Pokedex",
|
||
|
|
callback: commandExit,
|
||
|
|
}
|
||
|
|
|
||
|
|
var helpCommand = cliCommand{
|
||
|
|
name: "help",
|
||
|
|
description: "Displays a help message",
|
||
|
|
callback: commandHelp,
|
||
|
|
}
|
||
|
|
|
||
|
|
c := &context{
|
||
|
|
commands: map[string]cliCommand{},
|
||
|
|
}
|
||
|
|
|
||
|
|
c.register(exitCommand)
|
||
|
|
c.register(helpCommand)
|
||
|
|
|
||
|
|
return c
|
||
|
|
}
|
||
|
|
|
||
|
|
type commandFunc func(c *context) error
|
||
|
|
|
||
|
|
type cliCommand struct {
|
||
|
|
name string
|
||
|
|
description string
|
||
|
|
callback commandFunc
|
||
|
|
}
|
||
|
|
|
||
|
|
func commandExit(c *context) error {
|
||
|
|
fmt.Println("Closing the Pokedex... Goodbye!")
|
||
|
|
os.Exit(0)
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func commandHelp(c *context) error {
|
||
|
|
fmt.Println("Welcome to the Pokedex!")
|
||
|
|
fmt.Println("Usage:")
|
||
|
|
fmt.Println("")
|
||
|
|
|
||
|
|
sortedKeys := []string{}
|
||
|
|
|
||
|
|
for k := range c.commands {
|
||
|
|
sortedKeys = append(sortedKeys, k)
|
||
|
|
}
|
||
|
|
|
||
|
|
sort.Strings(sortedKeys)
|
||
|
|
|
||
|
|
for _, key := range sortedKeys {
|
||
|
|
command := c.commands[key]
|
||
|
|
fmt.Printf("%s: %s\n", command.name, command.description)
|
||
|
|
}
|
||
|
|
|
||
|
|
return nil
|
||
|
|
}
|