-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhandlers.go
297 lines (228 loc) · 7.53 KB
/
handlers.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package main
import (
"context"
"errors"
"fmt"
"os"
"strings"
"text/tabwriter"
"time"
"github.com/briandowns/spinner"
"github.com/manifoldco/promptui"
promptlist "github.com/manifoldco/promptui/list"
log "github.com/obalunenko/logger"
"github.com/savioxavier/termlink"
"github.com/urfave/cli/v2"
"github.com/obalunenko/advent-of-code/internal/command"
"github.com/obalunenko/advent-of-code/internal/puzzles"
)
func onExit(_ context.Context) cli.AfterFunc {
return func(_ *cli.Context) error {
fmt.Println("Exit...")
return nil
}
}
func printHeader(_ context.Context) cli.BeforeFunc {
const (
padding int = 1
minWidth int = 0
tabWidth int = 0
padChar byte = ' '
)
return func(c *cli.Context) error {
w := tabwriter.NewWriter(c.App.Writer, minWidth, tabWidth, padding, padChar, tabwriter.TabIndent)
_, err := fmt.Fprintf(w, `
█████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗████████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
██╔══██╗██╔══██╗██║ ██║██╔════╝████╗ ██║╚══██╔══╝ ██╔═══██╗██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔════╝
███████║██║ ██║██║ ██║█████╗ ██╔██╗ ██║ ██║ ██║ ██║█████╗ ██║ ██║ ██║██║ ██║█████╗
██╔══██║██║ ██║╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ██║ ██║██╔══╝ ██║ ██║ ██║██║ ██║██╔══╝
██║ ██║██████╔╝ ╚████╔╝ ███████╗██║ ╚████║ ██║ ╚██████╔╝██║ ╚██████╗╚██████╔╝██████╔╝███████╗
╚═╝ ╚═╝╚═════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝
`)
if err != nil {
return fmt.Errorf("print version: %w", err)
}
return nil
}
}
func notFound(ctx context.Context) cli.CommandNotFoundFunc {
return func(c *cli.Context, command string) {
if _, err := fmt.Fprintf(
c.App.Writer,
"Command [%s] not supported.\nTry --help flag to see how to use it\n",
command,
); err != nil {
log.WithError(ctx, err).Fatal("Failed to print not found message")
}
}
}
func menu(ctx context.Context) cli.ActionFunc {
return func(c *cli.Context) error {
ctx = command.ContextWithOptions(ctx, optionsFromCli(c)...)
ctx = command.ContextWithSession(ctx, sessionFromCli(c))
years := puzzles.GetYears()
items := makeMenuItemsList(years, exit)
prompt := promptui.Select{
Label: "Years menu (exit' for exit)",
Items: items,
Size: pageSize,
CursorPos: 0,
IsVimMode: false,
HideHelp: false,
HideSelected: false,
Templates: nil,
Keys: nil,
Searcher: searcher(items),
StartInSearchMode: false,
Pointer: promptui.DefaultCursor,
Stdin: nil,
Stdout: nil,
}
return handleYearChoices(ctx, prompt)
}
}
func menuPuzzle(ctx context.Context, year string) error {
solvers := puzzles.DaysByYear(year)
items := makeMenuItemsList(solvers, back, exit)
prompt := promptui.Select{
Label: "Puzzles menu (exit' for exit; back - to return to year selection)",
Items: items,
Size: pageSize,
CursorPos: 0,
IsVimMode: false,
HideHelp: false,
HideSelected: false,
Templates: nil,
Keys: nil,
Searcher: searcher(items),
StartInSearchMode: false,
Pointer: promptui.DefaultCursor,
Stdin: nil,
Stdout: nil,
}
return handlePuzzleChoices(ctx, year, prompt)
}
func makeMenuItemsList(list []string, commands ...string) []string {
items := make([]string, 0, len(list)+len(commands))
items = append(items, list...)
items = append(items, commands...)
return items
}
func searcher(items []string) promptlist.Searcher {
return func(input string, index int) bool {
itm := items[index]
itm = strings.ReplaceAll(strings.ToLower(itm), " ", "")
input = strings.ReplaceAll(strings.ToLower(input), " ", "")
return strings.Contains(itm, input)
}
}
func handleYearChoices(ctx context.Context, opt promptui.Select) error {
for {
_, yearOpt, err := opt.Run()
if err != nil {
if isAbort(err) {
return nil
}
return fmt.Errorf("prompt failed: %w", err)
}
if isExit(yearOpt) {
return nil
}
err = menuPuzzle(ctx, yearOpt)
if err != nil {
if errors.Is(err, errExit) {
return nil
}
log.WithError(ctx, err).Error("Puzzle menu failed")
continue
}
}
}
func handlePuzzleChoices(ctx context.Context, year string, opt promptui.Select) error {
for {
_, dayOpt, err := opt.Run()
if err != nil {
if isAbort(err) {
return errExit
}
return fmt.Errorf("prompt failed: %w", err)
}
if isExit(dayOpt) {
return errExit
}
if isBack(dayOpt) {
return nil
}
stopSpinner := setSpinner()
res, err := command.Run(ctx, year, dayOpt)
if err != nil {
stopSpinner()
if errors.Is(err, command.ErrUnauthorized) {
fmt.Println(termlink.Link("Authorize here", "https://adventofcode.com/auth/login"))
log.WithError(ctx, err).Fatal("Session expired")
}
log.WithError(ctx, err).Error("Puzzle run failed")
continue
}
stopSpinner("Solved!")
url := getURL(year, dayOpt)
fmt.Println(res.String())
fmt.Println(termlink.Link("Enter puzzle answers here", url))
}
}
func getURL(year, day string) string {
const urlFmt = "https://adventofcode.com/%s/day/%s"
return fmt.Sprintf(urlFmt, year, day)
}
func isExit(in string) bool {
return strings.EqualFold(exit, in)
}
func isAbort(err error) bool {
return strings.HasSuffix(err.Error(), abort)
}
func isBack(in string) bool {
return strings.EqualFold(back, in)
}
func optionsFromCli(c *cli.Context) []puzzles.RunOption {
const optsNum = 2
options := make([]puzzles.RunOption, 0, optsNum)
if c.Bool(flagElapsed) || c.Bool(flagShortElapsed) {
options = append(options, puzzles.WithElapsed())
}
if c.Bool(flagBenchmark) || c.Bool(flagShortBenchmark) {
options = append(options, puzzles.WithBenchmark())
}
return options
}
func sessionFromCli(c *cli.Context) string {
var sess string
sess = c.String(flagSession)
if sess != "" {
return sess
}
sess = c.String(flagShortSession)
if sess != "" {
return sess
}
return ""
}
// setSpinner runs the displaying of spinner to handle long time operations. Returns stop func.
func setSpinner() func(msg ...string) {
const delayMs = 100
s := spinner.New(
spinner.CharSets[62],
delayMs*time.Millisecond,
spinner.WithFinalMSG(""),
spinner.WithHiddenCursor(true),
spinner.WithColor("yellow"),
spinner.WithWriter(os.Stderr),
)
s.Prefix = "Solving in progress..."
s.Start()
return func(msg ...string) {
if len(msg) != 0 {
s.FinalMSG = msg[0]
}
s.Stop()
}
}