Skip to content

Commit

Permalink
refactor reader implementation for standard input support
Browse files Browse the repository at this point in the history
  • Loading branch information
itchyny committed Oct 12, 2024
1 parent bae53f4 commit 95c6916
Showing 1 changed file with 30 additions and 30 deletions.
60 changes: 30 additions & 30 deletions window/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,48 +159,48 @@ func expandBacktick(filename string) (string, error) {
}

func (m *Manager) read(r io.Reader) error {
bs, err := func() ([]byte, error) {

Check failure on line 162 in window/manager.go

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

this value of err is never used (SA4006)

Check failure on line 162 in window/manager.go

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

this value of err is never used (SA4006)

Check failure on line 162 in window/manager.go

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

this value of err is never used (SA4006)
r, stop := newReader(r)
defer stop()
return io.ReadAll(r)
}()
window, err := newWindow(bytes.NewReader(bs), "", "", m.eventCh, m.redrawCh)
if err != nil {
return err
}
return m.init(window)
}

type reader struct {
io.Reader
abort chan os.Signal
}

func newReader(r io.Reader) (*reader, func()) {
done := make(chan struct{})
defer close(done)
abort := make(chan os.Signal, 1)
signal.Notify(abort, os.Interrupt)
defer signal.Stop(abort)
go func() {
select {
case <-time.After(time.Second):
fmt.Fprint(os.Stderr, "Reading stdin took more than 1 second, press <C-c> to abort...")
case <-done:
}
}()
bs, err := func() ([]byte, error) {
// ref: io.ReadAll
bs := make([]byte, 0, 1024)
for {
n, err := r.Read(bs[len(bs):cap(bs)])
bs = bs[:len(bs)+n]
if err != nil {
if err == io.EOF {
err = nil
}
return bs, err
}
select {
case <-time.After(10 * time.Millisecond):
case <-abort:
return bs, nil
}
if len(bs) == cap(bs) {
bs = append(bs, 0)[:len(bs)]
}
}
}()
if err != nil {
return err
return &reader{r, abort}, func() {
signal.Stop(abort)
close(abort)
close(done)
}
window, err := newWindow(bytes.NewReader(bs), "", "", m.eventCh, m.redrawCh)
if err != nil {
return err
}

func (r *reader) Read(p []byte) (int, error) {
select {
case <-r.abort:
return 0, io.EOF
default:
}
return m.init(window)
return r.Reader.Read(p)
}

// SetSize sets the size of the screen.
Expand Down

0 comments on commit 95c6916

Please sign in to comment.