-
Notifications
You must be signed in to change notification settings - Fork 297
Expand file tree
/
Copy pathconsole.go
More file actions
1237 lines (1060 loc) · 34.7 KB
/
console.go
File metadata and controls
1237 lines (1060 loc) · 34.7 KB
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package input
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"os/signal"
"runtime"
"slices"
"strconv"
"sync"
syncatomic "sync/atomic"
"syscall"
"time"
"github.com/AlecAivazis/survey/v2"
surveyterm "github.com/AlecAivazis/survey/v2/terminal"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/azure/azure-dev/cli/azd/internal/tracing"
"github.com/azure/azure-dev/cli/azd/pkg/alpha"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/output/ux"
tm "github.com/buger/goterm"
"github.com/nathan-fiscaletti/consolesize-go"
"github.com/theckman/yacspin"
"go.uber.org/atomic"
)
type SpinnerUxType int
const (
Step SpinnerUxType = iota
StepDone
StepFailed
StepWarning
StepSkipped
)
// A shim to allow a single Console construction in the application.
// To be removed once formatter and Console's responsibilities are reconciled
type ConsoleShim interface {
// True if the console was instantiated with no format options.
IsUnformatted() bool
// Gets the underlying formatter used by the console
GetFormatter() output.Formatter
}
// ShowPreviewerOptions provide the settings to start a console previewer.
type ShowPreviewerOptions struct {
Prefix string
MaxLineCount int
Title string
}
// PreviewerPauser is an optional interface that Console implementations
// may support. When the progress table is active, callers can pause
// previewer output to prevent terminal corruption.
type PreviewerPauser interface {
PausePreviewer()
ResumePreviewer()
}
type PromptDialog struct {
Title string
Description string
Prompts []PromptDialogItem
}
type PromptDialogItem struct {
ID string
Kind string
DisplayName string
Description *string
DefaultValue *string
Required bool
Choices []PromptDialogChoice
}
type PromptDialogChoice struct {
Value string
Description string
}
type Console interface {
// Prints out a message to the underlying console write
Message(ctx context.Context, message string)
// Prints out a message following a contract ux item
MessageUxItem(ctx context.Context, item ux.UxItem)
WarnForFeature(ctx context.Context, id alpha.FeatureId)
// Prints progress spinner with the given title.
// If a previous spinner is running, the title is updated.
ShowSpinner(ctx context.Context, title string, format SpinnerUxType)
// Stop the current spinner from the console and change the spinner bar for the lastMessage
// Set lastMessage to empty string to clear the spinner message instead of a displaying a last message
// If there is no spinner running, this is a no-op function
StopSpinner(ctx context.Context, lastMessage string, format SpinnerUxType)
// Preview mode brings an embedded console within the current session.
// Use nil for options to use defaults.
// Use the returned io.Writer to produce the output within the previewer
ShowPreviewer(ctx context.Context, options *ShowPreviewerOptions) io.Writer
// Finalize the preview mode from console.
StopPreviewer(ctx context.Context, keepLogs bool)
// Determines if there is a current spinner running.
IsSpinnerRunning(ctx context.Context) bool
// Determines if the current spinner is an interactive spinner, where messages are updated periodically.
// If false, the spinner is non-interactive, which means messages are rendered as a new console message on each
// call to ShowSpinner, even when the title is unchanged.
IsSpinnerInteractive() bool
// IsNoPromptMode returns true when --no-prompt is active and interactive prompts are disabled.
IsNoPromptMode() bool
SupportsPromptDialog() bool
PromptDialog(ctx context.Context, dialog PromptDialog) (map[string]any, error)
// Prompts the user for a single value
Prompt(ctx context.Context, options ConsoleOptions) (string, error)
// PromptFs prompts the user for a filesystem path or directory.
PromptFs(ctx context.Context, options ConsoleOptions, fsOptions FsOptions) (string, error)
// Prompts the user to select a single value from a set of values
Select(ctx context.Context, options ConsoleOptions) (int, error)
// Prompts the user to select zero or more values from a set of values
MultiSelect(ctx context.Context, options ConsoleOptions) ([]string, error)
// Prompts the user to confirm an operation
Confirm(ctx context.Context, options ConsoleOptions) (bool, error)
// block terminal until the next enter
WaitForEnter()
// Writes a new line to the writer if there if the last two characters written are not '\n'
EnsureBlankLine(ctx context.Context)
// Sets the underlying writer for the console
SetWriter(writer io.Writer)
// Gets the underlying writer for the console
GetWriter() io.Writer
// Gets the standard input, output and error stream
Handles() ConsoleHandles
// Executes an interactive action, managing spinner state
DoInteraction(action func() error) error
ConsoleShim
}
type AskerConsole struct {
asker Asker
handles ConsoleHandles
// the writer the console was constructed with, and what we reset to when SetWriter(nil) is called.
defaultWriter io.Writer
// the writer which output is written to.
writer io.Writer
formatter output.Formatter
// isTerminal controls whether terminal-style input/output will be used.
//
// When isTerminal is false, the following notable behaviors apply:
// - Spinner progress will be written as standard newline messages.
// - Prompting assumes a non-terminal environment, where output written and input received are machine-friendly text,
// stripped of formatting characters.
isTerminal bool
noPrompt bool
// when non nil, use this client instead of prompting ourselves on the console.
promptClient *externalPromptClient
// noPromptDialog when true, disables SupportsPromptDialog() even when promptClient is set.
noPromptDialog bool
showProgressMu sync.Mutex // ensures atomicity when swapping the current progress renderer (spinner or previewer)
spinner *yacspin.Spinner
spinnerLineMu sync.Mutex // secures spinnerCurrentTitle and the line of spinner text
spinnerTerminalMode yacspin.TerminalMode
spinnerCurrentTitle string
previewer syncatomic.Pointer[progressLog]
previewerRefCount int // tracks concurrent ShowPreviewer callers; only stop when it reaches 0
previewerSuppressed syncatomic.Bool
currentIndent *atomic.String
// consoleWidth is the width of the underlying console window. The value is updated as the window resized. Nil when
// isTerminal is false.
consoleWidth *atomic.Int32
// holds the last 2 bytes written by message or messageUX. This is used to detect when there is already an empty
// line (\n\n)
last2Byte [2]byte
}
type ConsoleOptions struct {
Message string
Help string
Options []string
// OptionDetails is an optional field that can be used to provide additional information about the options.
OptionDetails []string
DefaultValue any
// Prompt-only options
IsPassword bool
}
type ConsoleHandles struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
// Sets the underlying writer for output the console or
// if writer is nil, sets it back to the default writer.
func (c *AskerConsole) SetWriter(writer io.Writer) {
if writer == nil {
writer = c.defaultWriter
}
c.writer = writer
}
func (c *AskerConsole) GetFormatter() output.Formatter {
return c.formatter
}
func (c *AskerConsole) IsUnformatted() bool {
return c.formatter == nil || c.formatter.Kind() == output.NoneFormat
}
// Prints out a message to the underlying console write
func (c *AskerConsole) Message(ctx context.Context, message string) {
// In JSON mode, emit structured event output instead of plain text.
if c.formatter != nil && c.formatter.Kind() == output.JsonFormat {
// Empty messages are visual separators (blank lines) in text mode.
// In JSON mode they have no semantic value, so skip them.
if message == "" {
return
}
// we call json.Marshal directly, because the formatter marshalls using indentation, and we would prefer
// these objects be written on a single line.
var obj any = output.EventForMessage(message)
if q, ok := c.formatter.(output.Queryable); ok {
if filtered, err := q.QueryFilter(obj); err == nil {
obj = filtered
} else {
log.Printf("failed to apply query filter in Message: %v", err)
}
}
jsonMessage, err := json.Marshal(obj)
if err != nil {
panic(fmt.Sprintf("Message: unexpected error during marshaling for a valid object: %v", err))
}
fmt.Fprintln(c.writer, string(jsonMessage))
} else if c.formatter != nil {
c.println(ctx, message)
} else {
log.Println(message)
}
// Adding "\n" b/c calling Fprintln is adding one new line at the end to the msg
c.updateLastBytes(message + "\n")
}
func (c *AskerConsole) updateLastBytes(msg string) {
msgLen := len(msg)
if msgLen == 0 {
return
}
if msgLen < 2 {
c.last2Byte[0] = c.last2Byte[1]
c.last2Byte[1] = msg[msgLen-1]
return
}
c.last2Byte[0] = msg[msgLen-2]
c.last2Byte[1] = msg[msgLen-1]
}
func (c *AskerConsole) WarnForFeature(ctx context.Context, key alpha.FeatureId) {
if shouldWarn() {
c.MessageUxItem(ctx, &ux.MultilineMessage{
Lines: []string{
"",
output.WithWarningFormat("WARNING: Feature '%s' is in alpha stage.", string(key)),
fmt.Sprintf("To learn more about alpha features and their support, visit %s.",
output.WithLinkFormat("https://aka.ms/azd-feature-stages")),
"",
},
})
}
}
// shouldWarn returns true if a warning should be emitted when using a given alpha feature.
func shouldWarn() bool {
noAlphaWarnings, err := strconv.ParseBool(os.Getenv("AZD_DEBUG_NO_ALPHA_WARNINGS"))
return err != nil || !noAlphaWarnings
}
func (c *AskerConsole) MessageUxItem(ctx context.Context, item ux.UxItem) {
if c.formatter != nil && c.formatter.Kind() == output.JsonFormat {
// no need to check the spinner for json format, as the spinner won't start when using json format
// instead, there would be a message about starting spinner
var obj any = item
if q, ok := c.formatter.(output.Queryable); ok {
// UxItem.MarshalJSON() produces an EventEnvelope. To apply JMESPath we
// need the unmarshaled structure, so round-trip through JSON first.
if raw, err := json.Marshal(item); err == nil {
var envelope any
if err := json.Unmarshal(raw, &envelope); err == nil {
if filtered, err := q.QueryFilter(envelope); err == nil {
obj = filtered
}
}
}
}
jsonBytes, err := json.Marshal(obj)
if err != nil {
panic(err)
}
fmt.Fprintln(c.writer, string(jsonBytes))
return
}
msg := item.ToString(c.currentIndent.Load())
c.println(ctx, msg)
// Adding "\n" b/c calling Fprintln is adding one new line at the end to the msg
c.updateLastBytes(msg + "\n")
}
func (c *AskerConsole) println(ctx context.Context, msg string) {
if c.IsSpinnerInteractive() && c.spinner.Status() == yacspin.SpinnerRunning {
c.StopSpinner(ctx, "", Step)
// default non-format
fmt.Fprintln(c.writer, msg)
_ = c.spinner.Start()
} else {
fmt.Fprintln(c.writer, msg)
}
}
func defaultShowPreviewerOptions() *ShowPreviewerOptions {
return &ShowPreviewerOptions{
MaxLineCount: 5,
}
}
func (c *AskerConsole) ShowPreviewer(ctx context.Context, options *ShowPreviewerOptions) io.Writer {
if c.previewerSuppressed.Load() {
log.Printf("ShowPreviewer suppressed — progress table active")
return io.Discard
}
c.showProgressMu.Lock()
defer c.showProgressMu.Unlock()
if c.previewer.Load() != nil {
// Previewer already active from a concurrent caller (e.g. concurrent graph steps).
// Reuse the existing previewer and increment the reference count so that
// StopPreviewer only tears it down when the last user is done.
c.previewerRefCount++
return &consolePreviewerWriter{
previewer: &c.previewer,
}
}
// Pause any active spinner
c.spinnerLineMu.Lock()
currentMsg := c.spinnerCurrentTitle
c.spinnerLineMu.Unlock()
_ = c.spinner.Pause()
if options == nil {
options = defaultShowPreviewerOptions()
}
p := newProgressLogWithWidthFn(
options.MaxLineCount,
options.Prefix,
options.Title,
c.currentIndent.Load()+currentMsg,
func() int {
if c.consoleWidth == nil {
return 0
}
return int(c.consoleWidth.Load())
})
p.Start()
c.previewer.Store(p)
c.writer = p
c.previewerRefCount = 1
return &consolePreviewerWriter{
previewer: &c.previewer,
}
}
func (c *AskerConsole) StopPreviewer(ctx context.Context, keepLogs bool) {
if c.previewerSuppressed.Load() {
return
}
c.showProgressMu.Lock()
defer c.showProgressMu.Unlock()
if c.previewerRefCount <= 0 {
// Already fully stopped or never started. No-op.
return
}
c.previewerRefCount--
if c.previewerRefCount > 0 {
// Other concurrent callers are still using the previewer.
return
}
c.previewer.Load().Stop(keepLogs)
c.previewer.Store(nil)
c.writer = c.defaultWriter
_ = c.spinner.Unpause()
}
// PausePreviewer prevents ShowPreviewer from rendering until ResumePreviewer
// is called. Use this when a progress table owns the terminal output and previewer
// content would corrupt the display.
func (c *AskerConsole) PausePreviewer() {
c.previewerSuppressed.Store(true)
}
// ResumePreviewer re-enables previewer rendering.
func (c *AskerConsole) ResumePreviewer() {
c.previewerSuppressed.Store(false)
}
// truncationDots is the text we use to indicate that text has been truncated.
const truncationDots = "..."
// The line of text for the spinner, displayed in the format of: <prefix><spinner> <message>
type spinnerLine struct {
// The prefix before the spinner.
Prefix string
// Charset that is used to animate the spinner.
CharSet []string
// The message to be displayed.
Message string
}
func (c *AskerConsole) spinnerLine(title string, indent string) spinnerLine {
if !c.isTerminal {
return spinnerLine{
Prefix: indent,
CharSet: spinnerNoTerminalCharSet,
Message: title,
}
}
spinnerLen := len(indent) + len(spinnerCharSet[0]) + 1 // adding one for the empty space before the message
width := int(c.consoleWidth.Load())
switch {
case width <= 3: // show number of dots up to 3
return spinnerLine{
CharSet: spinnerShortCharSet[:width],
}
case width <= spinnerLen+len(truncationDots): // show number of dots
return spinnerLine{
CharSet: spinnerShortCharSet,
}
case width <= spinnerLen+len(title): // truncate title
return spinnerLine{
Prefix: indent,
CharSet: spinnerCharSet,
Message: title[:width-spinnerLen-len(truncationDots)] + truncationDots,
}
default:
return spinnerLine{
Prefix: indent,
CharSet: spinnerCharSet,
Message: title,
}
}
}
func (c *AskerConsole) ShowSpinner(ctx context.Context, title string, format SpinnerUxType) {
c.showProgressMu.Lock()
defer c.showProgressMu.Unlock()
if c.formatter != nil && c.formatter.Kind() == output.JsonFormat {
// Spinner is disabled when using json format.
return
}
if p := c.previewer.Load(); p != nil {
// spinner is not compatible with previewer.
p.Header(c.currentIndent.Load() + title)
return
}
c.spinnerLineMu.Lock()
c.spinnerCurrentTitle = title
indentPrefix := c.getIndent()
line := c.spinnerLine(title, indentPrefix)
_ = c.spinner.Pause()
c.spinner.Message(line.Message)
_ = c.spinner.CharSet(line.CharSet)
c.spinner.Prefix(line.Prefix)
_ = c.spinner.Unpause()
if c.spinner.Status() == yacspin.SpinnerStopped {
// While it is indeed safe to call Start regardless of whether the spinner is running,
// calling Start may result in an additional line of output being written in non-tty scenarios
_ = c.spinner.Start()
}
c.spinnerLineMu.Unlock()
}
// spinnerTerminalMode determines the appropriate terminal mode.
func spinnerTerminalMode(isTerminal bool) yacspin.TerminalMode {
nonInteractiveMode := yacspin.ForceNoTTYMode | yacspin.ForceDumbTerminalMode
if !isTerminal {
return nonInteractiveMode
}
termMode := yacspin.ForceTTYMode
if os.Getenv("TERM") == "dumb" {
termMode |= yacspin.ForceDumbTerminalMode
} else {
termMode |= yacspin.ForceSmartTerminalMode
}
return termMode
}
var spinnerCharSet []string = []string{
"| |", "|= |", "|== |", "|=== |", "|==== |", "|===== |", "|====== |",
"|=======|", "| ======|", "| =====|", "| ====|", "| ===|", "| ==|", "| =|",
}
var spinnerShortCharSet []string = []string{".", "..", "..."}
var spinnerNoTerminalCharSet []string = []string{""}
func setIndentation(spaces int) string {
bytes := make([]byte, spaces)
for i := range bytes {
bytes[i] = byte(' ')
}
return string(bytes)
}
func (c *AskerConsole) getIndent() string {
requiredSize := 2
if requiredSize != len(c.currentIndent.Load()) {
c.currentIndent.Store(setIndentation(requiredSize))
}
return c.currentIndent.Load()
}
func (c *AskerConsole) StopSpinner(ctx context.Context, lastMessage string, format SpinnerUxType) {
if c.formatter != nil && c.formatter.Kind() == output.JsonFormat {
// Spinner is disabled when using json format.
return
}
// Do nothing when it is already stopped
if c.spinner.Status() == yacspin.SpinnerStopped {
return
}
c.spinnerLineMu.Lock()
c.spinnerCurrentTitle = ""
// Update style according to MessageUxType
if lastMessage != "" {
lastMessage = c.getStopChar(format) + " " + lastMessage
}
_ = c.spinner.Stop()
if lastMessage != "" {
// Avoid using StopMessage() as it may result in an extra Message line print in non-tty scenarios
fmt.Fprintln(c.writer, lastMessage)
}
c.spinnerLineMu.Unlock()
}
func (c *AskerConsole) IsSpinnerRunning(ctx context.Context) bool {
return c.spinner.Status() != yacspin.SpinnerStopped
}
func (c *AskerConsole) IsSpinnerInteractive() bool {
return c.spinnerTerminalMode&yacspin.ForceTTYMode > 0
}
var donePrefix string = output.WithSuccessFormat("(✓) Done:")
func (c *AskerConsole) getStopChar(format SpinnerUxType) string {
var stopChar string
switch format {
case StepDone:
stopChar = donePrefix
case StepFailed:
stopChar = output.WithErrorFormat("(x) Failed:")
case StepWarning:
stopChar = output.WithWarningFormat("(!) Warning:")
case StepSkipped:
stopChar = output.WithGrayFormat("(-) Skipped:")
}
return fmt.Sprintf("%s%s", c.getIndent(), stopChar)
}
func promptFromOptions(options ConsoleOptions) survey.Prompt {
if options.IsPassword {
// different than survey.Input, survey.Password doest not reset the line before rendering the question
// see password implementation: https://github.com/AlecAivazis/survey/blob/master/password.go#L51
// and input: https://github.com/AlecAivazis/survey/blob/master/input.go#L141
// by calling .Render(), the line is reset, cleaning any current message or spinner.
tm.Print(tm.ResetLine(""))
tm.Flush()
return &survey.Password{
Message: options.Message,
Help: options.Help,
}
}
var defaultValue string
if value, ok := options.DefaultValue.(string); ok {
defaultValue = value
}
return &survey.Input{
Message: options.Message,
Default: defaultValue,
Help: options.Help,
}
}
// afterIoSentinel is a sentinel value used after Input/Output operations as the state for the last 2-bytes written.
// For example, after running Prompt or Confirm, the last characters on the terminal should be any char (represented by the
// 0 in the sentinel), followed by a new line.
const afterIoSentinel = "0\n"
func (c *AskerConsole) IsNoPromptMode() bool {
return c.noPrompt
}
func (c *AskerConsole) SupportsPromptDialog() bool {
return c.promptClient != nil && !c.noPromptDialog
}
// PromptDialog prompts for multiple values using a single dialog. When successful, it returns a map of prompt IDs to their
// values.
func (c *AskerConsole) PromptDialog(ctx context.Context, dialog PromptDialog) (map[string]any, error) {
request := externalPromptDialogRequest{
Title: dialog.Title,
Description: dialog.Description,
Prompts: make([]externalPromptDialogPrompt, len(dialog.Prompts)),
}
for i, prompt := range dialog.Prompts {
request.Prompts[i] = externalPromptDialogPrompt{
ID: prompt.ID,
Kind: prompt.Kind,
DisplayName: prompt.DisplayName,
Description: prompt.Description,
DefaultValue: prompt.DefaultValue,
Required: prompt.Required,
}
}
resp, err := c.promptClient.PromptDialog(ctx, request)
if err != nil {
return nil, err
}
ret := make(map[string]any, len(*resp.Inputs))
for _, v := range *resp.Inputs {
var unmarshalledValue any
if err := json.Unmarshal(v.Value, &unmarshalledValue); err != nil {
return nil, fmt.Errorf("unmarshalling value %s: %w", v.ID, err)
}
ret[v.ID] = unmarshalledValue
}
return ret, nil
}
// Prompts the user for a single value
func (c *AskerConsole) Prompt(ctx context.Context, options ConsoleOptions) (string, error) {
var response string
if c.promptClient != nil {
opts := promptOptions{
Type: "string",
Options: promptOptionsOptions{
Message: options.Message,
Help: options.Help,
},
}
if options.IsPassword {
opts.Type = "password"
}
if value, ok := options.DefaultValue.(string); ok {
opts.Options.DefaultValue = to.Ptr[any](value)
}
result, err := c.promptClient.Prompt(ctx, opts)
if errors.Is(err, promptCancelledErr) {
return "", surveyterm.InterruptErr
} else if err != nil {
return "", err
}
if err := json.Unmarshal(result, &response); err != nil {
return "", fmt.Errorf("unmarshalling response: %w", err)
}
return response, nil
}
err := c.doInteraction(func(c *AskerConsole) error {
return c.asker(promptFromOptions(options), &response)
})
if err != nil {
return response, err
}
c.updateLastBytes(afterIoSentinel)
return response, nil
}
func choicesFromOptions(options ConsoleOptions) []promptChoice {
choices := make([]promptChoice, len(options.Options))
for i, option := range options.Options {
choices[i] = promptChoice{
Value: option,
}
if i < len(options.OptionDetails) && options.OptionDetails[i] != "" {
choices[i].Detail = &options.OptionDetails[i]
}
}
return choices
}
// Prompts the user to select from a set of values
func (c *AskerConsole) Select(ctx context.Context, options ConsoleOptions) (int, error) {
if c.promptClient != nil {
opts := promptOptions{
Type: "select",
Options: promptOptionsOptions{
Message: options.Message,
Help: options.Help,
Choices: new(choicesFromOptions(options)),
},
}
if value, ok := options.DefaultValue.(string); ok {
opts.Options.DefaultValue = to.Ptr[any](value)
}
result, err := c.promptClient.Prompt(ctx, opts)
if errors.Is(err, promptCancelledErr) {
return -1, surveyterm.InterruptErr
} else if err != nil {
return -1, err
}
var choice string
if err := json.Unmarshal(result, &choice); err != nil {
return -1, fmt.Errorf("unmarshalling response: %w", err)
}
res := slices.Index(options.Options, choice)
if res == -1 {
return -1, fmt.Errorf("invalid choice: %s", choice)
}
return res, nil
}
surveyOptions := make([]string, len(options.Options))
surveyDefault := options.DefaultValue
surveyDefaultAsString, surveyDefaultIsString := surveyDefault.(string)
// Modify the options and default value to include any details
for i, option := range options.Options {
surveyOptions[i] = option
if c.IsSpinnerInteractive() && i < len(options.OptionDetails) {
if options.OptionDetails[i] != "" {
detailString := output.WithGrayFormat("(%s)", options.OptionDetails[i])
surveyOptions[i] += fmt.Sprintf("\n %s\n", detailString)
} else {
surveyOptions[i] += "\n"
}
if surveyDefaultIsString && surveyDefaultAsString == option {
surveyDefault = surveyOptions[i]
}
}
}
survey := &survey.Select{
Message: options.Message,
Options: surveyOptions,
Default: surveyDefault,
Help: options.Help,
}
var response int
err := c.doInteraction(func(c *AskerConsole) error {
return c.asker(survey, &response)
})
if err != nil {
return -1, err
}
c.updateLastBytes(afterIoSentinel)
return response, nil
}
func (c *AskerConsole) MultiSelect(ctx context.Context, options ConsoleOptions) ([]string, error) {
var response []string
if c.promptClient != nil {
opts := promptOptions{
Type: "multiSelect",
Options: promptOptionsOptions{
Message: options.Message,
Help: options.Help,
Choices: new(choicesFromOptions(options)),
},
}
if value, ok := options.DefaultValue.([]string); ok {
opts.Options.DefaultValue = to.Ptr[any](value)
}
result, err := c.promptClient.Prompt(ctx, opts)
if errors.Is(err, promptCancelledErr) {
return nil, surveyterm.InterruptErr
} else if err != nil {
return nil, err
}
if err := json.Unmarshal(result, &response); err != nil {
return nil, fmt.Errorf("unmarshalling response: %w", err)
}
return response, nil
}
surveyOptions := make([]string, len(options.Options))
surveyDefault := options.DefaultValue
surveyDefaultAsArr, surveyDefaultIsArr := surveyDefault.([]string)
// Modify the options and default value to include any details
for i, option := range options.Options {
surveyOptions[i] = option
if c.IsSpinnerInteractive() && i < len(options.OptionDetails) {
detailString := output.WithGrayFormat("%s", options.OptionDetails[i])
surveyOptions[i] += fmt.Sprintf("\n %s\n", detailString)
}
if surveyDefaultIsArr {
for idx, defaultOption := range surveyDefaultAsArr {
if defaultOption == option {
surveyDefaultAsArr[idx] = surveyOptions[i]
}
}
}
}
survey := &survey.MultiSelect{
Message: options.Message,
Options: surveyOptions,
Default: surveyDefault,
Help: options.Help,
}
err := c.doInteraction(func(c *AskerConsole) error {
return c.asker(survey, &response)
})
if err != nil {
return nil, err
}
return response, nil
}
// Prompts the user to confirm an operation
func (c *AskerConsole) Confirm(ctx context.Context, options ConsoleOptions) (bool, error) {
if c.promptClient != nil {
opts := promptOptions{
Type: "confirm",
Options: promptOptionsOptions{
Message: options.Message,
Help: options.Help,
},
}
if value, ok := options.DefaultValue.(bool); ok {
opts.Options.DefaultValue = to.Ptr[any](value)
}
result, err := c.promptClient.Prompt(ctx, opts)
if errors.Is(err, promptCancelledErr) {
return false, surveyterm.InterruptErr
} else if err != nil {
return false, err
}
var response string
if err := json.Unmarshal(result, &response); err != nil {
return false, fmt.Errorf("unmarshalling response: %w", err)
}
switch response {
case "true":
return true, nil
case "false":
return false, nil
default:
return false, fmt.Errorf("invalid response: %s", response)
}
}
var defaultValue bool
if value, ok := options.DefaultValue.(bool); ok {
defaultValue = value
}
survey := &survey.Confirm{
Message: options.Message,
Help: options.Help,
Default: defaultValue,
}
var response bool
err := c.doInteraction(func(c *AskerConsole) error {
return c.asker(survey, &response)
})
if err != nil {
return false, err
}
c.updateLastBytes(afterIoSentinel)
return response, nil
}
const c_newLine = '\n'
func (c *AskerConsole) EnsureBlankLine(ctx context.Context) {
if c.last2Byte[0] == c_newLine && c.last2Byte[1] == c_newLine {
return
}
if c.last2Byte[1] != c_newLine {
c.Message(ctx, "\n")
return
}
// [1] is '\n' but [0] is not. One new line missing
c.Message(ctx, "")
}
// wait until the next enter
func (c *AskerConsole) WaitForEnter() {
if c.noPrompt {
return
}
inputScanner := bufio.NewScanner(c.handles.Stdin)
if scan := inputScanner.Scan(); !scan {
if err := inputScanner.Err(); err != nil {
log.Printf("error while waiting for enter: %v", err)
}
}
}
// Gets the underlying writer for the console
func (c *AskerConsole) GetWriter() io.Writer {
return c.writer
}
func (c *AskerConsole) Handles() ConsoleHandles {
return c.handles
}
// consoleWidth the number of columns in the active console window
func consoleWidth() int32 {
widthInt, _ := consolesize.GetConsoleSize()
// Suppress G115: integer overflow conversion int -> int32 below.
// Explanation: