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