From ef038cc345edc723f826d378bf09b37b8e73fe7b Mon Sep 17 00:00:00 2001 From: Lann Martin Date: Thu, 4 Apr 2024 14:28:05 -0400 Subject: [PATCH] Accept runtime config in either JSON or TOML Signed-off-by: Lann Martin --- crates/trigger/src/runtime_config.rs | 31 ++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/crates/trigger/src/runtime_config.rs b/crates/trigger/src/runtime_config.rs index 86f3431e1..cc2e85d7b 100644 --- a/crates/trigger/src/runtime_config.rs +++ b/crates/trigger/src/runtime_config.rs @@ -49,12 +49,7 @@ impl RuntimeConfig { /// later-loaded file take precedence over any earlier-loaded files. pub fn merge_config_file(&mut self, path: impl Into) -> Result<()> { let path = path.into(); - let bytes = fs::read(&path).with_context(|| { - format!("Failed to load runtime config file {}", quoted_path(&path)) - })?; - let mut opts: RuntimeConfigOpts = toml::from_slice(&bytes).with_context(|| { - format!("Failed to parse runtime config file {}", quoted_path(&path)) - })?; + let mut opts = RuntimeConfigOpts::parse_file(&path)?; opts.file_path = Some(path); self.files.push(opts); Ok(()) @@ -221,6 +216,30 @@ pub struct RuntimeConfigOpts { pub file_path: Option, } +impl RuntimeConfigOpts { + fn parse_file(path: &Path) -> Result { + let contents = fs::read_to_string(path) + .with_context(|| format!("Failed to read runtime config file {}", quoted_path(path)))?; + let ext = path.extension().unwrap_or_default(); + let is_json = ext != "toml" && (ext == "json" || contents.trim_start().starts_with('{')); + if is_json { + serde_json::from_str(&contents).with_context(|| { + format!( + "Failed to parse runtime config JSON file {}", + quoted_path(path) + ) + }) + } else { + toml::from_str(&contents).with_context(|| { + format!( + "Failed to parse runtime config TOML file {}", + quoted_path(path) + ) + }) + } + } +} + fn resolve_config_path(path: &Path, config_opts: &RuntimeConfigOpts) -> Result { if path.is_absolute() { return Ok(path.to_owned());