tq/
lib.rs

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use std::{fs::File, io::Read};
use thiserror::Error;
use toml::Value;

type TqResult<T> = std::result::Result<T, TqError>;

#[derive(Error, Debug)]
pub enum TqError {
    #[error("Failed to open file \"{file_name}\": {cause}")]
    FileOpenError { file_name: String, cause: String },

    #[error("Failed to parse TOML file \"{file_name}\": {cause}")]
    TomlParseError { file_name: String, cause: String },

    #[error("Could not find pattern {pattern}")]
    PatternNotFoundError { pattern: String },
}

pub fn extract_pattern<'a>(toml_file: &'a Value, pattern: &str) -> TqResult<&'a Value> {
    if pattern.is_empty() || pattern == "." {
        return Ok(toml_file);
    }

    let pattern = pattern.trim_start_matches('.');

    pattern
        .split('.')
        .fold(Some(toml_file), |acc, key| match acc {
            Some(a) => a.get(key),
            None => None,
        })
        .ok_or_else(|| TqError::PatternNotFoundError {
            pattern: pattern.to_string(),
        })
}

#[deprecated = 
    "Users should use/call the similar functions from the `toml` crate going forward. This function will be \
    removed in a future release"
]
pub fn load_toml_from_file(file_name: &str) -> TqResult<toml::Value> {
    let mut file = File::open(file_name).map_err(|e| TqError::FileOpenError {
        file_name: file_name.to_string(),
        cause: e.to_string(),
    })?;
    let mut contents = String::new();
    let _ = file.read_to_string(&mut contents);
    toml::from_str::<Value>(&contents).map_err(|e| TqError::TomlParseError {
        file_name: file_name.to_string(),
        cause: e.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_pattern() {
        let toml_file = toml::from_str(
            r#"
            [package]
            test = "test"
            "#,
        )
        .unwrap();

        let x = extract_pattern(&toml_file, "package.test").unwrap();

        assert_eq!(x, &Value::String("test".to_string()));
    }

    #[test]
    fn test_fail_extract() {
        let toml_file = toml::from_str(
            r#"
            [package]
            test = "test"
            "#,
        )
        .unwrap();

        let x = extract_pattern(&toml_file, "package.test2");

        assert!(x.is_err());
        assert_eq!(
            x.unwrap_err().to_string(),
            "Could not find pattern package.test2"
        );
    }

    #[test]
    fn test_get_prop_with_many_tables() {
        let toml_file = toml::from_str(
            r#"
            [package]
            test = "test"
            [package2]
            test2 = "test2"
            "#,
        )
        .unwrap();

        let x = extract_pattern(&toml_file, "package.test").unwrap();

        assert_eq!(x, &Value::String("test".to_string()));
    }
}