Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 31 additions & 10 deletions internal/core/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,17 +264,38 @@ func (k *Keys) ReadKey() (key rune, isAbort bool) {
k.mutex.RUnlock()
}()

switch {
case len(k.macroKeys) > 0:
key = k.macroKeys[0]
k.macroKeys = k.macroKeys[1:]
for {
switch {
case len(k.macroKeys) > 0:
key = k.macroKeys[0]
k.macroKeys = k.macroKeys[1:]
case k.waiting:
buf := <-k.keysOnce
if len(buf) == 0 {
if k.eof {
return 0, true
}
continue
}
key = []rune(string(buf))[0]
default:
buf, err := k.readInputFiltered()
if err != nil {
if errors.Is(err, io.EOF) {
k.eof = true
}
return 0, true
}
if len(buf) == 0 {
if k.eof {
return 0, true
}
continue
}
key = []rune(string(buf))[0]
}

case k.waiting:
buf := <-k.keysOnce
key = []rune(string(buf))[0]
default:
buf, _ := k.readInputFiltered()
key = []rune(string(buf))[0]
break
}

// Always mark those keys as matched, so that
Expand Down
82 changes: 82 additions & 0 deletions internal/core/keys_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package core

import (
"io"
"testing"
)

type readStep struct {
data []byte
err error
}

type stubReadCloser struct {
steps []readStep
index int
}

func (s *stubReadCloser) Read(p []byte) (int, error) {
if s.index >= len(s.steps) {
return 0, io.EOF
}

step := s.steps[s.index]
s.index++

copy(p, step.data)

return len(step.data), step.err
}

func (s *stubReadCloser) Close() error {
return nil
}

func TestKeysReadKeySkipsEmptyReads(t *testing.T) {
originalStdin := Stdin
Stdin = &stubReadCloser{
steps: []readStep{
{},
{data: []byte("x")},
},
}
t.Cleanup(func() {
Stdin = originalStdin
})

keys := &Keys{}

key, isAbort := keys.ReadKey()

if isAbort {
t.Fatal("expected ReadKey to continue after an empty read")
}

if key != 'x' {
t.Fatalf("expected key %q, got %q", 'x', key)
}
}

func TestKeysReadKeyReturnsAbortOnEOF(t *testing.T) {
originalStdin := Stdin
Stdin = &stubReadCloser{
steps: []readStep{
{err: io.EOF},
},
}
t.Cleanup(func() {
Stdin = originalStdin
})

keys := &Keys{}

key, isAbort := keys.ReadKey()

if !isAbort {
t.Fatal("expected ReadKey to abort on EOF")
}

if key != 0 {
t.Fatalf("expected zero key on EOF, got %q", key)
}
}
Loading