Add error handling for parsing errors

This commit is contained in:
sharkdp 2018-10-17 20:21:58 +02:00 committed by David Peter
parent ec27c78a8a
commit 2109a7830b
2 changed files with 11 additions and 10 deletions

View File

@ -19,7 +19,7 @@ impl<'b> Controller<'b> {
} }
pub fn run(&self) -> Result<bool> { pub fn run(&self) -> Result<bool> {
let mut output_type = OutputType::from_mode(self.config.paging_mode); let mut output_type = OutputType::from_mode(self.config.paging_mode)?;
let writer = output_type.handle()?; let writer = output_type.handle()?;
let mut no_errors: bool = true; let mut no_errors: bool = true;

View File

@ -15,22 +15,23 @@ pub enum OutputType {
} }
impl OutputType { impl OutputType {
pub fn from_mode(mode: PagingMode) -> Self { pub fn from_mode(mode: PagingMode) -> Result<Self> {
use self::PagingMode::*; use self::PagingMode::*;
match mode { Ok(match mode {
Always => OutputType::try_pager(false), Always => OutputType::try_pager(false)?,
QuitIfOneScreen => OutputType::try_pager(true), QuitIfOneScreen => OutputType::try_pager(true)?,
_ => OutputType::stdout(), _ => OutputType::stdout(),
} })
} }
/// Try to launch the pager. Fall back to stdout in case of errors. /// Try to launch the pager. Fall back to stdout in case of errors.
fn try_pager(quit_if_one_screen: bool) -> Self { fn try_pager(quit_if_one_screen: bool) -> Result<Self> {
let pager = env::var("BAT_PAGER") let pager = env::var("BAT_PAGER")
.or_else(|_| env::var("PAGER")) .or_else(|_| env::var("PAGER"))
.unwrap_or(String::from("less")); .unwrap_or(String::from("less"));
let pagerflags = shell_words::split(&pager).unwrap_or(vec![pager]); let pagerflags = shell_words::split(&pager)
.chain_err(|| "Could not parse (BAT_)PAGER environment variable.")?;
let less_path = PathBuf::from(&pagerflags[0]); let less_path = PathBuf::from(&pagerflags[0]);
let is_less = less_path.file_stem() == Some(&OsString::from("less")); let is_less = less_path.file_stem() == Some(&OsString::from("less"));
@ -49,12 +50,12 @@ impl OutputType {
Command::new(&less_path) Command::new(&less_path)
}; };
process Ok(process
.args(&pagerflags[1..]) .args(&pagerflags[1..])
.stdin(Stdio::piped()) .stdin(Stdio::piped())
.spawn() .spawn()
.map(OutputType::Pager) .map(OutputType::Pager)
.unwrap_or_else(|_| OutputType::stdout()) .unwrap_or_else(|_| OutputType::stdout()))
} }
fn stdout() -> Self { fn stdout() -> Self {