1use serde::{Deserialize, Serialize};
2use std::collections::BTreeMap;
3
4#[derive(Default, Deserialize)]
5#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
6pub struct Options {
7 pub json: bool,
8 pub tui: bool,
9 pub no_tui: bool,
10 pub accessible: bool,
11 pub no_color: bool,
12 pub environment_no_color: bool,
13 pub force_color: bool,
14 pub piped_input: bool,
15}
16
17#[derive(Deserialize)]
18#[serde(rename_all = "camelCase", deny_unknown_fields)]
19pub struct Capabilities {
20 pub stdin_tty: bool,
21 pub stdout_tty: bool,
22 pub stderr_tty: bool,
23 pub columns: u16,
24 pub rows: u16,
25 pub color_depth: u8,
26 pub unicode: bool,
27 pub ci: bool,
28 pub term: Option<String>,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
32#[serde(rename_all = "lowercase")]
33pub enum Mode {
34 Plain,
35 Json,
36 Tui,
37 Accessible,
38}
39
40#[derive(Debug, Serialize)]
41pub struct Selection {
42 pub mode: Mode,
43 pub explicit: bool,
44 pub reason: Option<&'static str>,
45 pub color: bool,
46 pub unicode: bool,
47}
48
49pub fn detect_ci(environment: &BTreeMap<String, String>) -> bool {
50 [
51 ("CI", "true"),
52 ("GITHUB_ACTIONS", "true"),
53 ("GITLAB_CI", "true"),
54 ("TF_BUILD", "True"),
55 ("BUILDKITE", "true"),
56 ]
57 .iter()
58 .any(|(name, value)| environment.get(*name).is_some_and(|found| found == value))
59 || environment.contains_key("JENKINS_URL")
60}
61
62pub fn capture() -> Capabilities {
63 use std::io::IsTerminal;
64 let environment: BTreeMap<_, _> = [
65 "TERM",
66 "COLORTERM",
67 "LC_ALL",
68 "LC_CTYPE",
69 "LANG",
70 "WT_SESSION",
71 "TERM_PROGRAM",
72 "CI",
73 "GITHUB_ACTIONS",
74 "GITLAB_CI",
75 "TF_BUILD",
76 "BUILDKITE",
77 "JENKINS_URL",
78 ]
79 .into_iter()
80 .filter_map(|name| {
81 std::env::var(name)
82 .ok()
83 .map(|value| (name.to_string(), value))
84 })
85 .collect();
86 capture_snapshot(
87 (
88 std::io::stdin().is_terminal(),
89 std::io::stdout().is_terminal(),
90 std::io::stderr().is_terminal(),
91 ),
92 crossterm::terminal::size().unwrap_or((0, 0)),
93 &environment,
94 cfg!(windows),
95 )
96}
97
98fn capture_snapshot(
99 terminals: (bool, bool, bool),
100 size: (u16, u16),
101 environment: &BTreeMap<String, String>,
102 windows: bool,
103) -> Capabilities {
104 let term = environment
105 .get("TERM")
106 .filter(|value| !value.is_empty())
107 .map(|value| {
108 if value.encode_utf16().count() <= 256 {
109 value.clone()
110 } else {
111 "?".into()
112 }
113 });
114 let valid = term
115 .as_deref()
116 .is_some_and(|term| valid_term(term) && !term.eq_ignore_ascii_case("dumb"));
117 let (columns, rows) = size;
118 let unicode = if windows {
119 environment.contains_key("WT_SESSION")
120 || environment
121 .get("TERM_PROGRAM")
122 .is_some_and(|value| value == "vscode")
123 } else {
124 ["LC_ALL", "LC_CTYPE", "LANG"]
125 .iter()
126 .find_map(|name| environment.get(*name))
127 .is_some_and(|value| {
128 let value = value.to_ascii_lowercase();
129 value.contains("utf-8") || value.contains("utf8")
130 })
131 };
132 Capabilities {
133 stdin_tty: terminals.0,
134 stdout_tty: terminals.1,
135 stderr_tty: terminals.2,
136 columns: if columns <= 10000 { columns } else { 0 },
137 rows: if rows <= 10000 { rows } else { 0 },
138 color_depth: if valid { 4 } else { 1 },
139 unicode: valid && unicode,
140 ci: detect_ci(environment),
141 term,
142 }
143}
144
145fn valid_term(term: &str) -> bool {
146 !term.is_empty()
147 && term.len() <= 128
148 && term.as_bytes()[0].is_ascii_alphanumeric()
149 && term
150 .bytes()
151 .all(|byte| byte.is_ascii_alphanumeric() || b"._+-".contains(&byte))
152}
153
154pub fn resolve(options: &Options, capabilities: &Capabilities) -> Result<Selection, &'static str> {
155 if capabilities.columns > 10000
156 || capabilities.rows > 10000
157 || ![1, 4, 8, 24].contains(&capabilities.color_depth)
158 || capabilities
159 .term
160 .as_ref()
161 .is_some_and(|term| term.encode_utf16().count() > 256)
162 {
163 return Err("invalid_capabilities");
164 }
165 if options.json && (options.tui || options.accessible) {
166 return Err("json_conflict");
167 }
168 if options.no_tui && (options.tui || options.accessible) {
169 return Err("mode_conflict");
170 }
171 let selection = |mode, explicit, reason| Selection {
172 mode,
173 explicit,
174 reason,
175 color: mode == Mode::Tui
176 && !options.no_color
177 && !options.environment_no_color
178 && capabilities.color_depth > 1,
179 unicode: mode == Mode::Tui && capabilities.unicode,
180 };
181 if options.json {
182 return Ok(selection(Mode::Json, true, None));
183 }
184 if options.no_tui {
185 return Ok(selection(Mode::Plain, true, Some("forced_plain")));
186 }
187 let term = capabilities.term.as_deref().unwrap_or("");
188 let reason = [
189 (options.piped_input, "piped_input"),
190 (!capabilities.stdin_tty, "stdin_not_tty"),
191 (!capabilities.stdout_tty, "stdout_not_tty"),
192 (!capabilities.stderr_tty, "stderr_not_tty"),
193 (term.is_empty(), "term_missing"),
194 (!term.is_empty() && !valid_term(term), "term_invalid"),
195 (term.eq_ignore_ascii_case("dumb"), "term_dumb"),
196 (capabilities.ci, "ci_environment"),
197 (
198 capabilities.columns < if options.accessible { 40 } else { 60 },
199 "terminal_width",
200 ),
201 (
202 capabilities.rows < if options.accessible { 10 } else { 16 },
203 "terminal_height",
204 ),
205 ]
206 .into_iter()
207 .find_map(|(failed, reason)| failed.then_some(reason));
208 let explicit = options.tui || options.accessible;
209 if let Some(reason) = reason {
210 if explicit {
211 return Err(reason);
212 }
213 return Ok(selection(Mode::Plain, false, Some(reason)));
214 }
215 Ok(selection(
216 if options.accessible {
217 Mode::Accessible
218 } else {
219 Mode::Tui
220 },
221 explicit,
222 None,
223 ))
224}
225
226#[cfg(test)]
227mod capture_tests {
228 use super::*;
229
230 #[test]
231 fn captured_environment_preserves_eligibility_and_safe_defaults() {
232 let environment = BTreeMap::from([
233 ("TERM".into(), "xterm-256color".into()),
234 ("LANG".into(), "en_US.UTF-8".into()),
235 ("GITHUB_ACTIONS".into(), "true".into()),
236 ]);
237 let captured = capture_snapshot((true, true, true), (100, 30), &environment, false);
238 assert!(captured.stdin_tty && captured.stdout_tty && captured.stderr_tty);
239 assert_eq!((captured.columns, captured.rows), (100, 30));
240 assert!(captured.unicode && captured.ci);
241 assert!(captured.color_depth > 1);
242 assert_eq!(captured.term.as_deref(), Some("xterm-256color"));
243
244 let empty = capture_snapshot(
245 (false, false, false),
246 (10001, 10001),
247 &BTreeMap::new(),
248 true,
249 );
250 assert!(!empty.stdin_tty && !empty.stdout_tty && !empty.stderr_tty);
251 assert_eq!((empty.columns, empty.rows, empty.color_depth), (0, 0, 1));
252 assert!(!empty.unicode && !empty.ci);
253 assert!(empty.term.is_none());
254 }
255
256 #[test]
257 fn captured_term_bounds_locale_precedence_and_windows_unicode_are_conservative() {
258 for length in [129, 256, 257, 10000] {
259 let environment = BTreeMap::from([("TERM".into(), "x".repeat(length))]);
260 let captured = capture_snapshot((true, true, true), (80, 24), &environment, false);
261 assert_eq!(
262 resolve(&Options::default(), &captured).unwrap().reason,
263 Some("term_invalid")
264 );
265 assert_eq!(captured.color_depth, 1);
266 assert!(!captured.unicode);
267 }
268 let mut environment = BTreeMap::from([
269 ("TERM".into(), "xterm".into()),
270 ("LANG".into(), "en_US.UTF-8".into()),
271 ("LC_ALL".into(), "C".into()),
272 ]);
273 assert!(!capture_snapshot((true, true, true), (80, 24), &environment, false).unicode);
274 assert!(!capture_snapshot((true, true, true), (80, 24), &environment, true).unicode);
275 environment.insert("WT_SESSION".into(), String::new());
276 assert!(capture_snapshot((true, true, true), (80, 24), &environment, true).unicode);
277 environment.insert("TERM".into(), "dumb".into());
278 assert!(!capture_snapshot((true, true, true), (80, 24), &environment, true).unicode);
279 }
280}