Skip to main content

runic_diagnostics/
terminal.rs

1use core::num::NonZeroU16;
2use std::{
3    env,
4    ffi::OsStr,
5    io::{self, IsTerminal, Write},
6};
7
8use crate::{
9    AnnotateRenderer, EmissionFailure, EmissionStatus, EmissionSummary, Emitter, IoEmissionError,
10    IoEmitter, PreparedDiagnostic, PreparedSet, RenderConfig,
11};
12
13/// An explicit override or environment-derived terminal choice.
14#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
15pub enum TerminalChoice {
16    #[default]
17    Auto,
18    Always,
19    Never,
20}
21
22/// An explicit render width or a width derived from the terminal environment.
23#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
24pub enum TerminalWidth {
25    #[default]
26    Auto,
27    Fixed(NonZeroU16),
28}
29
30/// Controls terminal capabilities for standard-stream rendering.
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub struct TerminalPolicy {
33    pub styled: TerminalChoice,
34    pub unicode: TerminalChoice,
35    pub hyperlinks: TerminalChoice,
36    pub width: TerminalWidth,
37}
38
39impl TerminalPolicy {
40    pub const DEFAULT: Self = Self {
41        styled: TerminalChoice::Auto,
42        unicode: TerminalChoice::Auto,
43        hyperlinks: TerminalChoice::Auto,
44        width: TerminalWidth::Auto,
45    };
46
47    /// Resolves this policy once against stderr and the current environment.
48    ///
49    /// This is a compatibility alias for [`Self::resolve_stderr`].
50    pub fn resolve(self) -> RenderConfig {
51        self.resolve_stderr()
52    }
53
54    /// Resolves this policy once against stdout and the current environment.
55    pub fn resolve_stdout(self) -> RenderConfig {
56        self.resolve_with(TerminalInputs::detect(io::stdout().is_terminal()))
57    }
58
59    /// Resolves this policy once against stderr and the current environment.
60    pub fn resolve_stderr(self) -> RenderConfig {
61        self.resolve_with(TerminalInputs::detect(io::stderr().is_terminal()))
62    }
63
64    fn resolve_with(self, inputs: TerminalInputs) -> RenderConfig {
65        let usable_terminal = inputs.is_terminal && !inputs.term_is_dumb;
66        RenderConfig {
67            styled: resolve_choice(self.styled, usable_terminal && !inputs.no_color_requested),
68            unicode: resolve_choice(self.unicode, usable_terminal && inputs.unicode_locale),
69            // Automatic hyperlink detection is intentionally conservative.
70            hyperlinks: resolve_choice(self.hyperlinks, false),
71            width: match self.width {
72                TerminalWidth::Fixed(width) => usize::from(width.get()),
73                TerminalWidth::Auto => inputs
74                    .columns
75                    .filter(|_| inputs.is_terminal)
76                    .map_or(RenderConfig::DEFAULT.width, usize::from),
77            },
78            ..RenderConfig::DEFAULT
79        }
80    }
81}
82
83impl Default for TerminalPolicy {
84    fn default() -> Self {
85        Self::DEFAULT
86    }
87}
88
89fn resolve_choice(choice: TerminalChoice, automatic: bool) -> bool {
90    match choice {
91        TerminalChoice::Auto => automatic,
92        TerminalChoice::Always => true,
93        TerminalChoice::Never => false,
94    }
95}
96
97#[derive(Clone, Copy, Debug, Eq, PartialEq)]
98struct TerminalInputs {
99    is_terminal: bool,
100    term_is_dumb: bool,
101    no_color_requested: bool,
102    unicode_locale: bool,
103    columns: Option<u16>,
104}
105
106impl TerminalInputs {
107    fn detect(is_terminal: bool) -> Self {
108        let term_is_dumb =
109            env::var_os("TERM").as_deref().is_some_and(|term| eq_ascii_case(term, "dumb"));
110        let no_color_requested =
111            env::var_os("NO_COLOR").as_deref().is_some_and(|value| !value.is_empty());
112        let unicode_locale = unicode_locale(is_terminal);
113        let columns = parse_columns(env::var_os("COLUMNS").as_deref());
114        Self {
115            is_terminal,
116            term_is_dumb,
117            no_color_requested,
118            unicode_locale,
119            columns,
120        }
121    }
122}
123
124fn parse_columns(value: Option<&OsStr>) -> Option<u16> {
125    value
126        .and_then(OsStr::to_str)
127        .and_then(|value| value.parse::<u16>().ok())
128        .filter(|columns| *columns != 0)
129}
130
131fn eq_ascii_case(value: &OsStr, expected: &str) -> bool {
132    value.to_str().is_some_and(|value| value.eq_ignore_ascii_case(expected))
133}
134
135#[cfg(windows)]
136fn unicode_locale(is_terminal: bool) -> bool {
137    is_terminal
138}
139
140#[cfg(not(windows))]
141fn unicode_locale(_is_terminal: bool) -> bool {
142    ["LC_ALL", "LC_CTYPE", "LANG"]
143        .into_iter()
144        .filter_map(env::var_os)
145        .find(|value| !value.is_empty())
146        .and_then(|value| value.into_string().ok())
147        .is_some_and(|locale| {
148            let locale = locale.to_ascii_uppercase();
149            locale.contains("UTF-8") || locale.contains("UTF8")
150        })
151}
152
153/// Emits diagnostics to stderr using capabilities resolved at construction.
154pub struct StderrEmitter {
155    renderer: AnnotateRenderer,
156}
157
158impl StderrEmitter {
159    pub fn new(policy: TerminalPolicy) -> Self {
160        Self {
161            renderer: AnnotateRenderer::new(policy.resolve_stderr()),
162        }
163    }
164
165    pub const fn renderer(&self) -> &AnnotateRenderer {
166        &self.renderer
167    }
168}
169
170impl Default for StderrEmitter {
171    fn default() -> Self {
172        Self::new(TerminalPolicy::default())
173    }
174}
175
176impl Emitter for StderrEmitter {
177    type Error = IoEmissionError;
178
179    fn emit(&mut self, diagnostic: &PreparedDiagnostic<'_>) -> Result<EmissionStatus, Self::Error> {
180        let stderr = io::stderr();
181        let lock = stderr.lock();
182        IoEmitter::new(lock, self.renderer).emit(diagnostic)
183    }
184
185    fn emit_set(
186        &mut self,
187        diagnostics: &PreparedSet<'_>,
188    ) -> Result<EmissionSummary, EmissionFailure<Self::Error>> {
189        let stderr = io::stderr();
190        let lock = stderr.lock();
191        IoEmitter::new(lock, self.renderer).emit_set(diagnostics)
192    }
193}
194
195/// Emits diagnostics to stdout using capabilities resolved at construction.
196pub struct StdoutEmitter {
197    renderer: AnnotateRenderer,
198}
199
200impl StdoutEmitter {
201    pub fn new(policy: TerminalPolicy) -> Self {
202        Self {
203            renderer: AnnotateRenderer::new(policy.resolve_stdout()),
204        }
205    }
206
207    pub const fn renderer(&self) -> &AnnotateRenderer {
208        &self.renderer
209    }
210}
211
212impl Default for StdoutEmitter {
213    fn default() -> Self {
214        Self::new(TerminalPolicy::default())
215    }
216}
217
218impl Emitter for StdoutEmitter {
219    type Error = IoEmissionError;
220
221    fn emit(&mut self, diagnostic: &PreparedDiagnostic<'_>) -> Result<EmissionStatus, Self::Error> {
222        let stdout = io::stdout();
223        let lock = stdout.lock();
224        IoEmitter::new(lock, self.renderer).emit(diagnostic)
225    }
226
227    fn emit_set(
228        &mut self,
229        diagnostics: &PreparedSet<'_>,
230    ) -> Result<EmissionSummary, EmissionFailure<Self::Error>> {
231        let stdout = io::stdout();
232        let lock = stdout.lock();
233        IoEmitter::new(lock, self.renderer).emit_set(diagnostics)
234    }
235}
236
237pub(crate) const PREPARATION_FALLBACK: &[u8] =
238    b"error: diagnostic preparation failed; rich output unavailable\n";
239pub(crate) const EMISSION_FALLBACK: &[u8] =
240    b"\nerror: diagnostic emission failed; rich output incomplete\n";
241pub(crate) const PANIC_FALLBACK: &[u8] = b"fatal: diagnostic panic report unavailable\n";
242
243pub(crate) fn write_stderr_fallback(message: &[u8]) {
244    let stderr = io::stderr();
245    let mut lock = stderr.lock();
246    let _ = lock.write_all(message);
247    let _ = lock.flush();
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    const NON_TERMINAL: TerminalInputs = TerminalInputs {
255        is_terminal: false,
256        term_is_dumb: false,
257        no_color_requested: false,
258        unicode_locale: true,
259        columns: Some(90),
260    };
261
262    #[test]
263    fn automatic_policy_is_conservative_off_terminal() {
264        assert_eq!(TerminalPolicy::DEFAULT.resolve_with(NON_TERMINAL), RenderConfig::DEFAULT);
265    }
266
267    #[test]
268    fn automatic_policy_honors_terminal_constraints() {
269        let resolved = TerminalPolicy::DEFAULT.resolve_with(TerminalInputs {
270            is_terminal: true,
271            term_is_dumb: false,
272            no_color_requested: false,
273            unicode_locale: true,
274            columns: Some(90),
275        });
276        assert!(resolved.styled);
277        assert!(resolved.unicode);
278        assert!(!resolved.hyperlinks);
279        assert_eq!(resolved.width, 90);
280
281        let dumb = TerminalPolicy::DEFAULT.resolve_with(TerminalInputs {
282            is_terminal: true,
283            term_is_dumb: true,
284            ..NON_TERMINAL
285        });
286        assert!(!dumb.styled);
287        assert!(!dumb.unicode);
288
289        let no_color = TerminalPolicy::DEFAULT.resolve_with(TerminalInputs {
290            is_terminal: true,
291            no_color_requested: true,
292            ..NON_TERMINAL
293        });
294        assert!(!no_color.styled);
295        assert!(no_color.unicode);
296    }
297
298    #[test]
299    fn automatic_width_parser_rejects_every_invalid_shape() {
300        assert_eq!(parse_columns(Some(OsStr::new("1"))), Some(1));
301        assert_eq!(parse_columns(Some(OsStr::new("65535"))), Some(65535));
302        for invalid in ["", "0", "-1", "not-a-number", "65536", "999999999999999"] {
303            assert_eq!(parse_columns(Some(OsStr::new(invalid))), None);
304        }
305
306        let valid = TerminalPolicy::DEFAULT.resolve_with(TerminalInputs {
307            is_terminal: true,
308            columns: parse_columns(Some(OsStr::new("91"))),
309            ..NON_TERMINAL
310        });
311        assert_eq!(valid.width, 91);
312        let invalid = TerminalPolicy::DEFAULT.resolve_with(TerminalInputs {
313            is_terminal: true,
314            columns: parse_columns(Some(OsStr::new("65536"))),
315            ..NON_TERMINAL
316        });
317        assert_eq!(invalid.width, RenderConfig::DEFAULT.width);
318    }
319
320    #[test]
321    fn explicit_choices_override_detection() {
322        let resolved = TerminalPolicy {
323            styled: TerminalChoice::Always,
324            unicode: TerminalChoice::Always,
325            hyperlinks: TerminalChoice::Always,
326            width: TerminalWidth::Fixed(NonZeroU16::new(72).unwrap()),
327        }
328        .resolve_with(NON_TERMINAL);
329        assert_eq!(
330            resolved,
331            RenderConfig {
332                styled: true,
333                unicode: true,
334                hyperlinks: true,
335                width: 72,
336                ..RenderConfig::DEFAULT
337            }
338        );
339    }
340
341    #[test]
342    fn resolve_remains_the_stderr_compatibility_alias() {
343        assert_eq!(TerminalPolicy::DEFAULT.resolve(), TerminalPolicy::DEFAULT.resolve_stderr());
344    }
345
346    #[test]
347    fn explicit_policy_resolves_and_constructs_both_standard_stream_emitters() {
348        let policy = TerminalPolicy {
349            styled: TerminalChoice::Always,
350            unicode: TerminalChoice::Never,
351            hyperlinks: TerminalChoice::Always,
352            width: TerminalWidth::Fixed(NonZeroU16::new(88).unwrap()),
353        };
354        let expected = RenderConfig {
355            styled: true,
356            unicode: false,
357            hyperlinks: true,
358            width: 88,
359            ..RenderConfig::DEFAULT
360        };
361
362        assert_eq!(policy.resolve_stdout(), expected);
363        assert_eq!(policy.resolve_stderr(), expected);
364        assert_eq!(StdoutEmitter::new(policy).renderer().config, expected);
365        assert_eq!(StderrEmitter::new(policy).renderer().config, expected);
366    }
367}