Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: x/term: Interruptable ReadLine #69217

Closed
dnbsd opened this issue Sep 2, 2024 · 2 comments
Closed

proposal: x/term: Interruptable ReadLine #69217

dnbsd opened this issue Sep 2, 2024 · 2 comments
Labels
Milestone

Comments

@dnbsd
Copy link

dnbsd commented Sep 2, 2024

Proposal Details

Reading a line from a terminal can only be interrupted by the user pressing CTRL+D or CTRL+C. API does not allow the reading to be interrupted via other means. This creates an impossible scenario if other goroutine should be the source of interrupt.

Closing an underlying file (os.Stdin) does not work as expected. A user is still required to touch at least a single key for the closure be detected. And, of course, closing stdin in itself is problematic in more complex programs.

I would like to propose adding a new method Terminal.Close which would terminate blocking ReadLine call, or adding ReadLineWithContext to achieve the same just using context.Context.

package main

import (
	"fmt"
	xterm "golang.org/x/term"
	"io"
	"os"
	"time"
)

var fd = int(os.Stdin.Fd())

func main() {
	origState, err := xterm.GetState(fd)
	if err != nil {
		panic(err)
	}
	defer xterm.Restore(fd, origState)

	term := xterm.NewTerminal(os.Stdin, "> ")

	go func(){
		<-time.After(10*time.Second)
		// Terminate ReadLine here...
	}()

	for {
		oldState, err := xterm.MakeRaw(fd)
		if err != nil {
			panic(err)
		}

		line, err := term.ReadLine()
		if err != nil {
			if err != io.EOF {
				panic(err)
			}
			return
		}

		err = xterm.Restore(fd, oldState)
		if err != nil {
			panic(err)
		}

		fmt.Printf("%q\n", line)
	}
}
@dnbsd dnbsd added the Proposal label Sep 2, 2024
@gopherbot gopherbot added this to the Proposal milestone Sep 2, 2024
@gabyhelp
Copy link

gabyhelp commented Sep 2, 2024

@seankhliao
Copy link
Member

I don't think this is possible by default, as the function would still be blocked on the read without a way to interrupt it properly. see #24842 and #26579 for related workarounds.

@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Sep 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants