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

cron - human text parsing #254

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
30 changes: 20 additions & 10 deletions cron/src/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use std::convert::TryFrom;
use std::str::{self, FromStr};

use crate::error::{Error, ErrorKind};
use crate::schedule::{ScheduleFields, Schedule};
use crate::ordinal::*;
use crate::schedule::{Schedule, ScheduleFields};
use crate::specifier::*;
use crate::time_unit::*;
use crate::ordinal::*;

impl FromStr for Schedule {
type Err = Error;
Expand Down Expand Up @@ -52,17 +52,19 @@ where
T: TimeUnitField,
{
fn from_field(field: Field) -> Result<T, Error> {
if field.specifiers.len() == 1 &&
field.specifiers.get(0).unwrap() == &RootSpecifier::from(Specifier::All)
{ return Ok(T::all()); }
let mut ordinals = OrdinalSet::new();
for specifier in field.specifiers {
let specifier_ordinals: OrdinalSet = T::ordinals_from_root_specifier(&specifier)?;
if field.specifiers.len() == 1
&& field.specifiers.get(0).unwrap() == &RootSpecifier::from(Specifier::All)
{
return Ok(T::all());
}
let mut ordinals = OrdinalSet::new();
for specifier in &field.specifiers {
let specifier_ordinals: OrdinalSet = T::ordinals_from_root_specifier(specifier)?;
for ordinal in specifier_ordinals {
ordinals.insert(T::validate_ordinal(ordinal)?);
}
}
Ok(T::from_ordinal_set(ordinals))
Ok(T::from_ordinal_set(ordinals, field.specifiers))
}
}

Expand Down Expand Up @@ -255,7 +257,15 @@ fn longhand(i: &str) -> IResult<&str, ScheduleFields> {
let months = map_res(field, Months::from_field);
let days_of_week = map_res(field_with_any, DaysOfWeek::from_field);
let years = opt(map_res(field, Years::from_field));
let fields = tuple((seconds, minutes, hours, days_of_month, months, days_of_week, years));
let fields = tuple((
seconds,
minutes,
hours,
days_of_month,
months,
days_of_week,
years,
));

map(
terminated(fields, eof),
Expand Down
74 changes: 74 additions & 0 deletions cron/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use chrono::{DateTime, Datelike, Timelike};
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::ops::Bound::{Included, Unbounded};

use crate::error::Error;
use crate::ordinal::*;
use crate::queries::*;
use crate::time_unit::*;
Expand All @@ -24,6 +25,79 @@ impl Schedule {
Schedule { source, fields }
}

pub fn to_human_text(&self) -> Result<String, Error> {
let fields = self.fields.clone();

let seconds = fields.seconds;
let minutes = fields.minutes;
let hours = fields.hours;
let days_of_week = fields.days_of_week;
let months = fields.months;
let days_of_month = fields.days_of_month;
let years = fields.years;

let days_anded = days_of_month.is_all() || days_of_week.is_all();

let s = match !days_of_month.to_human_text()?.is_empty()
&& !days_of_week.to_human_text()?.is_empty()
{
false => "".to_owned(),
true => match days_anded {
false => "and".to_owned(),
true => "if it's".to_owned(),
},
};

let time = match seconds.count() == 1 && minutes.count() == 1 && hours.count() == 1 {
true => {
let second = format!("0{}", &seconds.ordinals().iter().next().unwrap());
let minute = format!("0{}", &minutes.ordinals().iter().next().unwrap());
let hour = format!("0{}", &hours.ordinals().iter().next().unwrap());
Some([
second[second.len() - 2..].to_owned(),
minute[minute.len() - 2..].to_owned(),
hour[hour.len() - 2..].to_owned(),
])
}
false => None,
};

Ok(match time {
Some(t) => {
format!(
"At {}:{}:{} {} {} {} {} {}",
&t[2],
&t[1],
&t[0],
&days_of_month.to_human_text()?,
&s,
&days_of_week.to_human_text()?,
&months.to_human_text()?,
&years.to_human_text()?
)
.trim()
.to_owned()
+ "."
}
None => {
format!(
"At {} {} {} {} {} {} {} {}",
&seconds.to_human_text()?,
&minutes.to_human_text()?,
&hours.to_human_text()?,
&days_of_month.to_human_text()?,
&s,
&days_of_week.to_human_text()?,
&months.to_human_text()?,
&years.to_human_text()?
)
.trim()
.to_owned()
+ "."
}
})
}

pub fn next_after<Z>(&self, after: &DateTime<Z>) -> Option<DateTime<Z>>
where
Z: TimeZone,
Expand Down
8 changes: 5 additions & 3 deletions cron/src/specifier.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::ordinal::*;

#[derive(Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq)]
pub enum Specifier {
All,
Point(Ordinal),
Expand All @@ -15,7 +15,7 @@ pub enum Specifier {
// - named range: 'Mon-Thurs/2'
//
// Without this separation we would end up with invalid combinations such as 'Mon/2'
#[derive(Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq)]
pub enum RootSpecifier {
Specifier(Specifier),
Period(Specifier, u32),
Expand All @@ -26,4 +26,6 @@ impl From<Specifier> for RootSpecifier {
fn from(specifier: Specifier) -> Self {
Self::Specifier(specifier)
}
}
}

impl Eq for RootSpecifier {}
19 changes: 18 additions & 1 deletion cron/src/time_unit/days_of_month.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
use crate::TimeUnitSpec;
use crate::error::Error;
use crate::ordinal::{Ordinal, OrdinalSet};
use crate::specifier::RootSpecifier;
use crate::time_unit::TimeUnitField;
use std::borrow::Cow;

#[derive(Clone, Debug, Eq)]
pub struct DaysOfMonth {
ordinals: Option<OrdinalSet>,
field: Vec<RootSpecifier>
}

impl TimeUnitField for DaysOfMonth {
fn from_optional_ordinal_set(ordinal_set: Option<OrdinalSet>) -> Self {
fn from_optional_ordinal_set(ordinal_set: Option<OrdinalSet>, field: Vec<RootSpecifier>) -> Self {
DaysOfMonth {
ordinals: ordinal_set,
field
}
}
fn name() -> Cow<'static, str> {
Expand All @@ -28,6 +33,18 @@ impl TimeUnitField for DaysOfMonth {
None => DaysOfMonth::supported_ordinals(),
}
}
fn name_in_text() -> Cow<'static, str> {
Cow::from("day-of-month")
}
fn to_human_text (&self) -> Result<String, Error> {
match self.is_all() {
true => Ok("".to_owned()),
false => match Self::human_text_from_field(self.field.clone(), false) {
Ok(s) => Ok(format!("on {s}")),
Err(e) => Err(e)
}
}
}
}

impl PartialEq for DaysOfMonth {
Expand Down
39 changes: 37 additions & 2 deletions cron/src/time_unit/days_of_week.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
use crate::error::*;
use crate::{error::*, TimeUnitSpec};
use crate::ordinal::{Ordinal, OrdinalSet};
use crate::specifier::RootSpecifier;
use crate::time_unit::TimeUnitField;
use std::borrow::Cow;

#[derive(Clone, Debug, Eq)]
pub struct DaysOfWeek {
ordinals: Option<OrdinalSet>,
field: Vec<RootSpecifier>
}

impl TimeUnitField for DaysOfWeek {
fn from_optional_ordinal_set(ordinal_set: Option<OrdinalSet>) -> Self {
fn from_optional_ordinal_set(ordinal_set: Option<OrdinalSet>, field: Vec<RootSpecifier>) -> Self {
DaysOfWeek {
ordinals: ordinal_set,
field
}
}
fn name() -> Cow<'static, str> {
Expand Down Expand Up @@ -43,12 +46,44 @@ impl TimeUnitField for DaysOfWeek {
};
Ok(ordinal)
}
fn name_from_ordinal(ordinal: Ordinal) -> Result<String, Error> {
//TODO: Use phf crate
let name = match ordinal {
1 => "Sunday",
2 => "Monday",
3 => "Tuesday",
4 => "Wednesday",
5 => "Thursday",
6 => "Friday",
7 => "Saturday",
_ => {
return Err(ErrorKind::Expression(format!(
"'{}' is not a valid day of the week.",
ordinal
))
.into())
}
};
Ok(name.to_owned())
}
fn ordinals(&self) -> OrdinalSet {
match self.ordinals.clone() {
Some(ordinal_set) => ordinal_set,
None => DaysOfWeek::supported_ordinals(),
}
}
fn name_in_text() -> Cow<'static, str> {
Cow::from("day-of-week")
}
fn to_human_text (&self) -> Result<String, Error> {
match self.is_all() {
true => Ok("".to_owned()),
false => match Self::human_text_from_field(self.field.clone(), true) {
Ok(s) => Ok(format!("on {s}")),
Err(e) => Err(e)
}
}
}
}

impl PartialEq for DaysOfWeek {
Expand Down
19 changes: 18 additions & 1 deletion cron/src/time_unit/hours.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
use crate::TimeUnitSpec;
use crate::error::Error;
use crate::ordinal::{Ordinal, OrdinalSet};
use crate::specifier::RootSpecifier;
use crate::time_unit::TimeUnitField;
use std::borrow::Cow;

#[derive(Clone, Debug, Eq)]
pub struct Hours {
ordinals: Option<OrdinalSet>,
field: Vec<RootSpecifier>,
}

impl TimeUnitField for Hours {
fn from_optional_ordinal_set(ordinal_set: Option<OrdinalSet>) -> Self {
fn from_optional_ordinal_set(ordinal_set: Option<OrdinalSet>, field: Vec<RootSpecifier>) -> Self {
Hours {
ordinals: ordinal_set,
field,
}
}
fn name() -> Cow<'static, str> {
Expand All @@ -28,6 +33,18 @@ impl TimeUnitField for Hours {
None => Hours::supported_ordinals(),
}
}
fn name_in_text() -> Cow<'static, str> {
Cow::from("hour")
}
fn to_human_text (&self) -> Result<String, Error> {
match self.is_all() {
true => Ok("".to_owned()),
false => match Self::human_text_from_field(self.field.clone(), false) {
Ok(s) => Ok(format!("past {s}")),
Err(e) => Err(e)
}
}
}
}

impl PartialEq for Hours {
Expand Down
19 changes: 18 additions & 1 deletion cron/src/time_unit/minutes.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
use crate::TimeUnitSpec;
use crate::error::Error;
use crate::ordinal::{Ordinal, OrdinalSet};
use crate::specifier::RootSpecifier;
use crate::time_unit::TimeUnitField;
use std::borrow::Cow;

#[derive(Clone, Debug, Eq)]
pub struct Minutes {
ordinals: Option<OrdinalSet>,
field: Vec<RootSpecifier>,
}

impl TimeUnitField for Minutes {
fn from_optional_ordinal_set(ordinal_set: Option<OrdinalSet>) -> Self {
fn from_optional_ordinal_set(ordinal_set: Option<OrdinalSet>, field: Vec<RootSpecifier>) -> Self {
Minutes {
ordinals: ordinal_set,
field,
}
}
fn name() -> Cow<'static, str> {
Expand All @@ -28,6 +33,18 @@ impl TimeUnitField for Minutes {
None => Minutes::supported_ordinals(),
}
}
fn name_in_text() -> Cow<'static, str> {
Cow::from("minute")
}
fn to_human_text (&self) -> Result<String, Error> {
match self.is_all() {
true => Ok("".to_owned()),
false => match Self::human_text_from_field(self.field.clone(), false) {
Ok(s) => Ok(format!("past {s}")),
Err(e) => Err(e)
}
}
}
}

impl PartialEq for Minutes {
Expand Down
Loading