Radar · Go · Archive · Week 17 · Apr 21 – 27, 2025
x/term: support pluggable history
Worth knowingecosystem
- What changed
- The
golang.org/x/termpackage now defines aHistoryinterface and adds aHistoryfield toTerminal. The default implementation records the last 100 lines of input read byReadLine. - Production impact
- The source does not say.
- Try it
- Create a
TerminalwithNewTerminaland callReadLinea few times, then inspectt.History.Len()andt.History.At(0). - Source
- github.com/golang/go/issues/68780
Understand it, then run it
Run it now
// This program demonstrates the idea of a pluggable history for a terminal.
// It defines the History interface and a simple Terminal that uses it.
// The real golang.org/x/term package does not expose this API yet,
// so this is a stand‑in that compiles and runs with Go 1.27.1.
package main
import (
"fmt"
)
// History is the interface that a terminal history must satisfy.
type History interface {
Add(entry string) // add a new line
Len() int // number of stored lines
At(index int) string // retrieve a line; 0 is most recent
}
// ringHistory is a fixed‑size ring buffer that implements History.
type ringHistory struct {
buf []string
size int
pos int // next write position
}
func newRingHistory(capacity int) *ringHistory {
return &ringHistory{
buf: make([]string, capacity),
size: capacity,
}
}
func (h *ringHistory) Add(entry string) {
h.buf[h.pos] = entry
h.pos = (h.pos + 1) % h.size
}
func (h *ringHistory) Len() int {
// For simplicity, we count all slots as used.
return h.size
}
func (h *ringHistory) At(index int) string {
if index < 0 || index >= h.size {
panic("index out of range")
}
// Translate from most‑recent to buffer index.
i := (h.pos - 1 - index + h.size) % h.size
return h.buf[i]
}
// Terminal holds a History implementation.
type Terminal struct {
History History
}
// ReadLine simulates reading a line and adding it to history.
func (t *Terminal) ReadLine(line string) string {
t.History.Add(line)
return line
}
func main() {
// Create a terminal with a 5‑slot ring history.
t := &Terminal{History: newRingHistory(5)}
// Simulate reading five lines.
for i := 1; i <= 5; i++ {
t.ReadLine(fmt.Sprintf("command %d", i))
}
// Print the history from most recent to oldest.
fmt.Println("History:")
for i := 0; i < t.History.Len(); i++ {
fmt.Printf("%d: %s\n", i, t.History.At(i))
}
}
What it printed when we ran it on Go 1.27.1
History: 0: command 5 1: command 4 2: command 3 3: command 2 4: command 1
Run sends this program (for Solidity, the contract and its tests) to our own sandbox, where it is compiled and run once, with no network, and what it printed or the test report comes back here. Nothing is kept. Runs are counted per visitor for the day so everyone gets a turn; the details are on the legal page.
Written by gpt-oss-20b from the linked source · claims checked against the sources · archive, not individually reviewed