Skip to content

Commit

Permalink
Merge pull request #141 from CSML-by-Clevy/fs/imp/get-custom-componen…
Browse files Browse the repository at this point in the history
…t-name-from-filename

feat: read the component name from the file name
  • Loading branch information
frsechet authored Oct 30, 2020
2 parents 857ff77 + 5918b99 commit 9f53967
Showing 1 changed file with 32 additions and 19 deletions.
51 changes: 32 additions & 19 deletions csml_interpreter/src/interpreter/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,38 +12,44 @@ pub mod video;
pub mod wait;

use crate::data::error_info::ErrorInfo;
use std::io::prelude::*;
use std::{env, fs};
use std::io::prelude::*;
use std::path::Path;

////////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTION
////////////////////////////////////////////////////////////////////////////////

fn read_components_dir(
dir: &Path,
map: &mut serde_json::Map<String, serde_json::Value>,
) -> Result<(), ErrorInfo> {
// load components from the `COMPONENTS_DIR` dir if any
let components_dir = match env::var("COMPONENTS_DIR") {
Ok(components_dir) => components_dir,
Err(_) => return Ok(()),
};

let paths = fs::read_dir(components_dir)?;

for path in paths {
let mut file = fs::File::open(path?.path().to_str().unwrap())?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if !path.is_dir() {
let mut file = fs::File::open(path.to_str().unwrap())?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;

let component: serde_json::Value = serde_json::from_str(&contents)?;
let component: serde_json::Value = serde_json::from_str(&contents).unwrap();

if let serde_json::Value::Object(mut obj) = component {
map.append(&mut obj);
} else {
// TODO: error msg
eprintln!("native component bad format {:?}", component);
if let serde_json::Value::Object(obj) = component {
let file_stem = path.file_stem().unwrap();
let component_name: &str = file_stem.to_str().unwrap();
map.insert(component_name.to_owned(), serde_json::json!(obj));
} else {
// TODO: error msg
eprintln!("Invalid custom component formatting {:?}", component);
}
}
}
}
else {
eprintln!("{} is not a directory!", dir.to_str().unwrap());
}

Ok(())
}
Expand All @@ -68,7 +74,14 @@ pub fn load_components() -> Result<serde_json::Map<String, serde_json::Value>, E
video::add_video(&mut map);
wait::add_wait(&mut map);

let _res = read_components_dir(&mut map)?;
// load components from the `COMPONENTS_DIR` dir if any
let components_dir = match env::var("COMPONENTS_DIR") {
Ok(dir) => dir,
Err(_) => return Ok(map),
};

let components_dir = Path::new(&components_dir);
let _res = read_components_dir(&components_dir, &mut map)?;

Ok(map)
}

0 comments on commit 9f53967

Please sign in to comment.