genius_core_client/
utils.rs

1use std::{
2    env, fs,
3    path::{Path, PathBuf},
4};
5
6#[cfg(feature = "pyo3")]
7use pyo3::prelude::*;
8
9use kortex_gen_grpc::hstp::v1::ErrorCode;
10use serde_json::Value;
11
12use crate::types::{entity::HSMLEntity, error::HstpError};
13
14fn get_absolute_path<P: AsRef<Path>>(relative_path: P) -> Option<PathBuf> {
15    // Get the current working directory
16    let current_dir = env::current_dir().ok()?;
17
18    // Create a Path object from the relative path
19    let relative_path = relative_path.as_ref();
20
21    // Combine the current directory with the relative path to get the absolute path
22    let mut absolute_path = current_dir.join(relative_path);
23
24    // Clean up the path by removing '.', '..' and similar components
25    absolute_path = absolute_path
26        .components()
27        .fold(PathBuf::new(), |mut acc, component| {
28            match component {
29                std::path::Component::Normal(part) => acc.push(part),
30                std::path::Component::ParentDir => {
31                    acc.pop();
32                }
33                _ => (),
34            }
35            acc
36        });
37
38    // Return the absolute path
39    Some(absolute_path)
40}
41
42#[cfg(feature = "pyo3")]
43#[pyfunction]
44pub fn make_swid(class: &str) -> String {
45    let mut swid = format!("swid:{}:", class);
46    swid.push_str(&nanoid::nanoid!());
47    swid
48}
49
50pub fn read_hsml_json<P: AsRef<Path>>(path: P) -> Result<Vec<HSMLEntity>, HstpError> {
51    let ref_path: &Path = path.as_ref();
52    //read file to string
53    let file = fs::read_to_string(ref_path).map_err(|e| {
54        let absolute_str = get_absolute_path(ref_path).unwrap();
55        HstpError::new(
56            ErrorCode::None,
57            format!(
58                "Failed to read file, you were tyring to read {:?}. {}",
59                absolute_str.to_string_lossy().replace("./", ""),
60                e
61            ),
62            "".into(),
63        )
64    })?;
65
66    //parse file to json
67    let value: Value = serde_json::from_str(&file).map_err(|e| {
68        HstpError::new(
69            ErrorCode::None,
70            format!("Failed to parse json file (read_hsml_json): {}", e),
71            "".into(),
72        )
73    })?;
74
75    value_to_hsml(value)
76}
77
78pub fn value_to_hsml(value: Value) -> Result<Vec<HSMLEntity>, HstpError> {
79    //is json an array?
80    let is_array = value.is_array();
81
82    //if not an array, make it an array of one
83    let value = if !is_array {
84        vec![value]
85    } else {
86        value.as_array().unwrap().clone()
87    };
88
89    //convert json to hsml
90    value
91        .iter()
92        .map(HSMLEntity::from_value)
93        .collect::<Result<Vec<_>, _>>()
94}