1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
//! Provides the [`Utf8Output`] type, a UTF-8-decoded variant of [`std::process::Output`] (as
//! produced by [`std::process::Command::output`]).
//!
//! Construct [`Utf8Output`] from [`Output`] via the [`TryInto`] or [`TryFrom`] traits:
//!
//! ```
//! # use std::process::Command;
//! # use std::process::ExitStatus;
//! # use utf8_command::Utf8Output;
//! let output: Utf8Output = Command::new("echo")
//!     .arg("puppy")
//!     .output()
//!     .unwrap()
//!     .try_into()
//!     .unwrap();
//! assert_eq!(
//!     output,
//!     Utf8Output {
//!         status: ExitStatus::default(),
//!         stdout: String::from("puppy\n"),
//!         stderr: String::from(""),
//!     },
//! );
//! ```
//!
//! Error messages will include information about the stream that failed to decode, as well as the
//! output (with invalid UTF-8 bytes replaced with U+FFFD REPLACEMENT CHARACTER):
//!
//! ```
//! # use std::process::ExitStatus;
//! # use std::process::Output;
//! # use utf8_command::Utf8Output;
//! # use utf8_command::Error;
//! let invalid = Output {
//!     status: ExitStatus::default(),
//!     stdout: Vec::from(b"puppy doggy \xc3\x28"), // Invalid 2-byte sequence.
//!     stderr: Vec::from(b""),
//! };
//!
//! let err: Result<Utf8Output, Error> = invalid.try_into();
//! assert_eq!(
//!     err.unwrap_err().to_string(),
//!     "Stdout contained invalid utf-8 sequence of 1 bytes from index 12: \"puppy doggy �(\""
//! );
//! ```

#![deny(missing_docs)]

use std::fmt::Debug;
use std::fmt::Display;
use std::process::ExitStatus;
use std::process::Output;
use std::string::FromUtf8Error;

mod context;
use context::FromUtf8ErrorContext;

const ERROR_CONTEXT_BYTES: usize = 1024;

/// A UTF-8-decoded variant of [`std::process::Output`] (as
/// produced by [`std::process::Command::output`]).
///
/// Construct [`Utf8Output`] from [`Output`] via the [`TryInto`] or [`TryFrom`] traits:
///
/// ```
/// # use std::process::Command;
/// # use std::process::ExitStatus;
/// # use utf8_command::Utf8Output;
/// let output: Utf8Output = Command::new("echo")
///     .arg("puppy")
///     .output()
///     .unwrap()
///     .try_into()
///     .unwrap();
/// assert_eq!(
///     output,
///     Utf8Output {
///         status: ExitStatus::default(),
///         stdout: String::from("puppy\n"),
///         stderr: String::from(""),
///     },
/// );
/// ```
///
/// Error messages will include information about the stream that failed to decode, as well as the
/// output (with invalid UTF-8 bytes replaced with U+FFFD REPLACEMENT CHARACTER):
///
/// ```
/// # use std::process::ExitStatus;
/// # use std::process::Output;
/// # use utf8_command::Utf8Output;
/// # use utf8_command::Error;
/// let invalid = Output {
///     status: ExitStatus::default(),
///     stdout: Vec::from(b"\xc3\x28"), // Invalid 2-byte sequence.
///     stderr: Vec::from(b""),
/// };
///
/// let err: Result<Utf8Output, Error> = invalid.try_into();
/// assert_eq!(
///     err.unwrap_err().to_string(),
///     "Stdout contained invalid utf-8 sequence of 1 bytes from index 0: \"�(\""
/// );
/// ```
///
/// If there's a lot of output (currently, more than 1024 bytes), only the portion around the
/// decode error will be shown:
///
/// ```
/// # use std::process::ExitStatus;
/// # use std::process::Output;
/// # use utf8_command::Utf8Output;
/// # use utf8_command::Error;
/// let mut stdout = vec![];
/// for _ in 0..300 {
///     stdout.extend(b"puppy ");
/// }
/// // Add an invalid byte:
/// stdout[690] = 0xc0;
///
/// let invalid = Output {
///     status: ExitStatus::default(),
///     stdout,
///     stderr: Vec::from(b""),
/// };
///
/// let err: Result<Utf8Output, Error> = invalid.try_into();
/// assert_eq!(
///     err.unwrap_err().to_string(),
///     "Stdout contained invalid utf-8 sequence of 1 bytes from index 690: \
///     [178 bytes] \"y puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy �uppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy puppy \
///     puppy puppy puppy puppy puppy puppy puppy pu\" [598 bytes]"
/// );
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Utf8Output {
    /// The [`std::process::Command`]'s exit status.
    pub status: ExitStatus,
    /// The contents of the [`std::process::Command`]'s [`stdout` stream][stdout], decoded as
    /// UTF-8.
    ///
    /// [stdout]: https://linux.die.net/man/3/stdout
    pub stdout: String,
    /// The contents of the [`std::process::Command`]'s [`stderr` stream][stdout], decoded as
    /// UTF-8.
    ///
    /// [stdout]: https://linux.die.net/man/3/stdout
    pub stderr: String,
}

impl TryFrom<Output> for Utf8Output {
    type Error = Error;

