hyprshell_core_lib/config/
load.rs1use crate::config::Config;
2use anyhow::{bail, Context};
3use ron::extensions::Extensions;
4use ron::Options;
5use std::ffi::OsStr;
6use std::path::Path;
7use tracing::{span, Level};
8
9pub fn load_config(config_path: &Path) -> anyhow::Result<Config> {
10 let _span = span!(Level::TRACE, "load_config").entered();
11 if !config_path.exists() {
12 bail!("Config file does not exist, create it using `hyprshell config generate`");
13 }
14 let config = match config_path.extension().and_then(OsStr::to_str) {
15 None | Some("ron") => {
16 let options = Options::default()
17 .with_default_extension(Extensions::IMPLICIT_SOME)
18 .with_default_extension(Extensions::UNWRAP_NEWTYPES)
19 .with_default_extension(Extensions::UNWRAP_VARIANT_NEWTYPES);
20 let file = std::fs::File::open(config_path)
21 .with_context(|| format!("Failed to open config at ({config_path:?})"))?;
22 options
23 .from_reader(file)
24 .context("Failed to read ron config")?
25 }
26 #[cfg(feature = "json_config")]
27 Some("json") => {
28 let file = std::fs::File::open(config_path)
29 .with_context(|| format!("Failed to open config at ({config_path:?})"))?;
30 serde_json::from_reader(file).context("Failed to read json config")?
31 }
32 #[cfg(feature = "toml_config")]
33 Some("toml") => {
34 use std::io::Read;
35 let mut file = std::fs::File::open(config_path)
36 .with_context(|| format!("Failed to open config at ({config_path:?})"))?;
37 let mut content = String::new();
38 file.read_to_string(&mut content)
39 .context("Failed to read toml config")?;
40 toml::from_str(&content).context("Failed to parse toml config")?
41 }
42 Some(ext) => bail!("Invalid config file extension: {}", ext),
43 };
44
45 Ok(config)
46}