Gracefully handle opening an empty file

This commit is contained in:
Timothy Warren 2019-10-04 15:49:45 -04:00
parent 93ac2604b2
commit 8825cdb058
2 changed files with 23 additions and 12 deletions

View File

@ -1271,12 +1271,11 @@ impl Editor {
/// Open a file for display /// Open a file for display
pub fn open(&mut self, filename: &str) -> io::Result<()> { pub fn open(&mut self, filename: &str) -> io::Result<()> {
self.filename = filename.to_owned(); let file = File::open(filename);
self.select_syntax_highlight(); match file {
Ok(_) => {
let file = File::open(&self.filename)?; let buf_reader = BufReader::new(file.unwrap());
let buf_reader = BufReader::new(file);
let lines = buf_reader.lines().map(|l| clean_unwrap(l)); let lines = buf_reader.lines().map(|l| clean_unwrap(l));
@ -1284,7 +1283,19 @@ impl Editor {
self.insert_row(self.rows.len(), &line); self.insert_row(self.rows.len(), &line);
} }
// Make sure the whole file is loaded before
// showing the filename and selecting the syntax
// for highlighting
self.filename = filename.to_owned();
self.select_syntax_highlight();
self.dirty = 0; self.dirty = 0;
},
// Gracefully handle errors opening a file
Err(e) => {
self.set_status_message(&e.to_string());
}
}
Ok(()) Ok(())
} }
@ -1311,7 +1322,7 @@ impl Editor {
self.set_status_message(&format!("{} bytes written to disk", data.len())); self.set_status_message(&format!("{} bytes written to disk", data.len()));
} }
Err(e) => self.set_status_message(&format!("Failed to save: {:?}", e)), Err(e) => self.set_status_message(&format!("Failed to save: {}", e.to_string())),
}; };
file.sync_all()?; file.sync_all()?;

View File

@ -36,9 +36,9 @@ fn main() -> Result<(), Error> {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
if args.len() >= 2 { if args.len() >= 2 {
editor.open(&args[1])?; editor.open(&args[1])?;
} } else {
editor.set_status_message("HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find"); editor.set_status_message("HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find");
}
// Main input loop. Editor::process_keypress uses an Option Enum as a sentinel. // Main input loop. Editor::process_keypress uses an Option Enum as a sentinel.
// `None` is returned on a quit action, in other cases, `Some(())` is returned, // `None` is returned on a quit action, in other cases, `Some(())` is returned,