package matrix
Module Matrix_cli_unixSource
Command-line output on Unix: the standard outputs, a region of rows redrawn below them, and questions asked at the terminal.
An output (t) is a descriptor together with what is decided for it, its styling (Ansi.Styling) and the mode its progress shows in (Matrix_cli.Progress). The decisions are made once, when the output is made, from the program's choices, the process's environment, the terminal's capabilities (from TERM and its terminfo description) and whether the descriptor is a terminal. What a program prints through an output is adapted to its styling (Adapting what a program prints) and written at once, one write for each call to print and each flush of its formatter, so a pipe gets each record whole and as soon as it is printed. On an output whose mode is `Json, what it prints is events. A grid, such as a table that Matrix_cli.Table.grid lays out, is printed with print_grid. Outputs whose descriptors reach one terminal, or one file, share a lock, so their writes never interleave. What the program printed through Stdlib.stdout, Stdlib.stderr, Format.std_formatter and Format.err_formatter, such as with Fmt.pr, is flushed before each write, as Format.pp_print_flush flushes a formatter, so the standard outputs keep their order under 2>&1.
A live region (live) is a few rows that a program redraws below its output while it works, such as a progress bar. It is a Matrix_screen.Region, whose model says what a redraw may and may not erase. Its rows show below a blank row, its origin, where the cursor rests between two draws, so that what another process prints there stays whole. The cursor is hidden while the region shows, and shown again when the region goes off the screen, for suspend, a prompt or a stop, and when it ends. While it lives, the lines printed through any output on its terminal go above it, each in the write that redraws the rows below, and a line printed without its end waits for its end, or for the region to be suspended or closed. A frame is drawn at most ten times a second, as cargo and Rich redraw their progress bars, and at once when lines go above it. A scope may also have the region drawn on a clock (live's tick). The region is redrawn when the terminal's width changes, and drawn afresh when the job is continued. A job stopped with Ctrl+Z first erases it. A job in the background (Tty.background) draws no frame, so its rows never land among what the shell writes, and its lines go out as they are. A live scope that begins while another lives on the same terminal joins its region, and its rows show below the rows of the scopes that began before it. The region shows the last rows of a frame taller than the terminal. When a scope ends, its last rows go above the region, which stays for the others, and when the last one ends, its last rows stay in the scrollback with the cursor below them. A scope's last rows stay whole, however tall. A region is drawn on an output whose mode (progress) is `Tty. Where it is `Plain, such as on a pipe or in a CI job's log, the lines go out as they are printed and the last frame is printed once, at the end, and where it is `Quiet or `Json no frame is drawn or printed.
The program's own writes to a terminal that bypass its outputs, such as print_string or a child process's output, land where the cursor rests, at the start of the region's origin (in its second column on WezTerm, Matrix_screen.Region), and the next redraw erases what they leave on the origin without a line end. So a program prints through its outputs while a region lives, and runs a child that writes to the terminal inside suspend. On WezTerm a line a program prints while the cursor rests in the first column can be lost when the window's width changes, whatever library prints it.
A region and a prompt take the signals of their terminal, as Tty.Signal shares them, and give them back when they end. SIGINT, SIGTERM, SIGHUP and SIGQUIT, at their default action, end the process once the terminal is put back. The region's write that a signal cut is ended, the cursor is shown and moved below the region's rows, and a prompt's settings are restored. A process that ends with exit inside live scopes ends them as their ends would. A region leaves the last rows of every scope in the scrollback, with the cursor below them, and an output where no region may be drawn prints its last frame. This happens before the at_exit functions registered before the first scope run, so what they print goes below the rows. A terminal that stops taking output, as under Ctrl+S, holds this back for at most a second.
This prints the files a program compiles above a line that counts them, on standard error:
let compile files =
let err = Matrix_cli_unix.stderr () in
let n = List.length files in
let progress i ~width ~height:_ =
let g = Matrix_grid.create ~width ~height:1 () in
Matrix_grid.draw_text g ~x:0 ~y:0
~text:(Printf.sprintf "%d/%d compiled" i n);
[ g ]
in
Matrix_cli_unix.live err @@ fun live ->
List.iteri
(fun i file ->
Matrix_cli_unix.show live (progress i);
compile_one file;
Matrix_cli_unix.print err (file ^ "\n"))
files;
Matrix_cli_unix.show live (progress n)This prints a table as wide as standard output allows, with styles as the output decides:
let print_table cols rows =
let out = Matrix_cli_unix.stdout () in
let room = Option.value (Matrix_cli_unix.width out) ~default:80 in
let frame =
{ Matrix_cli.Table.edge = Some `Light; line = Some `Light; pad = 1 }
in
Matrix_cli_unix.print_grid out
(Matrix_cli.Table.grid frame ~room cols rows)Outputs
The type for outputs.
val make :
?color:Ansi.Styling.choice ->
?progress:Matrix_cli.Progress.choice ->
Unix.file_descr ->
tmake ~color ~progress fd is the output on fd, with the program's choices color and progress (`Auto by default). On Windows, a console's VT processing is turned on (Tty.enable_vt) and turned back off when the program exits.
stdout ~color ~progress () is make ~color ~progress Unix.stdout.
stderr ~color ~progress () is make ~color ~progress Unix.stderr.
styling o is o's styling, at which a program writes a grid for it (Matrix_grid.to_ansi).
width o is the width a program lays out its output in: COLUMNS when it is set to a positive number (POSIX's "user's preferred width in column positions"), else the width of o's terminal when o is one, read at each call, and None for a pipe or a file.
progress o is o's mode (Matrix_cli.Progress). A live region redraws its rows in place where it is `Tty. Where it is `Plain, a program prints what the rows would otherwise show, such as the start of each step, and where it is `Json, it prints its lines for people on another output.
print o s writes s to o, adapted to its styling, in one write. Where o's mode is `Json, it writes each line of s, and the text after its last line end, as Ansi.sanitize leaves them, as an event of its own, {"time":t,"event":"output","text":line}, where t is the seconds since o was made. The prints on o are one stream, so a control function or a character that s leaves unfinished is completed by the next print, and no part of a control function shows as text, wherever the prints cut it. So a program prints its own lines for people on another output.
print_grid o g writes the rows of g to o in one write, at o's styling (Matrix_grid.to_ansi), each row ending at its last cell that shows something and with a line end.
formatter o is a formatter that writes to o as print does, one write for each flush, with its margin at o's width. Fmt writes styles on it only when its style renderer is set (Fmt.set_style_renderer), as on any formatter, and o then decides how they show.
adapt_std_formatters ~color () makes Format.std_formatter and Format.err_formatter write as formatters of stdout ~color () and stderr ~color () do, with their margins at the outputs' widths. So the printers of a program that prints with Fmt.pr and Fmt.epr, or reports with Logs_fmt's reporter, obey the decision, and their lines go above a live region. Fmt writes styles there when its setup gives the two formatters `Ansi_tty, as Fmt_tty.setup_std_outputs does on a terminal. The two formatters stay adapted once domains are spawned. Another domain prints with Format.printf and Fmt.pr on a formatter of its own (Format.get_std_formatter), which writes to the standard channels as Format makes it, so its lines are not adapted.
write_raw o bytes writes bytes to o as they are, unadapted, for a control function the program means, such as a window title. Where a region lives on o's terminal, the region is first erased, and drawn again afterwards from a row of its own.
notify o ~title ~body posts a desktop notification through o's terminal, in the form it shows (Matrix_terminal.Caps.t's notification), wrapped for tmux inside it (Matrix_terminal.notify). It does nothing when o is not a terminal or is a dumb one.
bell o rings o's terminal's bell, and does nothing when o is not a terminal or is a dumb one.
Live regions
The type for live regions.
live ~tick o f runs f with a live region on o, the region that lives on o's terminal if one does, where o's mode (progress) is `Tty, or with one that draws nothing elsewhere. With tick, the region also draws every tick seconds while f runs, calling the frames again, for a frame that changes with the time, such as a spinner or an elapsed time, between two shows. A region whose scopes give ticks draws at the shortest, and at most ten times a second as any region. When f returns or raises, or the process exits in it, its last rows stay, as the module's preamble says, or are printed once, at o's width or 80 columns when it has none.
Raises Invalid_argument if tick is not positive, and what a frame given to show raised, if f returned.
show l frame makes frame l's rows and draws them, now or at most a tenth of a second later. frame ~width ~height is the grids the rows show, one under another, [] for none. The region calls it whenever it draws, from any thread, so frame must only read values that do not change while it runs, and must not print. A grid costs its making, so a frame gives few. width is the width its rows take and height the number of rows the region shows below the rows of the scopes that began before, both at least 1, so a frame can give way on a small terminal. Where no region is drawn, width is that of the last rows printed and height is LINES when it is set to a positive number, else the terminal's height, else 24. Rows wider than width are cut, and the region shows the last height rows of a taller frame, so its first grids give way first.
Raises what an earlier frame of l raised, which was dropped, and Invalid_argument if l's scope has ended.
suspend l f erases l's rows and runs f, for something else that writes to the terminal, such as a child process, then draws l again from a row of its own, below a line f left without its end.
Tasks
A task is a step of the work a program reports: a label, a count of items or of bytes done, out of a total when the program says one, the lines of output the program gives it, and how it ended. A task succeeds, fails or is cancelled, once. Tasks form a tree under a root, the work as a whole, which tasks makes for the scope of a function and shows on an output in the output's mode (progress):
`Ttydraws a live region (Task.rows): a row for each running task, with the latest lines of its output under it, in its window, and the tasks under it behind guides, a task that ended staying there, marked, while its top task runs. The last row is the summary, the line that says how far the work is. When a task of the root ends, its rows go above the region as it ended, with every task under it, then the whole output of each of them that failed. So the scrollback keeps the order of what happened by top task, as`Plainprints it.`Plainprints a line when a task starts, one for each line of its output and one when it ends, which saysfailedorcancelledin words when it did not succeed. Each line names its task by its path, the labels from the root's task down to it, so the lines of tasks that run at once can interleave. The summary is the last line.`Quietprints the ending line of each task that failed, then all its output.`Jsonprints each change as one event a line (JSON events).
The lines are for people and their format may change. A program reads `Json.
A transient task prints its lines only when it fails, and leaves nothing above the region when it succeeds. A task's label and lines show as text (Ansi.sanitize), a label on one line. A task is told from any thread, domain or fiber, and the lines of the changes are written in the order of the changes. A task that ended ignores what it is told. A task keeps its output until the work ends. Times are seconds since the root started, by the clock tasks is given.
An Eio fiber cancelled inside Task.run fails its task, and inside tasks fails the work. A program shows them cancelled with
let run parent label f =
Task.run parent label (fun t ->
try f t
with Eio.Cancel.Cancelled _ as e ->
Task.cancel t;
raise e)
let tasks out f =
Matrix_cli_unix.tasks out (fun root ->
try f root
with Eio.Cancel.Cancelled _ as e ->
Task.cancel root;
raise e)val tasks :
?label:string ->
?now:(unit -> float) ->
?frame:(Task.t -> width:int -> height:int -> Matrix_grid.t list) ->
t ->
(Task.t -> 'a) ->
'atasks ~label ~now ~frame o f is f root for the root of the work, named label on its summary line ("" by default), shown on o in o's mode until f ends. The root succeeds when f returns and fails when f raises, which is raised again, unless f ended it, and its ending ends the tasks still running as Task.succeed and Task.fail do. now is the clock in seconds, monotonic by default. With frame, the region of `Tty shows frame root in place of Task.rows root, and `Plain prints its last frame once, at the end, the summary by default. frame must not tell a task anything and must not print. A tasks inside another on one output numbers its tasks apart (JSON events).
JSON events
Under `Json, each change is an event, one JSON object on a line of its own, in the order of the changes, as ocaml-console writes them. Every event has two members: time, the seconds since the root started, rounded to the millisecond, and event, its name. An event of a task also has id, a number that no other task shown on the output has, and task, its path, an array of strings. The events are:
"start", withparent, theidof the task it started under unless that is the root;"progress", withcount,totalwhen the program gave one, andunit,"items"or"bytes";"label", withtext, its new label;"output", withtext, a line of output. An output event of no task is a line the program printed (print);"end", withstatus,"succeeded","failed"or"cancelled",elapsed, its seconds from start to end, andmessagewhen it has one. An end event of no task is the end of the work as a whole.
Strings are valid UTF-8, with their C0 controls and DEL escaped. Objects may gain members and new events may be added, but the members above keep their meaning, so a program skips a member or an event it does not know. This is the scope of a task that compiles one file:
{"time":0,"event":"start","id":0,"task":["compile"]}
{"time":0,"event":"output","id":0,"task":["compile"],"text":"parser.ml"}
{"time":0.5,"event":"end","id":0,"task":["compile"],"status":"succeeded","elapsed":0.5}
{"time":0.5,"event":"end","status":"succeeded","elapsed":0.5}