From 0d9c5a67f97af4d2b0fb543e2f1edf00ed0c7552 Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 4 May 2020 11:50:36 +0200 Subject: rewrite maybe_save_history This avoids unwrapping (and therefore panicing) when the path doens't have a parent. It also avoids the explicit Into::into() calls. --- src/main.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index 5b6d57f..0a98c4e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; -use anyhow::{anyhow, Error, Result}; +use anyhow::{anyhow, Context, Error, Result}; use chrono::{DateTime, TimeZone, Utc}; use colored::Colorize; use log::debug; @@ -334,13 +334,17 @@ fn maybe_load_history(rl: &mut Editor<()>, path: Option<&Path>) { } fn maybe_save_history(rl: &Editor<()>, path: Option<&Path>) { - if let Some(path) = path { + let run = |path: &Path| -> Result<()> { debug!("Saving history to {:?}", path); - let result: Result<(), Box> = - fs::create_dir_all(path.parent().unwrap()) - .map_err(Into::into) - .and_then(|_| rl.save_history(path).map_err(Into::into)); - if let Err(e) = result { + let parent = path + .parent() + .ok_or(anyhow!("Path does not have a parent"))?; + fs::create_dir_all(parent).context("Could not create directory")?; + rl.save_history(path)?; + Ok(()) + }; + if let Some(path) = path { + if let Err(e) = run(path) { debug!("Saving the history failed: {}", e); } } -- cgit v1.2.3