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<()> {