-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathout.rs
306 lines (272 loc) · 8.75 KB
/
out.rs
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
// Copyright (c) 2018-2023 Brendan Molloy <brendan@bbqsrc.net>,
// Ilya Solovyiov <ilya.solovyiov@gmail.com>,
// Kai Ren <tyranron@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Tools for writing output.
use std::{
borrow::Cow,
io::{self, IsTerminal},
mem, str,
};
use console::Style;
use derive_more::{Deref, DerefMut, Display, From, Into};
use super::Coloring;
/// [`Style`]s for terminal output.
#[derive(Clone, Debug)]
pub struct Styles {
/// [`Style`] for rendering successful events.
pub ok: Style,
/// [`Style`] for rendering skipped events.
pub skipped: Style,
/// [`Style`] for rendering errors and failed events.
pub err: Style,
/// [`Style`] for rendering retried [`Scenario`]s.
///
/// [`Scenario`]: gherkin::Scenario
pub retry: Style,
/// [`Style`] for rendering header.
pub header: Style,
/// [`Style`] for rendering __bold__.
pub bold: Style,
/// [`Term`] width.
///
/// [`Term`]: console::Term
pub term_width: Option<u16>,
/// Indicates whether the terminal was detected.
pub is_present: bool,
}
impl Default for Styles {
fn default() -> Self {
Self {
ok: Style::new().green(),
skipped: Style::new().cyan(),
err: Style::new().red(),
retry: Style::new().magenta(),
header: Style::new().blue(),
bold: Style::new().bold(),
term_width: console::Term::stdout().size_checked().map(|(_h, w)| w),
is_present: io::stdout().is_terminal() && console::colors_enabled(),
}
}
}
impl Styles {
/// Creates new [`Styles`].
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Applies the given [`Coloring`] to these [`Styles`].
pub fn apply_coloring(&mut self, color: Coloring) {
let is_present = match color {
Coloring::Always => true,
Coloring::Never => false,
Coloring::Auto => return,
};
let this = mem::take(self);
self.ok = this.ok.force_styling(is_present);
self.skipped = this.skipped.force_styling(is_present);
self.err = this.err.force_styling(is_present);
self.retry = this.retry.force_styling(is_present);
self.header = this.header.force_styling(is_present);
self.bold = this.bold.force_styling(is_present);
self.is_present = is_present;
}
/// Returns [`Styles`] with brighter colors.
#[must_use]
pub fn bright(&self) -> Self {
Self {
ok: self.ok.clone().bright(),
skipped: self.skipped.clone().bright(),
err: self.err.clone().bright(),
retry: self.retry.clone().bright(),
header: self.header.clone().bright(),
bold: self.bold.clone().bright(),
term_width: self.term_width,
is_present: self.is_present,
}
}
/// If terminal is present colors `input` with [`Styles::ok`] color or
/// leaves "as is" otherwise.
#[must_use]
pub fn ok<'a>(&self, input: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
if self.is_present {
self.ok.apply_to(input.into()).to_string().into()
} else {
input.into()
}
}
/// If terminal is present colors `input` with [`Styles::skipped`] color or
/// leaves "as is" otherwise.
#[must_use]
pub fn skipped<'a>(&self, input: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
if self.is_present {
self.skipped.apply_to(input.into()).to_string().into()
} else {
input.into()
}
}
/// If terminal is present colors `input` with [`Styles::err`] color or
/// leaves "as is" otherwise.
#[must_use]
pub fn err<'a>(&self, input: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
if self.is_present {
self.err.apply_to(input.into()).to_string().into()
} else {
input.into()
}
}
/// If terminal is present colors `input` with [`Styles::retry`] color or
/// leaves "as is" otherwise.
#[must_use]
pub fn retry<'a>(&self, input: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
if self.is_present {
self.retry.apply_to(input.into()).to_string().into()
} else {
input.into()
}
}
/// If terminal is present colors `input` with [`Styles::header`] color or
/// leaves "as is" otherwise.
#[must_use]
pub fn header<'a>(&self, input: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
if self.is_present {
self.header.apply_to(input.into()).to_string().into()
} else {
input.into()
}
}
/// If terminal is present makes `input` __bold__ or leaves "as is"
/// otherwise.
#[must_use]
pub fn bold<'a>(&self, input: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
if self.is_present {
self.bold.apply_to(input.into()).to_string().into()
} else {
input.into()
}
}
/// Returns number of lines for the provided `s`tring, considering wrapping
/// because of the [`Term`] width.
///
/// [`Term`]: console::Term
#[must_use]
pub fn lines_count(&self, s: impl AsRef<str>) -> usize {
// TODO: Remove, once `int_roundings` feature is stabilized:
// https://github.com/rust-lang/rust/issues/88581
let div_ceil = |l, r| {
let d = l / r;
let rem = l % r;
if rem > 0 && r > 0 {
d + 1
} else {
d
}
};
s.as_ref()
.lines()
.map(|l| {
self.term_width
.map_or(1, |w| div_ceil(l.len(), usize::from(w)))
})
.sum()
}
}
/// [`io::Write`] extension for easier manipulation with strings and special
/// sequences.
pub trait WriteStrExt: io::Write {
/// Writes the given `string` into this writer.
///
/// # Errors
///
/// If this writer fails to write the given `string`.
fn write_str(&mut self, string: impl AsRef<str>) -> io::Result<()> {
self.write(string.as_ref().as_bytes()).map(drop)
}
/// Writes the given `string` into this writer followed by a newline.
///
/// # Errors
///
/// If this writer fails to write the given `string`.
fn write_line(&mut self, string: impl AsRef<str>) -> io::Result<()> {
self.write_str(string.as_ref())
.and_then(|_| self.write_str("\n"))
.map(drop)
}
/// Writes a special sequence into this writer moving a cursor up on `n`
/// positions.
///
/// # Errors
///
/// If this writer fails to write a special sequence.
fn move_cursor_up(&mut self, n: usize) -> io::Result<()> {
(n > 0)
.then(|| self.write_str(format!("\x1b[{n}A")))
.unwrap_or(Ok(()))
}
/// Writes a special sequence into this writer moving a cursor down on `n`
/// positions.
///
/// # Errors
///
/// If this writer fails to write a special sequence.
fn move_cursor_down(&mut self, n: usize) -> io::Result<()> {
(n > 0)
.then(|| self.write_str(format!("\x1b[{n}B")))
.unwrap_or(Ok(()))
}
/// Writes a special sequence into this writer clearing the last `n` lines.
///
/// # Errors
///
/// If this writer fails to write a special sequence.
fn clear_last_lines(&mut self, n: usize) -> io::Result<()> {
self.move_cursor_up(n)?;
for _ in 0..n {
self.clear_line()?;
self.move_cursor_down(1)?;
}
self.move_cursor_up(n)
}
/// Writes a special sequence into this writer clearing the last line.
///
/// # Errors
///
/// If this writer fails to write a special sequence.
fn clear_line(&mut self) -> io::Result<()> {
self.write_str("\r\x1b[2K")
}
}
impl<T: io::Write + ?Sized> WriteStrExt for T {}
/// [`String`] wrapper implementing [`io::Write`].
#[derive(
Clone,
Debug,
Deref,
DerefMut,
Display,
Eq,
From,
Hash,
Into,
Ord,
PartialEq,
PartialOrd,
)]
pub struct WritableString(pub String);
impl io::Write for WritableString {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.push_str(
str::from_utf8(buf)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}