Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace failure to anyhow/thiserror for better error handling. (failure is deprecated.) #56

Merged
merged 1 commit into from
May 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 26 additions & 73 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ path = "src/main.rs"
[dependencies]
chrono = "^0.4"
clap = "^2.33"
failure = "^0.1"
anyhow = "^1.0"
thiserror = "^1.0"
lazy_static = "^1.4"
regex = "^1"
strum = "^0.18"
Expand Down
51 changes: 23 additions & 28 deletions src/cmd/generate/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ use std::convert::TryFrom;
use std::fmt::Debug;
use std::str::FromStr;

use anyhow::Context;
use chrono::prelude::*;
use clap::ArgMatches;
use failure::ResultExt;

use crate::datetime::{Hms, HmsError, Ymd, YmdError};
use crate::delta::DeltaItem;
use crate::error::{UtError, UtErrorKind};
use crate::find::FindByName;
use crate::parse::parse_argv_opt;
use crate::precision::Precision;
Expand All @@ -32,7 +31,7 @@ impl GenerateOptions {
&self,
provider: P,
precision: Precision,
) -> Result<DateTime<Tz>, UtError>
) -> Result<DateTime<Tz>, Box<dyn std::error::Error>>
where
Tz: TimeZone + Debug,
P: DateTimeProvider<Tz>,
Expand Down Expand Up @@ -62,7 +61,7 @@ impl GenerateOptions {
.fold(base, |dt, unit| unit.truncate(dt)))
}

fn base_date<P, Tz>(&self, provider: &P) -> Result<Option<Date<Tz>>, UtError>
fn base_date<P, Tz>(&self, provider: &P) -> Result<Option<Date<Tz>>, Box<dyn std::error::Error>>
where
Tz: TimeZone + Debug,
P: DateTimeProvider<Tz>,
Expand All @@ -75,36 +74,29 @@ impl GenerateOptions {
ymd.into_date(&provider.timezone()).map(Some)
})
})
.context(UtErrorKind::WrongDate)?;
.context("Wrong date.")?;

Ok(date)
}
}

impl TryFrom<&ArgMatches<'_>> for GenerateOptions {
type Error = UtError;
type Error = Box<dyn std::error::Error>;

fn try_from(m: &ArgMatches<'_>) -> Result<Self, Self::Error> {
fn delta_item_from(s: &str) -> Result<DeltaItem, UtError> {
Ok(DeltaItem::from_str(s).context(UtErrorKind::DeltaError)?)
fn delta_item_from(s: &str) -> Result<DeltaItem, Box<dyn std::error::Error>> {
Ok(DeltaItem::from_str(s).context("Delta error.")?)
}

let timestamp = m
.value_of("BASE_TIMESTAMP")
.map(|s| {
i64::from_str(s)
.map(Some)
.context(UtErrorKind::WrongTimestamp)
})
.map(|s| i64::from_str(s).map(Some).context("Wrong timestamp."))
.unwrap_or_else(|| Ok(None))?;
let preset =
Preset::find_by_name_opt(m.value_of("BASE")).context(UtErrorKind::PresetError)?;
let ymd =
parse_argv_opt::<Ymd, YmdError>(m.value_of("YMD")).context(UtErrorKind::WrongDate)?;
let hms =
parse_argv_opt::<Hms, HmsError>(m.value_of("HMS")).context(UtErrorKind::WrongTime)?;
let truncate = TimeUnit::find_by_name_opt(m.value_of("TRUNCATE"))
.context(UtErrorKind::TimeUnitError)?;
let preset = Preset::find_by_name_opt(m.value_of("BASE")).context("Preset error.")?;
let ymd = parse_argv_opt::<Ymd, YmdError>(m.value_of("YMD")).context("Wrong date.")?;
let hms = parse_argv_opt::<Hms, HmsError>(m.value_of("HMS")).context("Wrong time.")?;
let truncate =
TimeUnit::find_by_name_opt(m.value_of("TRUNCATE")).context("Time unit error.")?;
let deltas = m
.values_of("DELTA")
.map(|values| values.map(delta_item_from).collect())
Expand Down Expand Up @@ -135,12 +127,12 @@ where
m: &ArgMatches,
provider: P,
precision: Precision,
) -> Result<GenerateRequest<Tz>, UtError>
) -> Result<GenerateRequest<Tz>, Box<dyn std::error::Error>>
where
P: DateTimeProvider<Tz>,
{
let maybe_precision = Precision::find_by_name_opt(m.value_of("PRECISION"))
.context(UtErrorKind::PrecisionError)?;
let maybe_precision =
Precision::find_by_name_opt(m.value_of("PRECISION")).context("Precision error.")?;
if maybe_precision.is_some() {
eprintln!("-p PRECISION option is deprecated.");
}
Expand All @@ -157,14 +149,16 @@ where
}
}

