-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
78 lines (63 loc) · 1.64 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"bufio"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/mawkler/pokedex-cli/internal/cache"
"github.com/mawkler/pokedex-cli/internal/cli"
"github.com/mawkler/pokedex-cli/internal/cli/commands"
"github.com/mawkler/pokedex-cli/internal/pokeapi"
"github.com/mawkler/pokedex-cli/internal/pokedex"
)
func evaluate(input string, cfg *cli.Config, cliCommands map[string]commands.Command) error {
cmd, args := cli.SplitInput(input)
command, ok := cliCommands[cmd]
if !ok {
return fmt.Errorf("command not found: %s", input)
}
if err := command.Run(cfg, args...); err != nil {
return err
}
return nil
}
func repl(scanner *bufio.Scanner, cfg cli.Config, cliCommands map[string]commands.Command) {
println("Welcome to the Pokedex!")
for {
print("Pokedex > ")
scanner.Scan()
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
input := scanner.Text()
if len(input) == 0 {
continue
}
err := evaluate(input, &cfg, cliCommands)
if err != nil {
println(err.Error())
}
}
}
func main() {
cache := cache.NewCache(time.Minute * 2)
pokeApiUrl := "https://pokeapi.co/api/v2"
client := pokeapi.NewClient(pokeApiUrl, *http.DefaultClient, cache)
pokedex := pokedex.NewPokedex()
cfg := cli.NewConfig(client, pokedex)
scanner := bufio.NewScanner(os.Stdin)
cliCommands := commands.NewCLICommandMap()
// If CLI arguments were passed in
input := strings.Join(os.Args[1:], " ")
if len(input) > 0 {
if err := evaluate(input, &cfg, cliCommands); err != nil {
println(err.Error())
}
os.Exit(0)
}
// If no CLI arguments were passed in, start the REPL
repl(scanner, cfg, cliCommands)
}