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::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
155use std::{borrow::Cow, error::Error as StdError, fmt, io, num::ParseIntError};
156
157#[cfg(feature = "portable-pty")]
158pub use self::pty::{PtyCommand, PtyShell};
159pub use self::{
160    shell::{ShellOptions, StdShell},
161    term::{Captured, TermOutput},
162};
163
164#[cfg(feature = "portable-pty")]
165mod pty;
166mod shell;
167#[cfg(feature = "svg")]
168#[cfg_attr(docsrs, doc(cfg(feature = "svg")))]
169pub mod svg;
170mod term;
171#[cfg(feature = "test")]
172#[cfg_attr(docsrs, doc(cfg(feature = "test")))]
173pub mod test;
174pub mod traits;
175mod utils;
176
177pub(crate) type BoxedError = Box<dyn std::error::Error + Send + Sync>;
178
179/// Errors that can occur when processing terminal output.
180#[derive(Debug)]
181#[non_exhaustive]
182pub enum TermError {
183    /// Unfinished escape sequence.
184    UnfinishedSequence,
185    /// Unrecognized escape sequence (not a CSI or OSC one). The enclosed byte
186    /// is the first byte of the sequence (excluding `0x1b`).
187    UnrecognizedSequence(u8),
188    /// Invalid final byte for an SGR escape sequence.
189    InvalidSgrFinalByte(u8),
190    /// Unfinished color spec.
191    UnfinishedColor,
192    /// Invalid type of a color spec.
193    InvalidColorType(String),
194    /// Invalid ANSI color index.
195    InvalidColorIndex(ParseIntError),
196    /// IO error.
197    Io(io::Error),
198    /// Font embedding error.
199    FontEmbedding(BoxedError),
200}
201
202impl fmt::Display for TermError {
203    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204        match self {
205            Self::UnfinishedSequence => formatter.write_str("Unfinished ANSI escape sequence"),
206            Self::UnrecognizedSequence(byte) => {
207                write!(
208                    formatter,
209                    "Unrecognized escape sequence (first byte is {byte})"
210                )
211            }
212            Self::InvalidSgrFinalByte(byte) => {
213                write!(
214                    formatter,
215                    "Invalid final byte for an SGR escape sequence: {byte}"
216                )
217            }
218            Self::UnfinishedColor => formatter.write_str("Unfinished color spec"),
219            Self::InvalidColorType(ty) => {
220                write!(formatter, "Invalid type of a color spec: {ty}")
221            }
222            Self::InvalidColorIndex(err) => {
223                write!(formatter, "Failed parsing color index: {err}")
224            }
225            Self::Io(err) => write!(formatter, "I/O error: {err}"),
226            Self::FontEmbedding(err) => write!(formatter, "font embedding error: {err}"),
227        }
228    }
229}
230
231impl StdError for TermError {
232    fn source(&self) -> Option<&(dyn StdError + 'static)> {
233        match self {
234            Self::InvalidColorIndex(err) => Some(err),
235            Self::Io(err) => Some(err),
236            _ => None,
237        }
238    }
239}
240
241/// Transcript of a user interacting with the terminal.
242#[derive(Debug, Clone)]
243pub struct Transcript<Out: TermOutput = Captured> {
244    interactions: Vec<Interaction<Out>>,
245}
246
247impl<Out: TermOutput> Default for Transcript<Out> {
248    fn default() -> Self {
249        Self {
250            interactions: vec![],
251        }
252    }
253}
254
255impl<Out: TermOutput> Transcript<Out> {
256    /// Creates an empty transcript.
257    pub fn new() -> Self {
258        Self::default()
259    }
260
261    /// Returns interactions in this transcript.
262    pub fn interactions(&self) -> &[Interaction<Out>] {
263        &self.interactions
264    }
265
266    /// Returns a mutable reference to interactions in this transcript.
267    pub fn interactions_mut(&mut self) -> &mut [Interaction<Out>] {
268        &mut self.interactions
269    }
270}
271
272impl Transcript {
273    /// Manually adds a new interaction to the end of this transcript.
274    ///
275    /// This method allows capturing interactions that are difficult or impossible to capture
276    /// using more high-level methods: [`Self::from_inputs()`] or [`Self::capture_output()`].
277    /// The resulting transcript will [render](svg) just fine, but there could be issues
278    /// with [testing](crate::test) it.
279    pub fn add_existing_interaction(&mut self, interaction: Interaction) -> &mut Self {
280        self.interactions.push(interaction);
281        self
282    }
283
284    /// Manually adds a new interaction to the end of this transcript.
285    ///
286    /// This is a shortcut for calling [`Self::add_existing_interaction()`].
287    pub fn add_interaction(
288        &mut self,
289        input: impl Into<UserInput>,
290        output: impl Into<String>,
291    ) -> &mut Self {
292        self.add_existing_interaction(Interaction::new(input, output))
293    }
294}
295
296/// Portable, platform-independent version of [`ExitStatus`] from the standard library.
297///
298/// # Capturing `ExitStatus`
299///
300/// Some shells have means to check whether the input command was executed successfully.
301/// For example, in `sh`-like shells, one can compare the value of `$?` to 0, and
302/// in PowerShell to `True`. The exit status can be captured when creating a [`Transcript`]
303/// by setting a *checker* in [`ShellOptions::with_status_check()`]:
304///
305/// # Examples
306///
307/// ```
308/// # use term_transcript::{ExitStatus, ShellOptions, Transcript, UserInput};
309/// # fn test_wrapper() -> anyhow::Result<()> {
310/// let options = ShellOptions::default();
311/// let mut options = options.with_status_check("echo $?", |captured| {
312///     // Parse captured string to plain text. This transform
313///     // is especially important in transcripts captured from PTY
314///     // since they can contain a *wild* amount of escape sequences.
315///     let captured = captured.to_plaintext().ok()?;
316///     let code: i32 = captured.trim().parse().ok()?;
317///     Some(ExitStatus(code))
318/// });
319///
320/// let transcript = Transcript::from_inputs(&mut options, [
321///     UserInput::command("echo \"Hello world\""),
322///     UserInput::command("some-non-existing-command"),
323/// ])?;
324/// let status = transcript.interactions()[0].exit_status();
325/// assert!(status.unwrap().is_success());
326/// // The assertion above is equivalent to:
327/// assert_eq!(status, Some(ExitStatus(0)));
328///
329/// let status = transcript.interactions()[1].exit_status();
330/// assert!(!status.unwrap().is_success());
331/// # Ok(())
332/// # }
333/// # // We can compile test in any case, but it successfully executes only on *nix.
334/// # #[cfg(unix)] fn main() { test_wrapper().unwrap() }
335/// # #[cfg(not(unix))] fn main() { }
336/// ```
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
338pub struct ExitStatus(pub i32);
339
340impl ExitStatus {
341    /// Checks if this is the successful status.
342    pub fn is_success(self) -> bool {
343        self.0 == 0
344    }
345}
346
347/// One-time interaction with the terminal.
348#[derive(Debug, Clone)]
349pub struct Interaction<Out: TermOutput = Captured> {
350    input: UserInput,
351    output: Out,
352    exit_status: Option<ExitStatus>,
353}
354
355impl Interaction {
356    /// Creates a new interaction.
357    pub fn new(input: impl Into<UserInput>, output: impl Into<String>) -> Self {
358        Self {
359            input: input.into(),
360            output: Captured::from(output.into()),
361            exit_status: None,
362        }
363    }
364
365    /// Sets an exit status for this interaction.
366    pub fn set_exit_status(&mut self, exit_status: Option<ExitStatus>) {
367        self.exit_status = exit_status;
368    }
369
370    /// Assigns an exit status to this interaction.
371    #[must_use]
372    pub fn with_exit_status(mut self, exit_status: ExitStatus) -> Self {
373        self.exit_status = Some(exit_status);
374        self
375    }
376}
377
378impl<Out: TermOutput> Interaction<Out> {
379    /// Input provided by the user.
380    pub fn input(&self) -> &UserInput {
381        &self.input
382    }
383
384    /// Output to the terminal.
385    pub fn output(&self) -> &Out {
386        &self.output
387    }
388
389    /// Sets the output for this interaction.
390    pub fn set_output(&mut self, output: Out) {
391        self.output = output;
392    }
393
394    /// Returns exit status of the interaction, if available.
395    pub fn exit_status(&self) -> Option<ExitStatus> {
396        self.exit_status
397    }
398}
399
400/// User input during interaction with a terminal.
401#[derive(Debug, Clone, PartialEq, Eq)]
402#[cfg_attr(feature = "svg", derive(serde::Serialize))]
403pub struct UserInput {
404    text: String,
405    prompt: Option<Cow<'static, str>>,
406    hidden: bool,
407}
408
409impl UserInput {
410    #[cfg(feature = "test")]
411    pub(crate) fn intern_prompt(prompt: String) -> Cow<'static, str> {
412        match prompt.as_str() {
413            "$" => Cow::Borrowed("$"),
414            ">>>" => Cow::Borrowed(">>>"),
415            "..." => Cow::Borrowed("..."),
416            _ => Cow::Owned(prompt),
417        }
418    }
419
420    /// Creates a command input.
421    pub fn command(text: impl Into<String>) -> Self {
422        Self {
423            text: text.into(),
424            prompt: Some(Cow::Borrowed("$")),
425            hidden: false,
426        }
427    }
428
429    /// Creates a standalone / starting REPL command input with the `>>>` prompt.
430    pub fn repl(text: impl Into<String>) -> Self {
431        Self {
432            text: text.into(),
433            prompt: Some(Cow::Borrowed(">>>")),
434            hidden: false,
435        }
436    }
437
438    /// Creates a REPL command continuation input with the `...` prompt.
439    pub fn repl_continuation(text: impl Into<String>) -> Self {
440        Self {
441            text: text.into(),
442            prompt: Some(Cow::Borrowed("...")),
443            hidden: false,
444        }
445    }
446
447    /// Returns the prompt part of this input.
448    pub fn prompt(&self) -> Option<&str> {
449        self.prompt.as_deref()
450    }
451
452    /// Marks this input as hidden (one that should not be displayed in the rendered transcript).
453    #[must_use]
454    pub fn hide(mut self) -> Self {
455        self.hidden = true;
456        self
457    }
458}
459
460/// Returns the command part of the input without the prompt.
461impl AsRef<str> for UserInput {
462    fn as_ref(&self) -> &str {
463        &self.text
464    }
465}
466
467/// Calls [`Self::command()`] on the provided string reference.
468impl From<&str> for UserInput {
469    fn from(command: &str) -> Self {
470        Self::command(command)
471    }
472}
473
474#[cfg(doctest)]
475doc_comment::doctest!("../README.md");