snip_cli/actions/
open_file_with.rs

1use anyhow::{Context, Result};
2use opener;
3use std::{fs, process::Command};
4
5/// Opens the file specified in the configuration JSON file using the system's default text editor.
6///
7/// # Arguments
8///
9/// * `config_path` - A string slice that holds the path to the JSON configuration file.
10///
11/// # Returns
12///
13/// * `Result<()>` - Returns `Ok` if the file is successfully opened, otherwise returns an error.
14pub fn open_file_with(config_path: &str, editor: Option<String>) -> Result<()> {
15    // Read the configuration file
16    let config_content = fs::read_to_string(config_path)
17        .with_context(|| format!("Failed to read the configuration file at: {}", config_path))?;
18
19    // Parse the JSON to extract the `path` field
20    let config: serde_json::Value = serde_json::from_str(&config_content)
21        .with_context(|| "Failed to parse the configuration file as JSON")?;
22
23    // Extract the `path` field
24    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    // Open the file with the default editor
29    // If the editor is not provided, use the default editor
30    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        // Use the provided editor
36        let editor = editor.unwrap();
37        // get the path to the editor
38        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}