1//! ncurses-compatible database discovery.
2//!
3//! Does not support hashed database, only filesystem!
4
5use std::env;
6use std::fs;
7use std::path::PathBuf;
8
9#[cfg(test)]
10mod tests;
11
12/// Return path to database entry for `term`
13#[allow(deprecated)]
14pub(crate) fn get_dbpath_for_term(term: &str) -> Option<PathBuf> {
15 let mut dirs_to_search = Vec::new();
16 let first_char = term.chars().next()?;
17
18 // Find search directory
19 if let Some(dir) = env::var_os("TERMINFO") {
20 dirs_to_search.push(PathBuf::from(dir));
21 }
22
23 if let Ok(dirs) = env::var("TERMINFO_DIRS") {
24 for i in dirs.split(':') {
25 if i.is_empty() {
26 dirs_to_search.push(PathBuf::from("/usr/share/terminfo"));
27 } else {
28 dirs_to_search.push(PathBuf::from(i));
29 }
30 }
31 } else {
32 // Found nothing in TERMINFO_DIRS, use the default paths:
33 // According to /etc/terminfo/README, after looking at
34 // ~/.terminfo, ncurses will search /etc/terminfo, then
35 // /lib/terminfo, and eventually /usr/share/terminfo.
36 // On Haiku the database can be found at /boot/system/data/terminfo
37 if let Some(mut homedir) = env::home_dir() {
38 homedir.push(".terminfo");
39 dirs_to_search.push(homedir)
40 }
41
42 dirs_to_search.push(PathBuf::from("/etc/terminfo"));
43 dirs_to_search.push(PathBuf::from("/lib/terminfo"));
44 dirs_to_search.push(PathBuf::from("/usr/share/terminfo"));
45 dirs_to_search.push(PathBuf::from("/boot/system/data/terminfo"));
46 }
47
48 // Look for the terminal in all of the search directories
49 for mut p in dirs_to_search {
50 if fs::metadata(&p).is_ok() {
51 p.push(&first_char.to_string());
52 p.push(term);
53 if fs::metadata(&p).is_ok() {
54 return Some(p);
55 }
56 p.pop();
57 p.pop();
58
59 // on some installations the dir is named after the hex of the char
60 // (e.g., macOS)
61 p.push(&format!("{:x}", first_char as usize));
62 p.push(term);
63 if fs::metadata(&p).is_ok() {
64 return Some(p);
65 }
66 }
67 }
68 None
69}
70