Skip to content

Commit fe5a80d

Browse files
feat: add optional mask to InteractiveTextInputPrinter
...for prompting for secrets/passwords/tokens Co-authored-by: Rodrigo Bernardi <[email protected]>
1 parent 1ce176a commit fe5a80d

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

interactive_textinput_printer.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ var (
1515
DefaultInteractiveTextInput = InteractiveTextInputPrinter{
1616
DefaultText: "Input text",
1717
TextStyle: &ThemeDefault.PrimaryStyle,
18+
Mask: "",
1819
}
1920
)
2021

@@ -23,6 +24,7 @@ type InteractiveTextInputPrinter struct {
2324
TextStyle *Style
2425
DefaultText string
2526
MultiLine bool
27+
Mask string
2628

2729
input []string
2830
cursorXPos int
@@ -48,6 +50,12 @@ func (p InteractiveTextInputPrinter) WithMultiLine(multiLine ...bool) *Interacti
4850
return &p
4951
}
5052

53+
// WithMask sets the mask.
54+
func (p InteractiveTextInputPrinter) WithMask(mask string) *InteractiveTextInputPrinter {
55+
p.Mask = mask
56+
return &p
57+
}
58+
5159
// Show shows the interactive select menu and returns the selected entry.
5260
func (p InteractiveTextInputPrinter) Show(text ...string) (string, error) {
5361
// should be the first defer statement to make sure it is executed last
@@ -200,13 +208,19 @@ func (p InteractiveTextInputPrinter) updateArea(area *AreaPrinter) string {
200208
p.cursorYPos = 0
201209
}
202210
areaText := p.text
211+
203212
for i, s := range p.input {
204213
if i < len(p.input)-1 {
205214
areaText += s + "\n"
206215
} else {
207216
areaText += s
208217
}
209218
}
219+
220+
if p.Mask != "" {
221+
areaText = p.text + strings.Repeat(p.Mask, internal.GetStringMaxWidth(areaText)-internal.GetStringMaxWidth(p.text))
222+
}
223+
210224
if p.cursorXPos+internal.GetStringMaxWidth(p.input[p.cursorYPos]) < 1 {
211225
p.cursorXPos = -internal.GetStringMaxWidth(p.input[p.cursorYPos])
212226
}

interactive_textinput_printer_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package pterm_test
33
import (
44
"testing"
55

6+
"atomicgo.dev/keyboard"
7+
"atomicgo.dev/keyboard/keys"
68
"github.com/MarvinJWendt/testza"
79

810
"github.com/pterm/pterm"
@@ -28,3 +30,14 @@ func TestInteractiveTextInputPrinter_WithTextStyle(t *testing.T) {
2830
p := pterm.DefaultInteractiveTextInput.WithTextStyle(style)
2931
testza.AssertEqual(t, p.TextStyle, style)
3032
}
33+
34+
func TestInteractiveTextInputPrinter_WithMask(t *testing.T) {
35+
go func() {
36+
keyboard.SimulateKeyPress('a')
37+
keyboard.SimulateKeyPress('b')
38+
keyboard.SimulateKeyPress('c')
39+
keyboard.SimulateKeyPress(keys.Enter)
40+
}()
41+
result, _ := pterm.DefaultInteractiveTextInput.WithMask("*").Show()
42+
testza.AssertEqual(t, result, "abc")
43+
}

0 commit comments

Comments
 (0)