Skip to content

Commit

Permalink
Fix data race in prompt and select
Browse files Browse the repository at this point in the history
  • Loading branch information
minchao committed Oct 31, 2021
1 parent cc2590d commit 862377f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
10 changes: 10 additions & 0 deletions prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io"
"strings"
"sync"
"text/template"

"github.com/chzyer/readline"
Expand Down Expand Up @@ -157,8 +158,11 @@ func (p *Prompt) Run() (string, error) {
}
eraseDefault := input != "" && !p.AllowEdit
cur := NewCursor(input, p.Pointer, eraseDefault)
var curLock sync.Mutex

listen := func(input []rune, pos int, key rune) ([]rune, int, bool) {
defer curLock.Unlock()
curLock.Lock()
_, _, keepOn := cur.Listen(input, pos, key)
err := validFn(cur.Get())
var prompt []byte
Expand Down Expand Up @@ -193,7 +197,10 @@ func (p *Prompt) Run() (string, error) {

for {
_, err = rl.Readline()
curLock.Lock()
inputErr = validFn(cur.Get())
curLock.Unlock()

if inputErr == nil {
break
}
Expand All @@ -203,6 +210,9 @@ func (p *Prompt) Run() (string, error) {
}
}

defer curLock.Unlock()
curLock.Lock()

if err != nil {
switch err {
case readline.ErrInterrupt:
Expand Down
8 changes: 8 additions & 0 deletions select.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"sync"
"text/tabwriter"
"text/template"

Expand Down Expand Up @@ -246,6 +247,7 @@ func (s *Select) innerRun(cursorPos, scroll int, top rune) (int, string, error)
rl.Write([]byte(hideCursor))
sb := screenbuf.New(rl)

var curLock sync.Mutex
cur := NewCursor("", s.Pointer, false)

canSearch := s.Searcher != nil
Expand All @@ -254,6 +256,9 @@ func (s *Select) innerRun(cursorPos, scroll int, top rune) (int, string, error)
s.list.SetStart(scroll)

c.SetListener(func(line []rune, pos int, key rune) ([]rune, int, bool) {
defer curLock.Unlock()
curLock.Lock()

switch {
case key == KeyEnter:
return nil, 0, true
Expand Down Expand Up @@ -373,6 +378,9 @@ func (s *Select) innerRun(cursorPos, scroll int, top rune) (int, string, error)

}

defer curLock.Unlock()
curLock.Lock()

if err != nil {
if err.Error() == "Interrupt" {
err = ErrInterrupt
Expand Down

0 comments on commit 862377f

Please sign in to comment.