snip_cli/actions/
open_file_with.rs1use anyhow::{Context, Result};
2use opener;
3use std::{fs, process::Command};
4
5pub fn open_file_with(config_path: &str, editor: Option<String>) -> Result<()> {
15 let config_content = fs::read_to_string(config_path)
17 .with_context(|| format!("Failed to read the configuration file at: {}", config_path))?;
18
19 let config: serde_json::Value = serde_json::from_str(&config_content)
21 .with_context(|| "Failed to parse the configuration file as JSON")?;
22
23 let file_path = config["path"].as_str().ok_or_else(|| {
25 anyhow::anyhow!("`path` field is missing or invalid in configuration file")
26 })?;
27
28 if editor.is_none() {
31 opener::open(file_path)
32 .with_context(|| format!("Failed to open the file at path: {}", file_path))
33 .map_err(|err| anyhow::anyhow!("Failed to open the file: {}", err))?;
34 } else {
35 let editor = editor.unwrap();
37 Command::new(editor.clone())
39 .arg(file_path)
40 .spawn()
41 .with_context(|| {
42 format!(
43 "Failed to open the file at path: {} with program: {}",
44 file_path, editor
45 )
46 })?;
47 }
48 Ok(())
49}