hyprshell_core_lib/config/migrate/
mod.rs

1use crate::config;
2use crate::config::save::write_config;
3use anyhow::{bail, Context};
4use ron::extensions::Extensions;
5use ron::Options;
6use std::ffi::OsStr;
7use std::path::Path;
8use tracing::{span, Level};
9
10mod convert;
11mod old_structs;
12
13pub fn migrate(config_path: &Path) -> anyhow::Result<config::Config> {
14    let _span = span!(Level::TRACE, "migrate_if_needed").entered();
15    match load_old_config(config_path) {
16        Ok(old_config) => {
17            let new_config = config::Config::from(old_config);
18            write_config(config_path, &new_config, true)?;
19            Ok(new_config)
20        }
21        Err(e) => {
22            bail!("Failed to load old config for migration: {e:?}");
23        }
24    }
25}
26
27fn load_old_config(config_path: &Path) -> anyhow::Result<old_structs::Config> {
28    let _span = span!(Level::TRACE, "load_old_config").entered();
29    if !config_path.exists() {
30        bail!("Config file does not exist no need to migrate");
31    }
32    let config = match config_path.extension().and_then(OsStr::to_str) {
33        None | Some("ron") => {
34            let options = Options::default()
35                .with_default_extension(Extensions::IMPLICIT_SOME)
36                .with_default_extension(Extensions::UNWRAP_NEWTYPES)
37                .with_default_extension(Extensions::UNWRAP_VARIANT_NEWTYPES);
38            let file = std::fs::File::open(config_path)
39                .with_context(|| format!("Failed to open config at ({config_path:?})"))?;
40            options
41                .from_reader(file)
42                .context("Failed to read ron config")?
43        }
44        Some("json") => {
45            let file = std::fs::File::open(config_path)
46                .with_context(|| format!("Failed to open config at ({config_path:?})"))?;
47            serde_json::from_reader(file).context("Failed to read json config")?
48        }
49        #[cfg(feature = "toml_config")]
50        Some("toml") => {
51            use std::io::Read;
52            let mut file = std::fs::File::open(config_path)
53                .with_context(|| format!("Failed to open config at ({config_path:?})"))?;
54            let mut content = String::new();
55            file.read_to_string(&mut content)
56                .context("Failed to read toml config")?;
57            toml::from_str(&content).context("Failed to parse toml config")?
58        }
59        Some(ext) => bail!("Invalid config file extension: {} (check `FEATURES: ` debug log to see enabled extensions)", ext),
60    };
61
62    Ok(config)
63}