Skip to main content

nils_common/provider_runtime/
json.rs

1use serde_json::Value;
2use std::fs;
3use std::path::Path;
4
5use super::error::CoreError;
6
7pub fn read_json(path: &Path) -> Result<Value, CoreError> {
8    let raw = fs::read_to_string(path).map_err(|err| {
9        CoreError::auth(
10            "read-json-failed",
11            format!("failed to read json: {} ({err})", path.display()),
12        )
13    })?;
14    let value: Value = serde_json::from_str(&raw).map_err(|err| {
15        CoreError::auth(
16            "invalid-json",
17            format!("invalid json: {} ({err})", path.display()),
18        )
19    })?;
20    Ok(value)
21}
22
23pub fn string_at(value: &Value, path: &[&str]) -> Option<String> {
24    let mut cursor = value;
25    for key in path {
26        cursor = cursor.get(*key)?;
27    }
28    cursor.as_str().map(strip_newlines)
29}
30
31pub fn i64_at(value: &Value, path: &[&str]) -> Option<i64> {
32    let mut cursor = value;
33    for key in path {
34        cursor = cursor.get(*key)?;
35    }
36    match cursor {
37        Value::Number(value) => value.as_i64(),
38        Value::String(value) => value.trim().parse::<i64>().ok(),
39        _ => None,
40    }
41}
42
43pub fn strip_newlines(raw: &str) -> String {
44    raw.split(&['\n', '\r'][..])
45        .next()
46        .unwrap_or("")
47        .to_string()
48}