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,21 +1271,32 @@ 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 buf_reader = BufReader::new(file.unwrap());
let file = File::open(&self.filename)?; let lines = buf_reader.lines().map(|l| clean_unwrap(l));
let buf_reader = BufReader::new(file);
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 { // Make sure the whole file is loaded before
self.insert_row(self.rows.len(), &line); // 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(()) 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,10 +36,10 @@ 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,
// continuing the loop // continuing the loop