Remove calls to exit() and replace them with error propagation up to main()

Signed-off-by: Matthias Beyer <mail@beyermatthias.de>
This commit is contained in:
Matthias Beyer 2019-10-19 08:54:57 +02:00
parent 0e74225094
commit 9b8faec86e
2 changed files with 57 additions and 105 deletions

View file

@ -26,6 +26,7 @@ toml-query = "0.9.2"
handlebars = "2" handlebars = "2"
tempfile = "3.0.9" tempfile = "3.0.9"
failure = "0.1.5" failure = "0.1.5"
resiter = "0.3.0"
libimagstore = { version = "0.10.0", path = "../../../lib/core/libimagstore" } libimagstore = { version = "0.10.0", path = "../../../lib/core/libimagstore" }
libimagrt = { version = "0.10.0", path = "../../../lib/core/libimagrt" } libimagrt = { version = "0.10.0", path = "../../../lib/core/libimagrt" }

View file

@ -40,7 +40,8 @@ extern crate handlebars;
extern crate tempfile; extern crate tempfile;
extern crate toml; extern crate toml;
extern crate toml_query; extern crate toml_query;
extern crate failure; #[macro_use] extern crate failure;
extern crate resiter;
extern crate libimagentryview; extern crate libimagentryview;
extern crate libimagerror; extern crate libimagerror;
@ -52,26 +53,23 @@ use std::str::FromStr;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::io::Write; use std::io::Write;
use std::process::Command; use std::process::Command;
use std::process::exit;
use handlebars::Handlebars; use handlebars::Handlebars;
use toml_query::read::TomlValueReadTypeExt; use toml_query::read::TomlValueReadTypeExt;
use failure::Error; use failure::Error;
use failure::err_msg; use failure::err_msg;
use failure::Fallible as Result; use failure::Fallible as Result;
use resiter::AndThen;
use clap::App; use clap::App;
use libimagrt::runtime::Runtime; use libimagrt::runtime::Runtime;
use libimagrt::application::ImagApplication; use libimagrt::application::ImagApplication;
use libimagerror::trace::MapErrTrace;
use libimagerror::iter::TraceIterator;
use libimagerror::io::ToExitCode;
use libimagerror::exit::ExitUnwrap;
use libimagentryview::builtin::stdout::StdoutViewer; use libimagentryview::builtin::stdout::StdoutViewer;
use libimagentryview::builtin::md::MarkdownViewer; use libimagentryview::builtin::md::MarkdownViewer;
use libimagentryview::viewer::Viewer; use libimagentryview::viewer::Viewer;
use libimagstore::iter::get::StoreIdGetIteratorExtension; use libimagstore::iter::get::StoreIdGetIteratorExtension;
use libimagstore::store::FileLockEntry; use libimagstore::store::FileLockEntry;
use libimagerror::iter::IterInnerOkOrElse;
mod ui; mod ui;
@ -85,61 +83,42 @@ impl ImagApplication for ImagView {
let view_header = rt.cli().is_present("view-header"); let view_header = rt.cli().is_present("view-header");
let hide_content = rt.cli().is_present("not-view-content"); let hide_content = rt.cli().is_present("not-view-content");
let entries = rt let entries = rt
.ids::<::ui::PathProvider>() .ids::<::ui::PathProvider>()?
.map_err_trace_exit_unwrap() .ok_or_else(|| err_msg("No ids supplied"))?
.unwrap_or_else(|| {
error!("No ids supplied");
::std::process::exit(1);
})
.into_iter() .into_iter()
.map(Ok) .map(Ok)
.into_get_iter(rt.store()) .into_get_iter(rt.store())
.trace_unwrap_exit() .map_inner_ok_or_else(|| err_msg("Entry not found, please report this as a bug"));
.map(|e| {
e.ok_or_else(|| err_msg("Entry not found"))
.map_err(Error::from)
.map_err_trace_exit_unwrap()
});
if rt.cli().is_present("in") { if rt.cli().is_present("in") {
let files = entries let files = entries
.map(|entry| { .and_then_ok(|entry| {
let tmpfile = create_tempfile_for(&entry, view_header, hide_content); let tmpfile = create_tempfile_for(&entry, view_header, hide_content)?;
rt.report_touched(entry.get_location()).unwrap_or_exit(); rt.report_touched(entry.get_location())?;
tmpfile Ok(tmpfile)
}) })
.collect::<Vec<_>>(); .collect::<Result<Vec<_>>>()?;
let mut command = { let mut command = {
let viewer = rt let viewer = rt
.cli() .cli()
.value_of("in") .value_of("in")
.ok_or_else(|| Error::from(err_msg("No viewer given"))) .ok_or_else(|| err_msg("No viewer given"))?;
.map_err_trace_exit_unwrap();
let config = rt let config = rt
.config() .config()
.ok_or_else(|| Error::from(err_msg("No configuration, cannot continue"))) .ok_or_else(|| err_msg("No configuration, cannot continue"))?;
.map_err_trace_exit_unwrap();
let query = format!("view.viewers.{}", viewer); let query = format!("view.viewers.{}", viewer);
let viewer_template = config let viewer_template = config
.read_string(&query) .read_string(&query)?
.map_err(Error::from) .ok_or_else(|| format_err!("Cannot find '{}' in config", query))?;
.map_err_trace_exit_unwrap()
.unwrap_or_else(|| {
error!("Cannot find '{}' in config", query);
exit(1)
});
let mut handlebars = Handlebars::new(); let mut handlebars = Handlebars::new();
handlebars.register_escape_fn(::handlebars::no_escape); handlebars.register_escape_fn(::handlebars::no_escape);
let _ = handlebars handlebars.register_template_string("template", viewer_template)?;
.register_template_string("template", viewer_template)
.map_err(Error::from)
.map_err_trace_exit_unwrap();
let mut data = BTreeMap::new(); let mut data = BTreeMap::new();
@ -151,15 +130,9 @@ impl ImagApplication for ImagView {
data.insert("entries", file_paths); data.insert("entries", file_paths);
let call = handlebars let call = handlebars .render("template", &data)?;
.render("template", &data)
.map_err(Error::from)
.map_err_trace_exit_unwrap();
let mut elems = call.split_whitespace(); let mut elems = call.split_whitespace();
let command_string = elems let command_string = elems.next().ok_or_else(|| err_msg("No command"))?;
.next()
.ok_or_else(|| Error::from(err_msg("No command")))
.map_err_trace_exit_unwrap();
let mut cmd = Command::new(command_string); let mut cmd = Command::new(command_string);
for arg in elems { for arg in elems {
@ -172,15 +145,14 @@ impl ImagApplication for ImagView {
debug!("Calling: {:?}", command); debug!("Calling: {:?}", command);
if !command if !command
.status() .status()?
.map_err(Error::from)
.map_err_trace_exit_unwrap()
.success() .success()
{ {
exit(1) return Err(err_msg("Failed to execute command"))
} }
drop(files); drop(files);
Ok(())
} else { } else {
let out = rt.stdout(); let out = rt.stdout();
let mut outlock = out.lock(); let mut outlock = out.lock();
@ -202,32 +174,30 @@ impl ImagApplication for ImagView {
let viewer = MarkdownViewer::new(&rt); let viewer = MarkdownViewer::new(&rt);
let seperator = basesep.map(|s| build_seperator(s, sep_width)); let seperator = basesep.map(|s| build_seperator(s, sep_width));
entries let mut i = 0; // poor mans enumerate()
.enumerate()
.for_each(|(n, entry)| { entries.and_then_ok(|entry| {
if n != 0 { if i != 0 {
seperator if let Some(s) = seperator.as_ref() {
.as_ref() writeln!(outlock, "{}", s)?;
.map(|s| writeln!(outlock, "{}", s).to_exit_code().unwrap_or_exit()); }
} }
if let Err(e) = viewer.view_entry(&entry, &mut outlock) { viewer.view_entry(&entry, &mut outlock)?;
handle_error(e);
}
rt.report_touched(entry.get_location()).unwrap_or_exit(); i += 1;
}); rt.report_touched(entry.get_location()).map_err(Error::from)
})
.collect()
} else { } else {
let mut viewer = StdoutViewer::new(view_header, !hide_content); let mut viewer = StdoutViewer::new(view_header, !hide_content);
if rt.cli().occurrences_of("autowrap") != 0 { if rt.cli().occurrences_of("autowrap") != 0 {
let width = rt.cli().value_of("autowrap").unwrap(); // ensured by clap let width = rt.cli().value_of("autowrap").unwrap(); // ensured by clap
let width = usize::from_str(width).unwrap_or_else(|e| { let width = usize::from_str(width).map_err(|_| {
error!("Failed to parse argument to number: autowrap = {:?}", format_err!("Failed to parse argument to number: autowrap = {:?}",
rt.cli().value_of("autowrap").map(String::from)); rt.cli().value_of("autowrap").map(String::from))
error!("-> {:?}", e); })?;
::std::process::exit(1)
});
// Copying this value over, so that the seperator has the right len as well // Copying this value over, so that the seperator has the right len as well
sep_width = width; sep_width = width;
@ -236,25 +206,22 @@ impl ImagApplication for ImagView {
} }
let seperator = basesep.map(|s| build_seperator(s, sep_width)); let seperator = basesep.map(|s| build_seperator(s, sep_width));
entries let mut i = 0; // poor mans enumerate()
.enumerate() entries.and_then_ok(|entry| {
.for_each(|(n, entry)| { if i != 0 {
if n != 0 { if let Some(s) = seperator.as_ref() {
seperator writeln!(outlock, "{}", s)?;
.as_ref()
.map(|s| writeln!(outlock, "{}", s).to_exit_code().unwrap_or_exit());
}
if let Err(e) = viewer.view_entry(&entry, &mut outlock) {
handle_error(e);
}
rt.report_touched(entry.get_location()).unwrap_or_exit();
});
} }
} }
Ok(()) viewer.view_entry(&entry, &mut outlock)?;
i += 1;
rt.report_touched(entry.get_location()).map_err(Error::from)
})
.collect()
}
}
} }
fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> { fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
@ -275,41 +242,25 @@ impl ImagApplication for ImagView {
} }
fn create_tempfile_for<'a>(entry: &FileLockEntry<'a>, view_header: bool, hide_content: bool) fn create_tempfile_for<'a>(entry: &FileLockEntry<'a>, view_header: bool, hide_content: bool)
-> (tempfile::NamedTempFile, String) -> Result<(tempfile::NamedTempFile, String)>
{ {
let mut tmpfile = tempfile::NamedTempFile::new() let mut tmpfile = tempfile::NamedTempFile::new()?;
.map_err(Error::from)
.map_err_trace_exit_unwrap();
if view_header { if view_header {
let hdr = toml::ser::to_string_pretty(entry.get_header()) let hdr = toml::ser::to_string_pretty(entry.get_header())?;
.map_err(Error::from) let _ = tmpfile.write(format!("---\n{}---\n", hdr).as_bytes())?;
.map_err_trace_exit_unwrap();
let _ = tmpfile.write(format!("---\n{}---\n", hdr).as_bytes())
.map_err(Error::from)
.map_err_trace_exit_unwrap();
} }
if !hide_content { if !hide_content {
let _ = tmpfile.write(entry.get_content().as_bytes()) let _ = tmpfile.write(entry.get_content().as_bytes())?;
.map_err(Error::from)
.map_err_trace_exit_unwrap();
} }
let file_path = tmpfile let file_path = tmpfile
.path() .path()
.to_str() .to_str()
.map(String::from) .map(String::from)
.ok_or_else(|| Error::from(err_msg("Cannot build path"))) .ok_or_else(|| Error::from(err_msg("Cannot build path")))?;
.map_err_trace_exit_unwrap();
(tmpfile, file_path) Ok((tmpfile, file_path))
} }
fn handle_error(e: ::libimagentryview::error::Error) {
use libimagentryview::error::Error;
match e {
Error::Io(e) => Err(e).to_exit_code().unwrap_or_exit(),
Error::Other(e) => Err(e).map_err_trace_exit_unwrap()
}
}