pub fn run<Tz>(request: GenerateRequest<Tz>) -> Result<(), UtError>
pub fn run<Tz>(request: GenerateRequest<Tz>) -> Result<(), Box<dyn std::error::Error>>
where
Tz: TimeZone + Debug,
{
generate(request)
}

fn generate<Tz: TimeZone>(request: GenerateRequest<Tz>) -> Result<(), UtError> {
fn generate<Tz: TimeZone>(request: GenerateRequest<Tz>) -> Result<(), Box<dyn std::error::Error>> {
use anyhow::anyhow;

let delta = request
.deltas
.into_iter()
Expand All @@ -176,8 +170,9 @@ fn generate<Tz: TimeZone>(request: GenerateRequest<Tz>) -> Result<(), UtError> {
match delta.apply_datetime(request.base) {
Some(dt) => {
println!("{}", request.precision.to_timestamp(dt));
Ok(())
}
None => Err(UtError::from(UtErrorKind::TimeUnitError)),
None => Err(anyhow!("Time unit error."))?,
}

Ok(())
}
17 changes: 8 additions & 9 deletions src/cmd/parse/run.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use std::fmt::{Debug, Display};
use std::io;

use anyhow::Context;
use chrono::{Offset, TimeZone};
use clap::ArgMatches;
use failure::ResultExt;

use crate::error::{UtError, UtErrorKind};
use crate::find::FindByName;
use crate::precision::Precision;
use crate::provider::DateTimeProvider;
Expand All @@ -25,10 +24,10 @@ impl<P> ParseRequest<P> {
provider: P,
precision: Precision,
datetime_format: Option<&str>,
) -> Result<ParseRequest<P>, UtError> {
) -> Result<ParseRequest<P>, Box<dyn std::error::Error>> {
let timestamp = get_timestamp(m.value_of("TIMESTAMP"))?;
let maybe_precision = Precision::find_by_name_opt(m.value_of("PRECISION"))
.context(UtErrorKind::PrecisionError)?;
let maybe_precision =
Precision::find_by_name_opt(m.value_of("PRECISION")).context("Precision error.")?;
if maybe_precision.is_some() {
eprintln!("-p PRECISION option is deprecated.");
}
Expand All @@ -46,7 +45,7 @@ impl<P> ParseRequest<P> {
}
}

pub fn run<O, Tz, P>(request: ParseRequest<P>) -> Result<(), UtError>
pub fn run<O, Tz, P>(request: ParseRequest<P>) -> Result<(), Box<dyn std::error::Error>>
where
O: Offset + Display + Sized,
Tz: TimeZone<Offset = O> + Debug,
Expand All @@ -59,12 +58,12 @@ where
Ok(())
}

fn get_timestamp(maybe_timestamp: Option<&str>) -> Result<i64, UtError> {
fn get_timestamp(maybe_timestamp: Option<&str>) -> Result<i64, Box<dyn std::error::Error>> {
Ok(maybe_timestamp
.map(|s| s.parse::<i64>().context(UtErrorKind::WrongTimestamp))
.map(|s| s.parse::<i64>().context("Wrong timestamp."))
.unwrap_or_else(|| {
let stdin = io::stdin();
let r: Result<i64, ReadError> = read_next(stdin);
r.context(UtErrorKind::WrongTimestamp)
r.context("Wrong timestamp.")
})?)
}
Loading