strip_ansi_escapes/
lib.rs

1//! A crate for stripping ANSI escape sequences from byte sequences.
2//!
3//! This can be used to take output from a program that includes escape sequences and write
4//! it somewhere that does not easily support them, such as a log file.
5//!
6//! The simplest interface provided is the [`strip`] function, which takes a byte slice and returns
7//! a `Vec` of bytes with escape sequences removed. For writing bytes directly to a writer, you
8//! may prefer using the [`Writer`] struct, which implements `Write` and strips escape sequences
9//! as they are written.
10//!
11//! [`strip`]: fn.strip.html
12//! [`Writer`]: struct.Writer.html
13//!
14//! # Example
15//!
16//! ```
17//! use std::io::{self, Write};
18//!
19//! # fn foo() -> io::Result<()> {
20//! let bytes_with_colors = b"\x1b[32mfoo\x1b[m bar";
21//! let plain_bytes = strip_ansi_escapes::strip(&bytes_with_colors);
22//! io::stdout().write_all(&plain_bytes)?;
23//! # Ok(())
24//! # }
25//! ```
26
27extern crate vte;
28
29use std::io::{self, IntoInnerError, LineWriter, Write};
30use vte::{Parser, Perform};
31
32/// `Writer` wraps an underlying type that implements `Write`, stripping ANSI escape sequences
33/// from bytes written to it before passing them to the underlying writer.
34///
35/// # Example
36/// ```
37/// use std::io::{self, Write};
38/// use strip_ansi_escapes::Writer;
39///
40/// # fn foo() -> io::Result<()> {
41/// let bytes_with_colors = b"\x1b[32mfoo\x1b[m bar";
42/// let mut writer = Writer::new(io::stdout());
43/// // Only `foo bar` will be written to stdout
44/// writer.write_all(bytes_with_colors)?;
45/// # Ok(())
46/// # }
47/// ```
48
49pub struct Writer<W>
50where
51    W: Write,
52{
53    performer: Performer<W>,
54    parser: Parser,
55}
56
57/// Strip ANSI escapes from `data` and return the remaining bytes as a `Vec<u8>`.
58///
59/// See [the module documentation][mod] for an example.
60///
61/// [mod]: index.html
62pub fn strip<T>(data: T) -> Vec<u8>
63where
64    T: AsRef<[u8]>,
65{
66    fn strip_impl(data: &[u8]) -> io::Result<Vec<u8>> {
67        let mut writer = Writer::new(Vec::new());
68        writer.write_all(data)?;
69        Ok(writer.into_inner()?)
70    }
71
72    strip_impl(data.as_ref()).expect("writing to a Vec<u8> cannot fail")
73}
74
75/// Strip ANSI escapes from `data` and return the remaining contents as a `String`.
76///
77/// # Example
78///
79/// ```
80/// let str_with_colors = "\x1b[32mfoo\x1b[m bar";
81/// let string_without_colors = strip_ansi_escapes::strip_str(str_with_colors);
82/// assert_eq!(string_without_colors, "foo bar");
83/// ```
84pub fn strip_str<T>(data: T) -> String
85where
86    T: AsRef<str>,
87{
88    let bytes = strip(data.as_ref());
89    String::from_utf8(bytes)
90        .expect("stripping ANSI escapes from a UTF-8 string always results in UTF-8")
91}
92
93struct Performer<W>
94where
95    W: Write,
96{
97    writer: LineWriter<W>,
98    err: Option<io::Error>,
99}
100
101impl<W> Writer<W>
102where
103    W: Write,
104{
105    /// Create a new `Writer` that writes to `inner`.
106    pub fn new(inner: W) -> Writer<W> {
107        Writer {
108            performer: Performer {
109                writer: LineWriter::new(inner),
110                err: None,
111            },
112            parser: Parser::new(),
113        }
114    }
115
116    /// Unwraps this `Writer`, returning the underlying writer.
117    ///
118    /// The internal buffer is written out before returning the writer, which
119    /// may produce an [`IntoInnerError`].
120    ///
121    /// [IntoInnerError]: https://doc.rust-lang.org/std/io/struct.IntoInnerError.html
122    pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
123        self.performer.into_inner()
124    }
125}
126
127impl<W> Write for Writer<W>
128where
129    W: Write,
130{
131    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
132        self.parser.advance(&mut self.performer, buf);
133        match self.performer.err.take() {
134            Some(e) => Err(e),
135            None => Ok(buf.len()),
136        }
137    }
138
139    fn flush(&mut self) -> io::Result<()> {
140        self.performer.flush()
141    }
142}
143
144impl<W> Performer<W>
145where
146    W: Write,
147{
148    pub fn flush(&mut self) -> io::Result<()> {
149        self.writer.flush()
150    }
151
152    pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
153        self.writer.into_inner()
154    }
155}
156
157impl<W> Perform for Performer<W>
158where
159    W: Write,
160{
161    fn print(&mut self, c: char) {
162        // Just print bytes to the inner writer.
163        self.err = write!(self.writer, "{}", c).err();
164    }
165    fn execute(&mut self, byte: u8) {
166        // We only care about executing linefeeds.
167        if byte == b'\n' {
168            self.err = writeln!(self.writer).err();
169        }
170    }
171}
172
173#[cfg(doctest)]
174extern crate doc_comment;
175
176#[cfg(doctest)]
177doc_comment::doctest!("../README.md", readme);
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    fn assert_parsed(input: &[u8], expected: &[u8]) {
184        let bytes = strip(input);
185        assert_eq!(bytes, expected);
186    }
187
188    #[test]
189    fn test_simple() {
190        assert_parsed(b"\x1b[m\x1b[m\x1b[32m\x1b[1m    Finished\x1b[m dev [unoptimized + debuginfo] target(s) in 0.0 secs",
191                      b"    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs");
192    }
193
194    #[test]
195    fn test_newlines() {
196        assert_parsed(b"foo\nbar\n", b"foo\nbar\n");
197    }
198
199    #[test]
200    fn test_escapes_newlines() {
201        assert_parsed(b"\x1b[m\x1b[m\x1b[32m\x1b[1m   Compiling\x1b[m utf8parse v0.1.0
202\x1b[m\x1b[m\x1b[32m\x1b[1m   Compiling\x1b[m vte v0.3.2
203\x1b[m\x1b[m\x1b[32m\x1b[1m   Compiling\x1b[m strip-ansi-escapes v0.1.0-pre (file:///build/strip-ansi-escapes)
204\x1b[m\x1b[m\x1b[32m\x1b[1m    Finished\x1b[m dev [unoptimized + debuginfo] target(s) in 0.66 secs
205",
206                      b"   Compiling utf8parse v0.1.0
207   Compiling vte v0.3.2
208   Compiling strip-ansi-escapes v0.1.0-pre (file:///build/strip-ansi-escapes)
209    Finished dev [unoptimized + debuginfo] target(s) in 0.66 secs
210");
211    }
212}