diff --git a/.agents/skills/testing-the-mcp-server/SKILL.md b/.agents/skills/testing-the-mcp-server/SKILL.md index c0af2d856..43efcbec8 100644 --- a/.agents/skills/testing-the-mcp-server/SKILL.md +++ b/.agents/skills/testing-the-mcp-server/SKILL.md @@ -53,7 +53,9 @@ Give the whole run its own root so a sibling checkout's suite cannot end a server this one is using: ```console -$ export TMUX_TMPDIR=/tmp/libtmux-go-probe && mkdir -p "$TMUX_TMPDIR" && unset TMUX TMUX_PANE +$ export TMUX_TMPDIR=/tmp/libtmux-go-probe \ + && mkdir -p "$TMUX_TMPDIR" \ + && unset TMUX TMUX_PANE ``` ## Climb only as high as the question needs @@ -68,8 +70,10 @@ stdin open, matches replies by id, declines any question the server asks, and reads a plan of JSON-RPC calls from stdin. ```console -$ ./references/drive.py "$(command -v libtmux-mcp)" TMUX_TMPDIR=/tmp/libtmux-go-probe \ - <<< '[{"method":"tools/call","params":{"name":"list_panes","arguments":{}}}]' +$ ./references/drive.py "$(command -v libtmux-mcp)" \ + TMUX_TMPDIR=/tmp/libtmux-go-probe <<'EOF' +[{"method":"tools/call","params":{"name":"list_panes","arguments":{}}}] +EOF ``` It reports which advertised tools a plan never called, so a sweep can be grown diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 8a19bc9f3..8fef349b9 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -21,7 +21,9 @@ which surfaces as a version-specific failure that has nothing to do with the version: ```console -$ export TMUX_TMPDIR=/tmp/libtmux-go-test && mkdir -p "$TMUX_TMPDIR" && unset TMUX TMUX_PANE +$ export TMUX_TMPDIR=/tmp/libtmux-go-test \ + && mkdir -p "$TMUX_TMPDIR" \ + && unset TMUX TMUX_PANE ``` ## The gates @@ -36,7 +38,9 @@ packages as typecheck failures, and a newer one reports lints an older one has no analyzer for. Run the pinned release before believing a clean local one: ```console -$ go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0 run ./... +$ go run \ + github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0 \ + run ./... ``` Format, lint, vet, and test the tmux module: @@ -48,7 +52,14 @@ $ gofumpt -w . && golangci-lint run ./... && go vet ./... && go test ./... Then each of the others, from its own directory: ```console -$ for module in examples workspace mcp benchmarks internal/tools; do (cd "$module" && gofumpt -w . && golangci-lint run ./... && go vet ./... && go test ./...) || break; done +$ for module in examples workspace mcp benchmarks internal/tools; do + (cd "$module" \ + && gofumpt -w . \ + && golangci-lint run ./... \ + && go vet ./... \ + && go test ./...) \ + || break + done ``` Run them with the workspace on, which is the only way they see the working @@ -82,7 +93,8 @@ agreeing on one stale version is the failure that check exists for, and it is the failure that happened: ```console -$ go test ./tmux/internal/integration/ -run TestEveryRequirementNamesTheNewestRelease +$ go test ./tmux/internal/integration/ \ + -run TestEveryRequirementNamesTheNewestRelease ``` Release sibling modules in dependency order: core, workspace, then MCP. After @@ -105,7 +117,11 @@ Known vulnerabilities are checked per module, because each resolves its own dependencies: ```console -$ for module in . examples workspace mcp benchmarks internal/tools; do (cd "$module" && go run golang.org/x/vuln/cmd/govulncheck@v1.6.0 ./...) || break; done +$ for module in . examples workspace mcp benchmarks internal/tools; do + (cd "$module" \ + && go run golang.org/x/vuln/cmd/govulncheck@v1.6.0 ./...) \ + || break + done ``` It reports the standard library as well as dependencies, so it fails on a @@ -133,6 +149,16 @@ Then confirm that regeneration changed nothing: $ git diff --exit-code ``` +Examples stay within 80 columns, which gofumpt does not enforce. +`.github/example-width.toml` names the files the check reads and lists the few +lines allowed to stay wider. The self-test comes first because it proves the +check can fail: + +```console +$ python3 internal/tools/check_example_width.py --self-test && \ + python3 internal/tools/check_example_width.py +``` + The race detector is not optional before anything ships: ```console diff --git a/.github/WRITING.md b/.github/WRITING.md index 2e277d58e..5d33adb1e 100644 --- a/.github/WRITING.md +++ b/.github/WRITING.md @@ -185,6 +185,101 @@ Go blocks between `docs:` markers are generated. Edit their source program, not the Markdown block; [the examples README](../examples/README.md) identifies them. Unmarked blocks are handwritten. +## Examples + + + +An example is code written for a reader: a program under `examples/`, code in +a doc comment or docstring, and every fenced block in a README or docs page. +Shell blocks also follow [Code blocks](#code-blocks). + +The text between the shared markers is the same in every libtmux port. +Change it in all of them together. + +### Width + +- **Examples stay within 80 columns.** They render in fixed-width boxes that + scroll sideways, and 80 columns fits a libtmux.org code block in a + laptop-width window. Comments inside examples wrap at 80 too. +- **The width check enforces it.** It reads the tracked files that + `.github/example-width.toml` names and fails on a wider line. It measures + the whole source line, so code in a doc comment counts its indent and + comment marker. It skips output (a fence tagged `text`, and what a + `console` block prints), hidden setup lines, and a line that is only a URL; + an untagged fence counts as code. +- **A line that must stay wider is listed there with its reason.** An entry + that no longer matches a line fails the check, so no stale entry stays. +- **The formatter's width is the hard limit for all other source.** Example + directories set their formatter to 80 where the formatter takes a width. + +### Reaching 80 + +- **Change the code, not the line breaks.** A formatter rejoins any line that + fits its width. Name a sub-expression, use a short example name, hide setup + the reader does not need, or print less. +- **Break at the outermost level when a break is still needed:** after an + opening parenthesis with one argument per line, one call per line in a + chain, one field per line in a literal. +- **Put a comment on its own line above the code it explains.** Never trail + one after code in an example, unless the repository's example runner reads + it there, as with an assertion marker. +- **Break a long string at a word boundary,** never inside a tmux format + (`#{...}`) or an escape sequence; the joined text stays the same. +- **Continue a long command in a `console` block the way its shell does:** + `\` after a `$ ` prompt, a backtick after `PS> `, one flag per continuation + line. + +### What never breaks + +- **Output a test compares.** Wrapping it changes what the test expects. +- **A block copied from a source file.** Fix the width in the source, then + refresh the copy with the sync command the port block names, or by hand + where it names none; never fix the copy alone. +- **Marker lines and URLs,** which tools and readers take whole. + + + +### In this repository + +- **Hard limit:** `golines` in `examples/.golangci.yml` (`max-len` and + `tab-len`), enabled beside gofumpt in the `examples` module only; the width + check counts a tab as 4 columns, as `tab-len` does. `golangci-lint run` + fails a file either formatter would change, and + `(cd examples && golangci-lint fmt ./...)` applies both; use the version + `.github/workflows/tests.yml` pins, since another can format differently. + The width check is `python3 internal/tools/check_example_width.py`. +- **Not formatted:** other modules run gofumpt only. Their `example_test.go` + files, the `mcp/examples` and `workspace/examples` programs, + `examples/go.mod`, `examples/.golangci.yml`, Markdown blocks and doc-comment + code are held to 80 by hand and by the width check. Tag a table of program + output `text`; the check skips it. +- **Runs, compiles, exempt:** an `Example` runs only when it ends in + `// Output:`. One without output compiles only, and `examplesWithoutOutput` + in `tmux/documentation_test.go` lists it with a reason. A Markdown block + between `docs:` markers is quoted from a program that compiles and runs. An + unmarked block is handwritten and is neither. +- **Compared output and copied blocks:** `// Output:` text and `// docs:` + marker lines stay whole. After editing a program under `examples/`, run + `go generate ./...` in `tmux/`; after changing an MCP tool, run it in `mcp/` + to rebuild `TOOLS.md`. CI fails on any diff. + +Bad, over 80: + +```go + if _, err := connectedPane.Capture(ctx, tmux.CapturePaneRequest{}); !errors.Is( + err, + tmux.ErrConnectionRequiresProcess, + ) { +``` + +Good, a named request and one statement per step: + +```go + request := tmux.CapturePaneRequest{} + _, err = connectedPane.Capture(ctx, request) + if !errors.Is(err, tmux.ErrConnectionRequiresProcess) { +``` + ## Commits ```text diff --git a/.github/example-width.toml b/.github/example-width.toml new file mode 100644 index 000000000..15188dd40 --- /dev/null +++ b/.github/example-width.toml @@ -0,0 +1,38 @@ +width = 80 +tab_width = 4 +shared_digest = "28b74bae1f7a06731fea5a150cbde4430179b7788b7564ea1644c3951df8531b" +checker_digest = "eb87afceb3fc8f11ef5a478cd38f901ef3950e89ff94fbe0ca281c0cfc1a0e2e" +allow_ceiling = 4 +markdown = ["**/*.md"] +sources = [ + "**/examples/**/*.go", + "**/example_test.go", + "**/*_example_test.go", + "**/examples/go.mod", + "**/examples/.golangci.yml", +] +doc_comments = ["**/*.go"] + +[[exclude]] +glob = "examples/LICENSE" +reason = "license text; nobody reads it for code" + +[[allow]] +path = "examples/byte-streams/main.go" +line = "\t// docs:byte-streams given:ctx context.Context; server tmux.Server; pane tmux.Pane; payload *strings.Reader; archive string; marker string" +reason = "docs marker line; the generator reads it whole" + +[[allow]] +path = "examples/control-mode-subscribe/main.go" +line = "\t// docs:subscribing given:ctx context.Context; session tmux.Session; stream *tmux.NotificationStream" +reason = "docs marker line; the generator reads it whole" + +[[allow]] +path = "tmux/example_test.go" +line = "\t// Output: {\"id\":\"\",\"sessionId\":\"\",\"windowId\":\"\",\"windowIndex\":0,\"index\":0,\"formats\":{}}" +reason = "output the test compares" + +[[allow]] +path = ".github/WRITING.md" +line = "\tif _, err := connectedPane.Capture(ctx, tmux.CapturePaneRequest{}); !errors.Is(" +reason = "the Bad example in the port block; it shows the width problem the Good example fixes" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7c5588a0a..732aeba9c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -129,6 +129,14 @@ jobs: exit 1 fi + # Examples render in fixed-width boxes, and gofumpt never wraps a line, + # so the width has its own check. The self-test runs first: a check that + # cannot fail is not evidence. + - name: Check example width + run: | + python3 internal/tools/check_example_width.py --self-test + python3 internal/tools/check_example_width.py + # An exported identifier can change or vanish without anything saying so: the # changelog is written by hand, and nothing compares what a release exports # against what the last one did. This reports that difference into the run diff --git a/AGENTS.md b/AGENTS.md index 341c6654c..9cfafbeef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,8 +29,10 @@ subprocess transport, the checked-in generators, and `internal/integration`. ## Which policy applies - Documentation, user-facing text, `CHANGELOG.md`, release notes, commit - messages, doc comments, and source comments: - [.github/WRITING.md](.github/WRITING.md) + messages, doc comments, source comments, and any code example (example + programs, Example functions, Markdown code blocks): + [.github/WRITING.md](.github/WRITING.md), and its + [Examples](.github/WRITING.md#examples) section for code a reader sees - Building, testing, linting, the Go floor, the tmux matrix, and pull requests: [.github/CONTRIBUTING.md](.github/CONTRIBUTING.md) - Anything under `mcp/`: [mcp/AGENTS.md](mcp/AGENTS.md) diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 19ace38a2..23686db72 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -19,7 +19,7 @@ Each table below contains the same workload on a different tmux. ## tmux 3.2a -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 105ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -31,7 +31,7 @@ chained + connection 7ms 0 1 7 panes on the server [0 0 ## tmux 3.3a -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 105ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -43,7 +43,7 @@ chained + connection 8ms 0 1 7 panes on the server [0 0 ## tmux 3.4 -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 116ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -55,7 +55,7 @@ chained + connection 19ms 0 1 7 panes on the server [0 0 ## tmux 3.5 -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 143ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -67,7 +67,7 @@ chained + connection 9ms 0 1 7 panes on the server [0 0 ## tmux 3.6 -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 108ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -79,7 +79,7 @@ chained + connection 18ms 0 1 7 panes on the server [0 0 ## tmux 3.7 -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 113ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -91,7 +91,7 @@ chained + connection 9ms 0 1 7 panes on the server [0 0 ## tmux 3.7a -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 187ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -103,7 +103,7 @@ chained + connection 10ms 0 1 7 panes on the server [0 0 ## tmux 3.7b -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 92ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -115,7 +115,7 @@ chained + connection 7ms 0 1 7 panes on the server [0 0 ## tmux 3.7c -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 102ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -127,7 +127,7 @@ chained + connection 8ms 0 1 7 panes on the server [0 0 ## tmux 3.8-rc2 -``` +```text path wall processes clients query answer ---------------------------------------------------------------------------------------- process 67ms 17 0 7 panes on the server [0 0 1 2 3 4 5] @@ -193,7 +193,7 @@ named above against tmux 3.7c, 20 iterations per size: ```console $ go test ./tmux/ \ -run '^$' \ - -bench 'BenchmarkLoadBufferFrom|BenchmarkSaveBufferTo|BenchmarkCaptureScrollback' \ + -bench 'Benchmark(LoadBufferFrom|SaveBufferTo|CaptureScrollback)' \ -benchtime 20x \ -benchmem ``` @@ -236,7 +236,7 @@ woken by tmux. Ten waits each, for output 150ms away, on tmux 3.7d and the machine named above. `go -C benchmarks run .` prints this table too, and `TestWaitingEventDrivenCostsFewerProcesses` gates the comparison. -``` +```text path wall processes clients measurement ---------------------------------------------------------------------------------------- polled capture 161ms 18 0 10 waits for output 150ms away @@ -323,7 +323,10 @@ No tmux and no disk: decoding YAML into the document map and normalizing it into a build plan, on a fixed six-window, three-pane-each document. ```console -$ go test ./workspace/internal/cli/ -run '^$' -bench 'BenchmarkDecodeDocument|BenchmarkNormalize' -benchmem +$ go test ./workspace/internal/cli/ \ + -run '^$' \ + -bench 'Benchmark(DecodeDocument|Normalize)' \ + -benchmem ``` | Call | Cost | diff --git a/README.md b/README.md index 5721c6232..2c35b8186 100644 --- a/README.md +++ b/README.md @@ -68,12 +68,18 @@ if err != nil { return fmt.Errorf("create session: %w", err) } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() -window, err := session.NewWindow(ctx, tmux.NewWindowRequest{Name: new("work")}) +window, err := session.NewWindow( + ctx, + tmux.NewWindowRequest{Name: new("work")}, +) if err != nil { return fmt.Errorf("create window: %w", err) } @@ -88,7 +94,10 @@ if err != nil { return fmt.Errorf("watch pane: %w", err) } defer func() { err = errors.Join(err, output.Close()) }() -if _, err := fmt.Fprintln(pane.Writer(ctx), "printf 'libtmux ready\\n'"); err != nil { +if _, err := fmt.Fprintln( + pane.Writer(ctx), + "printf 'libtmux ready\\n'", +); err != nil { return fmt.Errorf("send command: %w", err) } ``` @@ -321,7 +330,8 @@ for { if err != nil { return fmt.Errorf("read notification: %w", err) } - if change, ok := notification.Subscription(); ok && change.Value == "2" { + change, ok := notification.Subscription() + if ok && change.Value == "2" { fmt.Println("session has", change.Value, "windows") return nil } @@ -487,7 +497,8 @@ func TestSomething(t *testing.T) { ctx := context.Background() server := tmuxtest.NewServer(ctx, t) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "under-test"}) + request := tmux.NewSessionRequest{Name: "under-test"} + session, err := server.NewSession(ctx, request) // ... } ``` @@ -499,7 +510,10 @@ answers the invocations you name, so the test needs no tmux installed: ```go server, err := tmux.NewServer(tmux.ServerOptions{ Binary: tmuxtest.ScriptedTmux(t, - tmuxtest.ScriptedCommand{Contains: []string{"-V"}, Stdout: "tmux 3.7\n"}, + tmuxtest.ScriptedCommand{ + Contains: []string{"-V"}, + Stdout: "tmux 3.7\n", + }, tmuxtest.ScriptedCommand{ Contains: []string{"kill-pane"}, Stderr: "can't find pane: %7\n", diff --git a/benchmarks/README.md b/benchmarks/README.md index 941a9d5cd..77b268748 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -6,7 +6,7 @@ What each way of reaching tmux costs, printed as one table. $ go -C benchmarks run . ``` -``` +```text building a 6-pane window, tmux 3.7c 12th Gen Intel(R) Core(TM) i7-12700H, 10 threads, linux, go1.26.5 diff --git a/examples/.golangci.yml b/examples/.golangci.yml index 992ed8ef9..df5bfd98b 100644 --- a/examples/.golangci.yml +++ b/examples/.golangci.yml @@ -47,6 +47,12 @@ linters: formatters: enable: - gofumpt + - golines + settings: + golines: + max-len: 80 + tab-len: 4 + shorten-comments: false issues: max-issues-per-linter: 0 diff --git a/examples/README.md b/examples/README.md index 3b7045e9d..4c252b654 100644 --- a/examples/README.md +++ b/examples/README.md @@ -46,7 +46,10 @@ A region is named where it is written: ```go // docs:quickstart windowName := "work" - window, err := session.NewWindow(ctx, tmux.NewWindowRequest{Name: &windowName}) + window, err := session.NewWindow( + ctx, + tmux.NewWindowRequest{Name: &windowName}, + ) // docs:end ``` @@ -111,7 +114,9 @@ A tmux on `PATH`, version 3.2a or newer. To keep these off a tmux server you are using: ```console -$ export TMUX_TMPDIR=/tmp/libtmux-go-examples && mkdir -p "$TMUX_TMPDIR" && unset TMUX TMUX_PANE +$ export TMUX_TMPDIR=/tmp/libtmux-go-examples && \ + mkdir -p "$TMUX_TMPDIR" && \ + unset TMUX TMUX_PANE ``` ## See also diff --git a/examples/byte-streams/main.go b/examples/byte-streams/main.go index 9c58e1935..0c7dbf92e 100644 --- a/examples/byte-streams/main.go +++ b/examples/byte-streams/main.go @@ -51,7 +51,10 @@ func run(ctx context.Context, server tmux.Server, archive string) (err error) { return fmt.Errorf("create session: %w", err) } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() @@ -64,7 +67,9 @@ func run(ctx context.Context, server tmux.Server, archive string) (err error) { // A payload with the characters a shell would fight over, from anything // that reads: a file, a socket, an HTTP body, or this strings.Reader. const marker = "'quoted'" - payload := strings.NewReader("$HOME 'quoted' \"double\" `backtick` \\ done\n") + payload := strings.NewReader( + "$HOME 'quoted' \"double\" `backtick` \\ done\n", + ) // docs:byte-streams given:ctx context.Context; server tmux.Server; pane tmux.Pane; payload *strings.Reader; archive string; marker string // Pasting hands the bytes to the pane's pty; the program reading it echoes diff --git a/examples/control-mode-subscribe/example_test.go b/examples/control-mode-subscribe/example_test.go index e3c495b25..1cf68e04c 100644 --- a/examples/control-mode-subscribe/example_test.go +++ b/examples/control-mode-subscribe/example_test.go @@ -29,9 +29,16 @@ func TestControlModeSubscribe(t *testing.T) { t.Errorf("printed %q, want it to contain %q", printed, want) } if want := "session has 2 windows"; !strings.Contains(printed, want) { - t.Errorf("printed %q, want the subscription to report %q", printed, want) + t.Errorf( + "printed %q, want the subscription to report %q", + printed, + want, + ) } if want := "notification:"; !strings.Contains(printed, want) { - t.Errorf("printed %q, want it to name the notifications it read", printed) + t.Errorf( + "printed %q, want it to name the notifications it read", + printed, + ) } } diff --git a/examples/control-mode-subscribe/main.go b/examples/control-mode-subscribe/main.go index a9db0e4d3..a921be936 100644 --- a/examples/control-mode-subscribe/main.go +++ b/examples/control-mode-subscribe/main.go @@ -32,12 +32,18 @@ func start() error { // run accepts injected server state so tests can isolate the example. func run(ctx context.Context, server tmux.Server) (err error) { - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "libtmux-control"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "libtmux-control"}, + ) if err != nil { return fmt.Errorf("create session: %w", err) } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() @@ -83,7 +89,8 @@ func run(ctx context.Context, server tmux.Server) (err error) { if err != nil { return fmt.Errorf("read notification: %w", err) } - if change, ok := notification.Subscription(); ok && change.Value == "2" { + change, ok := notification.Subscription() + if ok && change.Value == "2" { fmt.Println("session has", change.Value, "windows") return nil } diff --git a/examples/environment/main.go b/examples/environment/main.go index fb1937e15..b5bf29d7b 100644 --- a/examples/environment/main.go +++ b/examples/environment/main.go @@ -1,4 +1,5 @@ -// Command environment demonstrates session environment access and pane discovery. +// Command environment demonstrates session environment access and pane +// discovery. package main import ( @@ -31,17 +32,26 @@ func start() error { // run accepts injected server state so tests can isolate the example. func run(ctx context.Context, server tmux.Server) (err error) { - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "libtmux-environment"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "libtmux-environment"}, + ) if err != nil { return err } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() - window, err := session.NewWindow(ctx, tmux.NewWindowRequest{Name: new("discovery")}) + window, err := session.NewWindow( + ctx, + tmux.NewWindowRequest{Name: new("discovery")}, + ) if err != nil { return err } @@ -49,15 +59,30 @@ func run(ctx context.Context, server tmux.Server) (err error) { if err != nil { return err } - if err := session.SetEnvironment(ctx, "LIBTMUX_EXAMPLE", "ready", tmux.SetEnvironmentOptions{}); err != nil { + if err := session.SetEnvironment( + ctx, + "LIBTMUX_EXAMPLE", + "ready", + tmux.SetEnvironmentOptions{}, + ); err != nil { return err } value, present, err := session.GetEnvironment(ctx, "LIBTMUX_EXAMPLE") if err != nil || !present { - return errors.Join(err, errors.New("session environment value is absent")) + return errors.Join( + err, + errors.New("session environment value is absent"), + ) } - result, err := server.Cmd(ctx, "display-message", "-p", "-t", pane.ID().String(), "#{socket_path}") + result, err := server.Cmd( + ctx, + "display-message", + "-p", + "-t", + pane.ID().String(), + "#{socket_path}", + ) if err != nil || result.ExitCode != 0 || len(result.Stdout) != 1 { return errors.Join(err, errors.New("resolve tmux socket path")) } diff --git a/examples/fast-path/example_test.go b/examples/fast-path/example_test.go index 568dfacd7..b6c230539 100644 --- a/examples/fast-path/example_test.go +++ b/examples/fast-path/example_test.go @@ -22,7 +22,9 @@ func TestFastPath(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) defer cancel() - options := tmux.ServerOptions{SocketPath: filepath.Join(t.TempDir(), "tmux.sock")} + options := tmux.ServerOptions{ + SocketPath: filepath.Join(t.TempDir(), "tmux.sock"), + } printed := exampletest.Output(t, func() error { return run(ctx, options) }) for _, want := range []string{ diff --git a/examples/fast-path/main.go b/examples/fast-path/main.go index 9160eb039..654901251 100644 --- a/examples/fast-path/main.go +++ b/examples/fast-path/main.go @@ -27,7 +27,10 @@ func start() error { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() - return run(ctx, tmux.ServerOptions{SocketName: "libtmux-go-example-fast-path"}) + return run( + ctx, + tmux.ServerOptions{SocketName: "libtmux-go-example-fast-path"}, + ) } // run accepts options so tests can isolate the server. @@ -37,7 +40,10 @@ func run(ctx context.Context, options tmux.ServerOptions) error { return fmt.Errorf("configure tmux server: %w", err) } defer func() { - killCtx, killCancel := context.WithTimeout(context.Background(), 5*time.Second) + killCtx, killCancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer killCancel() _ = server.Kill(killCtx) }() @@ -67,8 +73,9 @@ func run(ctx context.Context, options tmux.ServerOptions) error { } fmt.Printf("connection path: %d searches\n", searchesPerPath) - // Arbitrary pane output can end a control frame. Exact printed capture needs - // the original subprocess handle; file staging stays on the connection. + // Arbitrary pane output can end a control frame. Exact printed capture + // needs the original subprocess handle; file staging stays on the + // connection. processPane, err := session.ResolveActivePane(ctx) if err != nil { return fmt.Errorf("resolve process pane: %w", err) @@ -77,12 +84,12 @@ func run(ctx context.Context, options tmux.ServerOptions) error { if err != nil { return fmt.Errorf("resolve connected pane: %w", err) } - if _, err := connectedPane.Capture(ctx, tmux.CapturePaneRequest{}); !errors.Is( - err, - tmux.ErrConnectionRequiresProcess, - ) { + request := tmux.CapturePaneRequest{} + _, err = connectedPane.Capture(ctx, request) + if !errors.Is(err, tmux.ErrConnectionRequiresProcess) { if err == nil { - return errors.New("connected printed capture unexpectedly succeeded") + const message = "connected printed capture unexpectedly succeeded" + return errors.New(message) } return fmt.Errorf("refuse connected printed capture: %w", err) } @@ -92,12 +99,12 @@ func run(ctx context.Context, options tmux.ServerOptions) error { } defer func() { _ = os.RemoveAll(directory) }() - if _, err := processPane.Capture(ctx, tmux.CapturePaneRequest{}); err != nil { + if _, err := processPane.Capture(ctx, request); err != nil { return fmt.Errorf("capture: %w", err) } if _, err := connectedPane.CaptureToFile( - ctx, filepath.Join(directory, "pane.txt"), tmux.CapturePaneRequest{}, + ctx, filepath.Join(directory, "pane.txt"), request, ); err != nil { return fmt.Errorf("capture to file: %w", err) } diff --git a/examples/filter-query/main.go b/examples/filter-query/main.go index 0139239ae..575703f39 100644 --- a/examples/filter-query/main.go +++ b/examples/filter-query/main.go @@ -32,12 +32,18 @@ func start() error { // run accepts injected server state so tests can isolate the example. func run(ctx context.Context, server tmux.Server) (err error) { - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "libtmux-filter"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "libtmux-filter"}, + ) if err != nil { return err } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() diff --git a/examples/internal/exampletest/exampletest.go b/examples/internal/exampletest/exampletest.go index f1d0f49ed..6820c9b11 100644 --- a/examples/internal/exampletest/exampletest.go +++ b/examples/internal/exampletest/exampletest.go @@ -63,7 +63,11 @@ func Output(t *testing.T, work func() error) string { } if workErr != nil { - t.Fatalf("run() error = %v; printed so far:\n%s", workErr, printed.String()) + t.Fatalf( + "run() error = %v; printed so far:\n%s", + workErr, + printed.String(), + ) } return printed.String() } diff --git a/examples/option-hook-editing/example_test.go b/examples/option-hook-editing/example_test.go index 322d08a0f..30bd35ca3 100644 --- a/examples/option-hook-editing/example_test.go +++ b/examples/option-hook-editing/example_test.go @@ -23,7 +23,8 @@ func TestOptionHookEditing(t *testing.T) { return run(ctx, tmuxtest.NewServer(ctx, t)) }) - if want := "client-attached hook present: true"; !strings.Contains(printed, want) { + want := "client-attached hook present: true" + if !strings.Contains(printed, want) { t.Errorf("printed %q, want it to contain %q", printed, want) } } diff --git a/examples/option-hook-editing/main.go b/examples/option-hook-editing/main.go index bf8100e63..d7542697a 100644 --- a/examples/option-hook-editing/main.go +++ b/examples/option-hook-editing/main.go @@ -31,12 +31,18 @@ func start() error { // run accepts injected server state so tests can isolate the example. func run(ctx context.Context, server tmux.Server) (err error) { - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "libtmux-options"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "libtmux-options"}, + ) if err != nil { return err } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() @@ -45,8 +51,14 @@ func run(ctx context.Context, server tmux.Server) (err error) { return err } status, err := tmux.NewSparseArray( - tmux.SparseEntry[string]{Index: 0, Value: "#[align=left]#{session_name}"}, - tmux.SparseEntry[string]{Index: 2, Value: "#[align=right]#{window_name}"}, + tmux.SparseEntry[string]{ + Index: 0, + Value: "#[align=left]#{session_name}", + }, + tmux.SparseEntry[string]{ + Index: 2, + Value: "#[align=right]#{window_name}", + }, ) if err != nil { return err @@ -59,7 +71,11 @@ func run(ctx context.Context, server tmux.Server) (err error) { if err := global.SetStatus(ctx, tmux.StatusOn); err != nil { return err } - if err := global.SetHook(ctx, "client-attached", "display-message 'client attached'"); err != nil { + if err := global.SetHook( + ctx, + "client-attached", + "display-message 'client attached'", + ); err != nil { return err } hooks, err := global.Hooks(ctx) diff --git a/examples/pane-io/README.md b/examples/pane-io/README.md index 4ab9fb9a5..045a7e44d 100644 --- a/examples/pane-io/README.md +++ b/examples/pane-io/README.md @@ -31,7 +31,10 @@ if err != nil { } defer func() { err = errors.Join(err, output.Close()) }() -if _, err := fmt.Fprintln(pane.Writer(ctx), "printf 'ready\\n'"); err != nil { +if _, err := fmt.Fprintln( + pane.Writer(ctx), + "printf 'ready\\n'", +); err != nil { return fmt.Errorf("type command: %w", err) } scanner := bufio.NewScanner(output.Reader(ctx)) diff --git a/examples/pane-io/main.go b/examples/pane-io/main.go index 3e5a9db71..93abaf47e 100644 --- a/examples/pane-io/main.go +++ b/examples/pane-io/main.go @@ -42,7 +42,10 @@ func run(ctx context.Context, server tmux.Server) (err error) { return fmt.Errorf("create session: %w", err) } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() @@ -59,7 +62,10 @@ func run(ctx context.Context, server tmux.Server) (err error) { } defer func() { err = errors.Join(err, output.Close()) }() - if _, err := fmt.Fprintln(pane.Writer(ctx), "printf 'ready\\n'"); err != nil { + if _, err := fmt.Fprintln( + pane.Writer(ctx), + "printf 'ready\\n'", + ); err != nil { return fmt.Errorf("type command: %w", err) } scanner := bufio.NewScanner(output.Reader(ctx)) diff --git a/examples/planned-build/example_test.go b/examples/planned-build/example_test.go index 9b34f871e..1a287c998 100644 --- a/examples/planned-build/example_test.go +++ b/examples/planned-build/example_test.go @@ -23,11 +23,13 @@ func TestPlannedBuild(t *testing.T) { return run(ctx, tmuxtest.NewServer(ctx, t)) }) - if want := "rendered when the split has reported its pane"; !strings.Contains(printed, want) { - t.Errorf("printed %q, want it to contain %q", printed, want) - } - if want := "tmux invocation carrying steps"; !strings.Contains(printed, want) { - t.Errorf("printed %q, want it to contain %q", printed, want) + for _, want := range []string{ + "rendered when the split has reported its pane", + "tmux invocation carrying steps", + } { + if !strings.Contains(printed, want) { + t.Errorf("printed %q, want it to contain %q", printed, want) + } } if want := `stdout ["editor"]`; !strings.Contains(printed, want) { t.Errorf("printed %q, want it to contain %q", printed, want) diff --git a/examples/planned-build/main.go b/examples/planned-build/main.go index 0dcfecc42..43662fc01 100644 --- a/examples/planned-build/main.go +++ b/examples/planned-build/main.go @@ -33,17 +33,26 @@ func start() error { // run accepts injected server state so tests can isolate the example. func run(ctx context.Context, server tmux.Server) (err error) { - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "libtmux-planned"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "libtmux-planned"}, + ) if err != nil { return fmt.Errorf("create session: %w", err) } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() - window, err := session.NewWindow(ctx, tmux.NewWindowRequest{Name: new("planned")}) + window, err := session.NewWindow( + ctx, + tmux.NewWindowRequest{Name: new("planned")}, + ) if err != nil { return fmt.Errorf("create window: %w", err) } @@ -66,7 +75,10 @@ func run(ctx context.Context, server tmux.Server) (err error) { } for index, argv := range preview { if argv == nil { - fmt.Printf("step %d: rendered when the split has reported its pane\n", index) + fmt.Printf( + "step %d: rendered when the split has reported its pane\n", + index, + ) continue } fmt.Printf("step %d: tmux %s\n", index, strings.Join(argv, " ")) @@ -80,10 +92,17 @@ func run(ctx context.Context, server tmux.Server) (err error) { dispatch.Ops, dispatch.Reason) } if len(dispatches) >= plan.Len() { - return fmt.Errorf("%d operations took %d tmux invocations, want fewer than one each", - plan.Len(), len(dispatches)) + return fmt.Errorf( + "%d operations took %d tmux invocations, want fewer than one each", + plan.Len(), + len(dispatches), + ) } - fmt.Printf("operations: %d, tmux invocations: %d\n", plan.Len(), len(dispatches)) + fmt.Printf( + "operations: %d, tmux invocations: %d\n", + plan.Len(), + len(dispatches), + ) result, err := plan.Run(ctx, server) if err != nil { @@ -103,7 +122,10 @@ func run(ctx context.Context, server tmux.Server) (err error) { } read := result.Ops[len(result.Ops)-1] if got := read.Stdout; len(got) != 1 || got[0] != "editor" { - return fmt.Errorf("the read reported %q, want the title the plan set", got) + return fmt.Errorf( + "the read reported %q, want the title the plan set", + got, + ) } return nil } diff --git a/examples/quickstart/main.go b/examples/quickstart/main.go index b74939d9c..ae94db315 100644 --- a/examples/quickstart/main.go +++ b/examples/quickstart/main.go @@ -1,4 +1,5 @@ -// Command quickstart demonstrates a complete session, window, and pane lifecycle. +// Command quickstart demonstrates a complete session, window, and pane +// lifecycle. package main import ( @@ -40,12 +41,18 @@ func run(ctx context.Context, server tmux.Server) (err error) { return fmt.Errorf("create session: %w", err) } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() - window, err := session.NewWindow(ctx, tmux.NewWindowRequest{Name: new("work")}) + window, err := session.NewWindow( + ctx, + tmux.NewWindowRequest{Name: new("work")}, + ) if err != nil { return fmt.Errorf("create window: %w", err) } @@ -60,7 +67,10 @@ func run(ctx context.Context, server tmux.Server) (err error) { return fmt.Errorf("watch pane: %w", err) } defer func() { err = errors.Join(err, output.Close()) }() - if _, err := fmt.Fprintln(pane.Writer(ctx), "printf 'libtmux ready\\n'"); err != nil { + if _, err := fmt.Fprintln( + pane.Writer(ctx), + "printf 'libtmux ready\\n'", + ); err != nil { return fmt.Errorf("send command: %w", err) } // docs:end diff --git a/examples/run-to-completion/README.md b/examples/run-to-completion/README.md index b4614b9cd..1c98bc7e7 100644 --- a/examples/run-to-completion/README.md +++ b/examples/run-to-completion/README.md @@ -70,7 +70,11 @@ is still going, so its output can be followed and it can be stopped. // followed and it can be stopped from another goroutine. The stream begins // where StreamTo opens it, so this command waits before its first line; // result.Lines holds the screen either way. -running, err := session.Start(ctx, "sleep 1; seq 1 3; sleep 30", tmux.RunOptions{}) +running, err := session.Start( + ctx, + "sleep 1; seq 1 3; sleep 30", + tmux.RunOptions{}, +) if err != nil { return fmt.Errorf("start command: %w", err) } diff --git a/examples/run-to-completion/example_test.go b/examples/run-to-completion/example_test.go index 576ce2a24..ddfcbd818 100644 --- a/examples/run-to-completion/example_test.go +++ b/examples/run-to-completion/example_test.go @@ -26,7 +26,8 @@ func TestRunToCompletion(t *testing.T) { if want := "exited 3"; !strings.Contains(printed, want) { t.Errorf("printed %q, want it to contain %q", printed, want) } - // tty prints the pane's terminal, so the command saw a tty rather than a pipe. + // tty prints the pane's terminal, so the command saw a tty rather than a + // pipe. if want := "screen: /dev/"; !strings.Contains(printed, want) { t.Errorf("printed %q, want the command's terminal on screen", printed) } diff --git a/examples/run-to-completion/main.go b/examples/run-to-completion/main.go index 57e637f9c..007e298f9 100644 --- a/examples/run-to-completion/main.go +++ b/examples/run-to-completion/main.go @@ -33,12 +33,18 @@ func start() error { // run accepts injected server state so tests can isolate the example. func run(ctx context.Context, server tmux.Server) (err error) { - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "libtmux-run"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "libtmux-run"}, + ) if err != nil { return fmt.Errorf("create session: %w", err) } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() @@ -59,7 +65,11 @@ func run(ctx context.Context, server tmux.Server) (err error) { // followed and it can be stopped from another goroutine. The stream begins // where StreamTo opens it, so this command waits before its first line; // result.Lines holds the screen either way. - running, err := session.Start(ctx, "sleep 1; seq 1 3; sleep 30", tmux.RunOptions{}) + running, err := session.Start( + ctx, + "sleep 1; seq 1 3; sleep 30", + tmux.RunOptions{}, + ) if err != nil { return fmt.Errorf("start command: %w", err) } diff --git a/examples/snapshot-browser/example_test.go b/examples/snapshot-browser/example_test.go index ebb3d8575..c6198a46e 100644 --- a/examples/snapshot-browser/example_test.go +++ b/examples/snapshot-browser/example_test.go @@ -30,6 +30,10 @@ func TestSnapshotBrowser(t *testing.T) { } } if want := "libtmux-snapshot"; !strings.Contains(printed, want) { - t.Errorf("printed %q, want it to contain the session it made, %q", printed, want) + t.Errorf( + "printed %q, want it to contain the session it made, %q", + printed, + want, + ) } } diff --git a/examples/snapshot-browser/main.go b/examples/snapshot-browser/main.go index de3cb0285..283d67b85 100644 --- a/examples/snapshot-browser/main.go +++ b/examples/snapshot-browser/main.go @@ -38,7 +38,10 @@ func run(ctx context.Context, server tmux.Server) (err error) { return err } defer func() { - cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second) + cleanupCtx, cleanupCancel := context.WithTimeout( + context.WithoutCancel(ctx), + time.Second, + ) defer cleanupCancel() err = errors.Join(err, session.Kill(cleanupCtx)) }() @@ -50,7 +53,8 @@ func run(ctx context.Context, server tmux.Server) (err error) { for _, session := range snapshot.Sessions() { name, _ := session.Name() fmt.Printf("session %s %q\n", session.ID(), name) - // Snapshot records carry relations; point lookups report them unavailable. + // Snapshot records carry relations; point lookups report them + // unavailable. windows, _ := session.Windows() for _, window := range windows { fmt.Printf(" window %s:%d\n", window.ID(), window.Index()) diff --git a/internal/tools/check_example_width.py b/internal/tools/check_example_width.py new file mode 100644 index 000000000..b29949890 --- /dev/null +++ b/internal/tools/check_example_width.py @@ -0,0 +1,3066 @@ +r"""Fail when code a reader sees in rendered documentation is too wide. + +Shared by every libtmux port; change it in all of them together. It +enforces the example rules in WRITING.md. Configuration lives in +``.github/example-width.toml``:: + + width = 80 + tab_width = 4 + markdown = ["**/*.md"] + sources = ["examples/**/*.rs"] + doc_comments = ["src/**/*.rs"] + shared_digest = "" + checker_digest = "" + allow_ceiling = 1 + + [[exclude]] + glob = "docs/decisions/**" + reason = "dated decision records, not reader-facing examples" + + [[formatter_copies]] + copy = "examples/rustfmt.toml" + root = "rustfmt.toml" + key = "max_width" + + [[allow]] + path = "README.md" + line = "the exact line, as it appears in the file" + reason = "why breaking it would make the example worse" + +It checks code in ``markdown`` files (fences, indented blocks, including +one four columns past a list item's text, and ``
`` blocks; literal
+and ``code-block`` blocks in a ``.rst`` one), every line of ``sources``
+files, and the code inside doc comments of ``doc_comments`` files:
+fences, read as a Markdown page reads them, ``>>>`` doctests, and reST
+literal blocks in Python docstrings. Output is not checked: fences
+tagged ``text``, and the lines a session prints (a ``console``,
+``shell-session`` or ``pycon`` block, or a ``python`` fence that opens
+with ``>>> ``). A command runs on through an open quote, heredoc, loop,
+conditional or brace block and past a trailing ``\``, backtick, pipe,
+``&&`` or ``||``; a ``$ `` command must continue with ``\`` and a
+``PS> `` command with a backtick. An untagged Markdown fence is code,
+and a ``text`` fence that opens with a ``$ `` or ``PS> `` prompt is a
+console session. A line that is only a URL (after an optional comment, list or
+quote marker) and a hidden line (a rustdoc ``# `` line, a doctest marked
+``# doctest: +HIDE``) are skipped. Wide characters count as two columns;
+a tab advances to the next multiple of 4.
+
+``width`` must be 80, the shared rule, and ``tab_width``, if set, 4.
+Every key must be known, at the top level and inside each ``[[...]]``
+entry, so a key written below a table header cannot be swallowed by that
+entry; every entry must hold
+the keys the check reads, and every value must have the type it reads.
+Every glob must match a tracked file, and every exclusion a checked file
+or a file under ``examples``;
+every exclusion and allow entry must give a reason, and every allow
+entry must match a line. Every tracked file under a directory named
+``examples`` must be checked or excluded, so a new example file cannot
+go unread. ``allow_ceiling`` must equal the number of allow entries, so
+the list grows only through a reviewed change to that number and a fixed
+line must lower it. Each formatter copy must equal its root file once
+its ``key`` value is set aside, and the digests of this checker and of
+WRITING.md's shared section must equal ``checker_digest`` and
+``shared_digest``, both required, so a local edit to either fails until
+every port changes together. A WRITING.md without both shared markers is
+reported by name. AGENTS.md must hold a Markdown link that resolves to
+this WRITING.md and the heading the shared section sits under, so an
+agent is routed to the rules, and WRITING.md's
+``### In this repository`` block must hold the four labelled bullets in
+order, then one Bad and one Good example, with the Bad example still
+past 80 columns.
+
+Run ``--self-test`` to prove the checker can fail. ``--digest`` prints the
+SHA-256 of this file and of WRITING.md's shared example section (between
+```` and ````), so a job
+that reads every port can confirm they still agree.
+"""
+
+from __future__ import annotations
+
+import argparse
+import dataclasses
+import hashlib
+import json
+import os
+import pathlib
+import re
+import subprocess
+import sys
+import typing as t
+import unicodedata
+
+try:
+    import tomllib
+except ModuleNotFoundError:  # tomllib is in the standard library from 3.11.
+    sys.exit("check_example_width.py needs Python 3.11 or newer")
+
+CONFIG = pathlib.PurePosixPath(".github/example-width.toml")
+KEYS = frozenset(
+    {
+        "width",
+        "tab_width",
+        "markdown",
+        "sources",
+        "doc_comments",
+        "exclude",
+        "allow",
+        "allow_ceiling",
+        "formatter_copies",
+        "shared_digest",
+        "checker_digest",
+    }
+)
+# Keys each [[table]] entry holds.
+TABLE_KEYS = {
+    "exclude": frozenset({"glob", "reason"}),
+    "allow": frozenset({"path", "line", "reason"}),
+    "formatter_copies": frozenset({"copy", "root", "key"}),
+}
+GLOB_KEYS = ("markdown", "sources", "doc_comments")
+# The reason the printed allow entry carries until someone writes a real one.
+PLACEHOLDER = "why breaking this line would make the example worse"
+# The type each top-level value must have; a TOML string where a list belongs
+# would otherwise be read one character at a time.
+VALUE_TYPES: dict[str, tuple[type, str]] = {
+    "width": (int, "an integer"),
+    "tab_width": (int, "an integer"),
+    "allow_ceiling": (int, "an integer"),
+    "shared_digest": (str, "a string"),
+    "checker_digest": (str, "a string"),
+}
+CODE_DIRECTIVES = frozenset({"code-block", "code", "code-cell", "sourcecode"})
+# gp-libs hides a doctest line carrying this directive from the rendered page.
+HIDDEN = re.compile(r"^\s*(?:>>>|\.\.\.) .*# doctest: \+HIDE\b")
+OUTPUT_TAGS = frozenset({"text"})
+# Fences that mix prompted commands with the output they print.
+SESSION_TAGS = frozenset({"console", "shell-session", "pycon"})
+# Fences of shell script, with no prompts and no output.
+SCRIPT_TAGS = frozenset({"sh", "bash", "zsh", "shell", "powershell", "pwsh", "ps1"})
+# A Python fence that opens with a doctest prompt is a session too.
+PYTHON_TAGS = frozenset({"python", "py", "python3"})
+PROMPTS = ("$ ", "PS> ", ">>> ", "... ")
+# Shell words that open and close a block a command continues through.
+SHELL_OPEN = frozenset({"if", "for", "while", "until", "case", "select"})
+SHELL_CLOSE = frozenset({"fi", "done", "esac"})
+HEREDOC = re.compile(r"(?[A-Za-z_]\w*)\1")
+# A reST line that opens an indented code block: a paragraph ending in
+# ``::`` or a code directive. Other directives, such as toctree, hold no code.
+REST_BLOCK = re.compile(
+    r"^\s*(?!\.\. )\S.*::\s*$|^\s*\.\. (code-block|code|sourcecode)::"
+)
+FENCE = re.compile(r"^(?P\s*)(?P`{3,}|~{3,})\s*(?P[^`]*)$")
+RUSTDOC_TAGS = frozenset({"rust", "no_run", "ignore", "should_panic", "compile_fail"})
+SHARED = re.compile(
+    r"\n(?P.*?)", re.DOTALL
+)
+DOC_LINE = re.compile(r"^\s*(?:///|//!|\*(?!/)|#'|--- ?)\s?")
+# Files under examples/ with no text lines to measure.
+BINARY = (
+    ".png",
+    ".jpg",
+    ".jpeg",
+    ".gif",
+    ".ico",
+    ".webp",
+    ".pdf",
+    ".woff",
+    ".woff2",
+    ".ttf",
+    ".zip",
+    ".gz",
+    ".tar",
+    ".wasm",
+    ".so",
+    ".dll",
+    ".exe",
+    ".jar",
+    ".class",
+    ".bin",
+    ".dylib",
+    ".a",
+    ".o",
+    ".db",
+    ".sqlite",
+)
+# Comments a test compares or a copy step reads: Go's `// Output:` and
+# `// docs:` lines, java's `// →` results, and region markers.
+MARKER = re.compile(
+    r"(?:Output:|Unordered output:|docs:|→|#?(?:end)?region\b)", re.IGNORECASE
+)
+# Shell and PowerShell scripts, whose lines continue the way a console command does.
+SCRIPTS = (".sh", ".bash", ".zsh", ".ps1", ".psm1")
+# Go marks doc-comment code with a tab after a bare //.
+GO_DOC = re.compile(r"^\s*//\t")
+DOCTEST = re.compile(r"(?:>>>|\.\.\.) ")
+BLOCK_OPEN = re.compile(r"
\s*\{@code|\s*$")
+BLOCK_CLOSE = re.compile(r"\}\s*
|^\s*") +URL = re.compile(r"^(?:(?:#+|//+!?|-+|\*|>|\n\n [x](y)\n- [z](w)\n") + 'a b \n\n- [z](w)\n' + >>> prose("```text\n[x](y)\n```\n") + '' + """ + text = unfenced(text) + code = {number for number, _ in markdown_lines(text)} + lines = text.splitlines(keepends=True) + text = "".join(line for n, line in enumerate(lines, 1) if n not in code) + text = re.sub(r"", "", text, flags=re.DOTALL) + span = r"(? list[str]: + r"""Return the targets of a Markdown text's inline and reference links. + + >>> links('[A](a.md#x "A"), [B]() and [C](c.md \'C\')\n[d]: d.md') + ['a.md#x', 'b.md', 'c.md', 'd.md'] + >>> links("![E](e.md) \\[F](f.md) [G\nH](g.md)") + ['g.md'] + """ + return [inline or reference for inline, reference in LINK.findall(text)] + + +def routing_problems(root: pathlib.Path) -> list[str]: + """Return a problem unless AGENTS.md links the shared section's heading. + + The heading is the last one of level one or two above the shared + markers: the section an agent routed from AGENTS.md should land in. + """ + writing = writing_path(root) + if writing is None: + return [] + text = writing.read_text(encoding="utf-8") + above = unfenced(text[: text.index("")]) + headings = [m[2] for m in HEADING.finditer(above) if len(m[1]) <= 2] + if not headings: + where = writing.relative_to(root).as_posix() + return [f"{where}: no heading above the shared section"] + anchor = slug(headings[-1]) + agents = root / "AGENTS.md" + where = f"{writing.relative_to(root).as_posix()}#{anchor}" + link = f"[{headings[-1]}]({where})" + if not agents.is_file(): + return [f"AGENTS.md is missing; add it with a link such as {link}"] + route = prose(agents.read_text(encoding="utf-8")) + for target in links(route): + path, _, fragment = target.partition("#") + # GitHub reads a leading slash as the repository root. + here = root / path.removeprefix("/") + if fragment == anchor and here.resolve() == writing.resolve(): + return [] + return [ + f"AGENTS.md: no link to {where}, the section with the example rules; " + + f"add one such as {link}" + ] + + +def port_block_problems(text: str) -> list[str]: + r"""Return how a WRITING.md's ``### In this repository`` block strays. + + >>> labels = "\n".join(label + " x" for label in PORT_LABELS) + >>> bad = "```text\n" + "x" * 81 + "\n```" + >>> head = f"### In this repository\n\n{labels}\n\n" + >>> block = head + f"Bad, over 80:\n\n{bad}\n\nGood, named:\n" + >>> port_block_problems(block) + [] + >>> [p.split(";")[0] for p in port_block_problems(block.replace("x" * 81, "x"))] + ['In this repository: the Bad example fits in 80 columns'] + >>> port_block_problems(block.replace("- **Not formatted:**", "- **Other:**")) + ['In this repository: no "- **Not formatted:**" bullet in its place'] + >>> port_block_problems("## Examples\n") + ['no "### In this repository" block'] + >>> port_block_problems(block + "\n" + block) + ['2 "### In this repository" blocks; keep one'] + """ + blocks = PORT_BLOCK.findall(unfenced(text)) + if len(blocks) > 1: + return [f'{len(blocks)} "### In this repository" blocks; keep one'] + match = PORT_BLOCK.search(unfenced(text)) + if match is None: + return ['no "### In this repository" block'] + lines = match["body"].splitlines() + problems = [] + at = 0 + for label in PORT_LABELS: + found = next((i for i, line in enumerate(lines) if line.startswith(label)), -1) + if found < at: + problems.append(f'In this repository: no "{label}" bullet in its place') + else: + at = found + for example in ("Bad, over 80", "Good"): + count = sum(line.startswith(example) for line in lines[at:]) + if count != 1: + problems.append(f'In this repository: {count} "{example}" examples, want 1') + # The fence after "Bad, over 80" is stripped above, so read it raw: a + # Bad example that a later edit brought within 80 no longer shows a fault. + raw = text[text.find("### In this repository") :].splitlines() + start = next( + (i for i, line in enumerate(raw) if line.startswith("Bad, over 80")), None + ) + if start is not None: + opens = [i for i in range(start + 1, len(raw)) if FENCE.match(raw[i])] + code = raw[opens[0] + 1 : opens[1]] if len(opens) > 1 else [] + if not any(columns(line.expandtabs(4)) > 80 for line in code): + problems.append( + "In this repository: the Bad example fits in 80 columns; " + "show a line that does not" + ) + return problems + + +# A comment after code, set off by two spaces as most style guides ask. +TRAILING = re.compile(r"\S\s{2,}(?://|#|--)\s+(?P.*)$") +# How a comment line starts in the languages the examples use. +COMMENTS = ("# ", "// ", "-- ", "/// ", "//! ", "/* ", "* ", "") + >>> fix_advice(html, "W.md")[:22] + 'Wrap the comment at 80' + >>> doc = Finding("a.rs", 2, 90, 80, "/// // a comment line in doc code", "doc") + >>> fix_advice(doc, "W.md")[:22] + 'Wrap the comment at 80' + >>> go = Finding("a.go", 2, 90, 80, "//\t// Wait for the marker line", "doc") + >>> pydoc = Finding("a.py", 2, 90, 80, " >>> # Wait for the marker", "doc") + >>> [fix_advice(f, "W.md")[:22] for f in (go, pydoc)] + ['Wrap the comment at 80', 'Wrap the comment at 80'] + >>> said = Finding("a.md", 2, 90, 80, ">>> # Wait for the marker", "session") + >>> data = Finding("a.md", 2, 90, 80, "# a heredoc line, not a comment", "session") + >>> fix_advice(said, "W.md")[:22] + 'Wrap the comment at 80' + >>> fix_advice(data, "W.md").split(":")[0] + 'Fix a wide line by changing the code, not the line breaks' + >>> doc = Finding("a.rs", 2, 90, 80, "/// let total = first + second;", "doc") + >>> fix_advice(doc, "W.md").split(":")[0], "copied" in fix_advice(doc, "W.md") + ('Fix a wide line by changing the code, not the line breaks', True) + >>> note = Finding("README.md", 3, 84, 80, "// wait until the pane prints it") + >>> "copied" in fix_advice(note, "W.md") + True + >>> line = "/// $ tmux new-session -d -s demo \\" + >>> doced = Finding("a.rs", 4, 90, 80, line, "doc:command") + >>> fix_advice(doced, "W.md").split(":")[0] + 'Split a wide command the way its shell continues' + >>> noted = Finding("a.rs", 5, 90, 80, "/// # Create a session first", "doc:note") + >>> fix_advice(noted, "W.md")[:24] + 'Move the comment out of ' + >>> bare_note = Finding("a.rs", 2, 90, 80, "/// # Create it", "doc:promptless") + >>> fix_advice(bare_note, "W.md")[:24] + 'Move the comment out of ' + >>> labelled = Finding("A.md", 3, 90, 80, "session.name(); // → demo", "") + >>> fix_advice(labelled, "W.md").split(": ")[0] + 'Keep the code and its marker on one line (W.md#what-never-breaks)' + >>> "shorten the code before the marker (W.md#reaching-80)" in fix_advice( + ... labelled, "W.md" + ... ) + True + >>> remark_copy = fix_advice(remark, "W.md").split(". ")[-1] + >>> remark_copy + 'If a Markdown block copies this file, re-copy it as W.md#in-this-repository says.' + >>> command = Finding("a.md", 1, 90, 80, " PS> Get-Item -Path x") + >>> fix_advice(command, "W.md") + 'Split a wide command the way its shell continues: W.md#reaching-80.' + """ + kind, text = finding.kind, finding.text.lstrip() + # A line in a doc-comment fence carries its Markdown kind after "doc:"; + # read it past its comment marker, as the Markdown line would be read. + if kind.startswith("doc:"): + marker = GO_DOC if GO_DOC.match(finding.text) else DOC_LINE + kind, text = kind[4:], marker.sub("", finding.text, count=1).lstrip() + reach = f"{rules}#reaching-80" + advice = f"Fix a wide line by changing the code, not the line breaks: {reach}." + # Code blocks keeps explanations out of a console block, in the prose. + prose = ( + f"Move the comment out of the block into the prose around it: " + f"{rules}#code-blocks." + ) + if kind == "note": + return prose + if kind == "promptless": + if text.startswith("# "): + return prose + return ( + "If it is a command, add the prompt its shell takes, `$ ` or `PS> `, " + f"and continue it the way that shell does ({reach}); if it is " + "output, tag the fence `text`." + ) + if kind == "command" or text.startswith(("$ ", "PS> ")): + dialect = "PS> " if text.startswith("PS> ") else "$ " + if scan(text, Shell(dialect))[3] < len(text): + return prose + if len(text.rstrip(" \\`").split()) < 2: + # One token has nowhere to split. + return advice + return f"Split a wide command the way its shell continues: {reach}." + if kind == "doc": + marker = GO_DOC if GO_DOC.match(finding.text) else DOC_LINE + text = marker.sub("", finding.text, count=1).lstrip() + # A doctest comment sits behind its prompt. A session line without one is + # heredoc or other data, where # starts no comment. + doctest = DOCTEST.match(text) if kind in ("doc", "session") else None + text = text[doctest.end() :] if doctest else text + commented = kind in ("", "source", "doc", "script") or bool(doctest) + # Markdown blocks and doc-comment fences can be copies of a source file, + # and a source file can be the original a block copies. + copied = ( + " In a block copied from a source file, fix the source, then follow the " + f"copy step that {rules}#in-this-repository gives." + if kind in ("", "doc", "script") + else " If a Markdown block copies this file, re-copy it as " + f"{rules}#in-this-repository says." + if kind == "source" + else "" + ) + if commented and text.startswith(COMMENTS): + if MARKER.match(text.split(None, 1)[1] if " " in text else ""): + return kept_whole(rules) + ": add this one to [[allow]] with its reason." + # Width says comments wrap at 80; What never breaks keeps compared + # output and marker lines whole. + return ( + f"Wrap the comment at 80 ({rules}#width); compared output and marker " + f"lines stay whole ({rules}#what-never-breaks).{copied}" + ) + # A marker after the code it labels, such as `name(); // → demo`, keeps + # its line whole too. + trailing = TRAILING.search(text) if commented else None + if trailing and MARKER.match(trailing["body"]): + return ( + f"Keep the code and its marker on one line ({rules}#what-never-breaks): " + f"shorten the code before the marker ({reach}); add it to [[allow]] only " + "if it still runs past 80." + ) + # A script line is a shell command, which breaks at its continuation. + script = kind == "script" or (kind == "source" and finding.path.endswith(SCRIPTS)) + if script and len(text.rstrip(" \\`").split()) > 1: + paste = ( + " A command a reader pastes goes in a `console` fence with its prompt " + f"({rules}#code-blocks)." + if kind == "script" + else "" + ) + return ( + f"{advice} If it is one command, it may instead continue the way its " + f"shell does.{paste}{copied}" + ) + if kind == "source": + return ( + f"If the port block names a formatter for this file, run it. {advice}" + + copied + ) + return advice + copied + + +# A line edited in place keeps most of its text; a stale entry and a wide line +# that share less are a deleted allowed line and a new wide one. +SIMILAR = 0.6 + + +def resemblance(finding: Finding, entry: dict[str, t.Any]) -> float: + """Return how alike a wide line and a stale entry's line are, 0 to 1. + + >>> line = Finding("a.md", 1, 90, 80, "print(totals, values)") + >>> round(resemblance(line, {"line": "print(total, values)"}), 2) + 0.98 + """ + return alike(finding.text, entry["line"]) + + +def alike(one: str, other: str) -> float: + """Return how alike two lines are, 0 to 1. + + >>> alike("abcd", "abce") + 0.75 + """ + import difflib + + return difflib.SequenceMatcher(None, one, other).ratio() + + +def edit_pairs( + findings: list[Finding], + stale: list[dict[str, t.Any]], + bad_path: str | None, + shortened: list[dict[str, t.Any]] | None = None, +) -> list[tuple[Finding, dict[str, t.Any]]]: + """Pair stale entries with the wide lines that kept most of their text. + + Each stale entry and each wide line joins at most one pair, closest + first, so two allowed lines edited in one file make two pairs; the rest + of the wide lines are new. + + >>> stale = [{"path": "a.md", "line": "alpha(" + "x" * 80 + ")"}] + >>> stale.append({"path": "a.md", "line": "beta(" + "y" * 80 + ")"}) + >>> one = Finding("a.md", 3, 90, 80, "alpha(" + "x" * 82 + ")") + >>> two = Finding("a.md", 7, 90, 80, "beta(" + "y" * 83 + ")") + >>> new = Finding("a.md", 9, 90, 80, "z" * 90) + >>> pairs = edit_pairs([two, new, one], stale, None) + >>> [(f.number, e["line"][:4]) for f, e in pairs] + [(7, 'beta'), (3, 'alph')] + >>> edit_pairs([one], stale, "a.md") + [] + >>> edit_pairs([one], stale, None, shortened=stale) + [] + """ + scored = sorted( + ( + (resemblance(f, e), i, j) + for i, f in enumerate(findings) + for j, e in enumerate(stale) + if f.path == e["path"] and f.path != bad_path and e not in (shortened or []) + ), + reverse=True, + ) + pairs, taken_lines, taken_entries = [], set(), set() + for score, i, j in scored: + if score < SIMILAR: + break + if i in taken_lines or j in taken_entries: + continue + taken_lines.add(i) + taken_entries.add(j) + pairs.append((i, findings[i], stale[j])) + return [(finding, entry) for _, finding, entry in sorted(pairs, key=lambda p: p[0])] + + +def edited_finding( + findings: list[Finding], stale: list[dict[str, t.Any]], bad_path: str | None +) -> Finding | None: + """Return the first wide line that is an edited allowed line, if any. + + >>> stale = [{"path": "a.md", "line": "print(total, " + "x" * 80 + ")"}] + >>> new = Finding("a.md", 2, 90, 80, "y" * 90) + >>> edit = Finding("a.md", 9, 95, 80, "print(totals, " + "x" * 80 + ")") + >>> edited_finding([new, edit], stale, None).number + 9 + >>> edited_finding([new, edit], stale, "a.md") is None + True + >>> far = Finding("a.md", 3, 92, 80, "print(total, " + "y" * 20 + "x" * 60 + ")") + >>> edited_finding([far, edit], stale, None).number + 9 + """ + pairs = edit_pairs(findings, stale, bad_path) + return pairs[0][0] if pairs else None + + +def shortened_entries( + root: pathlib.Path, + stale: list[dict[str, t.Any]], + width: int, + tab_width: int, +) -> list[dict[str, t.Any]]: + """Return stale entries whose line was shortened to fit since the last commit. + + Such an entry's file holds a line that fits, resembles the entry and is + not in the committed file. A wide line that also resembles the entry is + then new, not the allowed line edited, so it gets an entry of its own. + """ + found = [] + for entry in stale: + path = str(entry["path"]) + shown = subprocess.run( + ["git", "-C", str(root), "show", f"HEAD:{path}"], + capture_output=True, + text=True, + check=False, + ) + if shown.returncode != 0: + continue + before = {line.rstrip() for line in shown.stdout.splitlines()} + if any( + line not in before + and columns(line.expandtabs(tab_width)) <= width + and alike(line, str(entry["line"])) >= SIMILAR + for line in source_lines(root, entry) + ): + found.append(entry) + return found + + +def source_lines(root: pathlib.Path, entry: dict[str, t.Any]) -> set[str]: + """Return the stripped lines of an allow entry's file, or none if unreadable.""" + try: + text = (root / str(entry["path"])).read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + return set() + return {line.rstrip() for line in text.splitlines()} + + +def entry_name(entry: dict[str, t.Any], entries: list[dict[str, t.Any]]) -> str: + r"""Name an allow entry by its path, and by its line when the path has two. + + >>> one = {"path": "a.md", "line": "first line"} + >>> entry_name(one, [one]), entry_name(one, [one, {"path": "a.md", "line": "x"}]) + ('a.md', "a.md whose line begins 'first line'") + >>> indented = {"path": "a.md", "line": " first line"} + >>> entry_name(indented, [indented, one]) + "a.md whose line begins 'first line'" + >>> long = {"path": "a.md", "line": "print(total, first + second + third + fourth)"} + >>> entry_name(long, [long, one]) + "a.md whose line begins 'print(total, first +'" + >>> path = {"path": "a.ps1", "line": r"C:\Users\me\AppData\Local\Temp\run.ps1"} + >>> entry_name(path, [path, {"path": "a.ps1", "line": "x"}]) + "a.ps1 whose line begins 'C:\\Users\\me\\AppData\\Local\\Temp'" + """ + if sum(e.get("path") == entry["path"] for e in entries) < 2: + return str(entry["path"]) + text = entry["line"].strip() + if len(text) > 32: + # Cut at a space, or else before a backslash, so the quoted start + # never ends inside an escape. + space, slash = text.find(" ", 20), text.rfind("\\", 20, 33) + if 0 < space <= 40: + text = text[:space] + else: + text = text[:slash].rstrip("\\") if slash > 0 else text[:32] + return f"{entry['path']} whose line begins {quoted(text)}" + + +def quoted(text: str) -> str: + r"""Return a line in single quotes, as a TOML literal string writes it. + + A line that holds a single quote falls back to an escaped basic string. + + >>> print(quoted(r'"C:\Windows"'), quoted("it's")) + '"C:\Windows"' "it's" + """ + return f"'{text}'" if "'" not in text else literal(text) + + +def ceiling_hints( + findings: list[Finding], + stale: list[dict[str, t.Any]], + count: int, + bad_path: str | None = None, + hidden: list[dict[str, t.Any]] | None = None, + entries: list[dict[str, t.Any]] | None = None, + shortened: list[dict[str, t.Any]] | None = None, +) -> list[str]: + r"""Return what to change in the allow list after a failed run. + + A stale entry in a file that also has a wide line is an edited allowed + line, so its entry takes the new text. A stale entry for ``bad_path``, + the WRITING.md whose Bad example now fits, asks for a wide Bad line + again. Every other stale entry goes, and the last line gives the + ceiling all of that leaves. + + >>> wide = Finding("a.md", 3, 90, 80, "x" * 90) + >>> ceiling_hints([wide], [], 1) + ['Set allow_ceiling to 1 plus one for each line you add to [[allow]].'] + >>> edited = {"path": "a.md", "line": "x" * 88} + >>> for hint in ceiling_hints([wide], [edited], 1): + ... print(hint) + a.md: an allowed line changed; put its new text in the stale entry. + allow_ceiling stays 1. + >>> gone = {"path": "b.md", "line": "old"} + >>> for hint in ceiling_hints([wide], [edited, gone], 2): + ... print(hint) + a.md: an allowed line changed; put its new text in the stale entry. + Delete the stale allow entry for b.md. + Lower allow_ceiling to 1. + >>> kept = {"path": "b.md", "line": "kept"} + >>> ceiling_hints([], [gone], 2, entries=[gone, kept])[0] + "Delete the stale allow entry for b.md whose line begins 'old'." + >>> second = Finding("a.md", 5, 88, 80, "z" * 88) + >>> ceiling_hints([wide, second], [edited], 1)[-1] + 'Set allow_ceiling to 1 plus one for each line you add to [[allow]].' + >>> other = Finding("c.md", 7, 85, 80, "y" * 85) + >>> for hint in ceiling_hints([wide, other], [edited], 1): + ... print(hint) + a.md: an allowed line changed; put its new text in the stale entry. + Set allow_ceiling to 1 plus one for each line you add to [[allow]]. + >>> both = [edited, {"path": "a.md", "line": "y" * 88}] + >>> lines = [wide, Finding("a.md", 5, 90, 80, "y" * 90)] + >>> for hint in ceiling_hints(lines, both, 2): + ... print(hint) + a.md: an allowed line changed; put its new text in the stale entry. + a.md: an allowed line changed; put its new text in the stale entry. + allow_ceiling stays 2. + >>> kept = {"path": "a.md", "line": "x" * 90} + >>> for hint in ceiling_hints([], [kept], 1, hidden=[kept]): + ... print(hint.split(";")[0]) + a.md: the allowed line is still there but the check no longer reads it as wide + allow_ceiling stays 1. + >>> unrelated = {"path": "a.md", "line": "old"} + >>> for hint in ceiling_hints([wide], [unrelated], 1): + ... print(hint) + Delete the stale allow entry for a.md. + Set allow_ceiling to 0 plus one for each line you add to [[allow]]. + >>> bad = {"path": "WRITING.md", "line": "x" * 90} + >>> for hint in ceiling_hints([], [bad], 1, "WRITING.md"): + ... print(hint) + WRITING.md: restore a Bad example past 80; its [[allow]] entry quotes it. + allow_ceiling stays 1. + >>> other = Finding("WRITING.md", 9, 85, 80, "x" * 85) + >>> for hint in ceiling_hints([other], [bad], 1, "WRITING.md"): + ... print(hint) + WRITING.md: restore a Bad example past 80; its [[allow]] entry quotes it. + Set allow_ceiling to 1 plus one for each line you add to [[allow]]. + """ + pairs = edit_pairs(findings, stale, bad_path, shortened) + edited = [entry for _, entry in pairs] + hints = [ + f"{entry['path']}: an allowed line changed; put its new text in the " + "stale entry." + for entry in edited + ] + restored = [entry for entry in stale if entry["path"] == bad_path] + hints += [ + f"{bad_path}: restore a Bad example past 80; its [[allow]] entry quotes it." + ] * bool(restored) + # An allowed line still in its file was hidden by a config change, not + # fixed: deleting its entry would only weaken the gate. + hidden = [entry for entry in hidden or [] if entry in stale] + hints += [ + f"{entry_name(e, entries or stale)}: the allowed line is still there but " + "the check no longer reads it as wide; undo the change that hid it: a " + "glob, [[exclude]] or tab_width edit, or a fence tag or comment marker " + "around the line." + for e in hidden + ] + gone = [e for e in stale if e not in edited + restored + hidden] + hints += [ + f"Delete the stale allow entry for {entry_name(e, entries or stale)}." + for e in gone + ] + target = count - len(gone) + # Every wide line not paired with a stale entry is new. + if len(findings) > len(pairs): + hints.append( + f"Set allow_ceiling to {target} plus one for each line you add " + "to [[allow]]." + ) + elif target == count: + hints.append(f"allow_ceiling stays {count}.") + else: + hints.append(f"Lower allow_ceiling to {target}.") + return hints + + +def digests(root: pathlib.Path) -> list[str]: + """Return ``checker `` and ``shared `` lines. + + The shared digest covers the text between the markers in WRITING.md; + ``shared missing`` means no WRITING.md carries them. + """ + checker = hashlib.sha256(pathlib.Path(__file__).read_bytes()).hexdigest() + shared = "missing" + writing = writing_path(root) + if writing is not None: + match = SHARED.search(writing.read_text(encoding="utf-8")) + if match: + shared = hashlib.sha256(match["body"].encode()).hexdigest() + return [f"checker {checker}", f"shared {shared}"] + + +def digest_problems(root: pathlib.Path, config: dict[str, t.Any]) -> list[str]: + """Return digests that differ from the ones the configuration records. + + Each message names the file that changed. Both files are the same in + every port, so an intended change goes to all of them; an edit meant for + one repository is undone instead. + """ + actual = dict(line.split(" ", 1) for line in digests(root)) + here, top = pathlib.Path(__file__).resolve(), root.resolve() + script = here.relative_to(top) if here.is_relative_to(top) else here.name + writing = writing_file(root) + shared = writing.relative_to(root).as_posix() if writing else "WRITING.md" + where = {"checker": script, "shared": shared} + names = {"checker": "this checker", "shared": "the shared section"} + undo = { + "checker": f"it (`git checkout -- {script}`, or a copy from another port)", + "shared": ( + "the text between the shared markers, copied from " + f"`git show HEAD:{shared}` so port-block edits stay, or from another " + "port once the edit is committed" + ), + } + # A digest written below a [[...]] header or misspelled is reported as + # an unknown key already. + nested = { + key + for table in TABLE_KEYS + for entry in config.get(table, []) + if isinstance(entry, dict) + for key in entry + } | {meant(key) for key in set(config) - KEYS} + missing = [ + f"{CONFIG}: {name}_digest is missing; run `python3 {script} --digest` " + f"and set {name}_digest to the {name} value it prints" + for name in ("checker", "shared") + if name + "_digest" not in config and name + "_digest" not in nested + ] + return missing + [ + f"{where[name]}: {names[name]} has digest {actual[name][:12]}, but " + f"{name}_digest in {CONFIG} records {config[name + '_digest'][:12]}.\n" + f" To undo an edit meant for this repository only, restore {undo[name]}.\n" + " To change it everywhere, change libtmux/docs and each repository " + f"listed in {PORTS}, which also names where each keeps this checker; " + "run each copy with `--digest` and set checker_digest and " + "shared_digest to the values it prints." + for name in ("checker", "shared") + if name + "_digest" in config + and actual[name] not in (config[name + "_digest"], "missing") + ] + + +def self_test() -> int: + """Run the doctests above, plus planted failures and clean controls.""" + import contextlib + import doctest + import io + import tempfile + + failures, _ = doctest.testmod(sys.modules[__name__]) + + def expect(condition: bool, message: str) -> None: + nonlocal failures + if not condition: + print(f"self-test: {message}", file=sys.stderr) + failures += 1 + + with tempfile.TemporaryDirectory() as scratch: + root = pathlib.Path(scratch) + wide = "let total = " + " + ".join(["value"] * 12) + ";" + (root / "README.md").write_text(f"```rust\n{wide}\n```\n") + config: dict[str, t.Any] = {"width": 60, "markdown": ["README.md"]} + planted, _ = check(root, config, ["README.md"]) + expect(len(planted) == 1, "a planted wide line was not reported") + if planted: + pasted = tomllib.loads(allow_hint(planted[0]))["allow"][0] + expect(pasted["line"] == wide, "the allow hint does not round-trip") + excluded = dict(config, exclude=[{"glob": "README.md", "reason": "r"}]) + expect(not check(root, excluded, ["README.md"])[0], "an exclusion was read") + config["allow"] = [{"path": "README.md", "line": wide, "reason": "test"}] + clean, stale = check(root, config, ["README.md"]) + expect(not clean and not stale, "an allowed line was reported") + url = "https://example.com/" + "x" * 80 + hidden = ">>> setup = " + "x" * 70 + " # doctest: +HIDE" + (root / "skip.md").write_text(f"```\n{url}\n```\n```python\n{hidden}\n```\n") + skipped, _ = check(root, {"width": 80, "markdown": ["skip.md"]}, ["skip.md"]) + expect(not skipped, "a URL line or a hidden doctest line was reported") + body = "x" * 90 + (root / "here.md").write_text( + f"```console\n$ cat < one failed", + ) + (root / "page.rst").write_text(".. code-block:: sh\n\n " + "x" * 81 + "\n") + rst, _ = check(root, {"width": 80, "markdown": ["page.rst"]}, ["page.rst"]) + expect(len(rst) == 1, "a wide line in a reST code block passed") + config["allow"].append({"path": "README.md", "line": "gone", "reason": "x"}) + _, stale = check(root, config, ["README.md"]) + expect(len(stale) == 1, "a stale allow entry was not reported") + tabbed = "\t" + wide + (root / "main.go").write_text(tabbed + "\n") + config = {"width": 60, "sources": ["*.go"]} + config["allow"] = [{"path": "main.go", "line": tabbed, "reason": "test"}] + clean, stale = check(root, config, ["main.go"]) + expect(not clean and not stale, "a raw tabbed allow entry did not match") + (root / "tab.go").write_text("\t" + "x" * 78 + "\n") + tabbed_config = {"width": 80, "tab_width": 4, "sources": ["tab.go"]} + expanded, _ = check(root, tabbed_config, ["tab.go"]) + expect(len(expanded) == 1, "a tab counted as one column") + (root / "tab.go").write_text("\t" + "x" * 76 + "\n") + expanded, _ = check(root, tabbed_config, ["tab.go"]) + expect(not expanded, "a tabbed line within 80 was reported") + (root / "fmt.toml").write_text("edition = 1\nmax_width = 100\n") + (root / "copy.toml").write_text("edition = 1\nmax_width = 80\n") + pair = {"copy": "copy.toml", "root": "fmt.toml", "key": "max_width"} + copies = {"formatter_copies": [pair]} + expect(not copy_problems(root, copies), "a width-only copy was reported") + wider_copies = ( + "max_width = 120", + "max_width = 100 # was 80", + "# max_width = 80", + "# keep max_width = 80\nmax_width = 100", + "max_width = 80\nmax_width = 120", + "max_width = 80, max_width = 120", + ) + for wider in wider_copies: + (root / "copy.toml").write_text(f"edition = 1\n{wider}\n") + expect(bool(copy_problems(root, copies)), f"a copy with {wider!r} passed") + (root / "copy.toml").write_text( + "edition = 1\nmax_width = 80, max_width = 120\n" + ) + doubled = copy_problems(root, copies) + expect(bool(doubled) and "2 times" in doubled[0], "a doubled width passed") + (root / "copy.toml").write_text("edition = 1\nmax_width = 80 # was 120\n") + expect(not copy_problems(root, copies), "a commented width was read twice") + (root / "copy.toml").write_text( + "edition = 1\nmax_width = 80 # the root sets max_width = 100\n" + ) + expect( + not copy_problems(root, copies), "a width named in a comment was counted" + ) + (root / "copy.toml").write_text("edition = 1\nmax_width = 80\n") + (root / "copy.toml").write_text("edition = 2\nmax_width = 80\n") + expect(bool(copy_problems(root, copies)), "a drifted copy was not reported") + (root / "fmt.json").write_text('{\n "lineLength": 100, "indent": 2\n}\n') + (root / "copy.json").write_text('{\n "lineLength": 80, "indent": 9\n}\n') + same_line = {"copy": "copy.json", "root": "fmt.json", "key": "lineLength"} + expect( + bool(copy_problems(root, {"formatter_copies": [same_line]})), + "a setting changed on the width line passed", + ) + (root / "copy.json").write_text('{\n "lineLength": 80, "indent": 2\n}\n') + expect( + not copy_problems(root, {"formatter_copies": [same_line]}), + "a copy differing only in its width value was reported", + ) + expect(digests(root)[1] == "shared missing", "a missing section was digested") + shared = "\nrule\n\n" + (root / "WRITING.md").write_text(shared) + expect(digests(root)[1] != "shared missing", "a shared section was missed") + headless = routing_problems(root) + expect( + bool(headless) and "no heading" in headless[0], + "a shared section with no heading above passed", + ) + checker_now = digests(root)[0].split(" ", 1)[1] + recorded: dict[str, t.Any] = { + "checker_digest": checker_now, + "shared_digest": "0" * 64, + } + changed = digest_problems(root, recorded) + expect( + bool(changed) and "or from another port" in changed[0], + "a shared-section change was missed or offered only HEAD to restore", + ) + shared_now = digests(root)[1].split(" ", 1)[1] + recorded = {"checker_digest": checker_now, "shared_digest": shared_now} + expect(not digest_problems(root, recorded), "a matching digest was reported") + below = {"path": "a", "line": "b", "reason": "r"} + below["checker_digest"] = recorded.pop("checker_digest") + recorded["allow"] = [below] + expect( + not digest_problems(root, recorded), + "a digest below [[allow]] was also reported missing", + ) + del recorded["allow"] + recorded["checker_digset"] = below["checker_digest"] + expect( + not digest_problems(root, recorded), + "a misspelled digest key was also reported missing", + ) + del recorded["checker_digset"] + expect(bool(digest_problems(root, recorded)), "a missing digest passed") + (root / "WRITING.md").write_text("## Examples\n\n" + shared) + alone = root / "alone" / ".github" + alone.mkdir(parents=True) + section = "## Examples\n\n\n" + (alone / "WRITING.md").write_text(section) + broken = marker_problems(alone.parent) + expect( + bool(broken) and ".github/WRITING.md" in broken[0], + "a missing closing marker passed or named the wrong file", + ) + (alone / "WRITING.md").write_text(section + "x\n\n") + expect(not marker_problems(alone.parent), "balanced markers were reported") + body = " echo " + "x" * 80 + loop = f"```console\n$ for x in a; do\n{body}\ndone\n{'y' * 81}\n```\n" + (root / "loop.md").write_text(loop) + looped, _ = check(root, {"width": 80, "markdown": ["loop.md"]}, ["loop.md"]) + expect( + [finding.number for finding in looped] == [3], + "a wide loop body passed, or printed output was measured", + ) + expect(bool(routing_problems(root)), "a missing AGENTS.md link passed") + (root / "AGENTS.md").write_text("Code examples: WRITING.md#examples\n") + expect(bool(routing_problems(root)), "a bare anchor counted as a link") + (root / "AGENTS.md").write_text("[Examples](docs/WRITING.md#examples)\n") + expect(bool(routing_problems(root)), "a link to a missing file passed") + (root / "AGENTS.md").write_text("[Examples](WRITING.md#other)\n") + expect(bool(routing_problems(root)), "a link to the wrong heading passed") + (root / "AGENTS.md").write_text("[Examples](WRITING.md#examples)\n") + expect(not routing_problems(root), "a linked section was reported") + (root / "AGENTS.md").write_text("[Examples]()\n") + expect(not routing_problems(root), "an angle-bracket link was reported") + (root / "AGENTS.md").write_text("[Examples][ex]\n\n[ex]: WRITING.md#examples\n") + expect(not routing_problems(root), "a reference-style link was reported") + (root / "AGENTS.md").write_text("[Examples](/WRITING.md#examples)\n") + expect(not routing_problems(root), "a root-relative link was reported") + for hidden_link in ( + "- Code examples:\n\n {}\n", + "```\n{}\n```\n", + "`{}`\n", + "\n", + "!{}\n", + "\\{}\n", + ): + link = "[Examples](WRITING.md#examples)" + (root / "AGENTS.md").write_text(hidden_link.format(link)) + expect(bool(routing_problems(root)), f"a link in {hidden_link!r} passed") + (root / "AGENTS.md").write_text("[Examples](WRITING.md#examples)\n") + (root / "AGENTS.md").unlink() + gone = routing_problems(root) + expect( + bool(gone) and "is missing" in gone[0], "a missing AGENTS.md was unnamed" + ) + (root / "AGENTS.md").write_text("[Examples](WRITING.md#examples)\n") + labels = "\n".join(label + " x" for label in PORT_LABELS) + wide = "```text\n" + "x" * 81 + "\n```" + head = f"### In this repository\n\n{labels}\n\n" + block = head + f"Bad, over 80:\n\n{wide}\n\nGood, x:\n" + expect(not port_block_problems(block), "a complete port block was reported") + twice = block + f"\nBad, over 80:\n\n{wide}\n" + expect(bool(port_block_problems(twice)), "a second Bad example passed") + missing = block.replace(PORT_LABELS[2], "- **Other:**") + expect( + bool(port_block_problems(missing)), "a port block missing a label passed" + ) + fenced = "## Examples\n\n```sh\n# a comment\n```\n\n" + shared + (root / "WRITING.md").write_text(fenced) + expect(not routing_problems(root), "a fenced comment read as a heading") + nested = tomllib.loads( + 'allow_ceiling = 0\n[[exclude]]\nglob = "a"\nreason = "r"\n' + 'doc_comments = ["a"]\n' + ) + nested["markdown"] = ["a"] + expect( + any("doc_comments" in p for p in config_problems(nested, ["a"])), + "a key nested under [[exclude]] passed", + ) + del nested["exclude"][0]["doc_comments"] + expect(not config_problems(nested, ["a"]), "a clean [[exclude]] was reported") + nested["exclude"][0]["reason"] = " " + expect( + any("no reason" in p for p in config_problems(nested, ["a"])), + "an exclusion without a reason passed", + ) + table = {"exclude": {"glob": "a", "reason": "r"}} + expect(bool(type_problems(table)), "[exclude] written as one table passed") + typed = {"width": "80", "markdown": "**/*.md"} + expect(len(type_problems(typed)) == 2, "a string width or glob list passed") + listed = {"allow": [{"path": ["a"], "line": "b", "reason": "c"}]} + expect(bool(type_problems(listed)), "a list where a string belongs passed") + absent = {"copy": "gone.toml", "root": "fmt.toml", "key": "max_width"} + expect( + bool(copy_problems(root, {"formatter_copies": [absent]})), + "a missing formatter copy passed", + ) + expect(not type_problems({"width": 80, "markdown": ["a"]}), "good types failed") + misnamed: dict[str, t.Any] = { + "markdown": ["README.md"], + "exclude": [{"path": "README.md", "reason": "r"}], + "allow": [{"file": "README.md", "line": wide, "reason": "r"}], + "formatter_copies": [{"copy": "copy.toml", "root": "fmt.toml"}], + "allow_ceiling": 1, + } + found = " ".join(config_problems(misnamed, ["README.md"])) + expect( + all(f"has no {key}" in found for key in ("glob", "path", "key")), + "an entry missing a key the check reads passed", + ) + try: + check(root, misnamed, ["README.md"]) + copy_problems(root, misnamed) + except KeyError as error: + expect(False, f"an entry missing {error} crashed the check") + entry = {"path": "a", "line": "b", "reason": "c"} + ceiling: dict[str, t.Any] = {"allow": [entry, entry], "allow_ceiling": 1} + grown = config_problems(ceiling, ["a"]) + expect( + bool(grown) and "delete the new entry" in grown[0], + "a grown allow list passed or was not told to delete the new entry", + ) + ceiling = {"allow": [entry], "allow_ceiling": 2} + expect(bool(config_problems(ceiling, ["a"])), "a shrunk list kept its ceiling") + ceiling = {"allow": [entry], "allow_ceiling": 1} + expect(not config_problems(ceiling, ["a"]), "an exact ceiling was reported") + with tempfile.TemporaryDirectory() as scratch: + top = pathlib.Path(scratch) + git = ["git", "-C", scratch, "-c", "init.defaultBranch=main"] + subprocess.run([*git, "init", "-q"], check=True) + (top / ".github").mkdir() + (top / "README.md").write_text("x\n") + subprocess.run([*git, "add", "README.md"], check=True) + (top / "LINKED.md").symlink_to("README.md") + subprocess.run([*git, "add", "LINKED.md"], check=True) + expect( + tracked_files(top) == ["README.md"], + "a tracked symbolic link was read beside its target", + ) + + def run(config_text: str) -> str: + (top / CONFIG).write_text(config_text) + out = io.StringIO() + with contextlib.redirect_stdout(out): + code = main(["--root", scratch]) + expect(code == 1, "a broken config passed") + return out.getvalue() + + expect( + "fix the config first" in run('width = "80"\n'), + "a string width reached the width pass", + ) + expect( + "cannot read the config" in run("width = [\n"), + "a config that is not TOML went unreported", + ) + misspelled = ( + 'markdwn = ["*.md"]\nallow_ceiling = 1\n[[allow]]\n' + 'path = "README.md"\nline = "x"\nreason = "r"\n' + ) + expect( + "0 stale allow entries" in run(misspelled), + "a misspelled glob key made an allow entry look stale", + ) + allowed = "print(total, " + "x" * 80 + ")" + edited = allowed.replace("total", "totals") + (top / "README.md").write_text(f"```py\n{'y' * 90}\n{edited}\n```\n") + config_text = ( + 'markdown = ["README.md"]\nallow_ceiling = 1\n[[allow]]\n' + f'path = "README.md"\nline = "{allowed}"\nreason = "r"\n' + ) + advice = run(config_text) + expect( + advice.count(f'line = "{edited}"') == 1 + and f'[[allow]]\npath = "README.md"\nline = "{"y" * 90}"' in advice, + "an edited allowed line was paired with another wide line, or the " + "new wide line got no entry", + ) + expect( + "\nREADME.md: an allowed line changed; its entry says why it stays" + in "\n" + advice + and "give it an entry of its own" in advice + and "Fix a wide line by changing the code" in advice, + "an edited allowed line was told to change its code", + ) + (top / "README.md").write_text(f"```go\n// Output: {'o' * 80}\n```\n") + marked = run('markdown = ["README.md"]\nallow_ceiling = 0\n') + expect( + marked.split("\n[[allow]]")[0].count("[[allow]]") == 1 + and "#what-never-breaks); add the line to [[allow]]" in marked, + "a marker line's advice named [[allow]] twice", + ) + (top / "README.md").write_text(f"```py\nprint({'w' * 80})\n```\n") + plain = "\n" + run('markdown = ["README.md"]\nallow_ceiling = 0\n') + expect( + "\nFix a wide line by changing the code" in plain + and "\nIf no change keeps the example clear, add the line to" in plain, + "a wide line's advice and its allow fallback were not on lines of " + "their own", + ) + with tempfile.TemporaryDirectory() as other: + repo = pathlib.Path(other) + sub = ["git", "-C", other, "-c", "user.name=t", "-c", "user.email=t@t"] + subprocess.run([*sub, "init", "-q"], check=True) + allowed_line = "print(total, " + "x" * 80 + ")" + (repo / "README.md").write_text(f"```py\n{allowed_line}\n```\n") + subprocess.run([*sub, "add", "README.md"], check=True) + subprocess.run([*sub, "commit", "-qm", "x"], check=True) + # The allowed line is shortened to fit, and a new wide line that + # resembles it is added: the entry goes, the new line gets its own. + fits = "print(total, " + "x" * 40 + ")" + new = "print(totals, " + "x" * 80 + ")" + (repo / "README.md").write_text(f"```py\n{fits}\n{new}\n```\n") + (repo / ".github").mkdir() + (repo / CONFIG).write_text( + 'markdown = ["README.md"]\nallow_ceiling = 1\n[[allow]]\n' + f'path = "README.md"\nline = "{allowed_line}"\nreason = "r"\n' + ) + out = io.StringIO() + with contextlib.redirect_stdout(out): + main(["--root", other]) + told = out.getvalue() + expect( + "an allowed line changed" not in told + and f"names a line shortened to fit in 80: '{allowed_line}'" in told + and "Delete the stale allow entry for README.md." in told + and "Set allow_ceiling to 0 plus one" in told, + "a new wide line beside a shortened allowed line was taken for " + "its edit", + ) + # A short similar line already committed is not a shortening: an + # edit to the allowed line still takes its entry. + (repo / "README.md").write_text(f"```py\n{fits}\n{allowed_line}\n```\n") + subprocess.run([*sub, "commit", "-qam", "y"], check=True) + edited_line = allowed_line.replace("total", "totals") + (repo / "README.md").write_text(f"```py\n{fits}\n{edited_line}\n```\n") + out = io.StringIO() + with contextlib.redirect_stdout(out): + main(["--root", other]) + expect( + "an allowed line changed" in out.getvalue(), + "an edited allowed line beside a committed short line lost its entry", + ) + (top / "lib.rs").write_text("/// ```console\n/// $ ls `\n/// -l\n/// ```\n") + subprocess.run([*git, "add", "lib.rs"], check=True) + shells = run('doc_comments = ["lib.rs"]\nallow_ceiling = 0\n') + expect( + "lib.rs:2: this `$ ` command is continued with a backtick" in shells, + "a doc-comment console fence continued the other shell's way passed", + ) + subprocess.run([*git, "rm", "-q", "--cached", "lib.rs"], check=True) + (top / "lib.rs").unlink() + labelled = f"session.name(); // → {'d' * 80}" + (top / "README.md").write_text(f"```java\n{labelled}\n```\n") + told = run('markdown = ["README.md"]\nallow_ceiling = 0\n') + expect( + "Keep the code and its marker on one line" in told + and told.split("\n[[allow]]")[0].count("[[allow]]") == 1, + "a trailing marker line's advice named [[allow]] twice", + ) + output = f"// Output: {'o' * 80}" + (top / "README.md").write_text(f"```go\n{edited}\n{output}\n```\n") + marked = run( + 'markdown = ["README.md"]\nallow_ceiling = 1\n[[allow]]\n' + f'path = "README.md"\nline = "{allowed}"\nreason = "r"\n' + ) + expect( + "#what-never-breaks); add the first other wide line to [[allow]]" in marked, + "a marker line after an edited allowed line named [[allow]] twice", + ) + second = "print(count, " + "z" * 80 + ")" + moved = second.replace("count", "counts") + (top / "README.md").write_text(f"```py\n{edited}\n{moved}\n```\n") + both = run( + 'markdown = ["README.md"]\nallow_ceiling = 2\n[[allow]]\n' + f'path = "README.md"\nline = "{allowed}"\nreason = "r"\n' + f'[[allow]]\npath = "README.md"\nline = "{second}"\nreason = "r"\n' + ) + expect( + "[[allow]]" not in both + and f'line = "{moved}"' in both + and "allow_ceiling stays 2" in both, + "two allowed lines edited in one file were not both paired", + ) + (top / "notes.md").write_text("x\n") + subprocess.run([*git, "add", "notes.md"], check=True) + (top / "README.md").write_text(f"```py\n{allowed}\n```\n") + unread = run( + 'markdown = ["notes.md"]\nallow_ceiling = 1\n[[allow]]\n' + f'path = "README.md"\nline = "{allowed}"\nreason = "r"\n' + ) + expect( + "no longer reads it as wide" in unread and "Delete" not in unread, + "an allowed line a glob change hid was offered for deletion", + ) + (top / "README.md").write_text("```py\nprint(1)\n```\n") + fits = run( + 'markdown = ["README.md"]\nallow_ceiling = 1\n[[allow]]\n' + 'path = "README.md"\nline = "print(1)"\nreason = "r"\n' + ) + expect( + "Delete the stale allow entry for README.md" in fits + and "names a line that now fits in 80" in fits + and "no longer reads" not in fits, + "an allowed line that now fits was not offered for deletion", + ) + (top / "README.md").write_text(f"```py\n{allowed}\n```\n") + (top / "examples").mkdir() + (top / "examples" / "new.txt").write_text("x\n") + expect( + "examples/new.txt: untracked, under examples/ but selected by no glob; " + '`git add` it, then add "examples/new.txt" to sources' + in run('markdown = ["README.md"]\nallow_ceiling = 0\nwidth = 1\n'), + "an untracked, unselected example file went unnamed", + ) + (top / "README.md").write_text("```console\n$ ls `\n -l\n```\n") + expect( + "is continued with a backtick" + in run('markdown = ["README.md"]\nallow_ceiling = 0\n'), + "a run left a `$ ` command continued with a backtick unreported", + ) + print("self-test:", "failed" if failures else "ok") + return 1 if failures else 0 + + +def main(argv: list[str] | None = None) -> int: + """Check the repository, or run the self-test.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--self-test", action="store_true", help="prove the checker can fail" + ) + parser.add_argument( + "--digest", + action="store_true", + help="print digests of this checker and the shared WRITING.md section", + ) + parser.add_argument( + "--root", type=pathlib.Path, help="repository root (default: git toplevel)" + ) + args = parser.parse_args(argv) + if args.self_test: + return self_test() + root = args.root or pathlib.Path( + subprocess.run( + ["git", "rev-parse", "--show-toplevel"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + ) + if args.digest: + for line in digests(root): + print(line) + return 0 + try: + config = tomllib.loads((root / CONFIG).read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as error: + print(f"{CONFIG}: cannot read the config: {error}") + print("1 setup problem; fix the config first.") + return 1 + wrong = type_problems(config) + if wrong: + for problem in wrong: + print(f"{CONFIG}: {problem}") + print(f"{plural(len(wrong), 'setup problem')}; fix the config first.") + return 1 + files = tracked_files(root) + writing = writing_path(root) + # Each problem names the file to change; routing problems name their own. + setup = config_problems(config, files) + problems = ( + [f"{CONFIG}: {problem}" for problem in setup] + + copy_problems(root, config) + + digest_problems(root, config) + + marker_problems(root) + + routing_problems(root) + ) + new = untracked_matches(config, tracked_files(root, others=True)) + chosen = [path for path in new if selected(config, path)] + shown = ", ".join(chosen[:3]) + (", ..." if len(chosen) > 3 else "") + notice = ( + f"Not checked until `git add`: {plural(len(chosen), 'untracked file')} " + f"the config selects ({shown})." + if chosen + else "" + ) + # An untracked file does not fail the run, but its wide lines are shown + # so a new example can be fixed before it is added. + pending, _ = check(root, config, chosen) if chosen and not setup else ([], []) + if pending: + they = "it fails" if len(chosen) == 1 else "they fail" + notice += f" Once added, {they} on {plural(len(pending), 'wide line')}: " + ( + "; ".join(str(finding) for finding in pending[:3]) + ) + notice = "\n".join( + [notice] * bool(notice) + + [ + f"{path}: untracked, under examples/ but selected by no glob; `git add` " + "it, then " + select_advice(path) + for path in new + if path not in chosen + ] + ) + bad_path = None + if writing: + where = writing.relative_to(root).as_posix() + text = writing.read_text(encoding="utf-8") + block = port_block_problems(text) + problems += [f"{where}: {problem}" for problem in block] + bad_path = where if any("Bad example fits" in p for p in block) else None + # A config problem such as a misspelled glob key would make allow entries + # look stale, so the width pass waits until the config is right. + findings, stale = check(root, config, files) if not setup else ([], []) + problems += prompt_problems(root, config, files) if not setup else [] + annotate = os.environ.get("GITHUB_ACTIONS") == "true" + for problem in problems: + print(problem) + for finding in findings: + print(finding) + if annotate: + print( + f"::error file={finding.path},line={finding.number}::" + f"{finding.columns} columns > {finding.width}" + ) + # A line still in its file is hidden only while it is still wide; one that + # now fits needs its entry deleted. + width, tab_width = config.get("width", 80), config.get("tab_width", 4) + present = [entry for entry in stale if entry["line"] in source_lines(root, entry)] + hidden = [ + entry + for entry in present + if columns(entry["line"].expandtabs(tab_width)) > width + ] + absent = [entry for entry in stale if entry not in present] + shortened = shortened_entries(root, absent, width, tab_width) if absent else [] + for entry in stale: + how = ( + "names a line the check no longer reads" + if entry in hidden + else f"names a line that now fits in {width}" + if entry in present + else f"names a line shortened to fit in {width}" + if entry in shortened + else "matches no line" + ) + print( + f"{CONFIG}: allow entry for {entry['path']} {how}: {quoted(entry['line'])}" + ) + if problems or findings or stale: + page = writing or writing_file(root) + rules = page.relative_to(root).as_posix() if page else "WRITING.md" + print( + f"{plural(len(problems), 'problem')}, " + f"{plural(len(findings), 'wide line')}, " + f"{plural(len(stale), 'stale allow entry', 'stale allow entries')}." + ) + if setup: + print(f"The width check runs once the problems in {CONFIG} are fixed.") + edited = "" + # Name an entry by its line when its file has two allow entries. + allowed = [e for e in config.get("allow", []) if isinstance(e, dict)] + if findings: + first = findings[0] + many = len(findings) > 1 + pairs = edit_pairs(findings, stale, bad_path, shortened) + if pairs: + # An allowed line changed: its entry already says why it stays + # whole, so it takes the new text. + first, edited = pairs[0][0], pairs[0][0].path + named = entry_name(pairs[0][1], allowed) + print( + f"{edited}: an allowed line changed; its entry says why it stays " + f"whole. Put its new text in the stale entry for {named} (if the " + "line is new instead, give it an entry of its own):" + ) + else: + lead = ( + f"The first of {len(findings)}, as an entry:" + if many + else "As an entry:" + ) + advice = fix_advice(first, rules) + if "[[allow]]" in advice and not advice.startswith(kept_whole(rules)): + # The advice already says when to allow the line. + print(advice) + print(lead) + elif advice.startswith(kept_whole(rules)): + # The rule itself says to allow it; say [[allow]] once. + print( + f"{kept_whole(rules)}; add the line to [[allow]] in " + f"{CONFIG} with its reason. {lead}" + ) + else: + print(advice) + print( + "If no change keeps the example clear, add the line to " + f"[[allow]] in {CONFIG} with a reason. {lead}" + ) + hint = allow_hint(first) + print(hint.splitlines()[2] if edited else hint) + for finding, entry in pairs[1:]: + print(f"In the stale entry for {entry_name(entry, allowed)}, put:") + print(allow_hint(finding).splitlines()[2]) + paired = [finding for finding, _ in pairs] + others = [finding for finding in findings if finding not in paired] + if edited and others: + advice = fix_advice(others[0], rules) + if advice.startswith(kept_whole(rules)): + print( + f"{kept_whole(rules)}; add the first other wide line to " + f"[[allow]] in {CONFIG} with its reason:" + ) + else: + print(advice) + print( + "If no change keeps the example clear, add the first " + f"other wide line to [[allow]] in {CONFIG}:" + ) + print(allow_hint(others[0])) + if findings or stale: + count = len(config.get("allow", [])) + for hint in ceiling_hints( + findings, stale, count, bad_path, hidden, allowed, shortened + ): + if not (edited and "an allowed line changed" in hint): + print(hint) + if notice: + print(notice) + return 1 + read = [g for key in GLOB_KEYS for g in config.get(key, [])] + skip = [entry["glob"] for entry in entries(config, "exclude")] + count = sum(matches(path, read) and not matches(path, skip) for path in files) + print(f"{count} files checked; no example is over {config.get('width', 80)}.") + if notice: + print(notice) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/mcp/example_test.go b/mcp/example_test.go index 35eae7764..f7308fe24 100644 --- a/mcp/example_test.go +++ b/mcp/example_test.go @@ -21,7 +21,9 @@ import ( // CLI launches. [tmuxmcp.Run] holds the process until the client goes away. func ExampleRun() { ctx := context.Background() - target, err := tmux.NewServer(tmux.ServerOptions{SocketName: "my-application"}) + target, err := tmux.NewServer( + tmux.ServerOptions{SocketName: "my-application"}, + ) if err != nil { log.Fatal(err) } @@ -63,7 +65,10 @@ func whichPaneAmIIn(ctx context.Context) error { return err } defer killExampleServer(target) - if _, err := target.NewSession(ctx, tmux.NewSessionRequest{Name: "work"}); err != nil { + if _, err := target.NewSession( + ctx, + tmux.NewSessionRequest{Name: "work"}, + ); err != nil { return err } @@ -76,7 +81,10 @@ func whichPaneAmIIn(ctx context.Context) error { // A matching pane and socket identify the terminal carrying this process. // A program outside the selected tmux server is told so rather than left to // guess from a pane id alone. - result, err := session.CallTool(ctx, &sdk.CallToolParams{Name: "get_server_info"}) + result, err := session.CallTool( + ctx, + &sdk.CallToolParams{Name: "get_server_info"}, + ) if err != nil { return err } @@ -114,7 +122,9 @@ func Example_watchingAPane() { if _, err := session.CallTool(ctx, &sdk.CallToolParams{ Name: "run_shell_command", Arguments: map[string]any{ - "pane_id": paneID, "command": "printf 'deploy finished\\n'", "timeout": 30, + "pane_id": paneID, + "command": "printf 'deploy finished\\n'", + "timeout": 30, }, }); err != nil { fmt.Println("run the command:", err) @@ -336,7 +346,10 @@ func connectedExampleClient( // A plain POSIX shell, as byte-streams uses: a login shell's prompt can // be long enough to wrap a typed command, and a line editor's redraw can // then leave a row ending in the very word an example waits for. - created, err := target.NewSession(ctx, tmux.NewSessionRequest{Name: "work", Command: "sh"}) + created, err := target.NewSession( + ctx, + tmux.NewSessionRequest{Name: "work", Command: "sh"}, + ) if err != nil { panic(err) } @@ -383,7 +396,10 @@ func connectExampleClient( _ = instance.Close() return nil, nil, err } - client := sdk.NewClient(&sdk.Implementation{Name: "example", Version: "1"}, nil) + client := sdk.NewClient( + &sdk.Implementation{Name: "example", Version: "1"}, + nil, + ) session, err := client.Connect(ctx, clientTransport, nil) if err != nil { _ = serverSession.Close() @@ -432,12 +448,17 @@ func killExampleServer(server tmux.Server) { // waitForExampleShell blocks until the pane reports a shell as its foreground // command, which is when it starts reading keys. -func waitForExampleShell(ctx context.Context, target tmux.Server, paneID string) error { +func waitForExampleShell( + ctx context.Context, + target tmux.Server, + paneID string, +) error { deadline := time.Now().Add(20 * time.Second) for { pane, found, err := examplePane(ctx, target, paneID) if err == nil && found { - if command, ok := pane.CurrentCommand(); ok && exampleShell(command) { + command, ok := pane.CurrentCommand() + if ok && exampleShell(command) { return waitForExampleShellReadingInput(ctx, pane, deadline) } } @@ -462,7 +483,10 @@ func waitForExampleShellReadingInput( const marker = "libtmux-go-example-ready" command := "printf '" + marker + "\n'" for { - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}); err != nil { + if err := pane.SendKeys( + ctx, + tmux.SendKeysRequest{Command: &command}, + ); err != nil { return err } for attempt := 0; attempt < 20; attempt++ { diff --git a/mcp/examples/agent-workflow/main.go b/mcp/examples/agent-workflow/main.go index 08ddba6b7..947bf33f6 100644 --- a/mcp/examples/agent-workflow/main.go +++ b/mcp/examples/agent-workflow/main.go @@ -34,10 +34,17 @@ type paneSummary struct { } func main() { - socketName := flag.String("socket-name", "", "tmux socket name; empty uses tmux's default") + socketName := flag.String( + "socket-name", + "", + "tmux socket name; empty uses tmux's default", + ) flag.Parse() if _, set := os.LookupEnv(tmuxmcp.ToolsetsEnvironmentVariable); !set { - if err := os.Setenv(tmuxmcp.ToolsetsEnvironmentVariable, "inspect,manage,execute"); err != nil { + if err := os.Setenv( + tmuxmcp.ToolsetsEnvironmentVariable, + "inspect,manage,execute", + ); err != nil { fmt.Fprintln(os.Stderr, "agent-workflow:", err) os.Exit(1) } @@ -77,7 +84,8 @@ func run(socketName string) error { } // A socket nobody has started yet is an ordinary arrival. Creation accepts - // no command or environment payload; tmux starts only the configured process. + // no command or environment payload; tmux starts only the configured + // process. if !server.Alive { fmt.Println("no tmux server on that socket yet; starting one") if err := call(ctx, session, "create_session", map[string]any{ @@ -85,7 +93,13 @@ func run(socketName string) error { }, nil); err != nil { return err } - if err := call(ctx, session, "get_server_info", nil, &server); err != nil { + if err := call( + ctx, + session, + "get_server_info", + nil, + &server, + ); err != nil { return err } } @@ -103,14 +117,17 @@ func run(socketName string) error { fmt.Printf("running in pane %s; leaving it untouched\n", origin) } else { origin = activePane(before.Panes) - fmt.Printf("not running inside this tmux server; using active pane %s\n", origin) + fmt.Printf( + "not running inside this tmux server; using active pane %s\n", + origin, + ) } if origin == "" { return fmt.Errorf("selected server has no active pane") } - // Make room beside the origin. split_window starts the new pane's configured - // process and deliberately has no command field. + // Make room beside the origin. split_window starts the new pane's + // configured process and deliberately has no command field. var split struct { PaneID string `json:"paneId"` } @@ -146,7 +163,8 @@ func run(socketName string) error { // the shell's echoed command cannot satisfy wait_for_text prematurely. if err := call(ctx, session, "paste_text", map[string]any{ "pane_id": split.PaneID, - "text": "sleep 2; if tmux -V; then printf 'agent-workflow-%s\\n' ready; " + + "text": "sleep 2; if tmux -V; then " + + "printf 'agent-workflow-%s\\n' ready; " + "else printf 'agent-workflow-%s\\n' failed; fi", "enter": true, }, nil); err != nil { @@ -189,7 +207,11 @@ func run(socketName string) error { return err } if !waited.Found { - return fmt.Errorf("visible work ended with %s (%q)", waited.Outcome, waited.Matched) + return fmt.Errorf( + "visible work ended with %s (%q)", + waited.Outcome, + waited.Matched, + ) } // Collect only output written after the baseline. linesMissed would mean @@ -228,14 +250,19 @@ func run(socketName string) error { if ran.TimedOut { fmt.Println("the command did not finish in time") } else if ran.ExitStatus != nil { - fmt.Printf("exit %d, %d lines of output\n", *ran.ExitStatus, len(ran.Output)) + fmt.Printf( + "exit %d, %d lines of output\n", + *ran.ExitStatus, + len(ran.Output), + ) for _, line := range ran.Output { fmt.Println(" |", line) } } // Report what was built. The layout string is tmux's own, and - // select_layout takes it back, so this is also how a useful layout is saved. + // select_layout takes it back, so this is also how a useful layout is + // saved. var after struct { Panes []paneSummary `json:"panes"` Total int `json:"total"` @@ -264,13 +291,22 @@ func run(socketName string) error { }, &window); err != nil { return err } - fmt.Printf("window %dx%d, layout %s\n", window.Width, window.Height, window.Layout) + fmt.Printf( + "window %dx%d, layout %s\n", + window.Width, + window.Height, + window.Layout, + ) return nil } // window reports which window a pane is in, so later listings can be narrowed // to it. One call is better than a guess: a pane id carries no window relation. -func window(ctx context.Context, session *sdk.ClientSession, paneID string) (string, error) { +func window( + ctx context.Context, + session *sdk.ClientSession, + paneID string, +) (string, error) { var info struct { Pane struct { WindowID string `json:"windowId"` @@ -308,7 +344,10 @@ func panesInWindow(panes []paneSummary, windowID string) []paneSummary { // Over stdio this is the client's job and the server is a subprocess. Tool // names, arguments, metadata, and result shapes on either side are identical, // which lets this example run the same protocol without installing a client. -func connect(ctx context.Context, target tmux.Server) (*sdk.ClientSession, func(), error) { +func connect( + ctx context.Context, + target tmux.Server, +) (*sdk.ClientSession, func(), error) { clientTransport, serverTransport := sdk.NewInMemoryTransports() instance, err := tmuxmcp.NewServer(target) if err != nil { @@ -321,7 +360,10 @@ func connect(ctx context.Context, target tmux.Server) (*sdk.ClientSession, func( _ = instance.Close() return nil, nil, fmt.Errorf("start the server: %w", err) } - client := sdk.NewClient(&sdk.Implementation{Name: "agent-workflow", Version: "1"}, nil) + client := sdk.NewClient( + &sdk.Implementation{Name: "agent-workflow", Version: "1"}, + nil, + ) session, err := client.Connect(ctx, clientTransport, nil) if err != nil { _ = serverSession.Close() @@ -347,7 +389,10 @@ func call( arguments any, into any, ) error { - result, err := session.CallTool(ctx, &sdk.CallToolParams{Name: name, Arguments: arguments}) + result, err := session.CallTool( + ctx, + &sdk.CallToolParams{Name: name, Arguments: arguments}, + ) if err != nil { return fmt.Errorf("%s: %w", name, err) } diff --git a/tmux/api_new_server_example_test.go b/tmux/api_new_server_example_test.go index 489ec53f3..d000917d2 100644 --- a/tmux/api_new_server_example_test.go +++ b/tmux/api_new_server_example_test.go @@ -28,11 +28,17 @@ func ExampleNewServer_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -40,11 +46,18 @@ func ExampleNewServer_complete() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := server.CheckAlive(ctx); !errors.Is(err, tmux.ErrNoServer) { - return errors.Join(errors.New("expected no daemon before session creation"), err) + return errors.Join( + errors.New("expected no daemon before session creation"), + err, + ) } fmt.Println("construction started tmux: false") _, err = server.NewSession(ctx, tmux.NewSessionRequest{ - Name: "work", WindowName: "editor", Command: "cat", Width: 100, Height: 30, + Name: "work", + WindowName: "editor", + Command: "cat", + Width: 100, + Height: 30, }) if err != nil { return fmt.Errorf("create session: %w", err) diff --git a/tmux/api_pane_capture_example_test.go b/tmux/api_pane_capture_example_test.go index 19f7ce3cc..e0e1c6f75 100644 --- a/tmux/api_pane_capture_example_test.go +++ b/tmux/api_pane_capture_example_test.go @@ -31,11 +31,17 @@ func ExamplePane_Capture_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -43,7 +49,11 @@ func ExamplePane_Capture_complete() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() session, err := server.NewSession(ctx, tmux.NewSessionRequest{ - Name: "work", WindowName: "editor", Command: "cat", Width: 100, Height: 30, + Name: "work", + WindowName: "editor", + Command: "cat", + Width: 100, + Height: 30, }) if err != nil { return fmt.Errorf("create session: %w", err) @@ -53,10 +63,12 @@ func ExamplePane_Capture_complete() { return fmt.Errorf("resolve pane: %w", err) } text := "api input" - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &text, Literal: true}); err != nil { + keys := tmux.SendKeysRequest{Command: &text, Literal: true} + if err := pane.SendKeys(ctx, keys); err != nil { return fmt.Errorf("send literal input: %w", err) } - // Capture is a point-in-time read, so wait for a complete matching line. + // Capture is a point-in-time read, so wait for a complete matching + // line. ticker := time.NewTicker(10 * time.Millisecond) defer ticker.Stop() for { diff --git a/tmux/api_pane_send_keys_example_test.go b/tmux/api_pane_send_keys_example_test.go index 1817c93f6..18856fec6 100644 --- a/tmux/api_pane_send_keys_example_test.go +++ b/tmux/api_pane_send_keys_example_test.go @@ -30,11 +30,17 @@ func ExamplePane_SendKeys_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -42,7 +48,11 @@ func ExamplePane_SendKeys_complete() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() session, err := server.NewSession(ctx, tmux.NewSessionRequest{ - Name: "work", WindowName: "editor", Command: "cat", Width: 100, Height: 30, + Name: "work", + WindowName: "editor", + Command: "cat", + Width: 100, + Height: 30, }) if err != nil { return fmt.Errorf("create session: %w", err) @@ -52,10 +62,12 @@ func ExamplePane_SendKeys_complete() { return fmt.Errorf("resolve pane: %w", err) } text := "api input" - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &text, Literal: true}); err != nil { + keys := tmux.SendKeysRequest{Command: &text, Literal: true} + if err := pane.SendKeys(ctx, keys); err != nil { return fmt.Errorf("send literal input: %w", err) } - // Capture is a point-in-time read, so wait for a complete matching line. + // Capture is a point-in-time read, so wait for a complete matching + // line. ticker := time.NewTicker(10 * time.Millisecond) defer ticker.Stop() for { diff --git a/tmux/api_server_new_session_example_test.go b/tmux/api_server_new_session_example_test.go index 12197977a..45a0ec242 100644 --- a/tmux/api_server_new_session_example_test.go +++ b/tmux/api_server_new_session_example_test.go @@ -29,11 +29,17 @@ func ExampleServer_NewSession_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -41,7 +47,11 @@ func ExampleServer_NewSession_complete() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() session, err := server.NewSession(ctx, tmux.NewSessionRequest{ - Name: "work", WindowName: "editor", Command: "cat", Width: 100, Height: 30, + Name: "work", + WindowName: "editor", + Command: "cat", + Width: 100, + Height: 30, }) if err != nil { return fmt.Errorf("create session: %w", err) @@ -53,9 +63,15 @@ func ExampleServer_NewSession_complete() { fmt.Println("session:", name) _, relations := session.Windows() fmt.Println("window relations captured:", relations) - _, err = server.NewSession(ctx, tmux.NewSessionRequest{Name: "work", Command: "cat"}) + _, err = server.NewSession(ctx, tmux.NewSessionRequest{ + Name: "work", + Command: "cat", + }) if !errors.Is(err, tmux.ErrSessionExists) { - return errors.Join(errors.New("expected duplicate session error"), err) + return errors.Join( + errors.New("expected duplicate session error"), + err, + ) } fmt.Println("duplicate rejected: true") return nil diff --git a/tmux/api_server_panes_example_test.go b/tmux/api_server_panes_example_test.go index 238828534..5c4c09687 100644 --- a/tmux/api_server_panes_example_test.go +++ b/tmux/api_server_panes_example_test.go @@ -28,11 +28,17 @@ func ExampleServer_Panes_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -41,7 +47,11 @@ func ExampleServer_Panes_complete() { defer cancel() for _, name := range []string{"work", "docs"} { if _, err = server.NewSession(ctx, tmux.NewSessionRequest{ - Name: name, WindowName: name + "-editor", Command: "cat", Width: 100, Height: 30, + Name: name, + WindowName: name + "-editor", + Command: "cat", + Width: 100, + Height: 30, }); err != nil { return fmt.Errorf("create %s session: %w", name, err) } diff --git a/tmux/api_server_search_sessions_example_test.go b/tmux/api_server_search_sessions_example_test.go index b1e061688..89419cebd 100644 --- a/tmux/api_server_search_sessions_example_test.go +++ b/tmux/api_server_search_sessions_example_test.go @@ -29,11 +29,17 @@ func ExampleServer_SearchSessions_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -59,7 +65,7 @@ func ExampleServer_SearchSessions_complete() { return errors.New("matched session has no name") } if _, loaded := session.Windows(); loaded { - return errors.New("live session search unexpectedly loaded windows") + return errors.New("live search unexpectedly loaded windows") } names = append(names, name) } diff --git a/tmux/api_server_sessions_example_test.go b/tmux/api_server_sessions_example_test.go index 47d08b183..0d005f8b5 100644 --- a/tmux/api_server_sessions_example_test.go +++ b/tmux/api_server_sessions_example_test.go @@ -29,11 +29,17 @@ func ExampleServer_Sessions_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -42,7 +48,11 @@ func ExampleServer_Sessions_complete() { defer cancel() for _, name := range []string{"work", "docs"} { if _, err = server.NewSession(ctx, tmux.NewSessionRequest{ - Name: name, WindowName: name + "-editor", Command: "cat", Width: 100, Height: 30, + Name: name, + WindowName: name + "-editor", + Command: "cat", + Width: 100, + Height: 30, }); err != nil { return fmt.Errorf("create %s session: %w", name, err) } diff --git a/tmux/api_server_windows_example_test.go b/tmux/api_server_windows_example_test.go index 57038e168..18d49cdb1 100644 --- a/tmux/api_server_windows_example_test.go +++ b/tmux/api_server_windows_example_test.go @@ -29,11 +29,17 @@ func ExampleServer_Windows_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -42,7 +48,11 @@ func ExampleServer_Windows_complete() { defer cancel() for _, name := range []string{"work", "docs"} { if _, err = server.NewSession(ctx, tmux.NewSessionRequest{ - Name: name, WindowName: name + "-editor", Command: "cat", Width: 100, Height: 30, + Name: name, + WindowName: name + "-editor", + Command: "cat", + Width: 100, + Height: 30, }); err != nil { return fmt.Errorf("create %s session: %w", name, err) } diff --git a/tmux/api_session_new_window_example_test.go b/tmux/api_session_new_window_example_test.go index ce05ad825..6f6f39fb6 100644 --- a/tmux/api_session_new_window_example_test.go +++ b/tmux/api_session_new_window_example_test.go @@ -28,11 +28,17 @@ func ExampleSession_NewWindow_complete() { return errors.Join(err, os.RemoveAll(directory)) } defer func() { - // Cleanup has its own deadline because the operation may have timed out. - cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + // Cleanup has its own deadline because the operation may have + // timed out. + cleanup, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer cancel() - if err := server.Kill(cleanup); err != nil && !errors.Is(err, tmux.ErrNoServer) { - runErr = errors.Join(runErr, fmt.Errorf("stop server at %s: %w", directory, err)) + err := server.Kill(cleanup) + if err != nil && !errors.Is(err, tmux.ErrNoServer) { + stopErr := fmt.Errorf("stop server at %s: %w", directory, err) + runErr = errors.Join(runErr, stopErr) return } runErr = errors.Join(runErr, os.RemoveAll(directory)) @@ -40,7 +46,11 @@ func ExampleSession_NewWindow_complete() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() session, err := server.NewSession(ctx, tmux.NewSessionRequest{ - Name: "work", WindowName: "editor", Command: "cat", Width: 100, Height: 30, + Name: "work", + WindowName: "editor", + Command: "cat", + Width: 100, + Height: 30, }) if err != nil { return fmt.Errorf("create session: %w", err) diff --git a/tmux/example_test.go b/tmux/example_test.go index ec249b9ee..4ed06c217 100644 --- a/tmux/example_test.go +++ b/tmux/example_test.go @@ -123,7 +123,10 @@ func ExampleServer_CheckAlive() { return } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -153,7 +156,10 @@ func ExampleDisplayMessageRequest() { return } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -168,7 +174,10 @@ func ExampleDisplayMessageRequest() { _, err = server.DisplayMessage(ctx, tmux.DisplayMessageRequest{ Delay: new(time.Microsecond), }) - fmt.Println("fractional delay rejected:", errors.Is(err, tmux.ErrInvalidServerCommandRequest)) + fmt.Println( + "fractional delay rejected:", + errors.Is(err, tmux.ErrInvalidServerCommandRequest), + ) // Output: // build ready // fractional delay rejected: true @@ -186,7 +195,10 @@ func ExamplePane_SendKeys() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -246,7 +258,10 @@ func ExamplePane_CaptureBytes() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -321,7 +336,10 @@ func ExampleServer_Cmd() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -357,7 +375,10 @@ func ExampleServer_OpenControl() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -368,7 +389,10 @@ func ExampleServer_OpenControl() { return } defer func() { - closeCtx, closeCancel := context.WithTimeout(context.Background(), 5*time.Second) + closeCtx, closeCancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer closeCancel() _ = client.CloseContext(closeCtx) }() @@ -418,7 +442,10 @@ func ExampleServer_ShowBufferBytes() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -453,7 +480,10 @@ func ExampleServer_Snapshot() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -521,7 +551,10 @@ func ExamplePaneFilter_Predicate() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -619,7 +652,10 @@ func ExampleErrNoServer() { // Anything else means the question could not be answered: a socket // that cannot be read, a path that is not a socket, a tmux too old. if commandError, ok := errors.AsType[*tmux.CommandError](err); ok { - fmt.Println(commandError.Subcommand, commandError.Result.ExitCode) + fmt.Println( + commandError.Subcommand, + commandError.Result.ExitCode, + ) } default: fmt.Println(len(sessions), "sessions") @@ -627,7 +663,10 @@ func ExampleErrNoServer() { } report() - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -649,7 +688,10 @@ func ExampleSession_Options() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -694,7 +736,10 @@ func ExampleSession_SetMouse() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -729,7 +774,10 @@ func ExampleSession_SetUpdateEnvironment() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -766,7 +814,10 @@ func ExampleGlobalSessionScope_SetHook() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -774,7 +825,11 @@ func ExampleGlobalSessionScope_SetHook() { // The global scope sets a hook for every session, including ones created // after it, rather than for one session that already exists. global := server.GlobalSessionScope() - if err := global.SetHook(ctx, "client-attached", "display-message 'client attached'"); err != nil { + if err := global.SetHook( + ctx, + "client-attached", + "display-message 'client attached'", + ); err != nil { fmt.Println("set hook:", err) return } @@ -807,7 +862,10 @@ func ExampleServer_SearchPanes() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -836,7 +894,9 @@ func ExampleServer_SearchPanes() { func ExampleNewServer() { // NewServer validates and records configuration; it does not start tmux. - server, err := tmux.NewServer(tmux.ServerOptions{SocketPath: "/tmp/libtmux-go-example.sock"}) + server, err := tmux.NewServer( + tmux.ServerOptions{SocketPath: "/tmp/libtmux-go-example.sock"}, + ) if err != nil { fmt.Println("new server:", err) return @@ -887,7 +947,10 @@ func ExampleServer_WithProcessEnvironmentValue() { fmt.Println("new server:", err) return } - launcher, err := server.WithProcessEnvironmentValue("LIBTMUX_MCP_OWNER", "nonce") + launcher, err := server.WithProcessEnvironmentValue( + "LIBTMUX_MCP_OWNER", + "nonce", + ) if err != nil { fmt.Println("launch environment:", err) return @@ -939,7 +1002,10 @@ func ExampleServer_NewSession() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -962,15 +1028,21 @@ func ExampleSession_NewWindow() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return } - // Name is a pointer because a nonnil empty string is an explicit -n operand, - // while nil lets tmux apply automatic-rename. + // Name is a pointer because a nonnil empty string is an explicit -n + // operand, while nil lets tmux apply automatic-rename. windowName := "editor" - window, err := session.NewWindow(ctx, tmux.NewWindowRequest{Name: &windowName}) + window, err := session.NewWindow( + ctx, + tmux.NewWindowRequest{Name: &windowName}, + ) if err != nil { fmt.Println("create window:", err) return @@ -993,7 +1065,10 @@ func ExampleWindow_SplitPane() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1034,7 +1109,10 @@ func ExamplePane_Capture() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1047,7 +1125,10 @@ func ExamplePane_Capture() { return } command := "printf 'build ready\\n'" - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}); err != nil { + if err := pane.SendKeys( + ctx, + tmux.SendKeysRequest{Command: &command}, + ); err != nil { fmt.Println("send keys:", err) return } @@ -1103,7 +1184,10 @@ func ExampleServer_Session() { } defer killExampleServer(server) - created, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + created, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1167,7 +1251,10 @@ func ExampleServer_Pane() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1199,7 +1286,10 @@ func ExampleServer_Client() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -1223,7 +1313,10 @@ func ExampleWindow_SearchPanes() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1260,7 +1353,10 @@ func ExampleWindow_Panes() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1324,14 +1420,22 @@ func ExampleServer_SetOption() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } // SetOption takes any tmux option name, including one outside the generated // catalog. The empty options value states that no mutation flag applies. - if err := server.SetOption(ctx, "exit-empty", "off", tmux.SetOptionOptions{}); err != nil { + if err := server.SetOption( + ctx, + "exit-empty", + "off", + tmux.SetOptionOptions{}, + ); err != nil { fmt.Println("set option:", err) return } @@ -1352,7 +1456,10 @@ func ExampleServer_RawOption() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -1375,7 +1482,10 @@ func ExampleSession_SetBellAction() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1409,13 +1519,22 @@ func ExampleControlClient_Call() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return } alias := "go-two=display-message -p one ; display-message -p two" - configured, err := server.Cmd(ctx, "set-option", "-s", "command-alias[80]", alias) + configured, err := server.Cmd( + ctx, + "set-option", + "-s", + "command-alias[80]", + alias, + ) if err != nil || configured.ExitCode != 0 { fmt.Println("set alias:", err) return @@ -1453,7 +1572,10 @@ func ExampleServer_WaitFor() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -1462,7 +1584,10 @@ func ExampleServer_WaitFor() { // for a pane's output. A waiter blocks until something signals the channel, // so signal it from another goroutine. go func() { - signalCtx, signalCancel := context.WithTimeout(context.Background(), 10*time.Second) + signalCtx, signalCancel := context.WithTimeout( + context.Background(), + 10*time.Second, + ) defer signalCancel() _ = server.WaitFor(signalCtx, tmux.WaitForRequest{ Channel: "ready", @@ -1470,7 +1595,10 @@ func ExampleServer_WaitFor() { }) }() - if err := server.WaitFor(ctx, tmux.WaitForRequest{Channel: "ready"}); err != nil { + if err := server.WaitFor( + ctx, + tmux.WaitForRequest{Channel: "ready"}, + ); err != nil { fmt.Println("wait:", err) return } @@ -1491,7 +1619,10 @@ func ExampleServer_WaitFor_paneCompletion() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1508,11 +1639,17 @@ func ExampleServer_WaitFor_paneCompletion() { // tmux, and a client cannot signal a server built from a different release. command := "printf 'building\n'; " + server.Executable() + " -L " + socket + " wait-for -S built" - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}); err != nil { + if err := pane.SendKeys( + ctx, + tmux.SendKeysRequest{Command: &command}, + ); err != nil { fmt.Println("send keys:", err) return } - if err := server.WaitFor(ctx, tmux.WaitForRequest{Channel: "built"}); err != nil { + if err := server.WaitFor( + ctx, + tmux.WaitForRequest{Channel: "built"}, + ); err != nil { fmt.Println("wait:", err) return } @@ -1532,7 +1669,10 @@ func ExamplePoll() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1543,20 +1683,28 @@ func ExamplePoll() { return } command := "printf 'build ready\\n'" - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}); err != nil { + if err := pane.SendKeys( + ctx, + tmux.SendKeysRequest{Command: &command}, + ); err != nil { fmt.Println("send keys:", err) return } - // tmux accepts keys before the shell runs them, so poll for output. Match the - // whole line because a substring search would match the echoed command first. - err = tmux.Poll(ctx, 10*time.Millisecond, func(ctx context.Context) (bool, error) { - lines, err := pane.Capture(ctx, tmux.CapturePaneRequest{}) - if err != nil { - return false, err - } - return slices.Contains(lines, "build ready"), nil - }) + // tmux accepts keys before the shell runs them, so poll for output. Match + // the whole line because a substring search would match the echoed command + // first. + err = tmux.Poll( + ctx, + 10*time.Millisecond, + func(ctx context.Context) (bool, error) { + lines, err := pane.Capture(ctx, tmux.CapturePaneRequest{}) + if err != nil { + return false, err + } + return slices.Contains(lines, "build ready"), nil + }, + ) if err != nil { fmt.Println("wait for output:", err) return @@ -1583,7 +1731,10 @@ func ExampleControlClient_NextNotification() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "stream"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "stream"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1649,7 +1800,10 @@ func ExamplePane_CaptureToFile() { defer func() { _ = os.RemoveAll(directory) }() path := filepath.Join(directory, "pane.txt") - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "build"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "build"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1667,20 +1821,31 @@ func ExamplePane_CaptureToFile() { } command := "printf 'build ready\\n'" - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}); err != nil { + if err := pane.SendKeys( + ctx, + tmux.SendKeysRequest{Command: &command}, + ); err != nil { fmt.Println("send keys:", err) return } // The lines are the ones Pane.Capture reports, so the whole-line comparison // that survives the shell's echo is unchanged. - err = tmux.Poll(ctx, 10*time.Millisecond, func(ctx context.Context) (bool, error) { - lines, err := pane.CaptureToFile(ctx, path, tmux.CapturePaneRequest{}) - if err != nil { - return false, err - } - return slices.Contains(lines, "build ready"), nil - }) + err = tmux.Poll( + ctx, + 10*time.Millisecond, + func(ctx context.Context) (bool, error) { + lines, err := pane.CaptureToFile( + ctx, + path, + tmux.CapturePaneRequest{}, + ) + if err != nil { + return false, err + } + return slices.Contains(lines, "build ready"), nil + }, + ) if err != nil { fmt.Println("wait for output:", err) return @@ -1737,7 +1902,10 @@ func ExamplePane_OpenObservation() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "observe"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "observe"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1757,7 +1925,10 @@ func ExamplePane_OpenObservation() { defer func() { _ = observation.Close() }() command := "printf 'observation ready\\n'" - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}); err != nil { + if err := pane.SendKeys( + ctx, + tmux.SendKeysRequest{Command: &command}, + ); err != nil { fmt.Println("send keys:", err) return } @@ -1773,7 +1944,10 @@ func ExamplePane_OpenObservation() { output = append(output, data...) } } - fmt.Println("observed:", bytes.Contains(output, []byte("observation ready"))) + fmt.Println( + "observed:", + bytes.Contains(output, []byte("observation ready")), + ) if err := observation.Close(); err != nil { fmt.Println("close observation:", err) @@ -1803,7 +1977,11 @@ func ExampleServer_OpenNotifications() { fmt.Println("create session:", err) return } - stream, err := server.OpenNotifications(ctx, session, tmux.NotificationOptions{}) + stream, err := server.OpenNotifications( + ctx, + session, + tmux.NotificationOptions{}, + ) if err != nil { fmt.Println("open notifications:", err) return @@ -1882,7 +2060,10 @@ func ExamplePane_Writer() { defer killExampleServer(server) // A plain POSIX shell keeps the pane's startup out of the example. - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "type", Command: "sh"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "type", Command: "sh"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1934,7 +2115,10 @@ func ExamplePaneObservation_WaitFor() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "wait", Command: "sh"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "wait", Command: "sh"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1952,7 +2136,10 @@ func ExamplePaneObservation_WaitFor() { } defer func() { _ = observation.Close() }() - if _, err := fmt.Fprintln(pane.Writer(ctx), "printf 'build ready\\n'"); err != nil { + if _, err := fmt.Fprintln( + pane.Writer(ctx), + "printf 'build ready\\n'", + ); err != nil { fmt.Println("write:", err) return } @@ -1981,7 +2168,10 @@ func ExamplePaneObservation_Reader() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "read", Command: "sh"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "read", Command: "sh"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -1998,13 +2188,19 @@ func ExamplePaneObservation_Reader() { } defer func() { _ = observation.Close() }() - if _, err := fmt.Fprintln(pane.Writer(ctx), "printf 'ready\\n'"); err != nil { + if _, err := fmt.Fprintln( + pane.Writer(ctx), + "printf 'ready\\n'", + ); err != nil { fmt.Println("write:", err) return } // The reader is a byte stream, so any consumer of an io.Reader works on // it. The typed command echoes first; the exact line is the reply. - matched, err := regexp.MatchReader(`(?m)^ready\r?$`, bufio.NewReader(observation.Reader(ctx))) + matched, err := regexp.MatchReader( + `(?m)^ready\r?$`, + bufio.NewReader(observation.Reader(ctx)), + ) fmt.Println(matched, err) // Output: true } @@ -2021,7 +2217,10 @@ func ExamplePaneObservation_Notifications() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "range", Command: "sh"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "range", Command: "sh"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -2038,7 +2237,10 @@ func ExamplePaneObservation_Notifications() { } defer func() { _ = observation.Close() }() - if _, err := fmt.Fprintln(pane.Writer(ctx), "printf 'seen\\n'"); err != nil { + if _, err := fmt.Fprintln( + pane.Writer(ctx), + "printf 'seen\\n'", + ); err != nil { fmt.Println("write:", err) return } @@ -2052,7 +2254,8 @@ func ExamplePaneObservation_Notifications() { fmt.Println("notification:", err) return } - if id, data, isOutput := notification.Output(); isOutput && id == pane.ID() { + id, data, isOutput := notification.Output() + if isOutput && id == pane.ID() { heard = append(heard, data...) } if bytes.Contains(heard, []byte("seen\r\n")) { @@ -2075,7 +2278,10 @@ func ExampleNotificationStream_Subscribe() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "watch"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "watch"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -2104,7 +2310,8 @@ func ExampleNotificationStream_Subscribe() { fmt.Println("notification:", err) return } - if change, ok := notification.Subscription(); ok && change.Value == "2" { + change, ok := notification.Subscription() + if ok && change.Value == "2" { fmt.Println(change.Name, "=", change.Value) break } @@ -2124,7 +2331,10 @@ func ExampleNotificationStream_Unsubscribe() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "watch"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "watch"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -2166,7 +2376,11 @@ func ExampleSession_Run() { // The command has a terminal, and its exit status is a result rather // than an error. The window it ran in is gone by the time Run returns. - result, err := session.Run(ctx, "printf 'built\\n'; exit 3", tmux.RunOptions{}) + result, err := session.Run( + ctx, + "printf 'built\\n'; exit 3", + tmux.RunOptions{}, + ) if err != nil { fmt.Println("run:", err) return @@ -2187,7 +2401,10 @@ func ExampleServer_LoadBufferFrom() { } defer killExampleServer(server) - if _, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "payload"}); err != nil { + if _, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "payload"}, + ); err != nil { fmt.Println("create session:", err) return } @@ -2226,7 +2443,10 @@ func ExamplePane_CaptureTo() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "capture"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "capture"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -2237,7 +2457,10 @@ func ExamplePane_CaptureTo() { return } command := "printf 'captured\\n'" - if err := pane.SendKeys(ctx, tmux.SendKeysRequest{Command: &command}); err != nil { + if err := pane.SendKeys( + ctx, + tmux.SendKeysRequest{Command: &command}, + ); err != nil { fmt.Println("send keys:", err) return } @@ -2249,7 +2472,11 @@ func ExamplePane_CaptureTo() { defer ticker.Stop() for { var screen bytes.Buffer - if err := pane.CaptureTo(ctx, &screen, tmux.CapturePaneRequest{}); err != nil { + if err := pane.CaptureTo( + ctx, + &screen, + tmux.CapturePaneRequest{}, + ); err != nil { fmt.Println("capture:", err) return } @@ -2281,7 +2508,10 @@ func ExampleRunning_StreamTo() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "stream"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "stream"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -2320,7 +2550,10 @@ func ExampleErrNotFound() { } defer killExampleServer(server) - session, err := server.NewSession(ctx, tmux.NewSessionRequest{Name: "project"}) + session, err := server.NewSession( + ctx, + tmux.NewSessionRequest{Name: "project"}, + ) if err != nil { fmt.Println("create session:", err) return @@ -2344,7 +2577,10 @@ func ExampleErrNotFound() { // that is gone are the same condition, so one check covers both. _, lookupErr := server.Pane(ctx, tmux.PaneID("%999999")) commandErr := pane.Kill(ctx) - fmt.Println(errors.Is(lookupErr, tmux.ErrNotFound), errors.Is(commandErr, tmux.ErrNotFound)) + fmt.Println( + errors.Is(lookupErr, tmux.ErrNotFound), + errors.Is(commandErr, tmux.ErrNotFound), + ) // Output: true true } @@ -2355,7 +2591,10 @@ func ExampleCommandObserver() { // reader happens to be running. SocketName: "libtmux-go-example-observer", CommandObserver: func(trace tmux.CommandTrace) { - commands = append(commands, trace.Subcommand+" over "+trace.Transport.String()) + commands = append( + commands, + trace.Subcommand+" over "+trace.Transport.String(), + ) }, }) if err != nil { @@ -2386,7 +2625,9 @@ func ExampleSelectLayoutRequest_Validate() { fmt.Println(request.Validate()) request.Spread = true - fmt.Println(errors.Is(request.Validate(), tmux.ErrInvalidServerCommandRequest)) + fmt.Println( + errors.Is(request.Validate(), tmux.ErrInvalidServerCommandRequest), + ) // Output: // // true @@ -2394,11 +2635,14 @@ func ExampleSelectLayoutRequest_Validate() { func ExampleServer_ValidateLayouts() { server := tmux.Server{} - err := server.ValidateLayouts(context.Background(), func(yield func(string, int) bool) { - if yield("even-h", 2) { - yield("b25d,80x24,0,0,0", 2) - } - }) + err := server.ValidateLayouts( + context.Background(), + func(yield func(string, int) bool) { + if yield("even-h", 2) { + yield("b25d,80x24,0,0,0", 2) + } + }, + ) fmt.Println(errors.Is(err, tmux.ErrInvalidServerCommandRequest)) // Output: true } diff --git a/tmux/tmuxtest/README.md b/tmux/tmuxtest/README.md index 94fbd35c3..72e6fab8b 100644 --- a/tmux/tmuxtest/README.md +++ b/tmux/tmuxtest/README.md @@ -153,7 +153,9 @@ Sibling checkouts running their own suites on the same machine will fight over tmux sockets. Give yours a namespace: ```console -$ export TMUX_TMPDIR=/tmp/my-project-test && mkdir -p "$TMUX_TMPDIR" && unset TMUX TMUX_PANE +$ export TMUX_TMPDIR=/tmp/my-project-test && \ + mkdir -p "$TMUX_TMPDIR" && \ + unset TMUX TMUX_PANE ``` Some real-tmux tests are load-sensitive. Three signs a failure is the machine diff --git a/tmux/tmuxtest/example_test.go b/tmux/tmuxtest/example_test.go index fb22c19ab..4dfd9feea 100644 --- a/tmux/tmuxtest/example_test.go +++ b/tmux/tmuxtest/example_test.go @@ -12,10 +12,14 @@ import ( func ExampleWaitFor() { attempts := 0 - err := tmuxtest.WaitFor(context.Background(), time.Millisecond, func(context.Context) (bool, error) { - attempts++ - return attempts == 3, nil - }) + err := tmuxtest.WaitFor( + context.Background(), + time.Millisecond, + func(context.Context) (bool, error) { + attempts++ + return attempts == 3, nil + }, + ) fmt.Println(err) fmt.Println(attempts) // Output: @@ -47,12 +51,18 @@ func ExampleWaitForScreen() { ctx := context.Background() pane := tmuxtest.RunInPane(ctx, t, "printf 'host: up\nqueue: 0\n'") - tmuxtest.WaitForScreen(ctx, t, pane, "a settled status block", func(screen []string) bool { - var host, queue bool - for _, line := range screen { - host = host || strings.Contains(line, "host: up") - queue = queue || strings.Contains(line, "queue: 0") - } - return host && queue - }) + tmuxtest.WaitForScreen( + ctx, + t, + pane, + "a settled status block", + func(screen []string) bool { + var host, queue bool + for _, line := range screen { + host = host || strings.Contains(line, "host: up") + queue = queue || strings.Contains(line, "queue: 0") + } + return host && queue + }, + ) } diff --git a/tmux/tmuxtest/scripted.go b/tmux/tmuxtest/scripted.go index 7882d2ed7..3e0b649c6 100644 --- a/tmux/tmuxtest/scripted.go +++ b/tmux/tmuxtest/scripted.go @@ -32,7 +32,10 @@ type ScriptedCommand struct { // // server, err := tmux.NewServer(tmux.ServerOptions{ // Binary: tmuxtest.ScriptedTmux(t, -// tmuxtest.ScriptedCommand{Contains: []string{"-V"}, Stdout: "tmux 3.7\n"}, +// tmuxtest.ScriptedCommand{ +// Contains: []string{"-V"}, +// Stdout: "tmux 3.7\n", +// }, // tmuxtest.ScriptedCommand{ // Contains: []string{"kill-pane"}, // Stderr: "can't find pane: %7\n", diff --git a/tmuxq/example_test.go b/tmuxq/example_test.go index 5824e4a70..c3baea2c4 100644 --- a/tmuxq/example_test.go +++ b/tmuxq/example_test.go @@ -62,9 +62,8 @@ func ExampleWhereSeq() { {name: "shell", active: true}, } - for pane := range tmuxq.WhereSeq(slices.Values(panes), func(pane *pane) bool { - return pane.active - }) { + isActive := func(pane *pane) bool { return pane.active } + for pane := range tmuxq.WhereSeq(slices.Values(panes), isActive) { fmt.Println(pane.name) } diff --git a/workspace/README.md b/workspace/README.md index df075aa0f..ecfd8af48 100644 --- a/workspace/README.md +++ b/workspace/README.md @@ -115,7 +115,8 @@ because a directory a `shell_command_before` creates is ordinary. ```yaml session_name: project -start_directory: ~/src/project # created beforehand; tmux falls back to $HOME if absent +# created beforehand; tmux falls back to $HOME if absent +start_directory: ~/src/project environment: PROJECT_ENV: development windows: diff --git a/workspace/examples/build-workspace/main.go b/workspace/examples/build-workspace/main.go index f994ff7ce..6f31490e5 100644 --- a/workspace/examples/build-workspace/main.go +++ b/workspace/examples/build-workspace/main.go @@ -55,7 +55,10 @@ func run() error { return fmt.Errorf("construct tmux server: %w", err) } defer func() { - killCtx, killCancel := context.WithTimeout(context.Background(), 5*time.Second) + killCtx, killCancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) defer killCancel() _ = server.Kill(killCtx) }() @@ -73,7 +76,11 @@ func run() error { if err != nil { return fmt.Errorf("search windows: %w", err) } - fmt.Printf("built %q with %d windows\n", described.SessionName, len(windows)) + fmt.Printf( + "built %q with %d windows\n", + described.SessionName, + len(windows), + ) for _, window := range windows { name, _ := window.Formats().WindowName() index, _ := window.Formats().WindowIndex()