hyprshell_config_lib/
save.rs1use crate::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::io::Write;
9use std::path::Path;
10use tracing::{debug, debug_span, info};
11
12const CONFIG_EXPLANATION: &str =
13 "Edit via `hyprshell config edit`, generate via `hyprshell config generate`";
14
15pub fn write_config(
16 config_path: &Path,
17 config: &Config,
18 override_file: bool,
19) -> anyhow::Result<()> {
20 let _span = debug_span!("write_config").entered();
21 let config_path_display = config_path.display();
22 if config_path.exists() && !override_file {
23 bail!(
24 "Config file at {config_path_display} already exists, delete it before generating a new one or use -f to override"
25 );
26 }
27 if let Some(parent) = config_path.parent() {
28 create_dir_all(parent)
29 .with_context(|| format!("Failed to create config dir at ({})", parent.display()))?;
30 }
31 let str = match config_path.extension().and_then(OsStr::to_str) {
32 None | Some("ron") => Options::default()
33 .with_default_extension(Extensions::IMPLICIT_SOME)
34 .with_default_extension(Extensions::UNWRAP_NEWTYPES)
35 .with_default_extension(Extensions::UNWRAP_VARIANT_NEWTYPES)
36 .to_string_pretty(config, PrettyConfig::default())
37 .with_context(|| format!("Failed to write RON config to ({config_path_display})")),
38 Some("json5" | "json") => {
39 serde_json::to_string_pretty(config).context("Failed to generate JSON config")
40 }
41 Some("toml") => toml::to_string_pretty(config).context("Failed to generate TOML config"),
42 Some(ext) => bail!(
43 "Invalid config file extension: {ext} (run with -vv and check `FEATURES: ` debug log to see enabled extensions)"
44 ),
45 }?;
46 #[allow(clippy::match_same_arms)]
47 let header = match config_path.extension().and_then(OsStr::to_str) {
48 None | Some("ron") => format!("// {CONFIG_EXPLANATION}"),
49 Some("json5") => format!("// {CONFIG_EXPLANATION}"),
50 Some("toml") => format!("# {CONFIG_EXPLANATION}"),
51 _ => String::new(),
52 };
53 let content = format!("{header}\n{str}");
54 let mut file = File::create(config_path)
55 .with_context(|| format!("Failed to create config file at ({config_path_display})"))?;
56 file.write_all(content.as_bytes())
57 .with_context(|| format!("Failed to write to config file at ({config_path_display})"))
58 .inspect_err(|_| {
59 info!("New config contents: {config:?}");
60 })?;
61
62 debug!("Config file written successfully at {config_path_display}");
63 Ok(())
64}