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//! ## `font-subset`
79//!
80//! *(Off by default)*
81//!
82//! Enables subsetting and embedding OpenType fonts into snapshots. Requires the `svg` feature.
83//!
84//! ## `test`
85//!
86//! *(On by default)*
87//!
88//! Exposes [the eponymous module](crate::test) that allows parsing [`Transcript`]s
89//! from SVG files and testing them.
90//!
91//! ## `pretty_assertions`
92//!
93//! *(On by default)*
94//!
95//! Uses [the eponymous crate][`pretty_assertions`] when testing SVG files.
96//! Only really makes sense together with the `test` feature.
97//!
98//! ## `tracing`
99//!
100//! *(Off by default)*
101//!
102//! Uses [the eponymous facade][`tracing`] to trace main operations, which could be useful
103//! for debugging. Tracing is mostly performed on the `DEBUG` level.
104//!
105//! [SVG]: https://developer.mozilla.org/en-US/docs/Web/SVG
106//! [SGR]: https://en.wikipedia.org/wiki/ANSI_escape_code#SGR
107//! [CSI]: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences
108//! [`isatty`]: https://man7.org/linux/man-pages/man3/isatty.3.html
109//! [Handlebars]: https://handlebarsjs.com/
110//! [`pretty_assertions`]: https://docs.rs/pretty_assertions/
111//! [`portable-pty`]: https://docs.rs/portable-pty/
112//! [`tracing`]: https://docs.rs/tracing/
113//!
114//! # Examples
115//!
116//! Creating a terminal [`Transcript`] and rendering it to SVG.
117//!
118//! ```
119//! use term_transcript::{
120//! svg::{Template, TemplateOptions}, ShellOptions, Transcript, UserInput,
121//! };
122//! # use std::str;
123//!
124//! # fn main() -> anyhow::Result<()> {
125//! let transcript = Transcript::from_inputs(
126//! &mut ShellOptions::default(),
127//! vec![UserInput::command(r#"echo "Hello world!""#)],
128//! )?;
129//! let mut writer = vec![];
130//! // ^ Any `std::io::Write` implementation will do, such as a `File`.
131//! Template::new(TemplateOptions::default()).render(&transcript, &mut writer)?;
132//! println!("{}", str::from_utf8(&writer)?);
133//! # Ok(())
134//! # }
135//! ```
136//!
137//! Snapshot testing. See the [`test` module](crate::test) for more examples.
138//!
139//! ```no_run
140//! use term_transcript::{test::TestConfig, ShellOptions};
141//!
142//! #[test]
143//! fn echo_works() {
144//! TestConfig::new(ShellOptions::default()).test(
145//! "tests/__snapshots__/echo.svg",
146//! &[r#"echo "Hello world!""#],
147//! );
148//! }
149//! ```
150
151// Documentation settings.
152#![doc(html_root_url = "https://docs.rs/term-transcript/0.4.0")]
153#![cfg_attr(docsrs, feature(doc_cfg))]
154// Linter settings.
155#![warn(missing_debug_implementations, missing_docs, bare_trait_objects)]
156#![warn(clippy::all, clippy::pedantic)]
157#![allow(clippy::must_use_candidate, clippy::module_name_repetitions)]
158
159use std::{borrow::Cow, error::Error as StdError, fmt, io, num::ParseIntError};
160
161#[cfg(feature = "portable-pty")]
162pub use self::pty::{PtyCommand, PtyShell};
163pub use self::{
164 shell::{ShellOptions, StdShell},
165 term::{Captured, TermOutput},
166};
167
168#[cfg(feature = "portable-pty")]
169mod pty;
170mod shell;
171#[cfg(feature = "svg")]
172#[cfg_attr(docsrs, doc(cfg(feature = "svg")))]
173pub mod svg;
174mod term;
175#[cfg(feature = "test")]
176#[cfg_attr(docsrs, doc(cfg(feature = "test")))]
177pub mod test;
178pub mod traits;
179mod utils;
180mod write;
181
182pub(crate) type BoxedError = Box<dyn std::error::Error + Send + Sync>;
183
184/// Errors that can occur when processing terminal output.
185#[derive(Debug)]
186#[non_exhaustive]
187pub enum TermError {
188 /// Unfinished escape sequence.
189 UnfinishedSequence,
190 /// Unrecognized escape sequence (not a CSI or OSC one). The enclosed byte
191 /// is the first byte of the sequence (excluding `0x1b`).
192 UnrecognizedSequence(u8),
193 /// Invalid final byte for an SGR escape sequence.
194 InvalidSgrFinalByte(u8),
195 /// Unfinished color spec.
196 UnfinishedColor,
197 /// Invalid type of a color spec.
198 InvalidColorType(String),
199 /// Invalid ANSI color index.
200 InvalidColorIndex(ParseIntError),
201 /// IO error.
202 Io(io::Error),
203 /// Font embedding error.
204 FontEmbedding(BoxedError),
205}
206
207impl fmt::Display for TermError {
208 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
209 match self {
210 Self::UnfinishedSequence => formatter.write_str("Unfinished ANSI escape sequence"),
211 Self::UnrecognizedSequence(byte) => {
212 write!(
213 formatter,
214 "Unrecognized escape sequence (first byte is {byte})"
215 )
216 }
217 Self::InvalidSgrFinalByte(byte) => {
218 write!(
219 formatter,
220 "Invalid final byte for an SGR escape sequence: {byte}"
221 )
222 }
223 Self::UnfinishedColor => formatter.write_str("Unfinished color spec"),
224 Self::InvalidColorType(ty) => {
225 write!(formatter, "Invalid type of a color spec: {ty}")
226 }
227 Self::InvalidColorIndex(err) => {
228 write!(formatter, "Failed parsing color index: {err}")
229 }
230 Self::Io(err) => write!(formatter, "I/O error: {err}"),
231 Self::FontEmbedding(err) => write!(formatter, "font embedding error: {err}"),
232 }
233 }
234}
235
236impl StdError for TermError {
237 fn source(&self) -> Option<&(dyn StdError + 'static)> {
238 match self {
239 Self::InvalidColorIndex(err) => Some(err),
240 Self::Io(err) => Some(err),
241 _ => None,
242 }
243 }
244}
245
246/// Transcript of a user interacting with the terminal.
247#[derive(Debug, Clone)]
248pub struct Transcript<Out: TermOutput = Captured> {
249 interactions: Vec<Interaction<Out>>,
250}
251
252impl<Out: TermOutput> Default for Transcript<Out> {
253 fn default() -> Self {
254 Self {
255 interactions: vec![],
256 }
257 }
258}
259
260impl<Out: TermOutput> Transcript<Out> {
261 /// Creates an empty transcript.
262 pub fn new() -> Self {
263 Self::default()
264 }
265
266 /// Returns interactions in this transcript.
267 pub fn interactions(&self) -> &[Interaction<Out>] {
268 &self.interactions
269 }
270
271 /// Returns a mutable reference to interactions in this transcript.
272 pub fn interactions_mut(&mut self) -> &mut [Interaction<Out>] {
273 &mut self.interactions
274 }
275}
276
277impl Transcript {
278 /// Manually adds a new interaction to the end of this transcript.
279 ///
280 /// This method allows capturing interactions that are difficult or impossible to capture
281 /// using more high-level methods: [`Self::from_inputs()`] or [`Self::capture_output()`].
282 /// The resulting transcript will [render](svg) just fine, but there could be issues
283 /// with [testing](crate::test) it.
284 pub fn add_existing_interaction(&mut self, interaction: Interaction) -> &mut Self {
285 self.interactions.push(interaction);
286 self
287 }
288
289 /// Manually adds a new interaction to the end of this transcript.
290 ///
291 /// This is a shortcut for calling [`Self::add_existing_interaction()`].
292 pub fn add_interaction(
293 &mut self,
294 input: impl Into<UserInput>,
295 output: impl Into<String>,
296 ) -> &mut Self {
297 self.add_existing_interaction(Interaction::new(input, output))
298 }
299}
300
301/// Portable, platform-independent version of [`ExitStatus`] from the standard library.
302///
303/// # Capturing `ExitStatus`
304///
305/// Some shells have means to check whether the input command was executed successfully.
306/// For example, in `sh`-like shells, one can compare the value of `$?` to 0, and
307/// in PowerShell to `True`. The exit status can be captured when creating a [`Transcript`]
308/// by setting a *checker* in [`ShellOptions::with_status_check()`]:
309///
310/// # Examples
311///
312/// ```
313/// # use term_transcript::{ExitStatus, ShellOptions, Transcript, UserInput};
314/// # fn test_wrapper() -> anyhow::Result<()> {
315/// let options = ShellOptions::default();
316/// let mut options = options.with_status_check("echo $?", |captured| {
317/// // Parse captured string to plain text. This transform
318/// // is especially important in transcripts captured from PTY
319/// // since they can contain a *wild* amount of escape sequences.
320/// let captured = captured.to_plaintext().ok()?;
321/// let code: i32 = captured.trim().parse().ok()?;
322/// Some(ExitStatus(code))
323/// });
324///
325/// let transcript = Transcript::from_inputs(&mut options, [
326/// UserInput::command("echo \"Hello world\""),
327/// UserInput::command("some-non-existing-command"),
328/// ])?;
329/// let status = transcript.interactions()[0].exit_status();
330/// assert!(status.unwrap().is_success());
331/// // The assertion above is equivalent to:
332/// assert_eq!(status, Some(ExitStatus(0)));
333///
334/// let status = transcript.interactions()[1].exit_status();
335/// assert!(!status.unwrap().is_success());
336/// # Ok(())
337/// # }
338/// # // We can compile test in any case, but it successfully executes only on *nix.
339/// # #[cfg(unix)] fn main() { test_wrapper().unwrap() }
340/// # #[cfg(not(unix))] fn main() { }
341/// ```
342#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
343pub struct ExitStatus(pub i32);
344
345impl ExitStatus {
346 /// Checks if this is the successful status.
347 pub fn is_success(self) -> bool {
348 self.0 == 0
349 }
350}
351
352/// One-time interaction with the terminal.
353#[derive(Debug, Clone)]
354pub struct Interaction<Out: TermOutput = Captured> {
355 input: UserInput,
356 output: Out,
357 exit_status: Option<ExitStatus>,
358}
359
360impl Interaction {
361 /// Creates a new interaction.
362 pub fn new(input: impl Into<UserInput>, output: impl Into<String>) -> Self {
363 Self {
364 input: input.into(),
365 output: Captured::from(output.into()),
366 exit_status: None,
367 }
368 }
369
370 /// Sets an exit status for this interaction.
371 pub fn set_exit_status(&mut self, exit_status: Option<ExitStatus>) {
372 self.exit_status = exit_status;
373 }
374
375 /// Assigns an exit status to this interaction.
376 #[must_use]
377 pub fn with_exit_status(mut self, exit_status: ExitStatus) -> Self {
378 self.exit_status = Some(exit_status);
379 self
380 }
381}
382
383impl<Out: TermOutput> Interaction<Out> {
384 /// Input provided by the user.
385 pub fn input(&self) -> &UserInput {
386 &self.input
387 }
388
389 /// Output to the terminal.
390 pub fn output(&self) -> &Out {
391 &self.output
392 }
393
394 /// Sets the output for this interaction.
395 pub fn set_output(&mut self, output: Out) {
396 self.output = output;
397 }
398
399 /// Returns exit status of the interaction, if available.
400 pub fn exit_status(&self) -> Option<ExitStatus> {
401 self.exit_status
402 }
403}
404
405/// User input during interaction with a terminal.
406#[derive(Debug, Clone, PartialEq, Eq)]
407#[cfg_attr(feature = "svg", derive(serde::Serialize))]
408pub struct UserInput {
409 text: String,
410 prompt: Option<Cow<'static, str>>,
411 hidden: bool,
412}
413
414impl UserInput {
415 #[cfg(feature = "test")]
416 pub(crate) fn intern_prompt(prompt: String) -> Cow<'static, str> {
417 match prompt.as_str() {
418 "$" => Cow::Borrowed("$"),
419 ">>>" => Cow::Borrowed(">>>"),
420 "..." => Cow::Borrowed("..."),
421 _ => Cow::Owned(prompt),
422 }
423 }
424
425 /// Creates a command input.
426 pub fn command(text: impl Into<String>) -> Self {
427 Self {
428 text: text.into(),
429 prompt: Some(Cow::Borrowed("$")),
430 hidden: false,
431 }
432 }
433
434 /// Creates a standalone / starting REPL command input with the `>>>` prompt.
435 pub fn repl(text: impl Into<String>) -> Self {
436 Self {
437 text: text.into(),
438 prompt: Some(Cow::Borrowed(">>>")),
439 hidden: false,
440 }
441 }
442
443 /// Creates a REPL command continuation input with the `...` prompt.
444 pub fn repl_continuation(text: impl Into<String>) -> Self {
445 Self {
446 text: text.into(),
447 prompt: Some(Cow::Borrowed("...")),
448 hidden: false,
449 }
450 }
451
452 /// Returns the prompt part of this input.
453 pub fn prompt(&self) -> Option<&str> {
454 self.prompt.as_deref()
455 }
456
457 /// Marks this input as hidden (one that should not be displayed in the rendered transcript).
458 #[must_use]
459 pub fn hide(mut self) -> Self {
460 self.hidden = true;
461 self
462 }
463}
464
465/// Returns the command part of the input without the prompt.
466impl AsRef<str> for UserInput {
467 fn as_ref(&self) -> &str {
468 &self.text
469 }
470}
471
472/// Calls [`Self::command()`] on the provided string reference.
473impl From<&str> for UserInput {
474 fn from(command: &str) -> Self {
475 Self::command(command)
476 }
477}
478
479#[cfg(doctest)]
480doc_comment::doctest!("../README.md");