Skip to content

smarter config loading #589

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crossbeam_channel::Sender;
use crossterm::event::{Event, KeyEvent};
use std::{
cell::{Cell, RefCell},
path::{Path, PathBuf},
path::Path,
rc::Rc,
};
use tui::{
Expand Down Expand Up @@ -74,11 +74,12 @@ impl App {
pub fn new(
sender: &Sender<AsyncNotification>,
input: Input,
theme_path: PathBuf,
theme: Theme,
key_config: KeyConfig,
) -> Self {
let queue = Queue::default();
let theme = Rc::new(Theme::init(theme_path));
let key_config = Rc::new(KeyConfig::init());
let theme = Rc::new(theme);
let key_config = Rc::new(key_config);

Self {
input,
Expand Down
51 changes: 25 additions & 26 deletions src/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use crate::get_app_config_path;
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ron::{
de::from_bytes,
self,
ser::{to_string_pretty, PrettyConfig},
};
use serde::{Deserialize, Serialize};
use std::{
fs::File,
fs::{self, File},
io::{Read, Write},
path::PathBuf,
rc::Rc,
Expand Down Expand Up @@ -127,15 +127,14 @@ impl Default for KeyConfig {
}

impl KeyConfig {
fn save(&self) -> Result<()> {
let config_file = Self::get_config_file()?;
let mut file = File::create(config_file)?;
fn save(&self, file: PathBuf) -> Result<()> {
let mut file = File::create(file)?;
let data = to_string_pretty(self, PrettyConfig::default())?;
file.write_all(data.as_bytes())?;
Ok(())
}

fn get_config_file() -> Result<PathBuf> {
pub fn get_config_file() -> Result<PathBuf> {
let app_home = get_app_config_path()?;
Ok(app_home.join("key_config.ron"))
}
Expand All @@ -144,31 +143,31 @@ impl KeyConfig {
let mut f = File::open(config_file)?;
let mut buffer = Vec::new();
f.read_to_end(&mut buffer)?;
Ok(from_bytes(&buffer)?)
Ok(ron::de::from_bytes(&buffer)?)
}

fn init_internal() -> Result<Self> {
let file = Self::get_config_file()?;
pub fn init(file: PathBuf) -> Result<Self> {
if file.exists() {
Ok(Self::read_file(file)?)
} else {
let def = Self::default();
if def.save().is_err() {
log::warn!(
"failed to store default key config to disk."
)
}
Ok(def)
}
}
match Self::read_file(file.clone()) {
Err(e) => {
let config_path = file.clone();
let config_path_old =
format!("{}.old", file.to_string_lossy());
fs::rename(
config_path.clone(),
config_path_old.clone(),
)?;

Self::default().save(file)?;

pub fn init() -> Self {
match Self::init_internal() {
Ok(v) => v,
Err(e) => {
log::error!("failed loading key binding: {}", e);
Self::default()
Err(anyhow::anyhow!("{}\n Old file was renamed to {:?}.\n Defaults loaded and saved as {:?}",
e,config_path_old,config_path.to_string_lossy()))
}
Ok(res) => Ok(res),
}
} else {
Self::default().save(file)?;
Ok(Self::default())
}
}

Expand Down
11 changes: 10 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use crossterm::{
ExecutableCommand,
};
use input::{Input, InputEvent, InputState};
use keys::KeyConfig;
use profiler::Profiler;
use scopeguard::defer;
use scopetime::scope_time;
Expand All @@ -61,6 +62,7 @@ use tui::{
backend::{Backend, CrosstermBackend},
Terminal,
};
use ui::style::Theme;

static TICK_INTERVAL: Duration = Duration::from_secs(5);
static SPINNER_INTERVAL: Duration = Duration::from_millis(80);
Expand Down Expand Up @@ -88,6 +90,13 @@ fn main() -> Result<()> {
return Ok(());
}

let key_config = KeyConfig::init(KeyConfig::get_config_file()?)
.map_err(|e| eprintln!("KeyConfig loading error: {}", e))
.unwrap_or_default();
let theme = Theme::init(cliargs.theme)
.map_err(|e| eprintln!("Theme loading error: {}", e))
.unwrap_or_default();

setup_terminal()?;
defer! {
shutdown_terminal().expect("shutdown failed");
Expand All @@ -105,7 +114,7 @@ fn main() -> Result<()> {
let ticker = tick(TICK_INTERVAL);
let spinner_ticker = tick(SPINNER_INTERVAL);

let mut app = App::new(&tx_git, input, cliargs.theme);
let mut app = App::new(&tx_git, input, theme, key_config);

let mut spinner = Spinner::default();
let mut first_update = true;
Expand Down
36 changes: 22 additions & 14 deletions src/ui/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use ron::{
};
use serde::{Deserialize, Serialize};
use std::{
fs::File,
fs::{self, File},
io::{Read, Write},
path::PathBuf,
rc::Rc,
Expand Down Expand Up @@ -250,22 +250,30 @@ impl Theme {
Ok(from_bytes(&buffer)?)
}

fn init_internal(theme: PathBuf) -> Result<Self> {
if theme.exists() {
Ok(Self::read_file(theme)?)
} else {
// This will only be called when theme.ron doesn't already exists
let def = Self::default();
if def.save(theme).is_err() {
log::warn!("failed to store default theme to disk.")
pub fn init(file: PathBuf) -> Result<Self> {
if file.exists() {
match Self::read_file(file.clone()) {
Err(e) => {
let config_path = file.clone();
let config_path_old =
format!("{}.old", file.to_string_lossy());
fs::rename(
config_path.clone(),
config_path_old.clone(),
)?;

Self::default().save(file)?;

Err(anyhow::anyhow!("{}\n Old file was renamed to {:?}.\n Defaults loaded and saved as {:?}",
e,config_path_old,config_path.to_string_lossy()))
}
Ok(res) => Ok(res),
}
Ok(def)
} else {
Self::default().save(file)?;
Ok(Self::default())
}
}

pub fn init(theme_path: PathBuf) -> Self {
Self::init_internal(theme_path).unwrap_or_default()
}
}

impl Default for Theme {
Expand Down