Skip to content
Merged
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
56 changes: 56 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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 ./...
82 changes: 81 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -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).
24 changes: 24 additions & 0 deletions bind.go
Original file line number Diff line number Diff line change
@@ -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()
})
}
62 changes: 62 additions & 0 deletions bind_test.go
Original file line number Diff line number Diff line change
@@ -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, "$")
})
}
45 changes: 45 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -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.
}
24 changes: 24 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -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
)
38 changes: 38 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
Loading
Loading