    fn try_from(
        Output {
            status,
            stdout,
            stderr,
        }: Output,
    ) -> Result<Self, Self::Error> {
        let stdout =
            String::from_utf8(stdout).map_err(|err| Error::Stdout(StdoutError { inner: err }))?;
        let stderr =
            String::from_utf8(stderr).map_err(|err| Error::Stderr(StderrError { inner: err }))?;

        Ok(Utf8Output {
            status,
            stdout,
            stderr,
        })
    }
}

impl TryFrom<&Output> for Utf8Output {
    type Error = Error;

    fn try_from(
        Output {
            status,
            stdout,
            stderr,
        }: &Output,
    ) -> Result<Self, Self::Error> {
        let stdout = String::from_utf8(stdout.to_vec())
            .map_err(|err| Error::Stdout(StdoutError { inner: err }))?;
        let stderr = String::from_utf8(stderr.to_vec())
            .map_err(|err| Error::Stderr(StderrError { inner: err }))?;
        let status = *status;

        Ok(Utf8Output {
            status,
            stdout,
            stderr,
        })
    }
}

/// An error produced when converting [`Output`] to [`Utf8Output`], wrapping a [`FromUtf8Error`].
///
/// ```
/// use std::process::ExitStatus;
/// use std::process::Output;
/// use utf8_command::Utf8Output;
/// use utf8_command::Error;
///
/// let invalid = Output {
///     status: ExitStatus::default(),
///     stdout: Vec::from(b""),
///     stderr: Vec::from(b"\xe2\x28\xa1"), // Invalid 3-byte sequence.
/// };
///
/// let result: Result<Utf8Output, Error> = invalid.try_into();
/// assert_eq!(
///     result.unwrap_err().to_string(),
///     "Stderr contained invalid utf-8 sequence of 1 bytes from index 0: \"�(�\""
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// The [`Output`]'s stdout field contained invalid UTF-8.
    Stdout(StdoutError),
    /// The [`Output`]'s stderr field contained invalid UTF-8.
    Stderr(StderrError),
}

impl Error {
    /// Get a reference to the inner [`FromUtf8Error`].
    pub fn inner(&self) -> &FromUtf8Error {
        match self {
            Error::Stdout(err) => err.inner(),
            Error::Stderr(err) => err.inner(),
        }
    }
}

impl From<StdoutError> for Error {
    fn from(value: StdoutError) -> Self {
        Self::Stdout(value)
    }
}

impl From<StderrError> for Error {
    fn from(value: StderrError) -> Self {
        Self::Stderr(value)
    }
}

impl From<Error> for FromUtf8Error {
    fn from(value: Error) -> Self {
        match value {
            Error::Stdout(err) => err.inner,
            Error::Stderr(err) => err.inner,
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            Error::Stdout(err) => write!(f, "{}", err),
            Error::Stderr(err) => write!(f, "{}", err),
        }
    }
}

impl std::error::Error for Error {}

/// The [`Output`]'s `stdout` field contained invalid UTF-8. Wraps a [`FromUtf8Error`].
///
/// ```
/// use utf8_command::StdoutError;
///
/// let invalid_utf8 = Vec::from(b"\x80"); // Invalid single byte.
/// let inner_err = String::from_utf8(invalid_utf8).unwrap_err();
/// let err = StdoutError::from(inner_err);
/// assert_eq!(
///     err.to_string(),
///     "Stdout contained invalid utf-8 sequence of 1 bytes from index 0: \"�\""
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StdoutError {
    inner: FromUtf8Error,
}

impl StdoutError {
    /// Get a reference to the inner [`FromUtf8Error`].
    pub fn inner(&self) -> &FromUtf8Error {
        &self.inner
    }
}

impl From<StdoutError> for FromUtf8Error {
    fn from(value: StdoutError) -> Self {
        value.inner
    }
}

impl From<FromUtf8Error> for StdoutError {
    fn from(inner: FromUtf8Error) -> Self {
        Self { inner }
    }
}

impl Display for StdoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Stdout contained {}: {}",
            self.inner,
            FromUtf8ErrorContext::new(&self.inner, ERROR_CONTEXT_BYTES)
        )
    }
}

impl std::error::Error for StdoutError {}

/// The [`Output`]'s `stderr` field contained invalid UTF-8. Wraps a [`FromUtf8Error`].
///
/// ```
/// use utf8_command::StderrError;
///
/// let invalid_utf8 = Vec::from(b"\xf0\x90"); // Incomplete 4-byte sequence.
/// let inner_err = String::from_utf8(invalid_utf8).unwrap_err();
/// let err = StderrError::from(inner_err);
/// assert_eq!(
///     err.to_string(),
///     "Stderr contained incomplete utf-8 byte sequence from index 0: \"�\""
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StderrError {
    inner: FromUtf8Error,
}

impl StderrError {
    /// Get a reference to the inner [`FromUtf8Error`].
    pub fn inner(&self) -> &FromUtf8Error {
        &self.inner
    }
}

impl From<StderrError> for FromUtf8Error {
    fn from(value: StderrError) -> Self {
        value.inner
    }
}

impl From<FromUtf8Error> for StderrError {
    fn from(inner: FromUtf8Error) -> Self {
        Self { inner }
    }
}

impl Display for StderrError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Stderr contained {}: {}",
            self.inner,
            FromUtf8ErrorContext::new(&self.inner, ERROR_CONTEXT_BYTES)
        )
    }
}

impl std::error::Error for StderrError {}