terminal_light/
env.rs

1use crate::*;
2
3/// Query the $COLORFGBG env variable and parse
4/// the result to extract the background in ANSI.
5#[allow(clippy::iter_skip_next)]
6pub fn bg_color() -> Result<AnsiColor, TlError> {
7    let s = std::env::var("COLORFGBG").map_err(|_| TlError::NoColorFgBgEnv)?;
8    parse_colorfgbg(&s)
9}
10
11/// Parse the content of the COLORFGBG variable, which is supposed
12/// to be either like `17;45` or `0;default;15`, with the last token
13/// being the ansi code of the background color.
14///
15/// Note that there doesn't seem to be any authoritive documentation
16/// on the exact format.
17fn parse_colorfgbg(s: &str) -> Result<AnsiColor, TlError> {
18    let token: Vec<&str> = s.split(';').collect();
19    let bg = match token.len() {
20        2 => &token[1],
21        3 => &token[2],
22        _ => {
23            return Err(TlError::WrongFormat(s.to_string()));
24        }
25    };
26    let code = bg.parse()?;
27    Ok(AnsiColor { code })
28}
29
30#[test]
31fn test_parse_color_fgbg() {
32    assert_eq!(parse_colorfgbg("17;45").unwrap(), AnsiColor::new(45));
33    assert_eq!(parse_colorfgbg("0;default;15").unwrap(), AnsiColor::new(15));
34    assert!(matches!(
35        parse_colorfgbg("15").unwrap_err(),
36        TlError::WrongFormat(_)
37    ));
38    assert!(matches!(
39        parse_colorfgbg("15;FF").unwrap_err(),
40        TlError::ParseInt(_)
41    ));
42}