Bump github.com/xo/terminfo from 1.2.0 to 1.3.1

Bumps [github.com/xo/terminfo](https://github.com/xo/terminfo) from 1.2.0 to 1.3.1.
- [Release notes](https://github.com/xo/terminfo/releases)
- [Commits](https://github.com/xo/terminfo/compare/v1.2.0...v1.3.1)

---
updated-dependencies:
- dependency-name: github.com/xo/terminfo
  dependency-version: 1.3.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot] authored and GitHub committed 2026-11-11 00:03:29 +00:00
1 parent 8290cc9357
commit 8321e64652
17 files changed
+673 -302

No files matched your search

+1 -1
View File
@@ -39,7 +39,7 @@ require (
github.com/spkg/bom v1.0.1
github.com/stefanhaller/git-todo-parser v0.0.7-0.20250905083220-c50528f08304
github.com/stretchr/testify v1.12.1
github.com/xo/terminfo v1.2.0
github.com/xo/terminfo v1.3.1
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56
golang.org/x/sync v0.24.0
golang.org/x/sys v0.49.0
+2 -2
View File
@@ -128,8 +128,8 @@ github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUm
github.com/urfave/cli v1.20.1-0.20180226030253-8e01ec4cd3e2/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
github.com/xo/terminfo v1.2.0 h1:d0ZTOCpuGE0lwSAOs0zcJjwz3jWQyqcRt9XbGJpCOl4=
github.com/xo/terminfo v1.2.0/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio=
github.com/xo/terminfo v1.3.1 h1:4ZwPCuu4PEFw0PkNp3Hv/x3gqvgLCzYhurszsj101cM=
github.com/xo/terminfo v1.3.1/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
+1
View File
@@ -0,0 +1 @@
* text=auto eol=lf
+3
View File
@@ -7,3 +7,6 @@
/.out/
*.txt
# The Claude Code permissions of one person.
.claude/settings.local.json
+54
View File
@@ -0,0 +1,54 @@
version: "2"
linters:
default: all
disable:
- cyclop
- err113
- errcheck
- exhaustruct
- exhaustruct_v5
- funlen
- gochecknoglobals
- gochecknoinits
- gocognit
- goconst
- gomodguard
- lll
- maintidx
- mnd
- nestif
- nilnil
- nlreturn
- noinlineerr
- paralleltest
- prealloc
- sqlclosecheck
- testableexamples
- testpackage
- varnamelen
- wrapcheck
- wsl
- wsl_v5
settings:
depguard:
rules:
main:
list-mode: strict
allow:
- $gostd
- github.com/xo/terminfo
gosec:
excludes:
- G101
# Open and Load read the file that the caller names, by design
- G304
- G703
gocritic:
disabled-checks:
- exitAfterDefer
exclusions:
rules:
# a command prints its output
- path: cmd/
linters:
- forbidigo
+130
View File
@@ -0,0 +1,130 @@
# terminfo
`terminfo` reads the terminfo database in pure Go. The terminfo database
describes what each kind of terminal can do, and it holds one compiled file
for each terminal name. The package finds the file for a terminal name,
decodes it, and evaluates its parameterized strings. It is meant as a
replacement for `ncurses` in simple Go programs.
The module is one package, `github.com/xo/terminfo`, and one command,
`cmd/infocmp`. It has no cgo and it does not link `ncurses`.
## Standing rules
These rules hold in every `xo` repository, for every coding agent (D22).
1. Stage changes for review. Commit and push only when Ken says so.
2. Load the `simple-english` skill before you write any text that a person
reads: project documentation, a code comment, an error message or a
commit message.
3. In a Go project, load the `go-pedantry` skill before you write or review
Go code. A rule in this file wins where the two conflict.
`CLAUDE.md` holds one line that imports this file, so that Claude Code and
every other agent read the same rules. Edit this file, not that one.
## Which document to read
| If you are | Read |
| --- | --- |
| asking why something is the way it is | the table at the top of [docs/PLAN.md](docs/PLAN.md) |
| about to decide something that is not written down | "Open questions for Ken" at the end of [docs/PLAN.md](docs/PLAN.md). Ask Ken |
| looking for work that is known and not done | [docs/BACKLOG.md](docs/BACKLOG.md) |
| changing how a file is decoded | `dec.go` and `terminfo.go`, then D3, D13 and D15 |
| changing how a parameterized string is evaluated | `param.go` and `stack.go`, then D9 and D16 |
| changing a capability name or constant | `gen.go`, then D4 and D26. Never edit `capvals.go` by hand |
| changing color detection | `color.go`, then D10 and D24 |
| changing how padding is written | `Puts` in `terminfo.go`, then D23 |
| writing a document, a code comment, an error message or a commit message | the `simple-english` skill. Load it first |
| writing or reviewing Go code | the `go-pedantry` skill. Load it first |
| installing or updating an agent skill | [CONTRIBUTING.md](CONTRIBUTING.md), under Agent skills |
| looking for what the library does | [README.md](README.md) |
A document that is not in this table does not exist. If you cannot find where
something is written down, it is not written down. Ask Ken. Do not decide it
yourself, and do not write it as though it were settled.
## Decision numbers
A bare number, such as D3, names a decision of this repository. The decisions
are in [docs/PLAN.md](docs/PLAN.md), and the table at the top of that file
lists each one with its status. A decision of another repository names that
repository first, such as "dbmeta D110" or "tblfmt D37".
## Layout
- `terminfo.go` holds the `Terminfo` type, `Decode`, `Open`, the error
constants, and the methods that read and print capabilities. `Puts`
writes a capability with its padding applied (D23).
- `dec.go` holds the decoder for the compiled file format.
- `load.go` holds `Load` and `LoadFromEnv`. `Load` searches the directories
that terminfo(5) names, and caches each entry that it opens (D5). A caller
must not change a cached entry (D27).
- `param.go` and `stack.go` evaluate a parameterized string, such as the
value of `cup`. `Printf` and `Fprintf` are the exported entry points.
- `color.go` holds `ColorLevel` and `ColorLevelFromEnv` (D10).
- `caps.go` returns the long and short name of each capability.
- `capvals.go` holds the capability constants and names. `gen.go` writes it
from the `Caps` file of `ncurses` 6.6 (D4, D26). The file says
"DO NOT EDIT", and names the release.
- `gen.go` is the generator. It has the `ignore` build tag, so the package
build skips it.
- `cmd/infocmp` prints an entry in the form of `infocmp -1 -L`.
`cmd/infocmp/test.sh` compares its output with the system `infocmp` for
every entry in `/usr/share/terminfo`.
- `_examples/main.go` is the example that `README.md` links. The go command
skips a folder whose name starts with `_` (D12), so `go vet ./...` does not
check it. Run `go vet ./_examples/` after you change it.
- `skills_test.go` and `docs_test.go` hold the checks on the agent files and
on `docs/PLAN.md`.
## Tests and lint
Run these in the repository root. Each must pass, `gofmt -l .` must print
nothing, and `golangci-lint` must report 0 issues:
```sh
gofmt -l .
go vet ./...
go test -count=1 ./...
golangci-lint run ./...
```
CI runs the same commands in GitHub Actions. It runs the tests on Go 1.25
and on the latest stable Go (D17, D18). It runs golangci-lint v2.14.0 with
`.golangci.yml`, which is the configuration of dburl (D25). A `//nolint`
comment names the linter and gives the reason.
The tests read the real terminfo database. `TestLoad`, `TestOpen` and
`TestValues` walk every entry in `/lib/terminfo` and `/usr/share/terminfo`.
`TestValues` runs `/usr/bin/infocmp -E -x` on each entry and compares each
value with the decoded one (D3). A machine that runs the tests needs
`infocmp` at that path and a terminfo database. On Debian and Ubuntu, the
packages are `ncurses-bin` and `ncurses-term`.
## Go conventions
These are the conventions that the code follows now. Match them.
- A sentinel error is a constant of `type Error string`, declared in
`terminfo.go`, with an `Err` prefix (D11). The code does not use
`errors.New` in the package.
- An error string starts with a lowercase letter.
- A receiver is one or two letters: `ti` for `*Terminfo`, `d` for
`*decoder`, `p` for `*parametizer`, `s` for `*stack`, `c` for
`ColorLevel`.
- A comment inside a function is short and starts with a lowercase letter,
such as `// read header`. A doc comment is a full sentence that starts with
the name.
- The code uses `any`, `range` over an integer, and the `slices` and `maps`
packages. The module declares `go 1.25` (D18).
- A test is table driven where it has cases, and it names each case with
`t.Run`.
- The package imports only the standard library (D20).
## Writing documentation
Standing rule 2 applies: load `simple-english` first. Write short sentences
in the active voice. Do not use contractions, semicolons or em dashes. Use
"must" and "can", not "should" and "may". State the fact and not its
importance.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+71
View File
@@ -0,0 +1,71 @@
# Contributing to terminfo
`terminfo` reads the terminfo database in pure Go. `AGENTS.md` holds the full
rules for a coding agent. This file is the short form for a person.
## What a change must do
The system `infocmp` is the reference (D3 in [docs/PLAN.md](docs/PLAN.md)).
If the package decodes a value differently from `infocmp`, the package is
wrong. A fix comes with a test that fails before the fix.
Do not edit `capvals.go` by hand. `gen.go` writes it from the `Caps` file of
`ncurses` 6.6 (D4, D26). To move to a new release, change `ncursesVer` in
`gen.go` and run `go generate`.
`terminfo` makes no promise of backward compatibility (D21). If a change
renames or removes an exported identifier, name it in the pull request.
## Before you open a pull request
The tests read the terminfo database on your machine, and they run
`/usr/bin/infocmp`. On Debian and Ubuntu, install `ncurses-bin` and
`ncurses-term` first.
Run these in the repository root. Each must pass, `gofmt -l .` must print
nothing, and `golangci-lint` must report 0 issues:
```sh
gofmt -l .
go vet ./...
go test -count=1 ./...
golangci-lint run ./...
```
CI runs the same commands in GitHub Actions, with golangci-lint v2.14.0
(D25).
## Writing
Write documents, code comments, error messages and commit messages in plain
English. Use short sentences and the active voice. Do not use contractions,
semicolons or em dashes. Use "must" and "can", not "should" and "may". The
`simple-english` skill in `.agents/skills` holds the full rules.
## Agent skills
The repository carries two agent skills. A skill is a set of instructions
that a coding agent loads for a task. `simple-english` sets how prose is
written, and `go-pedantry` sets how Go is written.
`skills-lock.json` names the source of each skill. The `skills` command from
npm writes that file. It writes each skill into two folders. Codex and the
other agents read `.agents/skills/<name>`, and Claude Code reads
`.claude/skills/<name>`.
To install the skills again, or to update them, run these two commands in the
repository root:
```sh
npx skills@1.7.0 add AminBlg/SimpleEnglish --skill simple-english --agent codex claude-code --copy -y
npx skills@1.7.0 add oborchers/fractional-cto --skill go-pedantry --agent codex claude-code --copy -y
```
Keep `--copy`. Without it, the command writes `.claude/skills/<name>` as a
symbolic link. A Windows checkout writes a symbolic link as a small text
file, and Claude Code then loads no skill and says nothing.
`TestSkillsAreCopies` fails on a link, and it fails when the two folders
differ.
`.claude/settings.local.json` holds the Claude Code permissions of one
person. The root `.gitignore` ignores it.
+121 -107
View File
@@ -1,139 +1,153 @@
# About terminfo [![GoDoc][1]][2]
<div align="center">
<a href="#installing" title="Installing">Installing</a> |
<a href="#using" title="Using">Using</a> |
<a href="#the-example" title="The example">Example</a> |
<a href="#infocmp" title="infocmp">infocmp</a> |
<a href="https://pkg.go.dev/github.com/xo/terminfo" title="Go Reference">Reference</a> |
<a href="#documents" title="Documents">Documents</a> |
<a href="#about" title="About">About</a>
</div>
Package `terminfo` provides a pure-Go implementation of reading information
from the terminfo database.
<br/>
`terminfo` is meant as a replacement for `ncurses` in simple Go programs.
[![Unit Tests][terminfo-ci-status]][terminfo-ci]
[![Go Reference][goref-terminfo-status]][goref-terminfo]
[![Releases][release-status]][releases]
[![Discord Discussion][discord-status]][discord]
[terminfo-ci]: https://github.com/xo/terminfo/actions/workflows/test.yml "Test CI"
[terminfo-ci-status]: https://github.com/xo/terminfo/actions/workflows/test.yml/badge.svg "Test CI"
[goref-terminfo]: https://pkg.go.dev/github.com/xo/terminfo "Go Reference"
[goref-terminfo-status]: https://pkg.go.dev/badge/github.com/xo/terminfo.svg "Go Reference"
[release-status]: https://img.shields.io/github/v/release/xo/terminfo?display_name=tag "Latest Release"
[releases]: https://github.com/xo/terminfo/releases "Releases"
[discord]: https://discord.gg/WDWAgXwJqN "Discord Discussion"
[discord-status]: https://img.shields.io/discord/829150509658013727.svg?label=Discord&logo=Discord&colorB=7289da&style=flat-square "Discord Discussion"
# terminfo
`terminfo` reads the terminfo database in Go. The terminfo database describes
what each kind of terminal can do, and the byte sequences that make it do
each thing. A program uses those sequences to move the cursor, set colors,
clear the screen or flash it.
This package is written in pure Go. It does not use cgo, and it does not link
the `ncurses` library. It replaces `ncurses` in a Go program that needs the
terminal capabilities and not a full screen library.
The package can:
- Find the entry for a terminal name in the directories that terminfo(5)
names, and cache it.
- Decode the legacy format and the 32-bit number format of `ncurses` 6.1, with
the extended capabilities.
- Evaluate a parameterized string, such as the value of `cup`.
- Write a capability with its padding applied, as `tputs` does.
- Find the color level of the terminal from the environment.
The system `infocmp` is the reference. The tests compare each decoded value
with the output of `infocmp` for every entry on the machine.
## Installing
Install in the usual Go way:
Install `terminfo` with the [Go][go-project] tool:
```sh
$ go get -u github.com/xo/terminfo
go get github.com/xo/terminfo@latest
```
## Using
Please see the [GoDoc API listing][2] for more information on using `terminfo`.
`LoadFromEnv` loads the entry that `$TERM` names. `Printf` evaluates a
capability with its parameters, and `Puts` writes a capability with its
padding applied:
```go
// _examples/simple/main.go
package main
import (
"bytes"
"fmt"
"log"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"github.com/xo/terminfo"
)
func main() {
//r := rand.New(nil)
// load terminfo
// load the entry that $TERM names
ti, err := terminfo.LoadFromEnv()
if err != nil {
log.Fatal(err)
}
// cleanup
defer func() {
err := recover()
termreset(ti)
if err != nil {
log.Fatal(err)
}
}()
terminit(ti)
termtitle(ti, "simple example!")
termputs(ti, 3, 3, "Ctrl-C to exit")
maxColors := termcolors(ti)
if maxColors > 256 {
maxColors = 256
// move the cursor to row 5, column 10, and write in bold
fmt.Print(ti.Printf(terminfo.CursorAddress, 5, 10))
fmt.Print(ti.Printf(terminfo.EnterBoldMode) + "hello" + ti.Printf(terminfo.ExitAttributeMode))
// flash the screen, with the delay that the entry asks for
if _, err := ti.Puts(os.Stdout, ti.Printf(terminfo.FlashScreen), 1, 38400); err != nil {
log.Fatal(err)
}
for i := 0; i < maxColors; i++ {
termputs(ti, 5+i/16, 5+i%16, ti.Colorf(i, 0, "█"))
}
// wait for signal
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs
}
// terminit initializes the special CA mode on the terminal, and makes the
// cursor invisible.
func terminit(ti *terminfo.Terminfo) {
buf := new(bytes.Buffer)
// set the cursor invisible
ti.Fprintf(buf, terminfo.CursorInvisible)
// enter special mode
ti.Fprintf(buf, terminfo.EnterCaMode)
// clear the screen
ti.Fprintf(buf, terminfo.ClearScreen)
os.Stdout.Write(buf.Bytes())
}
// termreset is the inverse of terminit.
func termreset(ti *terminfo.Terminfo) {
buf := new(bytes.Buffer)
ti.Fprintf(buf, terminfo.ExitCaMode)
ti.Fprintf(buf, terminfo.CursorNormal)
os.Stdout.Write(buf.Bytes())
}
// termputs puts a string at row, col, interpolating v.
func termputs(ti *terminfo.Terminfo, row, col int, s string, v ...interface{}) {
buf := new(bytes.Buffer)
ti.Fprintf(buf, terminfo.CursorAddress, row, col)
fmt.Fprintf(buf, s, v...)
os.Stdout.Write(buf.Bytes())
}
// sl is the status line terminfo.
var sl *terminfo.Terminfo
// termtitle sets the window title.
func termtitle(ti *terminfo.Terminfo, s string) {
var once sync.Once
once.Do(func() {
if ti.Has(terminfo.HasStatusLine) {
return
}
// load the sl xterm if terminal is an xterm or has COLORTERM
if strings.Contains(strings.ToLower(os.Getenv("TERM")), "xterm") || os.Getenv("COLORTERM") == "truecolor" {
sl, _ = terminfo.Load("xterm+sl")
}
})
if sl != nil {
ti = sl
}
if !ti.Has(terminfo.HasStatusLine) {
return
}
buf := new(bytes.Buffer)
ti.Fprintf(buf, terminfo.ToStatusLine)
fmt.Fprint(buf, s)
ti.Fprintf(buf, terminfo.FromStatusLine)
os.Stdout.Write(buf.Bytes())
}
// termcolors returns the maximum colors available for the terminal.
func termcolors(ti *terminfo.Terminfo) int {
if colors := ti.Num(terminfo.MaxColors); colors > 0 {
return colors
}
return int(terminfo.ColorLevelBasic)
}
```
[1]: https://godoc.org/github.com/xo/terminfo?status.svg
[2]: https://godoc.org/github.com/xo/terminfo
A capability that holds a padding marker, such as the `$<100/>` in the
`flash` of `xterm`, must go through `Puts`. If you write the value of
`Strings` or of `Printf` directly, the terminal shows the marker.
`ColorLevelFromEnv` returns the color level of the terminal. It reads
`COLORTERM`, `FORCE_COLOR` and `TERM_PROGRAM` first, then the `max_colors`
capability of the entry.
`Load` and `Open` return the same `*Terminfo` to every caller. Do not change
the returned value or its maps.
## The example
[`_examples/main.go`](_examples/main.go) draws the color table of the
terminal and waits for Ctrl-C. Run it in the repository root:
```sh
go run ./_examples
```
## infocmp
[`cmd/infocmp`](cmd/infocmp) prints an entry in the same form as
`infocmp -1 -L`. It shows what the package decodes. Install it and run it:
```sh
go install github.com/xo/terminfo/cmd/infocmp@latest
TERM=xterm-256color infocmp -x
```
## Documents
- [CONTRIBUTING.md](CONTRIBUTING.md): how to change the project, the checks
to run, and how to install the agent skills.
- [AGENTS.md](AGENTS.md): the rules for a coding agent. `CLAUDE.md` imports
it.
- [docs/PLAN.md](docs/PLAN.md): the plan, every decision, and the open
questions.
- [docs/BACKLOG.md](docs/BACKLOG.md): the work that is known and not done.
## About
`terminfo` supports [rline][rline], the line editor of [usql][usql].
<br/>
<div align="center">
<a href="https://github.com/xo/usql" title="A command line client for many databases">usql</a> |
<a href="https://github.com/xo/dburl" title="Database connection URLs">dburl</a> |
<a href="https://github.com/xo/dbmeta" title="Database metadata">dbmeta</a> |
<a href="https://github.com/xo/dbimp" title="Database drivers in pure Go">dbimp</a> |
<a href="https://github.com/xo/cassandra" title="A database/sql driver for Cassandra">cassandra</a> |
<a href="https://github.com/xo/dbtpl" title="Go code generated from a database">dbtpl</a> |
<a href="https://github.com/xo/tblfmt" title="Tables of database results">tblfmt</a> |
<a href="https://github.com/xo/rline" title="The line editor of usql">rline</a> |
<a href="https://github.com/xo/terminfo" title="The terminfo database in pure Go, this project">terminfo</a> |
<a href="https://github.com/xo/transit" title="tree-sitter in pure Go">transit</a>
</div>
[go-project]: https://go.dev/project
[rline]: https://github.com/xo/rline
[usql]: https://github.com/xo/usql
+2 -1
View File
@@ -1,6 +1,7 @@
// Code generated by gen.go from the Caps file of ncurses 6.6. DO NOT EDIT.
package terminfo
// Code generated by gen.go. DO NOT EDIT.
// Bool capabilities.
const (
// The AutoLeftMargin [auto_left_margin, bw] bool capability indicates cub1 wraps from column 0 to last column.
+5 -4
View File
@@ -26,6 +26,7 @@ func (c ColorLevel) String() string {
return "hundreds"
case ColorLevelMillions:
return "millions"
case ColorLevelNone:
}
return "none"
}
@@ -40,6 +41,7 @@ func (c ColorLevel) ChromaFormatterName() string {
return "terminal256"
case ColorLevelMillions:
return "terminal16m"
case ColorLevelNone:
}
return "noop"
}
@@ -76,11 +78,10 @@ func ColorLevelFromEnv() (ColorLevel, error) {
if err != nil {
return ColorLevelNone, err
}
v, ok := ti.Nums[MaxColors]
switch {
case !ok || v <= 16:
switch v, ok := ti.Nums[MaxColors]; {
case !ok || v < 8:
return ColorLevelNone, nil
case ok && v >= 256:
case v >= 256:
return ColorLevelHundreds, nil
}
}
+24 -16
View File
@@ -33,9 +33,15 @@ const (
fieldExtTableSize
)
// hasInvalidCaps determines if the capabilities in h are invalid.
// hasInvalidCaps determines if the capabilities in h are invalid. As
// _nc_read_termtype in ncurses does, it refuses a negative count.
func hasInvalidCaps(h []int) bool {
return h[fieldBoolCount] > CapCountBool ||
return h[fieldNameSize] < 0 ||
h[fieldBoolCount] < 0 ||
h[fieldNumCount] < 0 ||
h[fieldStringCount] < 0 ||
h[fieldTableSize] < 0 ||
h[fieldBoolCount] > CapCountBool ||
h[fieldNumCount] > CapCountNum ||
h[fieldStringCount] > CapCountString
}
@@ -127,7 +133,7 @@ type decoder struct {
// readBytes reads the next n bytes of buf, incrementing pos by n.
func (d *decoder) readBytes(n int) ([]byte, error) {
if d.n < d.pos+n {
if n < 0 || d.n < d.pos+n {
return nil, ErrUnexpectedFileEnd
}
n, d.pos = d.pos, d.pos+n
@@ -150,9 +156,9 @@ func (d *decoder) readInts(n, w int) ([]int, error) {
case 1:
z[j] = int(buf[i])
case 2:
z[j] = int(int16(uint16(buf[i+1])<<8 | uint16(buf[i])))
z[j] = int(int16(uint16(buf[i+1])<<8 | uint16(buf[i]))) //nolint:gosec // a number is signed, and -1 and -2 mark absent and cancelled
case 4:
z[j] = int(int32(uint32(buf[i+3])<<24 | uint32(buf[i+2])<<16 | uint32(buf[i+1])<<8 | uint32(buf[i])))
z[j] = int(int32(uint32(buf[i+3])<<24 | uint32(buf[i+2])<<16 | uint32(buf[i+1])<<8 | uint32(buf[i]))) //nolint:gosec // as above
}
}
return z, nil
@@ -168,7 +174,7 @@ func (d *decoder) readBools(n int) (map[int]bool, map[int]bool, error) {
bools, boolsM := make(map[int]bool), make(map[int]bool)
for i, b := range buf {
bools[i] = b == 1
if int8(b) == -2 {
if int8(b) == -2 { //nolint:gosec // a bool byte of -2 marks a cancelled bool
boolsM[i] = true
}
}
@@ -245,23 +251,25 @@ func (d *decoder) readStrings(n, sz int) (map[int][]byte, map[int]bool, error) {
return strs, strsM, nil
}
// canonicalizeAscChars reorders chars to be unique, in order.
//
// see repair_ascc in ncurses-6.3/progs/dump_entry.c
// canonicalizeAscChars orders the pairs in z by their first byte, as
// repair_acsc in ncurses-6.6/progs/dump_entry.c does. When a first byte
// repeats, the last pair wins. An unpaired last byte stays at the end.
func canonicalizeAscChars(z []byte) []byte {
var c []byte
enc := make(map[byte]byte, len(z)/2)
for i := 0; i < len(z); i += 2 {
for i := 0; i+1 < len(z); i += 2 {
if _, ok := enc[z[i]]; !ok {
a, b := z[i], z[i+1]
// log.Printf(">>> a: %d %c, b: %d %c", a, a, b, b)
c, enc[a] = append(c, a), b
c = append(c, z[i])
}
enc[z[i]] = z[i+1]
}
slices.Sort(c)
r := make([]byte, 2*len(c))
for i := 0; i < len(c); i++ {
r[i*2], r[i*2+1] = c[i], enc[c[i]]
var r []byte
for _, a := range c {
r = append(r, a, enc[a])
}
if len(z)%2 == 1 {
r = append(r, z[len(z)-1])
}
return r
}
+16 -12
View File
@@ -1,24 +1,30 @@
package terminfo
import (
"errors"
"os"
"os/user"
"path"
"path/filepath"
"strings"
"sync"
)
// termCache is the terminfo cache.
var termCache = struct {
db map[string]*Terminfo
sync.RWMutex
db map[string]*Terminfo
}{
db: make(map[string]*Terminfo),
}
// Load follows the behavior described in terminfo(5) to find correct the
// terminfo file using the name, reads the file and then returns a Terminfo
// struct that describes the file.
// struct that describes the file. It returns ErrFileNotFound when no
// directory holds the file.
//
// Load caches each entry that it reads, and returns the same *Terminfo to
// every caller. A caller must not change the returned value or its maps,
// because the change is then seen by every other caller.
func Load(name string) (*Terminfo, error) {
if name == "" {
return nil, ErrEmptyTermName
@@ -34,12 +40,10 @@ func Load(name string) (*Terminfo, error) {
if dir := os.Getenv("TERMINFO"); dir != "" {
checkDirs = append(checkDirs, dir)
}
// check $HOME/.terminfo
u, err := user.Current()
if err != nil {
return nil, err
// check $HOME/.terminfo, as ncurses does, and skip it when $HOME is not set
if home := os.Getenv("HOME"); home != "" {
checkDirs = append(checkDirs, filepath.Join(home, ".terminfo"))
}
checkDirs = append(checkDirs, path.Join(u.HomeDir, ".terminfo"))
// check $TERMINFO_DIRS
if dirs := os.Getenv("TERMINFO_DIRS"); dirs != "" {
checkDirs = append(checkDirs, strings.Split(dirs, ":")...)
@@ -47,14 +51,14 @@ func Load(name string) (*Terminfo, error) {
// check fallback directories
checkDirs = append(checkDirs, "/etc/terminfo", "/lib/terminfo", "/usr/share/terminfo")
for _, dir := range checkDirs {
ti, err = Open(dir, name)
if err != nil && err != ErrFileNotFound && !os.IsNotExist(err) {
ti, err := Open(dir, name)
if err != nil && !errors.Is(err, ErrFileNotFound) && !os.IsNotExist(err) {
return nil, err
} else if err == nil {
return ti, nil
}
}
return nil, ErrDatabaseDirectoryNotFound
return nil, ErrFileNotFound
}
// LoadFromEnv loads the terminal info based on the name contained in
+55 -36
View File
@@ -9,7 +9,7 @@ import (
"sync"
)
// parametizer represents the a scan state for a parameterized string.
// parametizer holds the scan state for a parameterized string.
type parametizer struct {
// z is the string to parameterize
z []byte
@@ -31,8 +31,9 @@ type parametizer struct {
// staticVars are the static, global variables.
var staticVars = struct {
vars [26]any
sync.Mutex
vars [26]any
}{}
var parametizerPool = sync.Pool{
@@ -45,7 +46,7 @@ var parametizerPool = sync.Pool{
// newParametizer returns a new initialized parametizer from the pool.
func newParametizer(z []byte) *parametizer {
p := parametizerPool.Get().(*parametizer)
p, _ := parametizerPool.Get().(*parametizer)
p.z = z
return p
}
@@ -104,7 +105,7 @@ func (p *parametizer) scanTextFn() stateFn {
}
}
func (p *parametizer) scanCodeFn() stateFn {
func (p *parametizer) scanCodeFn() stateFn { //nolint:gocyclo // one case for each % code
ch, err := p.peek()
if err != nil {
return nil
@@ -112,16 +113,7 @@ func (p *parametizer) scanCodeFn() stateFn {
switch ch {
case '%':
p.buf.WriteByte('%')
case ':':
// this character is used to avoid interpreting "%-" and "%+" as operators.
// the next character is where the format really begins.
p.pos++
_, err = p.peek()
if err != nil {
return nil
}
return p.scanFormatFn
case '#', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.':
case ':', '#', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.':
return p.scanFormatFn
case 'o':
p.buf.WriteString(strconv.FormatInt(int64(p.s.popInt()), 8))
@@ -226,34 +218,61 @@ func (p *parametizer) scanCodeFn() stateFn {
return p.scanTextFn
}
// maxFormatWidth is the largest width or precision that a format can ask
// for. parse_format in ncurses drops the flags of a format over it.
const maxFormatWidth = 10000
// scanFormatFn reads a format, such as "%:-5d", as parse_format in ncurses
// does. Before the verb, it accepts only the flags '#', ' ' and, after a ':',
// '-', a width and a precision. Any other byte ends the format, and is read as
// a code. A width or precision over maxFormatWidth, or a second '.', drops
// every flag, so that a short string cannot ask for a long output.
func (p *parametizer) scanFormatFn() stateFn {
// the character was already read, so no need to check the error.
ch, _ := p.peek()
// 6 should be the maximum length of a format string, for example "%:-9.9d".
f := make([]byte, 2, 6)
f[0], f[1] = '%', ch
var err error
f := []byte{'%'}
var minus, dot, drop bool
var n int
for {
p.pos++
ch, err = p.peek()
ch, err := p.peek()
if err != nil {
return nil
}
f = append(f, ch)
switch ch {
case 'o', 'd', 'x', 'X':
fmt.Fprintf(p.buf, string(f), p.s.popInt())
p.pos++
return p.scanTextFn
case 's':
fmt.Fprintf(p.buf, string(f), p.s.popString())
p.pos++
return p.scanTextFn
case 'c':
fmt.Fprintf(p.buf, string(f), p.s.popByte())
switch {
case ch == 'o' || ch == 'd' || ch == 'x' || ch == 'X' || ch == 's' || ch == 'c':
if drop {
f = f[:1]
}
p.writeFormat(append(f, ch))
p.pos++
return p.scanTextFn
case ch == ':':
minus = true
case ch == '#', ch == ' ', ch == '-' && minus:
f = append(f, ch)
case ch == '.':
drop, dot, n = drop || dot, true, 0
f = append(f, ch)
case isDigit(ch):
if n = n*10 + int(ch-'0'); n > maxFormatWidth {
drop, n = true, maxFormatWidth
}
f = append(f, ch)
default:
return p.scanCodeFn
}
p.pos++
}
}
// writeFormat pops a value and writes it with the format f, which ends with
// its verb. As ncurses does, %c writes the byte and ignores the format.
func (p *parametizer) writeFormat(f []byte) {
switch f[len(f)-1] {
case 'c':
p.buf.WriteByte(p.s.popByte())
case 's':
fmt.Fprintf(p.buf, string(f), p.s.popString())
default:
fmt.Fprintf(p.buf, string(f), p.s.popInt())
}
}
@@ -267,7 +286,7 @@ func (p *parametizer) pushParamFn() stateFn {
} else {
p.s.push(0)
}
// skip the '}'
// skip the parameter digit
p.pos++
return p.scanTextFn
}
@@ -401,5 +420,5 @@ func Printf(z []byte, params ...any) string {
// Fprintf evaluates a parameterized terminfo value z, interpolating params and
// writing to w.
func Fprintf(w io.Writer, z []byte, params ...any) {
w.Write([]byte(Printf(z, params...)))
_, _ = io.WriteString(w, Printf(z, params...))
}
+17
View File
@@ -0,0 +1,17 @@
{
"version": 1,
"skills": {
"go-pedantry": {
"source": "oborchers/fractional-cto",
"sourceType": "github",
"skillPath": "pedantic-coder/skills/go-pedantry/SKILL.md",
"computedHash": "31d2344d7292bd589b1b37959b72bad61ea53cb0bc7d187d0ce1b2fe0ec9bf3e"
},
"simple-english": {
"source": "AminBlg/SimpleEnglish",
"sourceType": "github",
"skillPath": "skills/simple-english/SKILL.md",
"computedHash": "27ecd9fcbf49b035da6463dc2aa3459167ae2f2536b65d17eaf52afbaac87f7c"
}
}
}
+169 -122
View File
@@ -4,11 +4,13 @@ package terminfo
//go:generate go run gen.go
import (
"bytes"
"io"
"io/ioutil"
"path"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Error is a terminfo error.
@@ -36,8 +38,6 @@ const (
ErrInvalidExtendedHeader Error = "invalid extended header"
// ErrEmptyTermName is the empty term name error.
ErrEmptyTermName Error = "empty term name"
// ErrDatabaseDirectoryNotFound is the database directory not found error.
ErrDatabaseDirectoryNotFound Error = "database directory not found"
// ErrFileNotFound is the file not found error.
ErrFileNotFound Error = "file not found"
// ErrInvalidTermProgramVersion is the invalid TERM_PROGRAM_VERSION error.
@@ -64,17 +64,17 @@ type Terminfo struct {
StringsM map[int]bool
// ExtBools are the extended bool capabilities.
ExtBools map[int]bool
// ExtBoolsNames is the map of extended bool capabilities to their index.
// ExtBoolNames is the map of extended bool capabilities to their index.
ExtBoolNames map[int][]byte
// ExtNums are the extended num capabilities.
ExtNums map[int]int
// ExtNumsNames is the map of extended num capabilities to their index.
// ExtNumNames is the map of extended num capabilities to their index.
ExtNumNames map[int][]byte
// ExtStrings are the extended string capabilities.
ExtStrings map[int][]byte
// ExtStringsM are the missing extended string capabilities.
ExtStringsM map[int]bool
// ExtStringsNames is the map of extended string capabilities to their index.
// ExtStringNames is the map of extended string capabilities to their index.
ExtStringNames map[int][]byte
}
@@ -96,10 +96,10 @@ func Decode(buf []byte) (*Terminfo, error) {
}
var numWidth int
// check magic
switch {
case h[fieldMagic] == magic:
switch h[fieldMagic] {
case magic:
numWidth = 16
case h[fieldMagic] == magicExtended:
case magicExtended:
numWidth = 32
default:
return nil, ErrInvalidMagic
@@ -212,20 +212,21 @@ func Decode(buf []byte) (*Terminfo, error) {
if err != nil {
return nil, err
}
// extIndexes = extIndexes[eh[fieldExtStringCount]:]
return ti, nil
}
// Open reads the terminfo file name from the specified directory dir.
// Open reads the terminfo file name from the specified directory dir. Open
// adds the entry to the cache of Load, so a caller must not change the
// returned value, as for Load.
func Open(dir, name string) (*Terminfo, error) {
var err error
var buf []byte
var filename string
for _, f := range []string{
path.Join(dir, name[0:1], name),
path.Join(dir, strconv.FormatUint(uint64(name[0]), 16), name),
filepath.Join(dir, name[0:1], name),
filepath.Join(dir, strconv.FormatUint(uint64(name[0]), 16), name),
} {
buf, err = ioutil.ReadFile(f)
buf, err = os.ReadFile(f)
if err == nil {
filename = f
break
@@ -250,22 +251,6 @@ func Open(dir, name string) (*Terminfo, error) {
return ti, nil
}
// boolCaps returns all bool and extended capabilities using f to format the
// index key.
func (ti *Terminfo) boolCaps(f func(int) string, extended bool) map[string]bool {
m := make(map[string]bool, len(ti.Bools)+len(ti.ExtBools))
if !extended {
for k, v := range ti.Bools {
m[f(k)] = v
}
} else {
for k, v := range ti.ExtBools {
m[string(ti.ExtBoolNames[k])] = v
}
}
return m
}
// BoolCaps returns all bool capabilities.
func (ti *Terminfo) BoolCaps() map[string]bool {
return ti.boolCaps(BoolCapName, false)
@@ -288,22 +273,6 @@ func (ti *Terminfo) ExtBoolCapsShort() map[string]bool {
return ti.boolCaps(BoolCapNameShort, true)
}
// numCaps returns all num and extended capabilities using f to format the
// index key.
func (ti *Terminfo) numCaps(f func(int) string, extended bool) map[string]int {
m := make(map[string]int, len(ti.Nums)+len(ti.ExtNums))
if !extended {
for k, v := range ti.Nums {
m[f(k)] = v
}
} else {
for k, v := range ti.ExtNums {
m[string(ti.ExtNumNames[k])] = v
}
}
return m
}
// NumCaps returns all num capabilities.
func (ti *Terminfo) NumCaps() map[string]int {
return ti.numCaps(NumCapName, false)
@@ -326,23 +295,8 @@ func (ti *Terminfo) ExtNumCapsShort() map[string]int {
return ti.numCaps(NumCapNameShort, true)
}
// stringCaps returns all string and extended capabilities using f to format the
// index key.
func (ti *Terminfo) stringCaps(f func(int) string, extended bool) map[string][]byte {
m := make(map[string][]byte, len(ti.Strings)+len(ti.ExtStrings))
if !extended {
for k, v := range ti.Strings {
m[f(k)] = v
}
} else {
for k, v := range ti.ExtStrings {
m[string(ti.ExtStringNames[k])] = v
}
}
return m
}
// StringCaps returns all string capabilities.
// StringCaps returns all string capabilities. It leaves out each absent
// capability.
func (ti *Terminfo) StringCaps() map[string][]byte {
return ti.stringCaps(StringCapName, false)
}
@@ -388,10 +342,10 @@ func (ti *Terminfo) Fprintf(w io.Writer, i int, v ...any) {
Fprintf(w, ti.Strings[i], v...)
}
// Color takes a foreground and background color and returns string that sets
// them for this terminal.
// Colorf returns str with the escape sequences that set the foreground color
// fg and the background color bg before it, and reset them after it.
func (ti *Terminfo) Colorf(fg, bg int, str string) string {
maxColors := int(ti.Nums[MaxColors])
maxColors := ti.Nums[MaxColors]
// map bright colors to lower versions if the color table only holds 8.
if maxColors == 8 {
if fg > 7 && fg < 16 {
@@ -417,65 +371,158 @@ func (ti *Terminfo) Goto(row, col int) string {
return Printf(ti.Strings[CursorAddress], row, col)
}
// Puts emits the string to the writer, but expands inline padding indications
// (of the form $<[delay]> where [delay] is msec) to a suitable number of
// padding characters (usually null bytes) based upon the supplied baud. At
// high baud rates, more padding characters will be inserted.
/*func (ti *Terminfo) Puts(w io.Writer, s string, lines, baud int) (int, error) {
var err error
for {
start := strings.Index(s, "$<")
if start == -1 {
// most strings don't need padding, which is good news!
return io.WriteString(w, s)
// Puts writes s to w, and applies each padding marker in s, such as the
// $<100/> in the flash capability of xterm. It follows tputs in ncurses.
//
// A marker holds a delay in milliseconds, with one optional decimal place. A
// '*' after the number multiplies the delay by lines, the count of lines that
// the output affects. A '/' after the number makes the delay mandatory. Puts
// applies a delay when it is mandatory, when s is the bell or the flash
// capability, or when baud is at least the padding baud rate and the terminal
// has no xon/xoff flow control. Puts writes no marker to w.
//
// Puts writes a delay as pad characters, and the baud rate sets how many. If
// the terminal has no pad character, Puts sleeps for the delay instead. Puts
// limits each delay to 30 seconds.
func (ti *Terminfo) Puts(w io.Writer, s string, lines, baud int) (int, error) {
always := ti.isString(Bell, s) || ti.isString(FlashScreen, s)
normal := !ti.Bools[XonXoff] && ti.Nums[PaddingBaudRate] != 0 && baud >= ti.Nums[PaddingBaudRate]
var buf []byte
var n int
for i := 0; i < len(s); i++ {
if s[i] != '$' || i+1 == len(s) || s[i+1] != '<' {
buf = append(buf, s[i])
continue
}
end := strings.Index(s, ">")
if end == -1 {
// unterminated... just emit bytes unadulterated.
return io.WriteString(w, "$<"+s)
// a marker starts with a digit or a '.', and ends with a '>'
j := i + 2
if j == len(s) || (!isDigit(s[j]) && s[j] != '.') || !strings.Contains(s[j:], ">") {
buf = append(buf, '$', '<')
i++
continue
}
var c int
c, err = io.WriteString(w, s[:start])
if err != nil {
return n + c, err
d, end, mandatory := readDelay(s, j, lines)
// skip the '>', as ncurses skips one byte
i = end
if d <= 0 || (!always && !normal && !mandatory) {
continue
}
n += c
s = s[start+2:]
val := s[:end]
s = s[end+1:]
var ms int
var dot, mandatory, asterisk bool
unit := 1000
for _, ch := range val {
switch {
case ch >= '0' && ch <= '9':
ms = (ms * 10) + int(ch-'0')
if dot {
unit *= 10
}
case ch == '.' && !dot:
dot = true
case ch == '*' && !asterisk:
ms *= lines
asterisk = true
case ch == '/':
mandatory = true
default:
break
}
}
z, pad := ((baud/8)/unit)*ms, ti.Strings[PadChar]
b := make([]byte, len(pad)*z)
for bp := copy(b, pad); bp < len(b); bp *= 2 {
copy(b[bp:], b[:bp])
}
if (!ti.Bools[XonXoff] && baud > int(ti.Nums[PaddingBaudRate])) || mandatory {
c, err = w.Write(b)
ms := min(d/10, maxDelay)
if ti.Bools[NoPadChar] {
c, err := w.Write(buf)
n, buf = n+c, buf[:0]
if err != nil {
return n + c, err
return n, err
}
n += c
time.Sleep(time.Duration(ms) * time.Millisecond)
continue
}
pad := byte(0)
if p := ti.Strings[PadChar]; len(p) != 0 {
pad = p[0]
}
buf = append(buf, bytes.Repeat([]byte{pad}, max(ms*baud/(baudByte*1000), 0))...)
}
c, err := w.Write(buf)
return n + c, err
}
// boolCaps returns all bool and extended capabilities using f to format the
// index key.
func (ti *Terminfo) boolCaps(f func(int) string, extended bool) map[string]bool {
m := make(map[string]bool, len(ti.Bools)+len(ti.ExtBools))
if !extended {
for k, v := range ti.Bools {
m[f(k)] = v
}
} else {
for k, v := range ti.ExtBools {
m[string(ti.ExtBoolNames[k])] = v
}
}
return n, nil
}*/
return m
}
// numCaps returns all num and extended capabilities using f to format the
// index key.
func (ti *Terminfo) numCaps(f func(int) string, extended bool) map[string]int {
m := make(map[string]int, len(ti.Nums)+len(ti.ExtNums))
if !extended {
for k, v := range ti.Nums {
m[f(k)] = v
}
} else {
for k, v := range ti.ExtNums {
m[string(ti.ExtNumNames[k])] = v
}
}
return m
}
// stringCaps returns all string and extended capabilities using f to format the
// index key. It leaves out each absent capability, which has a nil value.
func (ti *Terminfo) stringCaps(f func(int) string, extended bool) map[string][]byte {
m := make(map[string][]byte, len(ti.Strings)+len(ti.ExtStrings))
if !extended {
for k, v := range ti.Strings {
if v != nil {
m[f(k)] = v
}
}
} else {
for k, v := range ti.ExtStrings {
if v != nil {
m[string(ti.ExtStringNames[k])] = v
}
}
}
return m
}
// readDelay reads the padding marker in s that starts at j, after the "$<".
// It returns the delay in tenths of a millisecond, the index of the byte after
// the delay, and whether the delay is mandatory.
func readDelay(s string, j, lines int) (int, int, bool) {
var d int
for ; j < len(s) && isDigit(s[j]); j++ {
d = d*10 + int(s[j]-'0')
}
d *= 10
if j < len(s) && s[j] == '.' {
if j++; j < len(s) && isDigit(s[j]) {
d += int(s[j] - '0')
j++
}
for j < len(s) && isDigit(s[j]) {
j++
}
}
var mandatory bool
for ; j < len(s) && (s[j] == '*' || s[j] == '/'); j++ {
if s[j] == '*' {
d *= lines
} else {
mandatory = true
}
}
return d, j, mandatory
}
// maxDelay is the longest delay that Puts applies, in milliseconds. It is
// MAX_DELAY_MSECS in ncurses.
const maxDelay = 30000
// baudByte is the count of bits that one byte takes on the line: 7 bits, 1
// parity bit and 1 stop bit. It is BAUDBYTE in ncurses.
const baudByte = 9
// isString reports whether the string capability i is present and equal to s.
func (ti *Terminfo) isString(i int, s string) bool {
v, ok := ti.Strings[i]
return ok && v != nil && string(v) == s
}
// isDigit reports whether c is an ASCII digit.
func isDigit(c byte) bool {
return '0' <= c && c <= '9'
}
+1 -1
View File
@@ -157,7 +157,7 @@ github.com/stretchr/testify/internal/spew
# github.com/wk8/go-ordered-map/v2 v2.1.8
## explicit; go 1.18
github.com/wk8/go-ordered-map/v2
# github.com/xo/terminfo v1.2.0
# github.com/xo/terminfo v1.3.1
## explicit; go 1.25
github.com/xo/terminfo
# go.yaml.in/yaml/v3 v3.0.5