handle errors when saving file to an invalid location

This commit is contained in:
Crispy 2023-03-12 20:40:07 +01:00
parent f17a78f088
commit 19742c38df

View file

@ -29,6 +29,7 @@ pub struct Editor {
path: Option<PathBuf>, path: Option<PathBuf>,
active: bool, active: bool,
unsaved_changes: bool, unsaved_changes: bool,
message: Option<String>,
} }
#[derive(Debug)] #[derive(Debug)]
@ -53,6 +54,7 @@ impl Editor {
path: Some(path), path: Some(path),
active: false, active: false,
unsaved_changes: false, unsaved_changes: false,
message: None,
}) })
} }
@ -67,6 +69,7 @@ impl Editor {
path: None, path: None,
active: false, active: false,
unsaved_changes: true, unsaved_changes: true,
message: None,
} }
} }
@ -81,6 +84,7 @@ impl Editor {
path: Some(path), path: Some(path),
active: false, active: false,
unsaved_changes: true, unsaved_changes: true,
message: None,
} }
} }
@ -107,6 +111,7 @@ impl Editor {
while self.active { while self.active {
self.draw(); self.draw();
self.message = None;
self.input(); self.input();
} }
} }
@ -229,6 +234,10 @@ impl Editor {
fn status_line(&self) { fn status_line(&self) {
queue!(stdout(), MoveTo(0, terminal::size().unwrap().1)).unwrap(); queue!(stdout(), MoveTo(0, terminal::size().unwrap().1)).unwrap();
if let Some(message) = &self.message {
print!("{message}");
} else {
print!( print!(
"({},{}) {}", "({},{}) {}",
self.cursor.line, self.cursor.line,
@ -236,6 +245,11 @@ impl Editor {
self.name(), self.name(),
); );
} }
}
fn message(&mut self, text: String) {
self.message = Some(text);
}
fn move_left(&mut self) { fn move_left(&mut self) {
if self.cursor.column > 0 { if self.cursor.column > 0 {
@ -438,6 +452,7 @@ impl Editor {
.unwrap() .unwrap()
} }
/// where the cursor is rendered in the terminal output
fn physical_column(&self) -> usize { fn physical_column(&self) -> usize {
let start = self.current_line().start; let start = self.current_line().start;
let end = self.char_index(); let end = self.char_index();
@ -449,14 +464,20 @@ impl Editor {
fn save(&mut self) { fn save(&mut self) {
if self.path.is_none() { if self.path.is_none() {
self.path = read_line("Enter path: ").map(|s| env::current_dir().unwrap().join(s)); self.path = read_line("Enter path: ").map(|s| env::current_dir().unwrap().join(s));
if self.path.is_none() {
return;
} }
} if let Some(path) = &self.path {
let mut file = File::create(self.path.as_ref().unwrap()).unwrap(); match File::create(path) {
Ok(mut file) => {
file.write_all(self.text.as_bytes()).unwrap(); file.write_all(self.text.as_bytes()).unwrap();
self.unsaved_changes = false; self.unsaved_changes = false;
} }
Err(e) => {
self.message(format!("Could not save file as '{}': {e}", path.display()));
self.path = None;
}
}
}
}
} }
fn color_selection() { fn color_selection() {