Terminal output
A command-line tool talks to a person: what it is doing, what went wrong,
how far it has got, and sometimes a question. weft/terminal writes all of
that so that it reads well on a terminal, and stays plain text through a
pipe or in a log.
wv add weft/terminalMessages, headers and lists
Section titled “Messages, headers and lists”Everything goes through a Term, an output and what it can show:
Term.stdout() or Term.stderr().
import weft.terminal.{Term, Style, Bullet}
fn main() { val t = Term.stdout() t.header("Release 1.2.0") t.info("building 3 packages") t.section("Packages") t.bulletList([ Bullet("app", level: 0), Bullet("app/cli", level: 1), Bullet("app/server", level: 1), Bullet("docs", level: 0) ]) t.warning("the changelog has no entry for 1.2.0") t.error("cannot sign the archive:\nno key in ~/.config/release") t.success("released ${t.paint("app 1.2.0", Style.fg(.green).bold())}")}Through a pipe, or with NO_COLOR set, the output is plain text, which a
log or a test can read:
════════════════════════════════ Release 1.2.0 ═════════════════════════════════[INFO] building 3 packages
Packages────────• app ◦ app/cli ◦ app/server• docs[WARNING] the changelog has no entry for 1.2.0[ERROR] cannot sign the archive: no key in ~/.config/release[SUCCESS] released app 1.2.0On a terminal, the same program shows its colors:
Release 1.2.0 INFO building 3 packages Packages ──────── • app ◦ app/cli ◦ app/server • docs WARNING the changelog has no entry for 1.2.0 ERROR cannot sign the archive: no key in ~/.config/release SUCCESS released app 1.2.0
Term finds once what the output can show:
- Colors: none if the output is not a terminal, if
NO_COLORis set orTERM=dumb;FORCE_COLORforces them. 24-bit ifCOLORTERMsaystruecolor, 256 ifTERMends with256color, the 16 basic ones otherwise. A color the terminal lacks becomes the nearest it has. - Width: the terminal’s, else
COLUMNS, else 80. Text is measured in columns, so that a CJK character or an emoji counts for two.
Styles
Section titled “Styles”A Style is a foreground and a background color, and attributes: bold,
dim, italic, underline, reverse, strike. Each method returns a new
style.
val alert = Style.fg(.red).bold()val orange = Style.fg(Color.rgb(255, 128, 0)).underline()t.line("${t.paint("failed", alert)}: ${t.paint("3 files", orange)}")The colors are the 16 named ones, black to brightWhite,
Color.index(n) among the 256, or Color.rgb(r, g, b). t.paint writes
the style only if t shows colors; Style.paint always does.
t.prefix(label, style, text) writes a message with a badge of its own,
like info and error; t.debug writes only when DEBUG is set.
Spinners and progress bars
Section titled “Spinners and progress bars”Work that takes a while shows it is alive. A spinner turns on a task of its own while the program works; a bar counts.
import weaver.time.{sleep, millis}import weft.terminal.{Term}
fn main() { val t = Term.stdout()
using s = t.spinner("Compiling") sleep(200.millis()).await catch _ => { } s.succeed("Compiled in 0.2 s")
using bar = t.progress(total: 40, title: "Uploading") for _ in 0..40 { sleep(5.millis()).await catch _ => { } bar.add(1) } bar.finish()}On a terminal, the spinner turns, ⠋⠙⠹…, until succeed replaces it with
a tick, or fail with a cross; the bar is redrawn in place, fitted to the
width:
✔ Compiled in 0.2 sUploading [██████████░░░░░░░░░░] 52 % 21/40 0:01 leftWithout a terminal, there is nothing to redraw: the spinner writes its text once and its outcome, the bar a line at each tenth:
Compiling…✔ Compiled in 0.2 sUploading 10 % 4/40Uploading 20 % 8/40Uploading 30 % 12/40Uploading 40 % 16/40Uploading 50 % 20/40Uploading 60 % 24/40Uploading 70 % 28/40Uploading 80 % 32/40Uploading 90 % 36/40Uploading 100 % 40/40- Both are resources, held by
using: if the work fails with!, the spinner’s line is cleared, and the terminal is left clean. - They write on standard error, so that standard output stays the program’s result, ready for a pipe.
s.text("…")changes a spinner’s text; a bar withtotal: Nonebounces, and counts without a percentage.
Asking questions
Section titled “Asking questions”input reads a line, select a choice in a menu, multiSelect several
boxes to tick, confirm a yes or no:
import weaver.io.printimport weaver.test.{assert, assertEq}import weft.terminal.{Term, ChoiceError}
/// What a new project is made of.type Project = { name: String, kind: String, features: String[], git: Bool }
val kinds = ["program", "library", "extension"]val features = ["tests", "docs", "ci"]
/// Asks for a project, on t.fn askProject(t: Term): Project ! ChoiceError { val name = t.input("Name", default: "app")! val kind = t.select("Kind", kinds)! val picked = t.multiSelect("Features", features, checked: [0])! val git = t.confirm("Create a git repository?", default: true)! return Project{name, kind: kinds[kind], features: picked.map(i => features[i]), git}}
fn main() { val p = askProject(Term.stdout()) catch e => { print("setup: ${e}") return } print("\n${p.name}: ${p.kind}, ${p.features.join(" and ")}, git ${p.git}")}
@test("answered by keys, as on a terminal")fn byKeys() ! ChoiceError { // Enter, down then Enter, space to tick docs then Enter, n. val t = Term.capture(interactive: true, keys: b"\r\x1b[B\r\x1b[B \rn") val p = askProject(t)! assertEq(p.kind, "library") assertEq(p.features, ["tests", "docs"]) assert(!p.git, "no repository")}
@test("answered by lines, without a terminal")fn byLines() ! ChoiceError { val t = Term.capture(keys: b"tool\n3\n1, 3\ny\n") val p = askProject(t)! print(t.captured()) assertEq(p.name, "tool") assertEq(p.kind, "extension") assertEq(p.features, ["tests", "ci"])}On a terminal, the arrow keys or j and k move in a menu, typed letters
filter its options, space ticks a box, and Enter answers. Escape or Ctrl-C
fails with Cancelled, and the terminal is put back as it was, even on a
panic. Without a terminal, each question is asked as text, its options
numbered, and answered by a line: the program can be scripted.
$ printf 'tool\n3\n1, 3\ny\n' | ./setupName (app): Kind 1) program 2) library 3) extension> Features 1) tests 2) docs 3) ci> Create a git repository? (Y/n)tool: extension, tests and ci, git trueTesting what a program writes
Section titled “Testing what a program writes”Term.capture(width:, colors:, interactive:, keys:) is a terminal in
memory. The tests above answer the questions with the keys a person would
type, arrows included, or with lines; t.captured() gives back what was
written, escape sequences included, to compare with what is expected.
A function that writes takes its Term as a parameter, like
askProject: the program gives it Term.stdout(), a test a captured
one.