Skip to content

Commit a3e233e

Browse files
committed
Convert existing theme to patch
1 parent 1f818f3 commit a3e233e

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

src/ui/style.rs

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1+
use anyhow::Result;
12
use asyncgit::{DiffLineType, StatusItemType};
23
use ratatui::style::{Color, Modifier, Style};
4+
use ron::ser::{to_string_pretty, PrettyConfig};
35
use serde::{Deserialize, Serialize};
4-
use std::{fs::File, path::PathBuf, rc::Rc};
6+
use std::{fs::File, io::Write, path::PathBuf, rc::Rc};
57
use struct_patch::Patch;
68

79
pub type SharedTheme = Rc<Theme>;
810

911
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Patch)]
10-
#[patch_derive(Deserialize)]
12+
#[patch_derive(Serialize, Deserialize)]
1113
pub struct Theme {
1214
selected_tab: Color,
1315
command_fg: Color,
@@ -253,12 +255,42 @@ impl Theme {
253255
.bg(self.push_gauge_bg)
254256
}
255257

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+
256281
pub fn init(theme_path: &PathBuf) -> Self {
257282
let mut theme = Self::default();
258283

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.");
262294
}
263295
}
264296

0 commit comments

Comments
 (0)