@@ -5,12 +5,12 @@ use crate::get_app_config_path;
55use anyhow:: Result ;
66use crossterm:: event:: { KeyCode , KeyEvent , KeyModifiers } ;
77use ron:: {
8- de :: from_bytes ,
8+ self ,
99 ser:: { to_string_pretty, PrettyConfig } ,
1010} ;
1111use serde:: { Deserialize , Serialize } ;
1212use std:: {
13- fs:: File ,
13+ fs:: { self , File } ,
1414 io:: { Read , Write } ,
1515 path:: PathBuf ,
1616 rc:: Rc ,
@@ -127,15 +127,14 @@ impl Default for KeyConfig {
127127}
128128
129129impl KeyConfig {
130- fn save ( & self ) -> Result < ( ) > {
131- let config_file = Self :: get_config_file ( ) ?;
132- let mut file = File :: create ( config_file) ?;
130+ fn save ( & self , file : PathBuf ) -> Result < ( ) > {
131+ let mut file = File :: create ( file) ?;
133132 let data = to_string_pretty ( self , PrettyConfig :: default ( ) ) ?;
134133 file. write_all ( data. as_bytes ( ) ) ?;
135134 Ok ( ( ) )
136135 }
137136
138- fn get_config_file ( ) -> Result < PathBuf > {
137+ pub fn get_config_file ( ) -> Result < PathBuf > {
139138 let app_home = get_app_config_path ( ) ?;
140139 Ok ( app_home. join ( "key_config.ron" ) )
141140 }
@@ -144,31 +143,31 @@ impl KeyConfig {
144143 let mut f = File :: open ( config_file) ?;
145144 let mut buffer = Vec :: new ( ) ;
146145 f. read_to_end ( & mut buffer) ?;
147- Ok ( from_bytes ( & buffer) ?)
146+ Ok ( ron :: de :: from_bytes ( & buffer) ?)
148147 }
149148
150- fn init_internal ( ) -> Result < Self > {
151- let file = Self :: get_config_file ( ) ?;
149+ pub fn init ( file : PathBuf ) -> Result < Self > {
152150 if file. exists ( ) {
153- Ok ( Self :: read_file ( file) ? )
154- } else {
155- let def = Self :: default ( ) ;
156- if def . save ( ) . is_err ( ) {
157- log :: warn! (
158- "failed to store default key config to disk."
159- )
160- }
161- Ok ( def )
162- }
163- }
151+ match Self :: read_file ( file. clone ( ) ) {
152+ Err ( e ) => {
153+ let config_path = file . clone ( ) ;
154+ let config_path_old =
155+ format ! ( "{}.old" , file . to_string_lossy ( ) ) ;
156+ fs :: rename (
157+ config_path . clone ( ) ,
158+ config_path_old . clone ( ) ,
159+ ) ? ;
160+
161+ Self :: default ( ) . save ( file ) ? ;
164162
165- pub fn init ( ) -> Self {
166- match Self :: init_internal ( ) {
167- Ok ( v) => v,
168- Err ( e) => {
169- log:: error!( "failed loading key binding: {}" , e) ;
170- Self :: default ( )
163+ Err ( anyhow:: anyhow!( "{}\n Old file was renamed to {:?}.\n Defaults loaded and saved as {:?}" ,
164+ e, config_path_old, config_path. to_string_lossy( ) ) )
165+ }
166+ Ok ( res) => Ok ( res) ,
171167 }
168+ } else {
169+ Self :: default ( ) . save ( file) ?;
170+ Ok ( Self :: default ( ) )
172171 }
173172 }
174173
0 commit comments