From 01e58d40374122083a1b9a0ae98a62fefdc22d78 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 9 Nov 2026 13:11:56 +0100 Subject: [PATCH] shellterm: a line-oriented terminal, extracted from the dashboard Session is go-wasmcontainers/dashboard v0.8.0's vm.Terminal on go-widgets/lineedit v0.1.1, with the dashboard-specific parts turned into options: Post (was app.post), OnDone (was app.Refresh), Greeting (was the wctr greeting), and Note (was note, minus the "# dashboard:" prefix, Clean and ShowActions, which stay with the caller). Bind wires a toolkit.Terminal as the dashboard's ui/scene.go did. The tests are the dashboard's TestTerminal on a vt.Screen, under -race, at 100 % coverage. Refs go-widgets/toolkit#548 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 56 +++++++ README.md | 82 ++++++++++- bind.go | 24 +++ bind_test.go | 62 ++++++++ example_test.go | 45 ++++++ go.mod | 24 +++ go.sum | 38 +++++ shellterm.go | 308 +++++++++++++++++++++++++++++++++++++++ shellterm_test.go | 272 ++++++++++++++++++++++++++++++++++ 9 files changed, 910 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yml create mode 100644 bind.go create mode 100644 bind_test.go create mode 100644 example_test.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 shellterm.go create mode 100644 shellterm_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..987c463 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,56 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + native: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - name: vet + run: go vet ./... + - name: vet (js/wasm) + shell: bash + run: GOOS=js GOARCH=wasm go vet ./... + - name: test + run: go test -race -count=1 ./... + - name: coverage gate (100%) + shell: bash + run: | + go test -count=1 -coverprofile=cov.out ./... + go tool cover -func=cov.out | tee cov.txt + grep -q 'total:.*100.0%' cov.txt || { echo "coverage below 100%"; exit 1; } + + linux-386: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - name: test (32-bit int) + env: + GOARCH: "386" + run: go test -count=1 ./... + + govulncheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - run: go run golang.org/x/vuln/cmd/govulncheck@latest ./... diff --git a/README.md b/README.md index d795d08..7b991d8 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,82 @@ # shellterm -A line-oriented terminal: toolkit.Terminal, lineedit and a Shell you supply. + +A line-oriented terminal for go-widgets. It puts a line editor +([go-widgets/lineedit](https://github.com/go-widgets/lineedit): history, Tab +completion, Ctrl-R, Ctrl-C, Ctrl-L) in front of a **Shell you supply**, and +draws into a `toolkit.Terminal`. Each application keeps only its shell. + +```sh +go get github.com/go-widgets/shellterm +``` + +## Use + +```go +type Shell interface { + Run(ctx context.Context, line string, out io.Writer) (code int, clear bool) +} + +s := shellterm.New(shellterm.Options{ + Post: post, // runs a func on the UI goroutine (required) + Greeting: "my shell\r\n", // written once, before the first prompt + OnDone: refresh, // optional: after each command, on the UI goroutine +}) +s.SetShell(myShell, myCompleter) // a lineedit.Completer, or nil +term := toolkit.NewTerminal(80, 24, 5000) +shellterm.Bind(term, s, invalidate) // typing → s, output → term, clear → screen and scrollback +``` + +[example_test.go](example_test.go) is the same code, compiled by `go vet` +on every change. + +**How a session behaves:** +- **The prompt:** a submitted line goes to `Shell.Run` on a goroutine of its + own. Its output becomes terminal output (`\n` → `\r\n`). A non-zero status + shows `[exit status N]`, then the prompt returns. +- **While a command runs:** only Ctrl-C reaches it (it cancels `ctx`). + `Running` (an `mvvm.Observable[bool]`) says so. +- **Keys:** they are handled on the session's goroutine, never the UI's, so a + `Completer` may ask a slow back end. Each key's work is bounded by + `CompleteTimeout`. +- **`Note(text)`:** shows a line above the prompt and keeps the line being + edited below it. Nothing is shown while a command runs. +- **Bounds:** at most `InputQueue` keystrokes wait (more are dropped, never + blocking the UI); at most `PendingWrites` outputs are kept before the first + `Attach`. +- **Hosts:** a host without `toolkit.Terminal` calls `Attach(out, clear)`, + `Input` and `Resize` itself. + +**Font and cell size:** set them on the terminal: `term.SetFont(face)`, +`term.SetCellSize(16, 16)` (toolkit v0.362.0). + +## Origin + +Extracted from go-wasmcontainers/dashboard v0.8.0 (`vm/terminal.go`) for +go-widgets/toolkit#548, so that two consumers share one implementation: +- the go-wasmcontainers dashboard and playground; +- wasmdesk/wasmbox (wasmdesk/wasmbox#173). + +**What changed in the move:** +- The dashboard's app queue became `Options.Post`, and its refresh became + `Options.OnDone`. +- The wctr greeting became `Options.Greeting`. +- The "# dashboard:" note became the generic `Note`; the caller formats and + cleans its text. +- wctr's shell and completer stay in go-wasmcontainers. + +## Tests + +- 100 % statement coverage, gated in CI. +- The session tests run under `-race` against a real `vt.Screen` and a + serialised UI goroutine, and cover: the greeting, history kept across + `SetShell`, Ctrl-C at the prompt and during a command, exit status, clear and + Ctrl-L, completion listings, notes, and the queue bounds. +- CI runs on Linux (amd64 and arm64), macOS, Windows and 32-bit Linux, vets + js/wasm, and runs govulncheck. +- Untrusted input (keys, terminal bytes) is parsed by lineedit, which fuzzes + it in its own CI. Untrusted output goes to `toolkit.Terminal`, which is safe + for it by construction. + +## Licence + +BSD 3-Clause, see [LICENSE](LICENSE). diff --git a/bind.go b/bind.go new file mode 100644 index 0000000..be9157a --- /dev/null +++ b/bind.go @@ -0,0 +1,24 @@ +package shellterm + +import "github.com/go-widgets/toolkit" + +// Bind connects a session to a toolkit.Terminal: what the user types goes +// to the session, a resize tells it the width, and its output and clears +// go to the terminal, after which invalidate (nil: nothing) asks the host +// to redraw. A clear empties the screen and the scrollback. Call it on the +// UI goroutine; it attaches the session. +func Bind(term *toolkit.Terminal, s *Session, invalidate func()) { + if invalidate == nil { + invalidate = func() {} + } + term.OnInput = s.Input + term.OnResize = func(cols, _ int) { s.Resize(cols) } + s.Attach(func(out string) { + _, _ = term.Write([]byte(out)) // a Terminal's Write never fails + invalidate() + }, func() { + term.Screen().WriteString("\x1b[H\x1b[2J") + term.Screen().ClearScrollback() + invalidate() + }) +} diff --git a/bind_test.go b/bind_test.go new file mode 100644 index 0000000..87342f5 --- /dev/null +++ b/bind_test.go @@ -0,0 +1,62 @@ +package shellterm + +import ( + "strings" + "testing" + + "github.com/go-widgets/toolkit" + "github.com/go-widgets/toolkit/vt" +) + +// Bind wires a toolkit.Terminal both ways: typing reaches the shell, its +// output reaches the screen, a clear empties screen and scrollback, and each +// change asks for a redraw. +func TestBind(t *testing.T) { + r := newRig(t, Options{Greeting: "hi\r\n"}) + term := toolkit.NewTerminal(80, 12, 100) + sh := &recShell{} + r.ses.SetShell(sh, nil) + redraws := 0 + r.onUI(func() { Bind(term, r.ses, func() { redraws++ }) }) + screen := func() (s string) { + r.onUI(func() { + sc := term.Screen() + s = sc.Text(vt.Pos{}, vt.Pos{Line: sc.Lines(), Col: 80}) + }) + return s + } + wait := func(want string) { + t.Helper() + r.until(want, func() bool { return strings.Contains(screen(), want) }) + } + wait("hi") + term.OnInput("echo 1\r") // what the widget hands over for typed keys + wait("ran echo 1") + term.OnResize(100, 12) + r.until("cols", func() bool { r.ses.mu.Lock(); defer r.ses.mu.Unlock(); return r.ses.r.Cols == 100 }) + + r.onUI(func() { term.Screen().WriteString(strings.Repeat("line\r\n", 40)) }) // into the scrollback + sh.set(0, true, nil) + term.OnInput("clear\r") + r.until("cleared", func() bool { + var n int + r.onUI(func() { n = term.Screen().ScrollbackLen() }) + return n == 0 && !strings.Contains(screen(), "line") && !r.running() + }) + if redraws == 0 { + t.Error("no redraw asked for") + } +} + +// A nil invalidate is allowed. +func TestBindWithoutInvalidate(t *testing.T) { + r := newRig(t, Options{Greeting: "hi\r\n"}) + term := toolkit.NewTerminal(80, 12, 0) + r.onUI(func() { Bind(term, r.ses, nil) }) + r.ses.Input("\x0c") // a clear through the bound Clear + r.until("prompt", func() bool { + var s string + r.onUI(func() { s = term.Screen().Text(vt.Pos{}, vt.Pos{Line: 1, Col: 80}) }) + return strings.HasPrefix(s, "$") + }) +} diff --git a/example_test.go b/example_test.go new file mode 100644 index 0000000..1c082ef --- /dev/null +++ b/example_test.go @@ -0,0 +1,45 @@ +package shellterm_test + +import ( + "context" + "fmt" + "io" + "strings" + + "github.com/go-widgets/lineedit" + "github.com/go-widgets/shellterm" + "github.com/go-widgets/toolkit" +) + +// echo is a Shell: it prints its line back, and "clear" clears the screen. +type echo struct{} + +func (echo) Run(_ context.Context, line string, out io.Writer) (int, bool) { + words, err := lineedit.Split(line) + if err != nil { + fmt.Fprintln(out, "syntax error:", err) + return 2, false + } + if len(words) > 0 && words[0] == "clear" { + return 0, true + } + fmt.Fprintln(out, strings.Join(words, " ")) + return 0, false +} + +// A session in front of a toolkit.Terminal. post runs a function on the UI +// goroutine; here it runs it at once, as a single-threaded host would. +func Example() { + post := func(f func()) { f() } + term := toolkit.NewTerminal(80, 24, 1000) + s := shellterm.New(shellterm.Options{Post: post, Greeting: "echo shell\r\n"}) + s.SetShell(echo{}, func(_ context.Context, words []string, _ string) ([]lineedit.Candidate, bool) { + if len(words) == 0 { + return []lineedit.Candidate{{Value: "clear"}}, false + } + return nil, false + }) + shellterm.Bind(term, s, func() { /* ask the host to redraw */ }) + // The host now draws term and routes its events to it: typed keys + // reach s, and s's output reaches term. +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..0d03aa5 --- /dev/null +++ b/go.mod @@ -0,0 +1,24 @@ +module github.com/go-widgets/shellterm + +go 1.27.3 + +require ( + github.com/go-widgets/lineedit v0.1.1 + github.com/go-widgets/mvvm v0.15.0 + github.com/go-widgets/toolkit v0.362.0 +) + +require ( + github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 // indirect + github.com/go-crdt/crdt v0.57.0 // indirect + github.com/go-gfx/gfx v0.41.0 // indirect + github.com/go-icons/iconoir v0.3.0 // indirect + github.com/go-images/images v0.1.1-0.20261026203936-4ac989d310a1 // indirect + github.com/go-opentype/fonts v0.14.0 // indirect + github.com/go-opentype/opentype v0.16.2-0.20261027113239-5e69589e9a5e // indirect + github.com/go-opentype/shape v0.7.0 // indirect + github.com/go-richdoc/richdoc v0.7.0 // indirect + github.com/go-typeset/bidi v0.3.1 // indirect + github.com/go-widgets/painter v0.17.0 // indirect + github.com/go-widgets/textinput v0.1.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..df008b0 --- /dev/null +++ b/go.sum @@ -0,0 +1,38 @@ +github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A= +github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 h1:2tV76y6Q9BB+NEBasnqvs7e49aEBFI8ejC89PSnWH+4= +github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707/go.mod h1:qssHWj60/X5sZFNxpG4HBPDHVqxNm4DfnCKgrbZOT+s= +github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY= +github.com/go-crdt/crdt v0.57.0 h1:sNLDTVCEnSb20gm77BUuYav8dzj5krmly/z9O7eRMCo= +github.com/go-crdt/crdt v0.57.0/go.mod h1:zdVTTDLGV5JYAoTJDqCivcAT+/B5gGebDsVd8QNZpVs= +github.com/go-gfx/gfx v0.41.0 h1:MVEnory0Zx8ypzuVDrTIWz4Cekv8hn5ilcYg3glJPrk= +github.com/go-gfx/gfx v0.41.0/go.mod h1:4OenoKrgdht6UXYf5SV8w2tb41hfAdy4QoxJRPsRDz4= +github.com/go-icons/iconoir v0.3.0 h1:kHG2sU5IsCvtBS1JICuXgfFo5f8UfwY1m7KYMVy97CI= +github.com/go-icons/iconoir v0.3.0/go.mod h1:lPh5OuzVQ+rR4qDPGgAdSRUhnCbHeCAX70HDdwp8/RI= +github.com/go-images/images v0.1.1-0.20261026203936-4ac989d310a1 h1:R7Phx1lhFniaqF+k7yE72HcadFeViKYXXb9w2puZJRI= +github.com/go-images/images v0.1.1-0.20261026203936-4ac989d310a1/go.mod h1:TXN7V9gKgEe8L4GVYeTO01sQI6n5JUL5Q1xIl09qOio= +github.com/go-opentype/fonts v0.14.0 h1:WHw7k9gkHT1pu9B2yyvd0FWyQqn/4NKFQoKhvMYt3Mo= +github.com/go-opentype/fonts v0.14.0/go.mod h1:od2QcmdpKo7QCqo6Jb16y4GULk+h2Hhfq6x3xfvn62Q= +github.com/go-opentype/opentype v0.16.2-0.20261027113239-5e69589e9a5e h1:SxBkVzp042LB0X7Ndu0WntqCVaewOm4DwikQYHenP5A= +github.com/go-opentype/opentype v0.16.2-0.20261027113239-5e69589e9a5e/go.mod h1:RujaDgR2h/ErgMkc5y/KYbX8NJtWw3yLRtVxbCfdvFQ= +github.com/go-opentype/shape v0.7.0 h1:hXUkI4xdpkzq31ZYf/6zfkDAgRLZnTjI1q8DWLu5MGQ= +github.com/go-opentype/shape v0.7.0/go.mod h1:n8pMQ/MH4Oscxwd9J0B7RiZ5gKlD0yagRQKYsAmJ9Rw= +github.com/go-richdoc/richdoc v0.7.0 h1:vhHypa0y26ulrOz6Aw1RIzeLjSMsFJyU1SzK5jd90lg= +github.com/go-richdoc/richdoc v0.7.0/go.mod h1:RhxAcqwoUg1pnTYCiRdKILzOZwOmraO0dMJI4N6yY70= +github.com/go-typeset/bidi v0.3.1 h1:fsTa0b9txt2SkH7M55EZ06+q3N9C4O0Oerf+SPLLGFs= +github.com/go-typeset/bidi v0.3.1/go.mod h1:ct3cmYT8Qt1FGJQ+2QaakrUxqaP4ZysgdQQg2ym5+Xo= +github.com/go-widgets/lineedit v0.1.1 h1:jvlwxIWyoz/oeYH5OHwFN03vQ9Q8uAFTRF8BFGOej7I= +github.com/go-widgets/lineedit v0.1.1/go.mod h1:UCPzWaFDsa3J1ORoWfuf2fOGLMWigDc5ATUOHQxMHQI= +github.com/go-widgets/mvvm v0.15.0 h1:VvZiLB7gm+5CIEeQH3GNI53ytUndzOznT/fJvaG8hOQ= +github.com/go-widgets/mvvm v0.15.0/go.mod h1:ZJj5M8zDg/gdzcvdWnJgZj/fcV0qe84fALq+EQVzUOM= +github.com/go-widgets/painter v0.17.0 h1:PB/Xr0flFR9qL2/RPhbJOeyU6PPzcGyf3Qx4RRngowg= +github.com/go-widgets/painter v0.17.0/go.mod h1:8kERcZUoWNyLIas1NsMWiYynvvyx+hcB2cNIh0Bx0yc= +github.com/go-widgets/textinput v0.1.0 h1:ifx1RjbPIWtlokoBLV1ZwlH+0CeixoMbswlqhNvYNmw= +github.com/go-widgets/textinput v0.1.0/go.mod h1:Y/k3PDtUEMQ/4psCVKdmUStNWa/EsVAMcCKG2lEtQ5c= +github.com/go-widgets/toolkit v0.362.0 h1:iJmqv/dwOiQW8bJQEyhAjo4uAS1VAuFM5gN4EthNou8= +github.com/go-widgets/toolkit v0.362.0/go.mod h1:dAs4uFSnRAV0aJ1IZkxQld5PP5ZdZDOS9bf9DF4jqQ8= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= +github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/shellterm.go b/shellterm.go new file mode 100644 index 0000000..bd4f78a --- /dev/null +++ b/shellterm.go @@ -0,0 +1,308 @@ +// Package shellterm is a line-oriented terminal: a line editor +// (github.com/go-widgets/lineedit: history, Tab completion, Ctrl-R, Ctrl-C, +// Ctrl-L) in front of a Shell that the caller supplies, drawing into a +// terminal (Bind connects a toolkit.Terminal). +// +// A Session is the model. Input arrives as the bytes a terminal sends; +// output goes to the function given to Attach. Keys are handled on the +// session's own goroutine, never the UI's: a Completer may ask a slow +// back end, and must not block the event loop that delivers its answer. +// Everything the session hands the view goes through Options.Post, which +// runs a function on the UI goroutine (an mvvm queue's Post, or a plain +// host's equivalent), so the view is only ever touched from there. +// +// It was extracted from go-wasmcontainers/dashboard v0.8.0 (vm/terminal.go) +// so that the dashboard and wasmdesk share one implementation. +package shellterm + +import ( + "context" + "fmt" + "io" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/go-widgets/lineedit" + "github.com/go-widgets/mvvm" +) + +// Shell runs one command line, writing its output to out, and returns the +// exit status and whether the screen should be cleared. It runs on a +// goroutine of its own; ctx is cancelled by Ctrl-C. +type Shell interface { + Run(ctx context.Context, line string, out io.Writer) (code int, clear bool) +} + +// Options configure a Session. +type Options struct { + // Post runs f on the UI goroutine, in order. Required: New panics + // without it, since a session that wrote from its own goroutine would + // race the view. + Post func(f func()) + // Greeting is written once, at the first Attach, before the prompt. + Greeting string + // OnDone, if set, runs on the UI goroutine after each command, once its + // output and the prompt are written (to refresh what it changed). + OnDone func() + // HistorySize bounds the history (0: 500). + HistorySize int +} + +// Limits on what waits for the view or for the key goroutine. +const ( + // InputQueue bounds the keystrokes waiting for the key goroutine; keys + // past it are dropped rather than blocking the UI. + InputQueue = 256 + // PendingWrites bounds the output kept before the first Attach. + PendingWrites = 256 + // CompleteTimeout bounds one key's work, a Tab completion included. + CompleteTimeout = 5 * time.Second +) + +// Session is the terminal's model. +type Session struct { + opts Options + + // Out receives everything to draw and Clear clears the screen; both + // are set by Attach and called on the UI goroutine. + Out func(string) + Clear func() + // Running says a command runs (only Ctrl-C reaches it). It is set on + // the UI goroutine. + Running *mvvm.Observable[bool] + + mu sync.Mutex + shell Shell + complete lineedit.Completer + ed *lineedit.Editor + r *lineedit.Renderer + run context.CancelFunc + in chan string + started bool + pending []string +} + +// New returns a session with no shell (a submitted line says so) until +// SetShell. +func New(o Options) *Session { + if o.Post == nil { + panic("shellterm: Options.Post is required") + } + if o.HistorySize <= 0 { + o.HistorySize = 500 + } + return &Session{opts: o, Running: mvvm.NewObservable(false), + in: make(chan string, InputQueue), r: &lineedit.Renderer{Cols: 80}} +} + +// SetShell sets what runs the lines and what completes them (nil: no +// completion). The history is kept. +func (t *Session) SetShell(s Shell, complete lineedit.Completer) { + t.mu.Lock() + defer t.mu.Unlock() + t.shell, t.complete = s, complete + hist := []string(nil) + if t.ed != nil { + hist = t.ed.History() + } + t.ed = lineedit.New(lineedit.Options{Complete: complete, Cols: t.r.Cols, HistorySize: t.opts.HistorySize}) + t.ed.SetHistory(hist) +} + +// History returns the lines entered, oldest first (for persistence). +func (t *Session) History() []string { + t.mu.Lock() + defer t.mu.Unlock() + if t.ed == nil { + return nil + } + return t.ed.History() +} + +// out hands s to the view, from any goroutine. +func (t *Session) out(s string) { t.opts.Post(func() { t.write(s) }) } + +// write runs on the UI goroutine. +func (t *Session) write(s string) { + if t.Out == nil { + if len(t.pending) < PendingWrites { + t.pending = append(t.pending, s) + } + return + } + t.Out(s) +} + +// Attach connects the view and starts the session: greeting, prompt, and +// the goroutine that handles keys. A second Attach (a new view) replays +// nothing and greets no more. Called on the UI goroutine. clear may be nil: +// the escape sequences that clear the screen are written instead. +func (t *Session) Attach(out func(string), clear func()) { + t.Out, t.Clear = out, clear + for _, s := range t.pending { + out(s) + } + t.pending = nil + if t.started { + return + } + t.started = true + if t.ed == nil { + t.SetShell(nil, nil) + } + t.mu.Lock() + t.write(t.opts.Greeting) + t.write(t.r.Render(t.ed.State())) + t.mu.Unlock() + go t.loop() +} + +// Resize tells the editor the terminal's width. It never blocks the +// caller (the UI goroutine): the key goroutine may hold the editor while a +// completion waits. +func (t *Session) Resize(cols int) { + go func() { + t.mu.Lock() + defer t.mu.Unlock() + t.r.Cols = cols + if t.ed != nil { + t.ed.SetCols(cols) + } + }() +} + +// Input queues what the user typed. It never blocks (keys past a full +// queue are dropped). +func (t *Session) Input(data string) { + select { + case t.in <- data: + default: + } +} + +func (t *Session) loop() { + for data := range t.in { + for _, k := range lineedit.ParseKeys(data) { + t.key(k) + } + } +} + +// Note shows one line of text above the prompt, the line being edited kept +// below it; nothing while a command runs or before Attach. The text is +// written as given (escape sequences included): clean anything untrusted +// first. Called on the UI goroutine, which it never blocks (see Resize). +func (t *Session) Note(text string) { + if !t.started || t.Running.Get() { + return + } + go func() { + t.mu.Lock() + defer t.mu.Unlock() + if t.run != nil { + return // a command owns the screen + } + t.out(t.r.Print([]string{text}, t.ed.State())) + }() +} + +func (t *Session) key(k lineedit.Key) { + t.mu.Lock() + defer t.mu.Unlock() + if t.run != nil { + if k.Code == lineedit.KeyCtrlC { + t.run() + t.out("^C") + } + return + } + ctx, cancel := context.WithTimeout(context.Background(), CompleteTimeout) + before := t.ed.State() + ev := t.ed.Key(ctx, k) + cancel() + switch { + case ev.Submit: + s := lineedit.State{Prompt: t.ed.State().Prompt, Line: ev.Line, Cursor: utf8.RuneCountInString(ev.Line)} + t.out(t.r.Render(s) + t.r.Leave(s)) + t.start(ev.Line) + case ev.Interrupt: + t.out("^C" + t.r.Leave(before) + t.r.Render(t.ed.State())) + case ev.Clear: + t.r.Forget() + t.clearOut(t.r.Render(t.ed.State())) + case ev.Print != nil: + t.out(t.r.Print(ev.Print, t.ed.State())) + default: + t.out(t.r.Render(t.ed.State())) + } +} + +// termWriter turns a command's output into terminal output: "\n" becomes +// "\r\n" (the screen is a terminal, not a log). +type termWriter struct{ t *Session } + +func (w termWriter) Write(p []byte) (int, error) { + w.t.out(strings.ReplaceAll(string(p), "\n", "\r\n")) + return len(p), nil +} + +// start runs a line; t.mu is held. +func (t *Session) start(line string) { + if strings.TrimSpace(line) == "" { + t.out(t.r.Render(t.ed.State())) + return + } + if t.shell == nil { + t.out("no shell attached\r\n" + t.r.Render(t.ed.State())) + return + } + ctx, cancel := context.WithCancel(context.Background()) + t.run = cancel + t.opts.Post(func() { t.Running.Set(true) }) + shell := t.shell + go func() { + code, clear := shell.Run(ctx, line, termWriter{t}) + cancel() + t.mu.Lock() + t.run = nil + var b strings.Builder + if clear { + t.r.Forget() + } else if code != 0 { + fmt.Fprintf(&b, "\x1b[2m[exit status %d]\x1b[0m\r\n", code) + } + b.WriteString(t.r.Render(t.ed.State())) + t.mu.Unlock() + out := b.String() + t.opts.Post(func() { + if clear { + t.clear() + } + t.write(out) + t.Running.Set(false) + if t.opts.OnDone != nil { + t.opts.OnDone() + } + }) + }() +} + +// clearOut clears the screen, then writes s (from any goroutine). +func (t *Session) clearOut(s string) { + t.opts.Post(func() { + t.clear() + t.write(s) + }) +} + +// clear runs on the UI goroutine: the view's Clear (screen and history), +// or the escape sequences that clear the screen. +func (t *Session) clear() { + if t.Clear != nil { + t.Clear() + return + } + t.write("\x1b[H\x1b[2J") +} diff --git a/shellterm_test.go b/shellterm_test.go new file mode 100644 index 0000000..b87212c --- /dev/null +++ b/shellterm_test.go @@ -0,0 +1,272 @@ +package shellterm + +import ( + "context" + "fmt" + "io" + "strings" + "sync" + "testing" + "time" + + "github.com/go-widgets/lineedit" + "github.com/go-widgets/toolkit/vt" +) + +// rig is a session drawing into a vt screen. Post runs each function at +// once under ui, which stands in for the UI goroutine: everything that +// touches the view or the screen is serialised by it. +type rig struct { + t *testing.T + ui sync.Mutex + s *vt.Screen + ses *Session + clears int + dones int +} + +func newRig(t *testing.T, o Options) *rig { + r := &rig{t: t, s: vt.New(80, 12, 200)} + o.Post = func(f func()) { r.ui.Lock(); defer r.ui.Unlock(); f() } + if o.OnDone == nil { + o.OnDone = func() { r.dones++ } + } + r.ses = New(o) + return r +} + +func (r *rig) onUI(f func()) { r.ui.Lock(); defer r.ui.Unlock(); f() } + +func (r *rig) attach() { + r.onUI(func() { + r.ses.Attach(func(out string) { r.s.WriteString(out) }, func() { + r.clears++ + r.s.WriteString("\x1b[H\x1b[2J") + }) + }) +} + +func (r *rig) text() (s string) { + r.onUI(func() { s = r.s.Text(vt.Pos{}, vt.Pos{Line: r.s.Lines(), Col: 80}) }) + return s +} + +// line is the cursor's line, trimmed. +func (r *rig) line() (s string) { + r.onUI(func() { + _, y, _ := r.s.Cursor() + l := r.s.ScrollbackLen() + y + s = strings.TrimRight(r.s.Text(vt.Pos{Line: l}, vt.Pos{Line: l, Col: 79}), " ") + }) + return s +} + +// counts reads the clears and OnDone calls, which change on the UI side. +func (r *rig) counts() (clears, dones int) { + r.onUI(func() { clears, dones = r.clears, r.dones }) + return clears, dones +} + +func (r *rig) running() (b bool) { + r.onUI(func() { b = r.ses.Running.Get() }) + return b +} + +// until waits for cond, failing after five seconds. +func (r *rig) until(what string, cond func() bool) { + r.t.Helper() + for end := time.Now().Add(5 * time.Second); time.Now().Before(end); time.Sleep(time.Millisecond) { + if cond() { + return + } + } + r.t.Fatalf("timed out waiting for %s; screen:\n%s", what, r.text()) +} + +// typeWait types in and waits until the screen shows want. +func (r *rig) typeWait(in, want string) { + r.t.Helper() + r.ses.Input(in) + r.until(want, func() bool { return strings.Contains(r.text(), want) }) +} + +// settle waits until the key goroutine has handled everything queued. +func (r *rig) settle() { + r.t.Helper() + r.until("queue drained", func() bool { return len(r.ses.in) == 0 }) + r.ses.mu.Lock() // the key in hand, if any, is done + r.ses.mu.Unlock() +} + +// recShell records the lines it runs. +type recShell struct { + mu sync.Mutex + lines []string + code int + clear bool + block chan struct{} // non-nil: Run waits for ctx (Ctrl-C) or a close +} + +func (s *recShell) Run(ctx context.Context, line string, out io.Writer) (int, bool) { + s.mu.Lock() + s.lines = append(s.lines, line) + code, clear, block := s.code, s.clear, s.block + s.mu.Unlock() + if block != nil { + select { + case <-ctx.Done(): + return 130, false + case <-block: + } + } + fmt.Fprintf(out, "ran %s\n", line) + return code, clear +} + +func (s *recShell) set(code int, clear bool, block chan struct{}) { + s.mu.Lock() + defer s.mu.Unlock() + s.code, s.clear, s.block = code, clear, block +} + +// static completes from a fixed table keyed by the words before the cursor. +func static(m map[string][]lineedit.Candidate) lineedit.Completer { + return func(_ context.Context, words []string, _ string) ([]lineedit.Candidate, bool) { + return m[strings.Join(words, " ")], false + } +} + +var words = static(map[string][]lineedit.Candidate{ + "": {{Value: "wctr"}, {Value: "help"}, {Value: "clear"}}, + "wctr": {{Value: "run"}, {Value: "rm"}}, +}) + +func TestSession(t *testing.T) { + r := newRig(t, Options{Greeting: "\x1b[1mhello\x1b[0m. Type help.\r\n"}) + ses := r.ses + if ses.History() != nil { + t.Error("history before any editor") + } + ses.Note("before attach: not shown") + r.onUI(func() { ses.write("early ") }) + r.attach() + r.attach() // greets once + if txt := r.text(); !strings.HasPrefix(txt, "early hello. Type help.") || strings.Count(txt, "hello") != 1 { + t.Fatalf("greeting = %q", txt) + } + r.typeWait("wctr ps\r", "no shell attached") + + sh := &recShell{} + ses.SetShell(sh, words) + ses.Resize(80) + r.typeWait("wctr images\r", "ran wctr images") + r.until("prompt back", func() bool { return !r.running() && r.line() == "$" }) + if _, dones := r.counts(); dones != 1 { + t.Errorf("OnDone ran %d times, want 1", dones) + } + // History survives SetShell; Up recalls. + ses.SetShell(sh, nil) + if h := ses.History(); len(h) != 2 || h[1] != "wctr images" { + t.Errorf("history = %q", h) + } + r.typeWait("\x1b[A", "$ wctr images") + r.typeWait("\x03", "^C") + r.until("prompt after ^C", func() bool { return r.line() == "$" }) + sh.set(3, false, nil) + r.typeWait("wctr ps\r", "[exit status 3]") + sh.set(0, true, nil) + ses.Input("clear\r") + r.until("cleared", func() bool { c, _ := r.counts(); return c == 1 && !r.running() }) + sh.set(0, false, nil) + ses.Input("\x0c") + r.until("Ctrl-L", func() bool { c, _ := r.counts(); return c == 2 }) + r.typeWait(" \r", "$") + // Completion lists candidates above the prompt. + ses.SetShell(sh, words) + r.typeWait("\t\t", "clear") + r.typeWait("\x15", "$") + + // A running command gets Ctrl-C only. + sh.set(0, false, make(chan struct{})) + ses.Input("wctr logs -f clock\r") + r.until("running", r.running) + r.onUI(func() { ses.Note("# not while a command runs") }) + ses.Input("xyz\x03") + r.until("interrupted", func() bool { return !r.running() }) + r.settle() + if txt := r.text(); strings.Contains(txt, "xyz") || strings.Contains(txt, "not while") { + t.Errorf("keys reached a running command:\n%s", txt) + } + sh.set(0, false, nil) + + // A command that starts between the call and the note's turn wins. + ses.mu.Lock() + ses.run = func() {} + ses.mu.Unlock() + r.onUI(func() { ses.Note("racing") }) + time.Sleep(20 * time.Millisecond) // the note's goroutine finds run set + ses.mu.Lock() + ses.run = nil + ses.mu.Unlock() + if strings.Contains(r.text(), "racing") { + t.Error("a note over a running command") + } + // A note shows above the prompt; the line being edited stays below. + r.typeWait("wc", "$ wc") + r.onUI(func() { ses.Note("# dashboard: wctr rm web") }) + r.until("note", func() bool { return strings.Contains(r.text(), "# dashboard: wctr rm web") }) + if r.line() != "$ wc" { + t.Errorf("line after a note = %q", r.line()) + } +} + +func TestSessionBounds(t *testing.T) { + r := newRig(t, Options{}) + ses := r.ses + // A full input queue drops keys instead of blocking. + for range InputQueue + 5 { + ses.Input("x") + } + if len(ses.in) != InputQueue { + t.Errorf("queue = %d", len(ses.in)) + } + r.onUI(func() { + for range PendingWrites + 44 { + ses.write("x") + } + }) + if len(ses.pending) != PendingWrites { + t.Errorf("pending = %d", len(ses.pending)) + } + ses.Resize(100) // before an editor exists: only the renderer learns it + r.until("resized", func() bool { ses.mu.Lock(); defer ses.mu.Unlock(); return ses.r.Cols == 100 }) + // Without the view's Clear, the escape sequences clear. + var b strings.Builder + ses.Out = func(s string) { b.WriteString(s) } + ses.clear() + if b.String() != "\x1b[H\x1b[2J" { + t.Errorf("clear = %q", b.String()) + } + if New(Options{Post: func(func()) {}}).opts.HistorySize != 500 { + t.Error("default history size") + } +} + +func TestNewRequiresPost(t *testing.T) { + defer func() { + if recover() == nil { + t.Error("New without Post did not panic") + } + }() + New(Options{}) +} + +// Without OnDone a command still finishes cleanly. +func TestSessionWithoutOnDone(t *testing.T) { + r := &rig{t: t, s: vt.New(80, 12, 200)} + r.ses = New(Options{Post: func(f func()) { r.ui.Lock(); defer r.ui.Unlock(); f() }}) + r.ses.SetShell(&recShell{}, nil) + r.attach() + r.typeWait("go\r", "ran go") + r.until("prompt", func() bool { return !r.running() && r.line() == "$" }) +}