@@ -5,12 +5,12 @@ use crate::get_app_config_path;
5
5
use anyhow:: Result ;
6
6
use crossterm:: event:: { KeyCode , KeyEvent , KeyModifiers } ;
7
7
use ron:: {
8
- de :: from_bytes ,
8
+ self ,
9
9
ser:: { to_string_pretty, PrettyConfig } ,
10
10
} ;
11
11
use serde:: { Deserialize , Serialize } ;
12
12
use std:: {
13
- fs:: File ,
13
+ fs:: { self , File } ,
14
14
io:: { Read , Write } ,
15
15
path:: PathBuf ,
16
16
rc:: Rc ,
@@ -127,15 +127,14 @@ impl Default for KeyConfig {
127
127
}
128
128
129
129
impl 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) ?;
133
132
let data = to_string_pretty ( self , PrettyConfig :: default ( ) ) ?;
134
133
file. write_all ( data. as_bytes ( ) ) ?;
135
134
Ok ( ( ) )
136
135
}
137
136
138
- fn get_config_file ( ) -> Result < PathBuf > {
137
+ pub fn get_config_file ( ) -> Result < PathBuf > {
139
138
let app_home = get_app_config_path ( ) ?;
140
139
Ok ( app_home. join ( "key_config.ron" ) )
141
140
}
@@ -144,31 +143,31 @@ impl KeyConfig {
144
143
let mut f = File :: open ( config_file) ?;
145
144
let mut buffer = Vec :: new ( ) ;
146
145
f. read_to_end ( & mut buffer) ?;
147
- Ok ( from_bytes ( & buffer) ?)
146
+ Ok ( ron :: de :: from_bytes ( & buffer) ?)
148
147
}
149
148
150
- fn init_internal ( ) -> Result < Self > {
151
- let file = Self :: get_config_file ( ) ?;
149
+ pub fn init ( file : PathBuf ) -> Result < Self > {
152
150
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 ) ? ;
164
162
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) ,
171
167
}
168
+ } else {
169
+ Self :: default ( ) . save ( file) ?;
170
+ Ok ( Self :: default ( ) )
172
171
}
173
172
}
174
173
0 commit comments