-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathrender.go
602 lines (543 loc) · 15.5 KB
/
render.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package render
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/bootdotdev/bootdev/checks"
api "github.com/bootdotdev/bootdev/client"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var green lipgloss.Style
var red lipgloss.Style
var gray lipgloss.Style
var borderBox = lipgloss.NewStyle().Border(lipgloss.RoundedBorder())
type testModel struct {
text string
passed *bool
finished bool
}
type startTestMsg struct {
text string
}
type resolveTestMsg struct {
index int
passed *bool
}
func renderTestHeader(header string, spinner spinner.Model, isFinished bool, isSubmit bool, passed *bool) string {
cmdStr := renderTest(header, spinner.View(), isFinished, &isSubmit, passed)
box := borderBox.Render(fmt.Sprintf(" %s ", cmdStr))
sliced := strings.Split(box, "\n")
sliced[2] = strings.Replace(sliced[2], "─", "┬", 1)
return strings.Join(sliced, "\n") + "\n"
}
func renderTestResponseVars(respVars []api.HTTPRequestResponseVariable) string {
var str string
for _, respVar := range respVars {
varStr := gray.Render(fmt.Sprintf(" * Saving `%s` from `%s`", respVar.Name, respVar.Path))
edges := " ├─"
for range lipgloss.Height(varStr) - 1 {
edges += "\n │ "
}
str += lipgloss.JoinHorizontal(lipgloss.Top, edges, varStr)
str += "\n"
}
return str
}
func renderTests(tests []testModel, spinner string) string {
var str string
for _, test := range tests {
testStr := renderTest(test.text, spinner, test.finished, nil, test.passed)
testStr = fmt.Sprintf(" %s", testStr)
edges := " ├─"
for range lipgloss.Height(testStr) - 1 {
edges += "\n │ "
}
str += lipgloss.JoinHorizontal(lipgloss.Top, edges, testStr)
str += "\n"
}
return str
}
func renderTest(text string, spinner string, isFinished bool, isSubmit *bool, passed *bool) string {
testStr := ""
if !isFinished {
testStr += fmt.Sprintf("%s %s", spinner, text)
} else if isSubmit != nil && !*isSubmit {
testStr += text
} else if passed == nil {
testStr += gray.Render(fmt.Sprintf("? %s", text))
} else if *passed {
testStr += green.Render(fmt.Sprintf("✓ %s", text))
} else {
testStr += red.Render(fmt.Sprintf("X %s", text))
}
return testStr
}
type doneStepMsg struct {
failure *api.StructuredErrCLI
}
type startStepMsg struct {
responseVariables []api.HTTPRequestResponseVariable
cmd string
url string
method string
}
type resolveStepMsg struct {
index int
passed *bool
result *api.CLIStepResult
}
type stepModel struct {
responseVariables []api.HTTPRequestResponseVariable
step string
passed *bool
result *api.CLIStepResult
finished bool
tests []testModel
}
type rootModel struct {
steps []stepModel
spinner spinner.Model
failure *api.StructuredErrCLI
isSubmit bool
success bool
finalized bool
clear bool
}
func initModel(isSubmit bool) rootModel {
s := spinner.New()
s.Spinner = spinner.Dot
return rootModel{
spinner: s,
isSubmit: isSubmit,
steps: []stepModel{},
}
}
func (m rootModel) Init() tea.Cmd {
green = lipgloss.NewStyle().Foreground(lipgloss.Color(viper.GetString("color.green")))
red = lipgloss.NewStyle().Foreground(lipgloss.Color(viper.GetString("color.red")))
gray = lipgloss.NewStyle().Foreground(lipgloss.Color(viper.GetString("color.gray")))
return m.spinner.Tick
}
func (m rootModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case doneStepMsg:
m.failure = msg.failure
if m.failure == nil && m.isSubmit {
m.success = true
}
m.clear = true
return m, tea.Quit
case startStepMsg:
step := fmt.Sprintf("Running: %s", msg.cmd)
if msg.cmd == "" {
step = fmt.Sprintf("%s %s", msg.method, msg.url)
}
m.steps = append(m.steps, stepModel{
step: step,
tests: []testModel{},
responseVariables: msg.responseVariables,
})
return m, nil
case resolveStepMsg:
m.steps[msg.index].passed = msg.passed
m.steps[msg.index].finished = true
m.steps[msg.index].result = msg.result
return m, nil
case startTestMsg:
m.steps[len(m.steps)-1].tests = append(
m.steps[len(m.steps)-1].tests,
testModel{text: msg.text},
)
return m, nil
case resolveTestMsg:
m.steps[len(m.steps)-1].tests[msg.index].passed = msg.passed
m.steps[len(m.steps)-1].tests[msg.index].finished = true
return m, nil
default:
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
}
}
func (m rootModel) View() string {
if m.clear {
return ""
}
s := m.spinner.View()
var str string
for _, step := range m.steps {
str += renderTestHeader(step.step, m.spinner, step.finished, m.isSubmit, step.passed)
str += renderTests(step.tests, s)
str += renderTestResponseVars(step.responseVariables)
if step.result == nil || !m.finalized {
continue
}
if step.result.CLICommandResult != nil {
// render the results
for _, test := range step.tests {
// for clarity, only show exit code if it's tested
if strings.Contains(test.text, "exit code") {
str += fmt.Sprintf("\n > Command exit code: %d\n", step.result.CLICommandResult.ExitCode)
break
}
}
str += " > Command stdout:\n\n"
sliced := strings.Split(step.result.CLICommandResult.Stdout, "\n")
for _, s := range sliced {
str += gray.Render(s) + "\n"
}
}
if step.result.HTTPRequestResult != nil {
str += printHTTPRequestResult(*step.result.HTTPRequestResult)
}
}
if m.failure != nil {
str += red.Render("\n\nError: "+m.failure.ErrorMessage) + "\n\n"
} else if m.success {
str += "\n\n" + green.Render("All tests passed! 🎉") + "\n\n"
str += green.Render("Return to your browser to continue with the next lesson.") + "\n\n"
}
return str
}
func prettyPrintCLICommand(test api.CLICommandTest, variables map[string]string) string {
if test.ExitCode != nil {
return fmt.Sprintf("Expect exit code %d", *test.ExitCode)
}
if test.StdoutLinesGt != nil {
return fmt.Sprintf("Expect > %d lines on stdout", *test.StdoutLinesGt)
}
if test.StdoutContainsAll != nil {
str := "Expect stdout to contain all of:"
for _, contains := range test.StdoutContainsAll {
interpolatedContains := checks.InterpolateVariables(contains, variables)
str += fmt.Sprintf("\n - '%s'", interpolatedContains)
}
return str
}
if test.StdoutContainsNone != nil {
str := "Expect stdout to contain none of:"
for _, containsNone := range test.StdoutContainsNone {
interpolatedContainsNone := checks.InterpolateVariables(containsNone, variables)
str += fmt.Sprintf("\n - '%s'", interpolatedContainsNone)
}
return str
}
return ""
}
func pointerToBool(a bool) *bool {
return &a
}
func printHTTPRequestResult(result api.HTTPRequestResult) string {
if result.Err != "" {
return fmt.Sprintf(" Err: %v\n\n", result.Err)
}
str := ""
str += fmt.Sprintf(" Response Status Code: %v\n", result.StatusCode)
filteredHeaders := make(map[string]string)
for respK, respV := range result.ResponseHeaders {
for _, test := range result.Request.Tests {
if test.HeadersContain == nil {
continue
}
interpolatedTestHeaderKey := checks.InterpolateVariables(test.HeadersContain.Key, result.Variables)
if strings.EqualFold(respK, interpolatedTestHeaderKey) {
filteredHeaders[respK] = respV
}
}
}
filteredTrailers := make(map[string]string)
for respK, respV := range result.ResponseTrailers {
for _, test := range result.Request.Tests {
if test.TrailersContain == nil {
continue
}
interpolatedTestTrailerKey := checks.InterpolateVariables(test.TrailersContain.Key, result.Variables)
if strings.EqualFold(respK, interpolatedTestTrailerKey) {
filteredTrailers[respK] = respV
}
}
}
if len(filteredHeaders) > 0 {
str += " Response Headers: \n"
for k, v := range filteredHeaders {
str += fmt.Sprintf(" - %v: %v\n", k, v)
}
}
str += " Response Body: \n"
bytes := []byte(result.BodyString)
contentType := http.DetectContentType(bytes)
if contentType == "application/json" || strings.HasPrefix(contentType, "text/") {
var unmarshalled any
err := json.Unmarshal([]byte(result.BodyString), &unmarshalled)
if err == nil {
pretty, err := json.MarshalIndent(unmarshalled, "", " ")
if err == nil {
str += string(pretty)
} else {
str += result.BodyString
}
} else {
str += result.BodyString
}
} else {
str += fmt.Sprintf("Binary %s file", contentType)
}
str += "\n"
if len(filteredTrailers) > 0 {
str += " Response Trailers: \n"
for k, v := range filteredTrailers {
str += fmt.Sprintf(" - %v: %v\n", k, v)
}
}
if len(result.Variables) > 0 {
str += " Variables available: \n"
for k, v := range result.Variables {
if v != "" {
str += fmt.Sprintf(" - %v: %v\n", k, v)
} else {
str += fmt.Sprintf(" - %v: [not found]\n", k)
}
}
}
str += "\n"
return str
}
func RenderRun(
data api.CLIData,
results []api.CLIStepResult,
) {
renderer(data, results, nil, false)
}
func RenderSubmission(
data api.CLIData,
results []api.CLIStepResult,
failure *api.StructuredErrCLI,
) {
renderer(data, results, failure, true)
}
func renderer(
data api.CLIData,
results []api.CLIStepResult,
failure *api.StructuredErrCLI,
isSubmit bool,
) {
var wg sync.WaitGroup
ch := make(chan tea.Msg, 1)
p := tea.NewProgram(initModel(isSubmit), tea.WithoutSignalHandler())
wg.Add(1)
go func() {
defer wg.Done()
if model, err := p.Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
} else if r, ok := model.(rootModel); ok {
r.clear = false
r.finalized = true
output := termenv.NewOutput(os.Stdout)
output.WriteString(r.View())
}
}()
go func() {
for {
msg := <-ch
p.Send(msg)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i, step := range data.Steps {
switch {
case step.CLICommand != nil && results[i].CLICommandResult != nil:
renderCLICommand(*step.CLICommand, *results[i].CLICommandResult, failure, isSubmit, ch, i)
case step.HTTPRequest != nil && results[i].HTTPRequestResult != nil:
renderHTTPRequest(*step.HTTPRequest, *results[i].HTTPRequestResult, failure, isSubmit, data.BaseURLDefault, ch, i)
default:
cobra.CheckErr("unable to run lesson: missing results")
}
}
time.Sleep(500 * time.Millisecond)
ch <- doneStepMsg{failure: failure}
}()
wg.Wait()
}
func renderCLICommand(
cmd api.CLIStepCLICommand,
result api.CLICommandResult,
failure *api.StructuredErrCLI,
isSubmit bool,
ch chan tea.Msg,
index int,
) {
ch <- startStepMsg{cmd: result.FinalCommand}
for _, test := range cmd.Tests {
ch <- startTestMsg{text: prettyPrintCLICommand(test, result.Variables)}
}
time.Sleep(500 * time.Millisecond)
earlierCmdFailed := false
if failure != nil {
earlierCmdFailed = failure.FailedStepIndex < index
}
for j := range cmd.Tests {
earlierTestFailed := false
if failure != nil {
if earlierCmdFailed {
earlierTestFailed = true
} else if failure.FailedStepIndex == index {
earlierTestFailed = failure.FailedTestIndex < j
}
}
if !isSubmit {
ch <- resolveTestMsg{index: j}
} else if earlierTestFailed {
ch <- resolveTestMsg{index: j}
} else {
time.Sleep(350 * time.Millisecond)
passed := failure == nil || failure.FailedStepIndex != index || failure.FailedTestIndex != j
ch <- resolveTestMsg{
index: j,
passed: pointerToBool(passed),
}
}
}
if !isSubmit {
ch <- resolveStepMsg{
index: index,
result: &api.CLIStepResult{
CLICommandResult: &result,
},
}
} else if earlierCmdFailed {
ch <- resolveStepMsg{index: index}
} else {
passed := failure == nil || failure.FailedStepIndex != index
if passed {
ch <- resolveStepMsg{
index: index,
passed: pointerToBool(passed),
}
} else {
ch <- resolveStepMsg{
index: index,
passed: pointerToBool(passed),
result: &api.CLIStepResult{
CLICommandResult: &result,
},
}
}
}
}
func renderHTTPRequest(
req api.CLIStepHTTPRequest,
result api.HTTPRequestResult,
failure *api.StructuredErrCLI,
isSubmit bool,
baseURLDefault string,
ch chan tea.Msg,
index int,
) {
baseURL := viper.GetString("override_base_url")
if baseURL == "" {
baseURL = baseURLDefault
}
fullURL := strings.Replace(req.Request.FullURL, api.BaseURLPlaceholder, baseURL, 1)
ch <- startStepMsg{
url: checks.InterpolateVariables(fullURL, result.Variables),
method: req.Request.Method,
responseVariables: req.ResponseVariables,
}
for _, test := range req.Tests {
ch <- startTestMsg{text: prettyPrintHTTPTest(test, result.Variables)}
}
time.Sleep(500 * time.Millisecond)
for j := range req.Tests {
if !isSubmit {
ch <- resolveTestMsg{index: j}
} else if failure != nil && (failure.FailedStepIndex < index || (failure.FailedStepIndex == index && failure.FailedTestIndex < j)) {
ch <- resolveTestMsg{index: j}
} else {
time.Sleep(350 * time.Millisecond)
ch <- resolveTestMsg{index: j, passed: pointerToBool(failure == nil || !(failure.FailedStepIndex == index && failure.FailedTestIndex == j))}
}
}
if !isSubmit {
ch <- resolveStepMsg{
index: index,
result: &api.CLIStepResult{
HTTPRequestResult: &result,
},
}
} else if failure != nil && failure.FailedStepIndex < index {
ch <- resolveStepMsg{index: index}
} else {
passed := failure == nil || failure.FailedStepIndex != index
if passed {
ch <- resolveStepMsg{
index: index,
passed: pointerToBool(passed),
}
} else {
ch <- resolveStepMsg{
index: index,
passed: pointerToBool(passed),
result: &api.CLIStepResult{
HTTPRequestResult: &result,
},
}
}
}
}
func prettyPrintHTTPTest(test api.HTTPRequestTest, variables map[string]string) string {
if test.StatusCode != nil {
return fmt.Sprintf("Expecting status code: %d", *test.StatusCode)
}
if test.BodyContains != nil {
interpolated := checks.InterpolateVariables(*test.BodyContains, variables)
return fmt.Sprintf("Expecting body to contain: %s", interpolated)
}
if test.BodyContainsNone != nil {
interpolated := checks.InterpolateVariables(*test.BodyContainsNone, variables)
return fmt.Sprintf("Expecting JSON body to not contain: %s", interpolated)
}
if test.HeadersContain != nil {
interpolatedKey := checks.InterpolateVariables(test.HeadersContain.Key, variables)
interpolatedValue := checks.InterpolateVariables(test.HeadersContain.Value, variables)
return fmt.Sprintf("Expecting headers to contain: '%s: %v'", interpolatedKey, interpolatedValue)
}
if test.TrailersContain != nil {
interpolatedKey := checks.InterpolateVariables(test.TrailersContain.Key, variables)
interpolatedValue := checks.InterpolateVariables(test.TrailersContain.Value, variables)
return fmt.Sprintf("Expecting trailers to contain: '%s: %v'", interpolatedKey, interpolatedValue)
}
if test.JSONValue != nil {
var val any
var op any
if test.JSONValue.IntValue != nil {
val = *test.JSONValue.IntValue
} else if test.JSONValue.StringValue != nil {
val = *test.JSONValue.StringValue
} else if test.JSONValue.BoolValue != nil {
val = *test.JSONValue.BoolValue
}
if test.JSONValue.Operator == api.OpEquals {
op = "to be equal to"
} else if test.JSONValue.Operator == api.OpGreaterThan {
op = "to be greater than"
} else if test.JSONValue.Operator == api.OpContains {
op = "contains"
} else if test.JSONValue.Operator == api.OpNotContains {
op = "to not contain"
}
expecting := fmt.Sprintf("Expecting JSON at %v %s %v", test.JSONValue.Path, op, val)
return checks.InterpolateVariables(expecting, variables)
}
return ""
}