From 60b5574ca7422fe3a84dd105b1b480ce46a3b4e4 Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Thu, 16 Mar 2023 15:38:28 -0600 Subject: [PATCH] stdin readline ok --- src/config.rs | 31 ++++++++++++++++++------------- src/engine.rs | 14 +++++++++++++- src/main.rs | 10 ++++++---- 3 files changed, 37 insertions(+), 18 deletions(-) diff --git a/src/config.rs b/src/config.rs index f1c45fc..33d8684 100644 --- a/src/config.rs +++ b/src/config.rs @@ -5,36 +5,41 @@ use std::env; #[derive(Serialize, Deserialize, Debug)] pub struct Config { - streams: Streams, + pub streams: Streams, } #[derive(Serialize, Deserialize, Debug)] -struct Streams { - input: Stream, - output: Stream, +pub struct Streams { + pub input: Stream, + pub output: Stream, } #[derive(Serialize, Deserialize, Debug)] -struct Stream { - engine: Engine, +pub struct Stream { + pub engine: Engine, } #[derive(Serialize, Deserialize, Debug)] -struct Engine { - name: String, +pub struct Engine { + pub name: String, } -pub fn build_config() -> Config { +pub fn build_config() -> Result { let config_path = env::var("CONFIG_PATH"); match config_path { Ok(p) => return build_config_yaml(p), - Err(_) => return build_config_std(), + Err(_) => return Ok(build_config_std()), } } -fn build_config_yaml(path: String) -> Config { - let buffer: String = fs::read_to_string(path).unwrap(); - return serde_yaml::from_str(&buffer).unwrap(); +fn build_config_yaml(path: String) -> Result { + match fs::read_to_string(&path) { + Ok(buffer) => match serde_yaml::from_str(&buffer) { + Ok(result) => Ok(result), + Err(_) => Err("failed to read ".to_string()+&path.as_str()), + }, + Err(_) => Err("failed to read ".to_string()+&path.as_str()), + } } fn build_config_std() -> Config { diff --git a/src/engine.rs b/src/engine.rs index 9b27d78..a64a17c 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1,12 +1,24 @@ +use crate::config::Engine; + pub trait InputEngine { fn get(&self) -> String; } +pub fn build_input_engine(cfg: &Engine) -> Result, String> { + match cfg.name.as_str() { + "stdin" => return Ok(Box::new(InputEngineStdin{})), + _ => return Err("unknown input engine name".to_string() + &cfg.name), + } +} + struct InputEngineStdin {} impl InputEngine for InputEngineStdin { fn get(&self) -> String { - return "hello world".to_string(); + let stdin = std::io::stdin(); + let mut result = String::new(); + stdin.read_line(&mut result).unwrap(); + return result.trim().to_string(); } } diff --git a/src/main.rs b/src/main.rs index 64f10b4..c63dfc7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,9 @@ -pub mod config; -pub mod engine; +mod config; +mod engine; fn main() { - let cfg = config::build_config(); - println!("{:?}", cfg); + let cfg = config::build_config().unwrap(); + let input_engine = engine::build_input_engine(&cfg.streams.input.engine); + println!("{:?} => {}", cfg.streams.input.engine.name, input_engine.is_ok()); + println!("{}", input_engine.unwrap().get()); }