use anyhow::{Context, Result};
use opener;
use std::{fs, process::Command};
pub fn open_file_with(config_path: &str, editor: Option<String>) -> Result<()> {
let config_content = fs::read_to_string(config_path)
.with_context(|| format!("Failed to read the configuration file at: {}", config_path))?;
let config: serde_json::Value = serde_json::from_str(&config_content)
.with_context(|| "Failed to parse the configuration file as JSON")?;
let file_path = config["path"].as_str().ok_or_else(|| {
anyhow::anyhow!("`path` field is missing or invalid in configuration file")
})?;
if editor.is_none() {
opener::open(file_path)
.with_context(|| format!("Failed to open the file at path: {}", file_path))
.map_err(|err| anyhow::anyhow!("Failed to open the file: {}", err))?;
} else {
let editor = editor.unwrap();
Command::new(editor.clone())
.arg(file_path)
.spawn()
.with_context(|| {
format!(
"Failed to open the file at path: {} with program: {}",
file_path, editor
)
})?;
}
Ok(())
}