Debian Codegraph @

helix-term/src/health.rs

raw symbols SCIP
1 use crate::config::{Config, ConfigLoadError};
2 use helix_core::config::{default_lang_config, user_lang_config};
3 use helix_loader::grammar::load_runtime_file;
4 use std::{
5 collections::HashSet,
6 io::{IsTerminal, Write},
7 };
8 use termina::{
9 style::{ColorSpec, StyleExt as _, Stylized},
10 Terminal as _,
11 };
12
13 #[derive(Copy, Clone)]
14 pub enum TsFeature {
15 Highlight,
16 TextObject,
17 AutoIndent,
18 Tags,
19 RainbowBracket,
20 }
21
22 impl TsFeature {
23 pub fn all() -> &'static [Self] {
24 &[
25 Self::Highlight,
26 Self::TextObject,
27 Self::AutoIndent,
28 Self::Tags,
29 Self::RainbowBracket,
30 ]
31 }
32
33 pub fn runtime_filename(&self) -> &'static str {
34 match *self {
35 Self::Highlight => "highlights.scm",
36 Self::TextObject => "textobjects.scm",
37 Self::AutoIndent => "indents.scm",
38 Self::Tags => "tags.scm",
39 Self::RainbowBracket => "rainbows.scm",
40 }
41 }
42
43 pub fn long_title(&self) -> &'static str {
44 match *self {
45 Self::Highlight => "Syntax Highlighting",
46 Self::TextObject => "Treesitter Textobjects",
47 Self::AutoIndent => "Auto Indent",
48 Self::Tags => "Code Navigation Tags",
49 Self::RainbowBracket => "Rainbow Brackets",
50 }
51 }
52
53 pub fn short_title(&self) -> &'static str {
54 match *self {
55 Self::Highlight => "Highlight",
56 Self::TextObject => "Textobject",
57 Self::AutoIndent => "Indent",
58 Self::Tags => "Tags",
59 Self::RainbowBracket => "Rainbow",
60 }
61 }
62 }
63
64 /// Display general diagnostics.
65 pub fn general() -> std::io::Result<()> {
66 let stdout = std::io::stdout();
67 let mut stdout = stdout.lock();
68
69 let config_file = helix_loader::config_file();
70 let lang_file = helix_loader::lang_config_file();
71 let log_file = helix_loader::log_file();
72 let rt_dirs = helix_loader::runtime_dirs();
73
74 if config_file.exists() {
75 writeln!(stdout, "Config file: {}", config_file.display())?;
76 } else {
77 writeln!(stdout, "Config file: default")?;
78 }
79 if lang_file.exists() {
80 writeln!(stdout, "Language file: {}", lang_file.display())?;
81 } else {
82 writeln!(stdout, "Language file: default")?;
83 }
84 writeln!(stdout, "Log file: {}", log_file.display())?;
85 writeln!(
86 stdout,
87 "Runtime directories: {}",
88 rt_dirs
89 .iter()
90 .map(|d| d.to_string_lossy())
91 .collect::<Vec<_>>()
92 .join(";")
93 )?;
94 for rt_dir in rt_dirs.iter() {
95 if let Ok(path) = std::fs::read_link(rt_dir) {
96 let msg = format!(
97 "Runtime directory {} is symlinked to: {}",
98 rt_dir.display(),
99 path.display()
100 );
101 writeln!(stdout, "{}", msg.yellow())?;
102 }
103 if !rt_dir.exists() {
104 let msg = format!("Runtime directory does not exist: {}", rt_dir.display());
105 writeln!(stdout, "{}", msg.yellow())?;
106 } else if rt_dir.read_dir().ok().map(|it| it.count()) == Some(0) {
107 let msg = format!("Runtime directory is empty: {}", rt_dir.display());
108 writeln!(stdout, "{}", msg.yellow())?;
109 }
110 }
111
112 Ok(())
113 }
114
115 pub fn clipboard() -> std::io::Result<()> {
116 let stdout = std::io::stdout();
117 let mut stdout = stdout.lock();
118
119 let config = match Config::load_default() {
120 Ok(config) => config,
121 Err(ConfigLoadError::Error(err)) if err.kind() == std::io::ErrorKind::NotFound => {
122 Config::default()
123 }
124 Err(err) => {
125 writeln!(stdout, "{}", "Configuration file malformed".red())?;
126 writeln!(stdout, "{}", err)?;
127 return Ok(());
128 }
129 };
130
131 match config.editor.clipboard_provider.name().as_ref() {
132 "none" => {
133 writeln!(
134 stdout,
135 "{}",
136 "System clipboard provider: Not installed".red()
137 )?;
138 writeln!(
139 stdout,
140 " {}",
141 "For troubleshooting system clipboard issues, refer".red()
142 )?;
143 writeln!(stdout, " {}",
144 "https://github.com/helix-editor/helix/wiki/Troubleshooting#copypaste-fromto-system-clipboard-not-working"
145 .red().underlined())?;
146 }
147 name => writeln!(stdout, "System clipboard provider: {}", name)?,
148 }
149
150 Ok(())
151 }
152
153 pub fn languages_all() -> std::io::Result<()> {
154 languages(None)
155 }
156
157 pub fn languages_selection() -> std::io::Result<()> {
158 let selection = helix_loader::grammar::get_grammar_names().unwrap_or_default();
159 languages(selection)
160 }
161
162 fn languages(selection: Option<HashSet<String>>) -> std::io::Result<()> {
163 let stdout = std::io::stdout();
164 let mut stdout = stdout.lock();
165
166 let trust = helix_loader::workspace_trust::WorkspaceTrust::fully_trusted();
167 let mut syn_loader_conf = match user_lang_config(&trust) {
168 Ok(conf) => conf,
169 Err(err) => {
170 let stderr = std::io::stderr();
171 let mut stderr = stderr.lock();
172
173 writeln!(
174 stderr,
175 "{}: {}",
176 "Error parsing user language config".red(),
177 err
178 )?;
179 writeln!(stderr, "{}", "Using default language config".yellow())?;
180 default_lang_config()
181 }
182 };
183
184 let mut headings = vec!["Language", "Language servers", "Debug adapter", "Formatter"];
185
186 for feat in TsFeature::all() {
187 headings.push(feat.short_title())
188 }
189
190 let terminal_cols = termina::PlatformTerminal::new()
191 .and_then(|terminal| terminal.get_dimensions())
192 .map(|size| size.cols)
193 .unwrap_or(80);
194 let column_width = terminal_cols as usize / headings.len();
195 let is_terminal = std::io::stdout().is_terminal();
196
197 let fit = |s: &str| -> Stylized<'static> {
198 format!(
199 "{:column_width$}",
200 s.get(..column_width - 2)
201 .map(|s| format!("{}…", s))
202 .unwrap_or_else(|| s.to_string())
203 )
204 .stylized()
205 };
206 let color = |s: Stylized<'static>, c: ColorSpec| if is_terminal { s.foreground(c) } else { s };
207 let bold = |s: Stylized<'static>| if is_terminal { s.bold() } else { s };
208
209 for heading in headings {
210 write!(stdout, "{}", bold(fit(heading)))?;
211 }
212 writeln!(stdout)?;
213
214 syn_loader_conf
215 .language
216 .sort_unstable_by_key(|l| l.language_id.clone());
217
218 let check_binary_with_name = |cmd: Option<(&str, &str)>| match cmd {
219 Some((name, cmd)) => match helix_stdx::env::which(cmd) {
220 Ok(_) => color(fit(&format!("✓ {}", name)), ColorSpec::BRIGHT_GREEN),
221 Err(_) => color(fit(&format!("✘ {}", name)), ColorSpec::BRIGHT_RED),
222 },
223 None => color(fit("None"), ColorSpec::BRIGHT_YELLOW),
224 };
225
226 let check_binary = |cmd: Option<&str>| check_binary_with_name(cmd.map(|cmd| (cmd, cmd)));
227
228 for lang in &syn_loader_conf.language {
229 if selection
230 .as_ref()
231 .is_some_and(|s| !s.contains(&lang.language_id))
232 {
233 continue;
234 }
235
236 write!(stdout, "{}", fit(&lang.language_id))?;
237
238 let mut cmds = lang.language_servers.iter().filter_map(|ls| {
239 syn_loader_conf
240 .language_server
241 .get(&ls.name)
242 .map(|config| (ls.name.as_str(), config.command.as_str()))
243 });
244 write!(stdout, "{}", check_binary_with_name(cmds.next()))?;
245
246 let dap = lang.debugger.as_ref().map(|dap| dap.command.as_str());
247 write!(stdout, "{}", check_binary(dap))?;
248
249 let formatter = lang
250 .formatter
251 .as_ref()
252 .map(|formatter| formatter.command.as_str());
253 write!(stdout, "{}", check_binary(formatter))?;
254
255 for ts_feat in TsFeature::all() {
256 match load_runtime_file(&lang.language_id, ts_feat.runtime_filename()).is_ok() {
257 true => write!(stdout, "{}", color(fit("✓"), ColorSpec::BRIGHT_GREEN))?,
258 false => write!(stdout, "{}", color(fit("✘"), ColorSpec::BRIGHT_RED))?,
259 }
260 }
261
262 writeln!(stdout)?;
263
264 for cmd in cmds {
265 write!(stdout, "{}", fit(""))?;
266 writeln!(stdout, "{}", check_binary_with_name(Some(cmd)))?;
267 }
268 }
269
270 if selection.is_some() {
271 writeln!(
272 stdout,
273 "\nThis list is filtered according to the 'use-grammars' option in languages.toml file.\n\
274 To see the full list, use the '--health all' or '--health all-languages' option."
275 )?;
276 }
277
278 Ok(())
279 }
280
281 /// Display diagnostics pertaining to a particular language (LSP,
282 /// highlight queries, etc).
283 pub fn language(lang_str: String) -> std::io::Result<()> {
284 let stdout = std::io::stdout();
285 let mut stdout = stdout.lock();
286
287 let trust = helix_loader::workspace_trust::WorkspaceTrust::fully_trusted();
288 let syn_loader_conf = match user_lang_config(&trust) {
289 Ok(conf) => conf,
290 Err(err) => {
291 let stderr = std::io::stderr();
292 let mut stderr = stderr.lock();
293
294 writeln!(
295 stderr,
296 "{}: {}",
297 "Error parsing user language config".red(),
298 err
299 )?;
300 writeln!(stderr, "{}", "Using default language config".yellow())?;
301 default_lang_config()
302 }
303 };
304
305 let lang = match syn_loader_conf
306 .language
307 .iter()
308 .find(|l| l.language_id == lang_str)
309 {
310 Some(l) => l,
311 None => {
312 let msg = format!("Language '{}' not found", lang_str);
313 writeln!(stdout, "{}", msg.red())?;
314 let suggestions: Vec<&str> = syn_loader_conf
315 .language
316 .iter()
317 .filter(|l| l.language_id.starts_with(lang_str.chars().next().unwrap()))
318 .map(|l| l.language_id.as_str())
319 .collect();
320 if !suggestions.is_empty() {
321 let suggestions = suggestions.join(", ");
322 writeln!(
323 stdout,
324 "Did you mean one of these: {} ?",
325 suggestions.yellow()
326 )?;
327 }
328 return Ok(());
329 }
330 };
331
332 probe_protocols(
333 "language server",
334 lang.language_servers.iter().filter_map(|ls| {
335 syn_loader_conf
336 .language_server
337 .get(&ls.name)
338 .map(|config| (ls.name.as_str(), config.command.as_str()))
339 }),
340 )?;
341
342 probe_protocol(
343 "debug adapter",
344 lang.debugger.as_ref().map(|dap| dap.command.to_string()),
345 )?;
346
347 probe_protocol(
348 "formatter",
349 lang.formatter
350 .as_ref()
351 .map(|formatter| formatter.command.to_string()),
352 )?;
353
354 probe_parser(lang.grammar.as_ref().unwrap_or(&lang.language_id))?;
355
356 for ts_feat in TsFeature::all() {
357 probe_treesitter_feature(&lang_str, *ts_feat)?
358 }
359
360 Ok(())
361 }
362
363 fn probe_parser(grammar_name: &str) -> std::io::Result<()> {
364 let stdout = std::io::stdout();
365 let mut stdout = stdout.lock();
366
367 write!(stdout, "Tree-sitter parser: ")?;
368
369 match helix_loader::grammar::get_language(grammar_name) {
370 Ok(Some(_)) => writeln!(stdout, "{}", "✓".green()),
371 Ok(None) | Err(_) => writeln!(stdout, "{}", "None".yellow()),
372 }
373 }
374
375 /// Display diagnostics about multiple LSPs and DAPs.
376 fn probe_protocols<'a, I: Iterator<Item = (&'a str, &'a str)> + 'a>(
377 protocol_name: &str,
378 server_cmds: I,
379 ) -> std::io::Result<()> {
380 let stdout = std::io::stdout();
381 let mut stdout = stdout.lock();
382 let mut server_cmds = server_cmds.peekable();
383
384 write!(stdout, "Configured {}s:", protocol_name)?;
385 if server_cmds.peek().is_none() {
386 writeln!(stdout, "{}", " None".yellow())?;
387 return Ok(());
388 }
389 writeln!(stdout)?;
390
391 for (name, cmd) in server_cmds {
392 let (diag, icon) = match helix_stdx::env::which(cmd) {
393 Ok(path) => (path.display().to_string().green(), "✓".green()),
394 Err(_) => (format!("'{}' not found in $PATH", cmd).red(), "✘".red()),
395 };
396 writeln!(stdout, " {} {}: {}", icon, name, diag)?;
397 }
398
399 Ok(())
400 }
401
402 /// Display diagnostics about LSP and DAP.
403 fn probe_protocol(protocol_name: &str, server_cmd: Option<String>) -> std::io::Result<()> {
404 let stdout = std::io::stdout();
405 let mut stdout = stdout.lock();
406
407 write!(stdout, "Configured {}:", protocol_name)?;
408 let Some(cmd) = server_cmd else {
409 writeln!(stdout, "{}", " None".yellow())?;
410 return Ok(());
411 };
412 writeln!(stdout)?;
413
414 let (diag, icon) = match helix_stdx::env::which(&cmd) {
415 Ok(path) => (path.display().to_string().green(), "✓".green()),
416 Err(_) => (format!("'{}' not found in $PATH", cmd).red(), "✘".red()),
417 };
418 writeln!(stdout, " {} {}", icon, diag)?;
419
420 Ok(())
421 }
422
423 /// Display diagnostics about a feature that requires tree-sitter
424 /// query files (highlights, textobjects, etc).
425 fn probe_treesitter_feature(lang: &str, feature: TsFeature) -> std::io::Result<()> {
426 let stdout = std::io::stdout();
427 let mut stdout = stdout.lock();
428
429 let found = match load_runtime_file(lang, feature.runtime_filename()).is_ok() {
430 true => "✓".green(),
431 false => "✘".red(),
432 };
433 writeln!(stdout, "{} queries: {}", feature.short_title(), found)?;
434
435 Ok(())
436 }
437
438 pub fn print_health(health_arg: Option<String>) -> std::io::Result<()> {
439 match health_arg.as_deref() {
440 Some("languages") => languages_selection()?,
441 Some("all-languages") => languages_all()?,
442 Some("clipboard") => clipboard()?,
443 None => {
444 general()?;
445 clipboard()?;
446 writeln!(std::io::stdout().lock())?;
447 languages_selection()?;
448 }
449 Some("all") => {
450 general()?;
451 clipboard()?;
452 writeln!(std::io::stdout().lock())?;
453 languages_all()?;
454 }
455 Some(lang) => language(lang.to_string())?,
456 }
457 Ok(())
458 }