From 8825cdb0584ec76bb8c07021fb947c59f0c28a50 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Fri, 4 Oct 2019 15:49:45 -0400 Subject: [PATCH] Gracefully handle opening an empty file --- src/editor.rs | 31 +++++++++++++++++++++---------- src/main.rs | 4 ++-- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/src/editor.rs b/src/editor.rs index 9f9bdde..4466c7f 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -1271,21 +1271,32 @@ impl Editor { /// Open a file for display 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 buf_reader = BufReader::new(file.unwrap()); - let file = File::open(&self.filename)?; - 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)); + for line in lines { + self.insert_row(self.rows.len(), &line); + } - for line in lines { - 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; + }, + // Gracefully handle errors opening a file + Err(e) => { + self.set_status_message(&e.to_string()); + } } - self.dirty = 0; - Ok(()) } @@ -1311,7 +1322,7 @@ impl Editor { 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()?; diff --git a/src/main.rs b/src/main.rs index 9c88b73..878a6a9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,10 +36,10 @@ fn main() -> Result<(), Error> { let args: Vec = env::args().collect(); if args.len() >= 2 { 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. // `None` is returned on a quit action, in other cases, `Some(())` is returned, // continuing the loop