shell: Move changes outside so we can properly handle errors

imgbot
Blaž Hrastnik 3 years ago
parent e772808a5b
commit 4a76ea8f88

@ -4346,9 +4346,10 @@ fn shell(cx: &mut Context, prompt: &str, behavior: ShellBehavior) {
if event == PromptEvent::Validate {
let (view, doc) = current!(cx.editor);
let selection = doc.selection(view.id);
let mut error: Option<&str> = None;
let transaction =
Transaction::change_by_selection(doc.text(), selection, |range| {
let mut changes = Vec::with_capacity(selection.len());
for range in selection.ranges() {
let mut process;
match Command::new(&shell[0])
.args(&shell[1..])
@ -4361,8 +4362,8 @@ fn shell(cx: &mut Context, prompt: &str, behavior: ShellBehavior) {
Ok(p) => process = p,
Err(e) => {
log::error!("Failed to start shell: {}", e);
error = Some("Failed to start shell");
return (0, 0, None);
cx.editor.set_error("Failed to start shell".to_owned());
return;
}
}
if pipe {
@ -4376,21 +4377,19 @@ fn shell(cx: &mut Context, prompt: &str, behavior: ShellBehavior) {
if !output.status.success() {
let stderr = output.stderr;
if !stderr.is_empty() {
log::error!(
"Shell error: {}",
String::from_utf8_lossy(&stderr)
);
log::error!("Shell error: {}", String::from_utf8_lossy(&stderr));
}
error = Some("Command failed");
return (0, 0, None);
cx.editor.set_error("Command failed".to_owned());
return;
}
let stdout = output.stdout;
let tendril;
match Tendril::try_from_byte_slice(&stdout) {
Ok(t) => tendril = t,
Err(_) => {
error = Some("Process did not output valid UTF-8");
return (0, 0, None);
cx.editor
.set_error("Process did not output valid UTF-8".to_owned());
return;
}
}
let (from, to) = match behavior {
@ -4399,21 +4398,21 @@ fn shell(cx: &mut Context, prompt: &str, behavior: ShellBehavior) {
ShellBehavior::Append => (range.to(), range.to()),
_ => (range.from(), range.from()),
};
(from, to, Some(tendril))
changes.push((from, to, Some(tendril)));
} else {
// if the process exits successfully, keep the selection, otherwise delete it.
let keep = output.status.success();
(
changes.push((
range.from(),
if keep { range.from() } else { range.to() },
None,
)
));
}
});
}
let transaction = Transaction::change(doc.text(), changes.into_iter());
if let Some(error) = error {
cx.editor.set_error(error.to_owned());
} else if behavior != ShellBehavior::Ignore {
if behavior != ShellBehavior::Ignore {
doc.apply(&transaction, view.id);
doc.append_changes_to_history(view.id);
}

Loading…
Cancel
Save