Skip to main content

terminfokit_cli/
lib.rs

1// SPDX-FileCopyrightText: 2026 Yasunobu Sakashita
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5#![forbid(unsafe_code)]
6
7use clap::{Parser, ValueEnum};
8use terminfokit::error::{Diagnostic, DiagnosticLabel, Severity};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
11pub enum DiagnosticFormat {
12    Human,
13    #[value(alias = "json")]
14    Ndjson,
15}
16
17#[derive(Debug, Clone, Copy)]
18pub struct Reporter {
19    program: &'static str,
20    format: DiagnosticFormat,
21}
22
23#[derive(Debug, Parser)]
24#[command(name = "terminfokit doctor", about = "Inspect terminfo lookup")]
25struct DoctorArgs {
26    /// Set the terminal name.
27    #[arg(short = 'T')]
28    terminal: Option<String>,
29    #[arg(long, value_enum, default_value_t = DiagnosticFormat::Human)]
30    diagnostic_format: DiagnosticFormat,
31}
32
33/// Runs database diagnostics.
34pub fn doctor_from(arguments: Vec<String>) -> std::process::ExitCode {
35    use terminfokit::caps::{BooleanCap, NumericCap, StringCap};
36    use terminfokit::database::{
37        DirectoryLayout, LoadOrigin, SearchPath, TransportEncoding, load_from_env_report,
38    };
39    use terminfokit::{BooleanState, CapabilityState, Magic};
40
41    let args = DoctorArgs::parse_from(arguments);
42    let reporter = Reporter::new("terminfokit doctor", args.diagnostic_format);
43    let terminal = match args
44        .terminal
45        .or_else(|| std::env::var("TERM").ok())
46        .filter(|value| !value.is_empty())
47    {
48        Some(terminal) => terminal,
49        None => {
50            reporter.error("TIKC501", "terminal required; use -T or TERM");
51            return std::process::ExitCode::from(2);
52        }
53    };
54
55    println!("TERM={terminal}");
56    let search = SearchPath::from_env();
57    for (index, root) in search.roots().iter().enumerate() {
58        println!("search[{index}]={}", root.display());
59    }
60    if search.roots().is_empty() {
61        // Windows has no system terminfo database, so an unset TERMINFO leaves
62        // nothing to search and every lookup fails. Say so here rather than
63        // letting the user read a bare NotFound and assume the entry is broken.
64        println!("search=<none>; set TERMINFO or TERMINFO_DIRS to a directory you control");
65    }
66    let report = match load_from_env_report(&terminal) {
67        Ok(report) => report,
68        Err(error) => {
69            reporter.error("TIKC502", error.to_string());
70            return std::process::ExitCode::from(3);
71        }
72    };
73    match report.origin() {
74        LoadOrigin::Inline { encoding } => println!(
75            "origin=inline:{}",
76            match encoding {
77                TransportEncoding::Hex => "hex",
78                TransportEncoding::Base64 => "base64",
79            }
80        ),
81        LoadOrigin::Directory { path, layout } => println!(
82            "origin=directory:{} layout={}",
83            path.display(),
84            match layout {
85                DirectoryLayout::Auto => "auto",
86                DirectoryLayout::Letter => "letter",
87                DirectoryLayout::Hex => "hex",
88                _ => "unknown",
89            }
90        ),
91        _ => println!("origin=unknown"),
92    }
93    let entry = report.entry();
94    println!("name.primary={}", entry.names().primary());
95    println!("name.aliases={}", entry.names().aliases().join(","));
96    println!(
97        "name.verbose={}",
98        entry.names().verbose_name().unwrap_or("")
99    );
100    println!(
101        "format={}",
102        match report.magic() {
103            Magic::Legacy => "legacy-16",
104            Magic::ExtendedNumbers => "extended-32",
105        }
106    );
107    let number = |cap| match entry.number(cap) {
108        CapabilityState::Value(value) => value.to_string(),
109        CapabilityState::Absent | CapabilityState::Cancelled => "-".into(),
110    };
111    println!(
112        "size={}x{}",
113        number(NumericCap::COLUMNS),
114        number(NumericCap::LINES)
115    );
116    println!(
117        "colors={} pairs={}",
118        number(NumericCap::MAX_COLORS),
119        number(NumericCap::MAX_PAIRS)
120    );
121    println!(
122        "capabilities=am:{} clear:{} cup:{} setaf:{}",
123        entry.boolean(BooleanCap::AUTO_RIGHT_MARGIN) == BooleanState::Set,
124        matches!(
125            entry.string(StringCap::CLEAR_SCREEN),
126            CapabilityState::Value(_)
127        ),
128        matches!(
129            entry.string(StringCap::CURSOR_ADDRESS),
130            CapabilityState::Value(_)
131        ),
132        matches!(
133            entry.string(StringCap::SET_A_FOREGROUND),
134            CapabilityState::Value(_)
135        )
136    );
137    println!("extended={}", entry.extended().len());
138    std::process::ExitCode::SUCCESS
139}
140
141impl Reporter {
142    pub const fn new(program: &'static str, format: DiagnosticFormat) -> Self {
143        Self { program, format }
144    }
145
146    pub fn error(self, code: &str, message: impl AsRef<str>) {
147        self.message("error", code, message.as_ref());
148    }
149
150    pub fn warning(self, code: &str, message: impl AsRef<str>) {
151        self.message("warning", code, message.as_ref());
152    }
153
154    pub fn info(self, code: &str, message: impl AsRef<str>) {
155        self.message("info", code, message.as_ref());
156    }
157
158    pub fn diagnostic(self, value: &Diagnostic) {
159        match self.format {
160            DiagnosticFormat::Human => {
161                if let Some(label) = value.primary() {
162                    let span = label.span();
163                    eprintln!(
164                        "source-{}:{}: {} [{}]: {}",
165                        span.source_id().get(),
166                        span.range().start(),
167                        severity(value.severity()),
168                        value.code(),
169                        value.message()
170                    );
171                } else {
172                    eprintln!(
173                        "{}: {} [{}]: {}",
174                        self.program,
175                        severity(value.severity()),
176                        value.code(),
177                        value.message()
178                    );
179                }
180                for label in value.secondary() {
181                    let span = label.span();
182                    eprintln!(
183                        "  source-{}:{}: {}",
184                        span.source_id().get(),
185                        span.range().start(),
186                        label.message().unwrap_or("related location")
187                    );
188                }
189                for note in value.notes() {
190                    eprintln!("  note: {note}");
191                }
192            }
193            DiagnosticFormat::Ndjson => {
194                let primary = value
195                    .primary()
196                    .map_or_else(|| "null".to_owned(), label_json);
197                let secondary = value
198                    .secondary()
199                    .iter()
200                    .map(label_json)
201                    .collect::<Vec<_>>()
202                    .join(",");
203                let notes = value
204                    .notes()
205                    .iter()
206                    .map(|note| format!("\"{}\"", json(note)))
207                    .collect::<Vec<_>>()
208                    .join(",");
209                eprintln!(
210                    "{{\"program\":\"{}\",\"severity\":\"{}\",\"code\":\"{}\",\"message\":\"{}\",\"primary\":{primary},\"secondary\":[{secondary}],\"notes\":[{notes}]}}",
211                    json(self.program),
212                    severity(value.severity()),
213                    json(value.code()),
214                    json(value.message())
215                );
216            }
217        }
218    }
219
220    fn message(self, severity: &str, code: &str, message: &str) {
221        match self.format {
222            DiagnosticFormat::Human => eprintln!("{}: {message}", self.program),
223            DiagnosticFormat::Ndjson => eprintln!(
224                "{{\"program\":\"{}\",\"severity\":\"{}\",\"code\":\"{}\",\"message\":\"{}\"}}",
225                json(self.program),
226                json(severity),
227                json(code),
228                json(message)
229            ),
230        }
231    }
232}
233
234fn label_json(label: &DiagnosticLabel) -> String {
235    let span = label.span();
236    let message = label.message().map_or_else(
237        || "null".to_owned(),
238        |message| format!("\"{}\"", json(message)),
239    );
240    format!(
241        "{{\"source\":{},\"start\":{},\"end\":{},\"message\":{message}}}",
242        span.source_id().get(),
243        span.range().start(),
244        span.range().end()
245    )
246}
247
248fn severity(value: Severity) -> &'static str {
249    match value {
250        Severity::Warning => "warning",
251        Severity::Error => "error",
252        _ => "diagnostic",
253    }
254}
255
256fn json(value: &str) -> String {
257    let mut output = String::with_capacity(value.len());
258    for character in value.chars() {
259        match character {
260            '"' => output.push_str("\\\""),
261            '\\' => output.push_str("\\\\"),
262            '\n' => output.push_str("\\n"),
263            '\r' => output.push_str("\\r"),
264            '\t' => output.push_str("\\t"),
265            character if character.is_control() => {
266                use std::fmt::Write as _;
267                let _ = write!(output, "\\u{:04x}", u32::from(character));
268            }
269            character => output.push(character),
270        }
271    }
272    output
273}