1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
mod errors;
mod fields;
pub mod lang;
mod strtab;
mod terminfo;
mod terminfobuf;

pub use self::errors::*;
pub use self::fields::*;
pub use self::terminfo::*;
pub use self::terminfobuf::*;

pub use self::BooleanField::*;
pub use self::NumericField::*;
pub use self::StringField::*;

use failure::ResultExt;
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;

/// Enumerate any know terminfo databases on the system.
pub fn databases() -> Vec<PathBuf> {
    let mut dbs = Vec::new();

    if let Ok(terminfo) = env::var("TERMINFO") {
        dbs.push(PathBuf::from(terminfo))
    }

    if let Some(home) = env::home_dir() {
        dbs.push(home.join(".terminfo"))
    }

    if let Ok(dirs) = env::var("TERMINFO_DIRS") {
        dbs.extend(
            dirs.split(":")
                .filter(|p| !p.is_empty())
                .map(|p| PathBuf::from(p)),
        );
    }

    dbs.push(PathBuf::from("/usr/share/terminfo"));
    dbs
}

/// Get a path to the terminfo file base on the `$TERM` environment variable.
///
/// This function emulates the `curses` method for finding the compiled terminfo file.
/// This method is explained in detail in `terminfo.5`.
pub fn path() -> Option<PathBuf> {
    let terminal_name = match env::var("TERM") {
        Ok(v) => {
            if v.is_empty() {
                return None;
            } else {
                v
            }
        }
        Err(_) => return None,
    };

    let suffix = PathBuf::from(&terminal_name[..1]).join(terminal_name);
    databases()
        .iter()
        .find(|p| p.join(&suffix).exists())
        .map(|p| p.join(suffix))
}

pub fn from_env() -> Result<TermInfoBuf> {
    let path = match path() {
        Some(v) => v,
        None => return Err(ErrorKind::FailedToFindTermInfo.into()),
    };

    let mut file = File::open(path).context(ErrorKind::FailedToParseFile)?;
    let mut data = Vec::new();

    file.read_to_end(&mut data)
        .context(ErrorKind::FailedToParseFile)?;

    Ok(TermInfo::parse(&data)
        .context(ErrorKind::FailedToParseFile)?
        .into())
}