From 75f2eafc4c932239bde4f657efcf9127866c7f35 Mon Sep 17 00:00:00 2001 From: tali Date: Sun, 16 Apr 2023 20:24:44 -0400 Subject: [PATCH] all the tidepool config file to be JSON --- tidepool/src/main.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/tidepool/src/main.rs b/tidepool/src/main.rs index 8821eda..eff3ecf 100644 --- a/tidepool/src/main.rs +++ b/tidepool/src/main.rs @@ -61,7 +61,7 @@ fn create_mailbox() -> (mpsc::SyncSender, mpsc::Receiver) { } fn single(args: SingleRun) -> Result<()> { - let config = parse_config_file(&args.config_file)?; + let config = read_config_file(&args.config_file)?; let (tx, rx) = create_mailbox(); let exit_early = Arc::new(atomic::AtomicBool::new(false)); @@ -114,7 +114,7 @@ fn single(args: SingleRun) -> Result<()> { } fn multi(args: MultiRun) -> Result<()> { - let config = parse_config_file(&args.config_file)?; + let config = read_config_file(&args.config_file)?; let (tx, rx) = create_mailbox(); let tasks = args.count.map_or(i64::MAX, |n| n as i64); @@ -182,13 +182,33 @@ fn multi(args: MultiRun) -> Result<()> { Ok(()) } -fn parse_config_file(path: &Path) -> Result { +fn read_config_file(path: &Path) -> Result { + enum Format { + Json, + Toml, + } + + let extension = path.extension().and_then(|e| e.to_str()); + let format = match extension { + Some(e) if e.eq_ignore_ascii_case("json") => Format::Json, + Some(e) if e.eq_ignore_ascii_case("toml") => Format::Toml, + _ => { + return Err(anyhow::anyhow!( + "invalid config file extension, supports .toml or .json" + )); + } + }; + let mut contents = String::new(); std::fs::File::open(path) .with_context(|| format!("error opening config file '{}'", path.display()))? .read_to_string(&mut contents) .context("error reading config file")?; - toml::from_str(&contents).context("error parsing config file") + + match format { + Format::Json => serde_json::from_str(&contents).context("error parsing config file"), + Format::Toml => toml::from_str(&contents).context("error parsing config file"), + } } fn write_output(io_args: &IoArgs, path: Option<&Path>, output: &Output) -> Result<()> {