|
| 1 | +use anyhow::Result; |
1 | 2 | use asyncgit::{DiffLineType, StatusItemType};
|
2 | 3 | use ratatui::style::{Color, Modifier, Style};
|
| 4 | +use ron::ser::{to_string_pretty, PrettyConfig}; |
3 | 5 | use serde::{Deserialize, Serialize};
|
4 |
| -use std::{fs::File, path::PathBuf, rc::Rc}; |
| 6 | +use std::{fs::File, io::Write, path::PathBuf, rc::Rc}; |
5 | 7 | use struct_patch::Patch;
|
6 | 8 |
|
7 | 9 | pub type SharedTheme = Rc<Theme>;
|
8 | 10 |
|
9 | 11 | #[derive(Serialize, Deserialize, Debug, Copy, Clone, Patch)]
|
10 |
| -#[patch_derive(Deserialize)] |
| 12 | +#[patch_derive(Serialize, Deserialize)] |
11 | 13 | pub struct Theme {
|
12 | 14 | selected_tab: Color,
|
13 | 15 | command_fg: Color,
|
@@ -253,12 +255,42 @@ impl Theme {
|
253 | 255 | .bg(self.push_gauge_bg)
|
254 | 256 | }
|
255 | 257 |
|
| 258 | + fn load_patch(theme_path: &PathBuf) -> Result<ThemePatch> { |
| 259 | + let file = File::open(theme_path)?; |
| 260 | + |
| 261 | + Ok(ron::de::from_reader(file)?) |
| 262 | + } |
| 263 | + |
| 264 | + fn load_old_theme(theme_path: &PathBuf) -> Result<Self> { |
| 265 | + let old_file = File::open(theme_path)?; |
| 266 | + |
| 267 | + Ok(ron::de::from_reader::<File, Self>(old_file)?) |
| 268 | + } |
| 269 | + |
| 270 | + // This is supposed to be called when theme.ron doesn't already exists. |
| 271 | + fn save_patch(&self, theme_path: &PathBuf) -> Result<()> { |
| 272 | + let mut file = File::create(theme_path)?; |
| 273 | + let patch = self.into_patch_by_diff(Self::default()); |
| 274 | + let data = to_string_pretty(&patch, PrettyConfig::default())?; |
| 275 | + |
| 276 | + file.write_all(data.as_bytes())?; |
| 277 | + |
| 278 | + Ok(()) |
| 279 | + } |
| 280 | + |
256 | 281 | pub fn init(theme_path: &PathBuf) -> Self {
|
257 | 282 | let mut theme = Self::default();
|
258 | 283 |
|
259 |
| - if let Ok(file) = File::open(theme_path) { |
260 |
| - if let Ok(patch) = ron::de::from_reader(file) { |
261 |
| - theme.apply(patch); |
| 284 | + if let Ok(patch) = Self::load_patch(theme_path) { |
| 285 | + theme.apply(patch); |
| 286 | + } else if let Ok(old_theme) = Self::load_old_theme(theme_path) |
| 287 | + { |
| 288 | + theme = old_theme; |
| 289 | + |
| 290 | + if theme.save_patch(theme_path).is_ok() { |
| 291 | + log::info!("Converted old theme to new format."); |
| 292 | + } else { |
| 293 | + log::warn!("Failed to save theme in new format."); |
262 | 294 | }
|
263 | 295 | }
|
264 | 296 |
|
|
0 commit comments