use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::io::{self, IsTerminal, Read, Write};
use std::path::Path;
use std::process::ExitCode;
use std::time::{Duration, Instant};
use termlens::{Screen, ScreenDiff, Terminal};
const USAGE: &str = "\
usage: termlens <command> [options]
commands:
inspect [options] <program> [args…] run a program in a PTY and print its screen
diff [--color WHEN] <a> <b> compare two saved screens; exit 1 when they differ
render --svg|--html|--ansi|--text|--json [--out PATH] <a> render a saved screen
A saved screen is the snapshot text format termlens prints — what `inspect`
writes to stdout, an insta .snap with or without its header, the block a
wait error prints, a TERMLENS_ARTIFACT_DIR file — or the JSON the crate's
`serde` feature writes. `diff` and `render` read `-` as standard input; only
one of diff's two operands can be, since stdin is read once.
Exit code 0: the command ran (diff: the screens are the same picture).
Exit code 1: diff found a difference. Exit code 2: termlens itself could not
run — bad arguments, an unreadable file, a program that could not be spawned.
-h, --help print this text (also after a command)
--version print the version";
const INSPECT_USAGE: &str = "\
usage: termlens inspect [--size COLSxROWS] [--timeout SECONDS] [--idle MILLIS]
[--cwd DIR] [--inherit-env] [--ansi]
[--env KEY=VALUE]... [--] <program> [args…]
Runs <program> in an 80x24 pseudo-terminal (or --size) and prints the
rendered screen. The wait ends on whichever comes first: the program
exits, or, once it has drawn something, its output has been silent for
--idle milliseconds (default 300). --timeout (default 5 seconds) bounds
both, and a program still running when the wait ends is killed.
The child environment is cleared except for PATH, and gets
TERM=xterm-256color and SHELL=/bin/sh; --inherit-env keeps the caller's
environment instead, but for TERM, and repeatable --env sets selected
values, TERM included.
--cwd runs the program in DIR, which must be an existing directory. A
relative DIR is taken from where inspect runs, and a relative program
path such as ./myapp is then found inside DIR.
--ansi paints the screen in colour on a terminal.
-- ends the options; the program name follows. Options already stop at
the first argument that does not begin with `-`, so this matters only for
a program whose name does. Every option that takes a value also accepts
it attached with `=`, as in --size=100x30 or --env=KEY=VALUE.
What goes to stdout depends on where stdout goes. A terminal gets what
you came to look at: the plain text, or the painted screen with --ansi.
Anything else — a redirect, a pipe — gets a saved screen with its
styles: block, because that is the rendering that carries colour and the
one `termlens diff` and `termlens render` read back. So a redirect never
loses a style, and never writes an escape those two would refuse.
The screen goes to stdout and nothing else does, so `inspect … > file`
saves a screen that `termlens diff` and `termlens render` read back. The
trailer that says what the program did — its exit status, or that it was
still running when the wait ended — goes to stderr. Exit code 2 means inspect
itself could not run: bad arguments, or a program that could not be spawned.";
const DIFF_USAGE: &str = "\
usage: termlens diff [--color auto|always|never] <a> <b>
Either <a> or <b> may be `-`, meaning standard input — not both, since
stdin is read once.
Parses two saved screens and prints what changed from <a> to <b>: the rows
that differ side by side, the size and cursor deltas, the style runs before
and after. On a terminal the changed cells are coloured (red in <a>, green
in <b>) unless --color never or NO_COLOR is set; in a pipe the rendering is
the plain one Screen::diff prints in a CI log. Every option that takes a
value also accepts it attached with `=`, as in --color=never.
Exit code 0 when the two are the same picture, 1 when they differ, 2 when
diff itself could not run — bad arguments, or a file that is missing or not
a saved screen.";
const RENDER_USAGE: &str = "\
usage: termlens render (--svg | --html | --ansi | --text | --json) [--out PATH] <a>
Prints a saved screen as an SVG image, an HTML fragment, the screen in ANSI
colour for a terminal, the plain text format with its styles: block, or the
format-1 JSON document the crate's `serde` feature writes.
<a> may be `-`, meaning standard input. --out writes to PATH instead of
stdout; `--out -` is standard output, and a file named `-` is still `./-`.
--out creates nothing when the render fails — unlike a shell redirect,
which truncates the file before termlens runs. Every option that takes a
value also accepts it attached with `=`, as in --out=screen.svg.
Exit code 0: the screen was rendered. Exit code 2: render itself could not
run — bad arguments, a file that is missing or not a saved screen, or an
--out path that cannot be written.";
fn print(out: &str) -> ExitCode {
let mut stdout = io::stdout().lock();
match stdout
.write_all(out.as_bytes())
.and_then(|()| stdout.flush())
{
Ok(()) => ExitCode::SUCCESS,
Err(e) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
Err(e) => fail(&format!("writing the output failed: {e}")),
}
}
fn fail(message: &str) -> ExitCode {
let _ = report(&format!("termlens: {message}"));
ExitCode::from(2)
}
fn report(line: &str) -> io::Result<()> {
let mut stderr = io::stderr().lock();
writeln!(stderr, "{line}").and_then(|()| stderr.flush())
}
fn usage_error(usage: &str) -> ExitCode {
let _ = report(usage);
ExitCode::from(2)
}
fn utf8(arg: OsString) -> Result<String, String> {
arg.into_string()
.map_err(|arg| format!("{arg:?} is not valid UTF-8; termlens's own arguments must be"))
}
fn version() -> String {
format!("termlens {}\n", env!("CARGO_PKG_VERSION"))
}
fn main() -> ExitCode {
let mut args = std::env::args_os().skip(1);
let Some(command) = args.next() else {
return usage_error(USAGE);
};
let command = match utf8(command) {
Ok(command) => command,
Err(e) => return fail(&e),
};
let rest: Vec<OsString> = args.collect();
if command == "inspect" {
return inspect(rest);
}
let rest = match rest.into_iter().map(utf8).collect::<Result<Vec<_>, _>>() {
Ok(rest) => rest,
Err(e) => return fail(&e),
};
match command.as_str() {
"-h" | "--help" => print(&format!("{USAGE}\n")),
"--version" => print(&version()),
"diff" => diff(&rest),
"render" => render(&rest),
other if other.starts_with('-') && other != STDIN => {
fail(&format!("unknown option {other:?} (try --help)"))
}
other => fail(&format!("unknown command {other:?} (try --help)")),
}
}
fn load(path: &str) -> Result<Screen, String> {
let raw = if path == STDIN {
let mut raw = String::new();
io::stdin()
.read_to_string(&mut raw)
.map_err(|e| format!("{STDIN_NAME}: {e}"))?;
raw
} else {
std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?
};
let raw = raw.replace("\r\n", "\n");
let body = strip_insta_header(&raw).trim_start_matches('\n');
if body.starts_with('{') {
return serde_json::from_str(body)
.map_err(|e| format!("{}: not a termlens Screen: {e}", name_of(path)));
}
Screen::parse(strip_inspect_trailer(body)).map_err(|e| format!("{}: {e}", name_of(path)))
}
const STDIN: &str = "-";
const STDIN_NAME: &str = "<stdin>";
const REAP_GRACE: Duration = if cfg!(windows) {
Duration::from_secs(2)
} else {
Duration::from_millis(500)
};
fn name_of(path: &str) -> &str {
if path == STDIN {
STDIN_NAME
} else {
path
}
}
fn strip_insta_header(text: &str) -> &str {
text.strip_prefix("---\n")
.and_then(|rest| rest.find("\n---\n").map(|end| &rest[end + 5..]))
.unwrap_or(text)
}
fn strip_inspect_trailer(text: &str) -> &str {
let trimmed = text.trim_end_matches('\n');
let start = trimmed.rfind('\n').map_or(0, |at| at + 1);
let last = &trimmed[start..];
let is_trailer = last.ends_with(" ---")
&& [
"--- exited: ",
"--- still running",
"--- waiting for the program failed: ",
]
.iter()
.any(|prefix| last.starts_with(prefix));
if is_trailer {
&trimmed[..start]
} else {
text
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ColorWhen {
Auto,
Always,
Never,
}
impl ColorWhen {
fn enabled(self) -> bool {
match self {
ColorWhen::Always => true,
ColorWhen::Never => false,
ColorWhen::Auto => {
io::stdout().is_terminal()
&& std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty())
}
}
}
}
fn color_when(word: &str) -> Result<ColorWhen, String> {
match word {
"auto" => Ok(ColorWhen::Auto),
"always" => Ok(ColorWhen::Always),
"never" => Ok(ColorWhen::Never),
other => Err(format!(
"--color takes auto, always or never, got {other:?}"
)),
}
}
fn diff(args: &[String]) -> ExitCode {
let mut color = ColorWhen::Auto;
let mut files = Vec::new();
let mut args = args.iter();
while let Some(arg) = args.next() {
match arg.as_str() {
"-h" | "--help" => return print(&format!("{DIFF_USAGE}\n")),
"--version" => return print(&version()),
"--color" => {
let Some(word) = args.next() else {
return fail("--color needs a WHEN argument");
};
match color_when(word) {
Ok(when) => color = when,
Err(e) => return fail(&e),
}
}
other if other.starts_with("--color=") => {
match color_when(&other["--color=".len()..]) {
Ok(when) => color = when,
Err(e) => return fail(&e),
}
}
other if other.starts_with('-') && other != "-" => {
return fail(&format!(
"unknown option {other:?} (try `termlens diff --help`)"
));
}
_ => files.push(arg),
}
}
let [a, b] = files.as_slice() else {
return usage_error(DIFF_USAGE);
};
if a.as_str() == STDIN && b.as_str() == STDIN {
return fail("only one of the two screens can be `-`: stdin is read once");
}
let (before, after) = match (load(a), load(b)) {
(Ok(a), Ok(b)) => (a, b),
(Err(e), _) | (_, Err(e)) => return fail(&e),
};
let diff = before.diff(&after);
let rendered = if color.enabled() {
colored(&before, &after, &diff)
} else {
diff.to_string()
};
let code = print(&format!("{rendered}\n"));
if code != ExitCode::SUCCESS {
return code;
}
if diff.is_empty() {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
fn is_row_line(line: &str) -> bool {
let Some((number, _)) = line.split_once('│') else {
return false;
};
let Some(number) = number.strip_suffix(' ') else {
return false;
};
number.chars().any(|c| c.is_ascii_digit())
&& number.chars().all(|c| c.is_ascii_digit() || c == ' ')
}
fn colored(before: &Screen, after: &Screen, diff: &ScreenDiff) -> String {
let plain = diff.to_string();
if diff.is_empty() {
return plain;
}
let mut lines = plain.lines();
let mut out = String::new();
for line in lines.by_ref() {
if is_row_line(line) {
break;
}
if !out.is_empty() {
out.push('\n');
}
out.push_str(line);
}
let mut changed_rows: Vec<u16> = diff.cells().map(|(row, _, _, _)| row).collect();
changed_rows.dedup();
let changed: HashSet<(u16, u16)> = diff.cells().map(|(row, col, _, _)| (row, col)).collect();
for row in changed_rows {
let paint = |screen: &Screen, sgr: &str| -> String {
let mut cells: Vec<String> = Vec::new();
for col in 0..screen.cols() {
let Some(cell) = screen.cell(row, col) else {
continue;
};
if cell.is_wide_continuation() {
continue;
}
let text = if cell.contents().is_empty() {
" "
} else {
cell.contents()
};
cells.push(if changed.contains(&(row, col)) {
format!("\x1b[{sgr}m{text}\x1b[0m")
} else {
text.to_owned()
});
}
cells.concat()
};
let after_row = paint(after, "32");
let after_row = after_row.trim_end();
out.push_str(&format!("\n{row:>3} │{}│{after_row}", paint(before, "31")));
}
for line in lines.filter(|l| l.starts_with('…') || l.starts_with("styles:")) {
out.push('\n');
out.push_str(line);
}
out
}
fn render_usage_error(reason: &str) -> ExitCode {
let _ = report(&format!("termlens: {reason}\n\n{RENDER_USAGE}"));
ExitCode::from(2)
}
fn render(args: &[String]) -> ExitCode {
let mut format: Option<&str> = None;
let mut files = Vec::new();
let mut out_path: Option<&str> = None;
let mut args = args.iter();
while let Some(arg) = args.next() {
match arg.as_str() {
"-h" | "--help" => return print(&format!("{RENDER_USAGE}\n")),
"--version" => return print(&version()),
"--svg" | "--html" | "--ansi" | "--text" | "--json" => {
if let Some(first) = format {
return render_usage_error(&if first == arg {
format!("{arg} is given twice; render writes one format")
} else {
format!("{first} and {arg} are two formats; render writes one")
});
}
format = Some(arg.as_str());
}
"--out" => match args.next() {
Some(path) if path.is_empty() => return fail("--out needs a PATH argument"),
Some(path) => {
if out_path.is_some() {
return render_usage_error("--out is given twice; render writes one file");
}
out_path = Some(path.as_str());
}
None => return fail("--out needs a PATH argument"),
},
other if other.starts_with("--out=") => {
let path = &other["--out=".len()..];
if path.is_empty() {
return fail("--out needs a PATH argument");
}
if out_path.is_some() {
return render_usage_error("--out is given twice; render writes one file");
}
out_path = Some(path);
}
other if other.starts_with('-') && other != STDIN => {
return fail(&format!(
"unknown option {other:?} (try `termlens render --help`)"
));
}
_ => files.push(arg),
}
}
let (Some(format), [file]) = (format, files.as_slice()) else {
return usage_error(RENDER_USAGE);
};
let screen = match load(file) {
Ok(screen) => screen,
Err(e) => return fail(&e),
};
let out = match format {
"--svg" => screen.to_svg(),
"--html" => screen.to_html(),
"--ansi" => screen.to_ansi(),
"--json" => match serde_json::to_string_pretty(&screen) {
Ok(json) => format!("{json}\n"),
Err(e) => return fail(&format!("writing the JSON failed: {e}")),
},
_ => format!("{}\n", screen.with_styles()),
};
match out_path {
Some(STDIN) | None => print(&out),
Some(path) => match std::fs::write(path, &out) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&format!("{path}: {e}")),
},
}
}
fn take<T>(
args: &mut impl Iterator<Item = OsString>,
flag: &str,
kind: &str,
example: &str,
parse: impl Fn(&str) -> Option<T>,
) -> Result<T, String> {
let Some(raw) = args.next() else {
return Err(format!("{flag} needs a {kind} argument"));
};
let raw = utf8(raw)?;
parse(&raw).ok_or_else(|| format!("bad {flag} {raw:?}, expected e.g. {example}"))
}
fn timeout_secs(spec: &str) -> Option<Duration> {
let timeout = Duration::from_secs(spec.parse().ok()?);
Instant::now().checked_add(timeout.checked_add(Duration::from_secs(3600))?)?;
Some(timeout)
}
fn is_option(arg: &OsStr) -> bool {
arg.as_encoded_bytes().starts_with(b"-") && arg != STDIN
}
fn inspect_render(screen: &Screen, ansi: bool) -> String {
if !io::stdout().is_terminal() {
screen.with_styles().to_string()
} else if ansi {
let header = screen.to_string();
let header = header.lines().next().unwrap_or_default();
format!("{header}\n{}", screen.to_ansi())
} else {
screen.to_string()
}
}
fn shows_something(screen: &termlens::Screen) -> bool {
let (row, col, _) = screen.cursor();
(row, col) != (0, 0) || !screen.text().trim().is_empty()
}
fn inspect(args: Vec<OsString>) -> ExitCode {
let artifact_dir = std::env::var_os("TERMLENS_ARTIFACT_DIR");
std::env::remove_var("TERMLENS_ARTIFACT_DIR");
let mut args = args.into_iter().peekable();
let mut size = (80u16, 24u16);
let mut timeout = Duration::from_secs(5);
let mut idle = Duration::from_millis(300);
let mut inherit_env = false;
let mut ansi = false;
let mut env = Vec::new();
let mut cwd: Option<String> = None;
while args.peek().is_some_and(|a| is_option(a)) {
let flag = match utf8(args.next().unwrap_or_default()) {
Ok(flag) => flag,
Err(e) => return fail(&e),
};
let (name, inline) = match flag.split_once('=') {
Some((name, value))
if matches!(name, "--size" | "--timeout" | "--idle" | "--cwd" | "--env") =>
{
(name, Some(value))
}
_ => (flag.as_str(), None),
};
let mut args = inline.map(OsString::from).into_iter().chain(args.by_ref());
let parsed = match name {
"-h" | "--help" => return print(&format!("{INSPECT_USAGE}\n")),
"--version" => return print(&version()),
"--" => break,
"--size" => take(&mut args, "--size", "COLSxROWS", "120x40", |spec| {
let (c, r) = spec.split_once('x')?;
Some((c.parse().ok()?, r.parse().ok()?))
})
.map(|s| size = s),
"--timeout" => {
take(&mut args, "--timeout", "SECONDS", "30", timeout_secs).map(|t| timeout = t)
}
"--idle" => take(&mut args, "--idle", "MILLIS", "1000", |s| s.parse().ok())
.map(|millis| idle = Duration::from_millis(millis)),
"--inherit-env" => {
inherit_env = true;
Ok(())
}
"--ansi" => {
ansi = true;
Ok(())
}
"--cwd" => {
take(&mut args, "--cwd", "DIR", "/tmp", |s| Some(s.to_owned())).and_then(|dir| {
if Path::new(&dir).is_dir() {
cwd = Some(dir);
Ok(())
} else {
Err(format!("bad --cwd {dir:?}, not an existing directory"))
}
})
}
"--env" => take(&mut args, "--env", "KEY=VALUE", "NO_COLOR=1", |s| {
let (key, value) = s.split_once('=')?;
(!key.is_empty()).then(|| (key.to_owned(), value.to_owned()))
})
.map(|pair| env.push(pair)),
_ => Err(format!(
"unknown option {flag:?} (try `termlens inspect --help`)"
)),
};
if let Err(message) = parsed {
return fail(&message);
}
}
let Some(program) = args.next() else {
return usage_error(INSPECT_USAGE);
};
let mut builder = Terminal::builder()
.size(size.0, size.1)
.timeout(timeout)
.args(args);
if !inherit_env {
builder = builder.env_clear();
if let Some(path) = std::env::var_os("PATH") {
builder = builder.env("PATH", path);
}
} else if let Some(dir) = artifact_dir {
builder = builder.env("TERMLENS_ARTIFACT_DIR", dir);
}
for (key, value) in env {
builder = builder.env(key, value);
}
if let Some(dir) = cwd {
builder = builder.current_dir(dir);
}
let mut t = match builder.spawn(&program) {
Ok(t) => t,
Err(e) => return fail(&e.to_string()),
};
let still_running = "--- still running (killed on exit) ---";
let at_the_deadline = "--- still running at the deadline (killed on exit) ---";
let reap = |t: &mut termlens::Terminal| match t.wait_exit_for(REAP_GRACE) {
Ok(status) => format!("--- exited: {status} ---"),
Err(termlens::Error::Timeout { .. }) => still_running.to_owned(),
Err(e) => format!("--- waiting for the program failed: {e} ---"),
};
let deadline = Instant::now() + timeout;
let trailer = match t.wait_until_for(shows_something, timeout) {
Ok(()) => {
let remaining = deadline.saturating_duration_since(Instant::now());
match t.wait_idle_for(idle, remaining) {
Ok(()) => reap(&mut t),
Err(termlens::Error::Timeout { .. }) => at_the_deadline.to_owned(),
Err(e) => format!("--- waiting for the program failed: {e} ---"),
}
}
Err(termlens::Error::Eof { .. }) => reap(&mut t),
Err(termlens::Error::Timeout { .. }) => at_the_deadline.to_owned(),
Err(e) => format!("--- waiting for the program failed: {e} ---"),
};
let code = print(&format!("{}\n", inspect_render(&t.screen(), ansi)));
if report(&trailer).is_err() {
return ExitCode::from(2);
}
code
}