hyprshell_core_lib/config/
save.rs

1use crate::config::Config;
2use anyhow::{Context, bail};
3use ron::Options;
4use ron::extensions::Extensions;
5use ron::ser::PrettyConfig;
6use std::ffi::OsStr;
7use std::fs::{File, create_dir_all};
8use std::path::Path;
9use tracing::{Level, info, span};
10
11pub fn write_config(
12    config_path: &Path,
13    config: &Config,
14    override_file: bool,
15) -> anyhow::Result<()> {
16    let _span = span!(Level::TRACE, "write_config").entered();
17
18    if config_path.exists() && !override_file {
19        bail!(
20            "Config file at {config_path:?} already exists, delete it before generating a new one or use -f to override"
21        );
22    }
23    if let Some(parent) = config_path.parent() {
24        create_dir_all(parent)
25            .with_context(|| format!("Failed to create config dir at ({parent:?})"))?;
26    }
27    match config_path.extension().and_then(OsStr::to_str) {
28        None | Some("ron") => {
29            let file = File::create(config_path)
30                .with_context(|| format!("Failed to create config at ({config_path:?})"))?;
31            Options::default()
32                .with_default_extension(Extensions::IMPLICIT_SOME)
33                .with_default_extension(Extensions::UNWRAP_NEWTYPES)
34                .with_default_extension(Extensions::UNWRAP_VARIANT_NEWTYPES)
35                .to_io_writer_pretty(file, config, PrettyConfig::default())
36                .context("Failed to write ron config")?;
37        }
38        Some("json") => {
39            let file = File::create(config_path)
40                .with_context(|| format!("Failed to create config at ({config_path:?})"))?;
41            serde_json::to_writer_pretty(file, config).context("Failed to write json config")?
42        }
43        #[cfg(feature = "toml_config")]
44        Some("toml") => {
45            use std::fs::write;
46            let str = toml::to_string_pretty(config).context("Failed to write toml config")?;
47            write(config_path, str)
48                .with_context(|| format!("Failed to create config at ({config_path:?})"))?;
49        }
50        Some(ext) => bail!(
51            "Invalid config file extension: {} (check `FEATURES: ` debug log to see enabled extensions)",
52            ext
53        ),
54    };
55
56    info!("Config file written successfully at {:?}", config_path);
57    Ok(())
58}