term_transcript/lib.rs
1//! Snapshot testing for CLI / REPL applications, in a fun way.
2//!
3//! # What it does
4//!
5//! This crate allows to:
6//!
7//! - Create [`Transcript`]s of interacting with a terminal, capturing both the output text
8//! and [ANSI-compatible color info][SGR].
9//! - Save these transcripts in the [SVG] format, so that they can be easily embedded as images
10//! into HTML / Markdown documents. (Output format customization
11//! [is also supported](svg::Template#customization) via [Handlebars] templates.)
12//! - Parse transcripts from SVG
13//! - Test that a parsed transcript actually corresponds to the terminal output (either as text
14//! or text + colors).
15//!
16//! The primary use case is easy to create and maintain end-to-end tests for CLI / REPL apps.
17//! Such tests can be embedded into a readme file.
18//!
19//! # Design decisions
20//!
21//! - **Static capturing.** Capturing dynamic interaction with the terminal essentially
22//! requires writing / hacking together a new terminal, which looks like an overkill
23//! for the motivating use case (snapshot testing).
24//!
25//! - **(Primarily) static SVGs.** Animated SVGs create visual noise and make simple things
26//! (e.g., copying text from an SVG) harder than they should be.
27//!
28//! - **Self-contained tests.** Unlike generic snapshot files, [`Transcript`]s contain
29//! both user inputs and outputs. This allows using them as images with little additional
30//! explanation.
31//!
32//! # Limitations
33//!
34//! - Terminal coloring only works with ANSI escape codes. (Since ANSI escape codes
35//! are supported even on Windows nowadays, this shouldn't be a significant problem.)
36//! - ANSI escape sequences other than [SGR] ones are either dropped (in case of [CSI]
37//! and OSC sequences), or lead to [`TermError::UnrecognizedSequence`].
38//! - By default, the crate exposes APIs to perform capture via OS pipes.
39//! Since the terminal is not emulated in this case, programs dependent on [`isatty`] checks
40//! or getting term size can produce different output than if launched in an actual shell
41//! (no coloring, no line wrapping etc.).
42//! - It is possible to capture output from a pseudo-terminal (PTY) using the `portable-pty`
43//! crate feature. However, since most escape sequences are dropped, this is still not a good
44//! option to capture complex outputs (e.g., ones moving cursor).
45//!
46//! # Alternatives / similar tools
47//!
48//! - [`insta`](https://crates.io/crates/insta) is a generic snapshot testing library, which
49//! is amazing in general, but *kind of* too low-level for E2E CLI testing.
50//! - [`rexpect`](https://crates.io/crates/rexpect) allows testing CLI / REPL applications
51//! by scripting interactions with them in tests. It works in Unix only.
52//! - [`trybuild`](https://crates.io/crates/trybuild) snapshot-tests output
53//! of a particular program (the Rust compiler).
54//! - [`trycmd`](https://crates.io/crates/trycmd) snapshot-tests CLI apps using
55//! a text-based format.
56//! - Tools like [`termtosvg`](https://github.com/nbedos/termtosvg) and
57//! [Asciinema](https://asciinema.org/) allow recording terminal sessions and save them to SVG.
58//! The output of these tools is inherently *dynamic* (which, e.g., results in animated SVGs).
59//! This crate [intentionally chooses](#design-decisions) a simpler static format, which
60//! makes snapshot testing easier.
61//!
62//! # Crate features
63//!
64//! ## `portable-pty`
65//!
66//! *(Off by default)*
67//!
68//! Allows using pseudo-terminal (PTY) to capture terminal output rather than pipes.
69//! Uses [the eponymous crate][`portable-pty`] under the hood.
70//!
71//! ## `svg`
72//!
73//! *(On by default)*
74//!
75//! Exposes [the eponymous module](svg) that allows rendering [`Transcript`]s
76//! into the SVG format.
77//!
78//! ## `test`
79//!
80//! *(On by default)*
81//!
82//! Exposes [the eponymous module](crate::test) that allows parsing [`Transcript`]s
83//! from SVG files and testing them.
84//!
85//! ## `pretty_assertions`
86//!
87//! *(On by default)*
88//!
89//! Uses [the eponymous crate][`pretty_assertions`] when testing SVG files.
90//! Only really makes sense together with the `test` feature.
91//!
92//! ## `tracing`
93//!
94//! *(Off by default)*
95//!
96//! Uses [the eponymous facade][`tracing`] to trace main operations, which could be useful
97//! for debugging. Tracing is mostly performed on the `DEBUG` level.
98//!
99//! [SVG]: https://developer.mozilla.org/en-US/docs/Web/SVG
100//! [SGR]: https://en.wikipedia.org/wiki/ANSI_escape_code#SGR
101//! [CSI]: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences
102//! [`isatty`]: https://man7.org/linux/man-pages/man3/isatty.3.html
103//! [Handlebars]: https://handlebarsjs.com/
104//! [`pretty_assertions`]: https://docs.rs/pretty_assertions/
105//! [`portable-pty`]: https://docs.rs/portable-pty/
106//! [`tracing`]: https://docs.rs/tracing/
107//!
108//! # Examples
109//!
110//! Creating a terminal [`Transcript`] and rendering it to SVG.
111//!
112//! ```
113//! use term_transcript::{
114//! svg::{Template, TemplateOptions}, ShellOptions, Transcript, UserInput,
115//! };
116//! # use std::str;
117//!
118//! # fn main() -> anyhow::Result<()> {
119//! let transcript = Transcript::from_inputs(
120//! &mut ShellOptions::default(),
121//! vec![UserInput::command(r#"echo "Hello world!""#)],
122//! )?;
123//! let mut writer = vec![];
124//! // ^ Any `std::io::Write` implementation will do, such as a `File`.
125//! Template::new(TemplateOptions::default()).render(&transcript, &mut writer)?;
126//! println!("{}", str::from_utf8(&writer)?);
127//! # Ok(())
128//! # }
129//! ```
130//!
131//! Snapshot testing. See the [`test` module](crate::test) for more examples.
132//!
133//! ```
134//! use term_transcript::{test::TestConfig, ShellOptions};
135//!
136//! #[test]
137//! fn echo_works() {
138//! TestConfig::new(ShellOptions::default()).test(
139//! "tests/__snapshots__/echo.svg",
140//! &[r#"echo "Hello world!""#],
141//! );
142//! }
143//! ```
144
145// Documentation settings.
146#![doc(html_root_url = "https://docs.rs/term-transcript/0.3.0")]
147#![cfg_attr(docsrs, feature(doc_cfg))]
148// Linter settings.
149#![warn(missing_debug_implementations, missing_docs, bare_trait_objects)]
150#![warn(clippy::all, clippy::pedantic)]
151#![allow(clippy::must_use_candidate, clippy::module_name_repetitions)]
152
153use std::{borrow::Cow, error::Error as StdError, fmt, io, num::ParseIntError};
154
155#[cfg(feature = "portable-pty")]
156mod pty;
157mod shell;
158#[cfg(feature = "svg")]
159#[cfg_attr(docsrs, doc(cfg(feature = "svg")))]
160pub mod svg;
161mod term;
162#[cfg(feature = "test")]
163#[cfg_attr(docsrs, doc(cfg(feature = "test")))]
164pub mod test;
165pub mod traits;
166mod utils;
167mod write;
168
169#[cfg(feature = "portable-pty")]
170pub use self::pty::{PtyCommand, PtyShell};
171pub use self::{
172 shell::{ShellOptions, StdShell},
173 term::{Captured, TermOutput},
174};
175
176/// Errors that can occur when processing terminal output.
177#[derive(Debug)]
178#[non_exhaustive]
179pub enum TermError {
180 /// Unfinished escape sequence.
181 UnfinishedSequence,
182 /// Unrecognized escape sequence (not a CSI or OSC one). The enclosed byte
183 /// is the first byte of the sequence (excluding `0x1b`).
184 UnrecognizedSequence(u8),
185 /// Invalid final byte for an SGR escape sequence.
186 InvalidSgrFinalByte(u8),
187 /// Unfinished color spec.
188 UnfinishedColor,
189 /// Invalid type of a color spec.
190 InvalidColorType(String),
191 /// Invalid ANSI color index.
192 InvalidColorIndex(ParseIntError),
193 /// IO error.
194 Io(io::Error),
195}
196
197impl fmt::Display for TermError {
198 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
199 match self {
200 Self::UnfinishedSequence => formatter.write_str("Unfinished ANSI escape sequence"),
201 Self::UnrecognizedSequence(byte) => {
202 write!(
203 formatter,
204 "Unrecognized escape sequence (first byte is {byte})"
205 )
206 }
207 Self::InvalidSgrFinalByte(byte) => {
208 write!(
209 formatter,
210 "Invalid final byte for an SGR escape sequence: {byte}"
211 )
212 }
213 Self::UnfinishedColor => formatter.write_str("Unfinished color spec"),
214 Self::InvalidColorType(ty) => {
215 write!(formatter, "Invalid type of a color spec: {ty}")
216 }
217 Self::InvalidColorIndex(err) => {
218 write!(formatter, "Failed parsing color index: {err}")
219 }
220 Self::Io(err) => write!(formatter, "I/O error: {err}"),
221 }
222 }
223}
224
225impl StdError for TermError {
226 fn source(&self) -> Option<&(dyn StdError + 'static)> {
227 match self {
228 Self::InvalidColorIndex(err) => Some(err),
229 Self::Io(err) => Some(err),
230 _ => None,
231 }
232 }
233}
234
235/// Transcript of a user interacting with the terminal.
236#[derive(Debug, Clone)]
237pub struct Transcript<Out: TermOutput = Captured> {
238 interactions: Vec<Interaction<Out>>,
239}
240
241impl<Out: TermOutput> Default for Transcript<Out> {
242 fn default() -> Self {
243 Self {
244 interactions: vec![],
245 }
246 }
247}
248
249impl<Out: TermOutput> Transcript<Out> {
250 /// Creates an empty transcript.
251 pub fn new() -> Self {
252 Self::default()
253 }
254
255 /// Returns interactions in this transcript.
256 pub fn interactions(&self) -> &[Interaction<Out>] {
257 &self.interactions
258 }
259}
260
261impl Transcript {
262 /// Manually adds a new interaction to the end of this transcript.
263 ///
264 /// This method allows capturing interactions that are difficult or impossible to capture
265 /// using more high-level methods: [`Self::from_inputs()`] or [`Self::capture_output()`].
266 /// The resulting transcript will [render](svg) just fine, but there could be issues
267 /// with [testing](crate::test) it.
268 pub fn add_existing_interaction(&mut self, interaction: Interaction) -> &mut Self {
269 self.interactions.push(interaction);
270 self
271 }
272
273 /// Manually adds a new interaction to the end of this transcript.
274 ///
275 /// This is a shortcut for calling [`Self::add_existing_interaction(_)`].
276 pub fn add_interaction(
277 &mut self,
278 input: impl Into<UserInput>,
279 output: impl Into<String>,
280 ) -> &mut Self {
281 self.add_existing_interaction(Interaction::new(input, output))
282 }
283}
284
285/// Portable, platform-independent version of [`ExitStatus`] from the standard library.
286///
287/// # Capturing `ExitStatus`
288///
289/// Some shells have means to check whether the input command was executed successfully.
290/// For example, in `sh`-like shells, one can compare the value of `$?` to 0, and
291/// in PowerShell to `True`. The exit status can be captured when creating a [`Transcript`]
292/// by setting a *checker* in [`ShellOptions::with_status_check()`]:
293///
294/// # Examples
295///
296/// ```
297/// # use term_transcript::{ExitStatus, ShellOptions, Transcript, UserInput};
298/// # fn test_wrapper() -> anyhow::Result<()> {
299/// let options = ShellOptions::default();
300/// let mut options = options.with_status_check("echo $?", |captured| {
301/// // Parse captured string to plain text. This transform
302/// // is especially important in transcripts captured from PTY
303/// // since they can contain a *wild* amount of escape sequences.
304/// let captured = captured.to_plaintext().ok()?;
305/// let code: i32 = captured.trim().parse().ok()?;
306/// Some(ExitStatus(code))
307/// });
308///
309/// let transcript = Transcript::from_inputs(&mut options, [
310/// UserInput::command("echo \"Hello world\""),
311/// UserInput::command("some-non-existing-command"),
312/// ])?;
313/// let status = transcript.interactions()[0].exit_status();
314/// assert!(status.unwrap().is_success());
315/// // The assertion above is equivalent to:
316/// assert_eq!(status, Some(ExitStatus(0)));
317///
318/// let status = transcript.interactions()[1].exit_status();
319/// assert!(!status.unwrap().is_success());
320/// # Ok(())
321/// # }
322/// # // We can compile test in any case, but it successfully executes only on *nix.
323/// # #[cfg(unix)] fn main() { test_wrapper().unwrap() }
324/// # #[cfg(not(unix))] fn main() { }
325/// ```
326#[allow(clippy::doc_markdown)] // false positive on "PowerShell"
327#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
328pub struct ExitStatus(pub i32);
329
330impl ExitStatus {
331 /// Checks if this is the successful status.
332 pub fn is_success(self) -> bool {
333 self.0 == 0
334 }
335}
336
337/// One-time interaction with the terminal.
338#[derive(Debug, Clone)]
339pub struct Interaction<Out: TermOutput = Captured> {
340 input: UserInput,
341 output: Out,
342 exit_status: Option<ExitStatus>,
343}
344
345impl Interaction {
346 /// Creates a new interaction.
347 pub fn new(input: impl Into<UserInput>, output: impl Into<String>) -> Self {
348 Self {
349 input: input.into(),
350 output: Captured::new(output.into()),
351 exit_status: None,
352 }
353 }
354
355 /// Assigns an exit status to this interaction.
356 #[must_use]
357 pub fn with_exit_status(mut self, exit_status: ExitStatus) -> Self {
358 self.exit_status = Some(exit_status);
359 self
360 }
361}
362
363impl<Out: TermOutput> Interaction<Out> {
364 /// Input provided by the user.
365 pub fn input(&self) -> &UserInput {
366 &self.input
367 }
368
369 /// Output to the terminal.
370 pub fn output(&self) -> &Out {
371 &self.output
372 }
373
374 /// Returns exit status of the interaction, if available.
375 pub fn exit_status(&self) -> Option<ExitStatus> {
376 self.exit_status
377 }
378}
379
380/// User input during interaction with a terminal.
381#[derive(Debug, Clone, PartialEq, Eq)]
382#[cfg_attr(feature = "svg", derive(serde::Serialize))]
383pub struct UserInput {
384 text: String,
385 prompt: Option<Cow<'static, str>>,
386 hidden: bool,
387}
388
389impl UserInput {
390 #[cfg(feature = "test")]
391 pub(crate) fn intern_prompt(prompt: String) -> Cow<'static, str> {
392 match prompt.as_str() {
393 "$" => Cow::Borrowed("$"),
394 ">>>" => Cow::Borrowed(">>>"),
395 "..." => Cow::Borrowed("..."),
396 _ => Cow::Owned(prompt),
397 }
398 }
399
400 /// Creates a command input.
401 pub fn command(text: impl Into<String>) -> Self {
402 Self {
403 text: text.into(),
404 prompt: Some(Cow::Borrowed("$")),
405 hidden: false,
406 }
407 }
408
409 /// Creates a standalone / starting REPL command input with the `>>>` prompt.
410 pub fn repl(text: impl Into<String>) -> Self {
411 Self {
412 text: text.into(),
413 prompt: Some(Cow::Borrowed(">>>")),
414 hidden: false,
415 }
416 }
417
418 /// Creates a REPL command continuation input with the `...` prompt.
419 pub fn repl_continuation(text: impl Into<String>) -> Self {
420 Self {
421 text: text.into(),
422 prompt: Some(Cow::Borrowed("...")),
423 hidden: false,
424 }
425 }
426
427 /// Returns the prompt part of this input.
428 pub fn prompt(&self) -> Option<&str> {
429 self.prompt.as_deref()
430 }
431
432 /// Marks this input as hidden (one that should not be displayed in the rendered transcript).
433 #[must_use]
434 pub fn hide(mut self) -> Self {
435 self.hidden = true;
436 self
437 }
438}
439
440/// Returns the command part of the input without the prompt.
441impl AsRef<str> for UserInput {
442 fn as_ref(&self) -> &str {
443 &self.text
444 }
445}
446
447/// Calls [`Self::command()`] on the provided string reference.
448impl From<&str> for UserInput {
449 fn from(command: &str) -> Self {
450 Self::command(command)
451 }
452}
453
454#[cfg(doctest)]
455doc_comment::doctest!("../README.md");