You've already forked parse_datetime
mirror of
https://github.com/uutils/parse_datetime.git
synced 2026-06-10 16:13:15 -07:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 29e64c3cda | |||
| db00d0686f | |||
| 1f0eae3536 | |||
| 6d6b0c39e3 | |||
| 7decfeeb7f | |||
| 9ac69eef7d | |||
| 4bd207f6fc | |||
| 3b05dabf54 | |||
| a68f15e034 | |||
| 492c6f76f4 | |||
| 306e1e21a9 | |||
| 87372718f1 | |||
| 112b7bf86d | |||
| 8a7f4ec8cc | |||
| b3dbb3cb50 | |||
| 50212c6d04 | |||
| 89cd5a2d54 |
@@ -0,0 +1,166 @@
|
||||
on: [push, pull_request]
|
||||
|
||||
name: Basic CI
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: cargo check
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macOS-latest, windows-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: check
|
||||
|
||||
test:
|
||||
name: cargo test
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macOS-latest, windows-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
|
||||
fmt:
|
||||
name: cargo fmt --all -- --check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- run: rustup component add rustfmt
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: fmt
|
||||
args: --all -- --check
|
||||
|
||||
clippy:
|
||||
name: cargo clippy -- -D warnings
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macOS-latest, windows-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
- run: rustup component add clippy
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: clippy
|
||||
args: -- -D warnings
|
||||
|
||||
coverage:
|
||||
name: Code Coverage
|
||||
runs-on: ${{ matrix.job.os }}
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
job:
|
||||
- { os: ubuntu-latest , features: unix }
|
||||
- { os: macos-latest , features: macos }
|
||||
- { os: windows-latest , features: windows }
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Initialize workflow variables
|
||||
id: vars
|
||||
shell: bash
|
||||
run: |
|
||||
## VARs setup
|
||||
outputs() { step_id="vars"; for var in "$@" ; do echo steps.${step_id}.outputs.${var}="${!var}"; echo "${var}=${!var}" >> $GITHUB_OUTPUT; done; }
|
||||
# toolchain
|
||||
TOOLCHAIN="nightly" ## default to "nightly" toolchain (required for certain required unstable compiler flags) ## !maint: refactor when stable channel has needed support
|
||||
# * specify gnu-type TOOLCHAIN for windows; `grcov` requires gnu-style code coverage data files
|
||||
case ${{ matrix.job.os }} in windows-*) TOOLCHAIN="$TOOLCHAIN-x86_64-pc-windows-gnu" ;; esac;
|
||||
# * use requested TOOLCHAIN if specified
|
||||
if [ -n "${{ matrix.job.toolchain }}" ]; then TOOLCHAIN="${{ matrix.job.toolchain }}" ; fi
|
||||
outputs TOOLCHAIN
|
||||
# target-specific options
|
||||
# * CARGO_FEATURES_OPTION
|
||||
CARGO_FEATURES_OPTION='--all -- --check' ; ## default to '--all-features' for code coverage
|
||||
# * CODECOV_FLAGS
|
||||
CODECOV_FLAGS=$( echo "${{ matrix.job.os }}" | sed 's/[^[:alnum:]]/_/g' )
|
||||
outputs CODECOV_FLAGS
|
||||
|
||||
- name: rust toolchain ~ install
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: ${{ steps.vars.outputs.TOOLCHAIN }}
|
||||
default: true
|
||||
profile: minimal # minimal component installation (ie, no documentation)
|
||||
- name: Test
|
||||
uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: test
|
||||
args: ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} --no-fail-fast
|
||||
env:
|
||||
CARGO_INCREMENTAL: "0"
|
||||
RUSTC_WRAPPER: ""
|
||||
RUSTFLAGS: "-Zprofile -Ccodegen-units=1 -Copt-level=0 -Clink-dead-code -Coverflow-checks=off -Zpanic_abort_tests -Cpanic=abort"
|
||||
RUSTDOCFLAGS: "-Cpanic=abort"
|
||||
- name: "`grcov` ~ install"
|
||||
id: build_grcov
|
||||
shell: bash
|
||||
run: |
|
||||
git clone https://github.com/mozilla/grcov.git ~/grcov/
|
||||
cd ~/grcov
|
||||
# Hardcode the version of crossbeam-epoch. See
|
||||
# https://github.com/uutils/coreutils/issues/3680
|
||||
sed -i -e "s|tempfile =|crossbeam-epoch = \"=0.9.8\"\ntempfile =|" Cargo.toml
|
||||
cargo install --path .
|
||||
cd -
|
||||
# Uncomment when the upstream issue
|
||||
# https://github.com/mozilla/grcov/issues/849 is fixed
|
||||
# uses: actions-rs/install@v0.1
|
||||
# with:
|
||||
# crate: grcov
|
||||
# version: latest
|
||||
# use-tool-cache: false
|
||||
- name: Generate coverage data (via `grcov`)
|
||||
id: coverage
|
||||
shell: bash
|
||||
run: |
|
||||
## Generate coverage data
|
||||
COVERAGE_REPORT_DIR="target/debug"
|
||||
COVERAGE_REPORT_FILE="${COVERAGE_REPORT_DIR}/lcov.info"
|
||||
mkdir -p "${COVERAGE_REPORT_DIR}"
|
||||
# display coverage files
|
||||
grcov . --output-type files --ignore build.rs --ignore "vendor/*" --ignore "/*" --ignore "[a-zA-Z]:/*" --excl-br-line "^\s*((debug_)?assert(_eq|_ne)?!|#\[derive\()" | sort --unique
|
||||
# generate coverage report
|
||||
grcov . --output-type lcov --output-path "${COVERAGE_REPORT_FILE}" --branch --ignore build.rs --ignore "vendor/*" --ignore "/*" --ignore "[a-zA-Z]:/*" --excl-br-line "^\s*((debug_)?assert(_eq|_ne)?!|#\[derive\()"
|
||||
echo "report=${COVERAGE_REPORT_FILE}" >> $GITHUB_OUTPUT
|
||||
- name: Upload coverage results (to Codecov.io)
|
||||
uses: codecov/codecov-action@v3
|
||||
# if: steps.vars.outputs.HAS_CODECOV_TOKEN
|
||||
with:
|
||||
# token: ${{ secrets.CODECOV_TOKEN }}
|
||||
file: ${{ steps.coverage.outputs.report }}
|
||||
## flags: IntegrationTests, UnitTests, ${{ steps.vars.outputs.CODECOV_FLAGS }}
|
||||
flags: ${{ steps.vars.outputs.CODECOV_FLAGS }}
|
||||
name: codecov-umbrella
|
||||
fail_ci_if_error: false
|
||||
@@ -1,22 +0,0 @@
|
||||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Build
|
||||
run: cargo build --verbose
|
||||
- name: Run tests
|
||||
run: cargo test --verbose
|
||||
Generated
+1
-1
@@ -13,7 +13,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "humantime_to_duration"
|
||||
version = "0.1.0"
|
||||
version = "0.1.4"
|
||||
dependencies = [
|
||||
"regex",
|
||||
"time",
|
||||
|
||||
+3
-2
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "humantime_to_duration"
|
||||
description = " parsing human-readable relative time strings and converting them to a Duration"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/uutils/humantime_to_duration"
|
||||
readme = "README.md"
|
||||
|
||||
[dependencies]
|
||||
regex = "1.8.1"
|
||||
regex = "1.7"
|
||||
time = "0.3.20"
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# humantime_to_duration
|
||||
|
||||
[](https://crates.io/crates/humantime_to_duration)
|
||||
[](https://github.com/uutils/humantime_to_duration/blob/main/LICENSE)
|
||||
[](https://codecov.io/gh/uutils/humantime_to_duration)
|
||||
|
||||
A Rust crate for parsing human-readable relative time strings and converting them to a `Duration`.
|
||||
|
||||
## Features
|
||||
@@ -7,6 +11,7 @@ A Rust crate for parsing human-readable relative time strings and converting the
|
||||
- Parses a variety of human-readable time formats.
|
||||
- Supports positive and negative durations.
|
||||
- Allows for chaining time units (e.g., "1 hour 2 minutes" or "2 days and 2 hours").
|
||||
- Calculate durations relative to a specified date.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -14,21 +19,28 @@ Add this to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
humantime_to_duration = "0.1.0"
|
||||
humantime_to_duration = "0.1.1"
|
||||
```
|
||||
|
||||
Then, import the crate and use the from_str function:
|
||||
Then, import the crate and use the `from_str` and `from_str_at_date` functions:
|
||||
```
|
||||
use humantime_to_duration::from_str;
|
||||
use humantime_to_duration::{from_str, from_str_at_date};
|
||||
use time::Duration;
|
||||
|
||||
let duration = from_str("+3 days");
|
||||
assert_eq!(duration.unwrap(), Duration::days(3));
|
||||
|
||||
let today = OffsetDateTime::now_utc().date();
|
||||
let yesterday = today - Duration::days(1);
|
||||
assert_eq!(
|
||||
from_str_at_date(yesterday, "2 days").unwrap(),
|
||||
Duration::days(1)
|
||||
);
|
||||
```
|
||||
|
||||
### Supported Formats
|
||||
|
||||
The `from_str` function supports the following formats for relative time:
|
||||
The `from_str` and `from_str_at_date` functions support the following formats for relative time:
|
||||
|
||||
- `num` `unit` (e.g., "-1 hour", "+3 days")
|
||||
- `unit` (e.g., "hour", "day")
|
||||
@@ -43,7 +55,7 @@ The `from_str` function supports the following formats for relative time:
|
||||
|
||||
## Return Values
|
||||
|
||||
The `from_str` function returns:
|
||||
The `from_str` and `from_str_at_date` functions return:
|
||||
|
||||
- `Ok(Duration)` - If the input string can be parsed as a relative time
|
||||
- `Err(ParseDurationError)` - If the input string cannot be parsed as a relative time
|
||||
@@ -51,7 +63,7 @@ The `from_str` function returns:
|
||||
This function will return `Err(ParseDurationError::InvalidInput)` if the input string
|
||||
cannot be parsed as a relative time.
|
||||
|
||||
##Â Fuzzer
|
||||
## Fuzzer
|
||||
|
||||
To run the fuzzer:
|
||||
```
|
||||
|
||||
+86
-7
@@ -4,7 +4,7 @@
|
||||
use regex::{Error as RegexError, Regex};
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Display};
|
||||
use time::Duration;
|
||||
use time::{Date, Duration, OffsetDateTime};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ParseDurationError {
|
||||
@@ -77,18 +77,34 @@ impl From<RegexError> for ParseDurationError {
|
||||
///
|
||||
/// This function will return `Err(ParseDurationError::InvalidInput)` if the input string
|
||||
/// cannot be parsed as a relative time.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use time::Duration;
|
||||
/// use humantime_to_duration::{from_str, ParseDurationError};
|
||||
///
|
||||
/// assert_eq!(from_str("1 hour, 30 minutes").unwrap(), Duration::minutes(90));
|
||||
/// assert_eq!(from_str("tomorrow").unwrap(), Duration::days(1));
|
||||
/// assert!(matches!(from_str("invalid"), Err(ParseDurationError::InvalidInput)));
|
||||
/// ```
|
||||
pub fn from_str(s: &str) -> Result<Duration, ParseDurationError> {
|
||||
let time_pattern: Regex = Regex::new(
|
||||
r"(?x)
|
||||
(?P<value>[-+]?\d*)\s*
|
||||
(?P<unit>years?|months?|fortnights?|weeks?|days?|hours?|h|minutes?|mins?|m|seconds?|secs?|s|yesterday|tomorrow|now|today)
|
||||
(\s*(?P<separator>and|,)?\s*)?",
|
||||
(?:(?P<value>[-+]?\d*)\s*)?
|
||||
(?P<unit>years?|months?|fortnights?|weeks?|days?|hours?|h|minutes?|mins?|m|seconds?|secs?|s|yesterday|tomorrow|now|today)
|
||||
(\s*(?P<separator>and|,)?\s*)?
|
||||
(\s*(?P<ago>ago)?)?",
|
||||
)?;
|
||||
|
||||
let mut total_duration = Duration::ZERO;
|
||||
let mut is_ago = s.contains(" ago");
|
||||
let mut captures_processed = 0;
|
||||
let mut total_length = 0;
|
||||
|
||||
for capture in time_pattern.captures_iter(s) {
|
||||
captures_processed += 1;
|
||||
|
||||
let value_str = capture
|
||||
.name("value")
|
||||
.ok_or(ParseDurationError::InvalidInput)?
|
||||
@@ -129,21 +145,58 @@ pub fn from_str(s: &str) -> Result<Duration, ParseDurationError> {
|
||||
Some(duration) => duration,
|
||||
None => return Err(ParseDurationError::InvalidInput),
|
||||
};
|
||||
|
||||
// Calculate the total length of the matched substring
|
||||
if let Some(m) = capture.get(0) {
|
||||
total_length += m.end() - m.start();
|
||||
}
|
||||
}
|
||||
|
||||
if total_duration == Duration::ZERO && !time_pattern.is_match(s) {
|
||||
// Check if the entire input string has been captured
|
||||
if total_length != s.len() {
|
||||
return Err(ParseDurationError::InvalidInput);
|
||||
}
|
||||
|
||||
if captures_processed == 0 {
|
||||
Err(ParseDurationError::InvalidInput)
|
||||
} else {
|
||||
Ok(total_duration)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a duration string and returns a `Duration` instance, with the duration
|
||||
/// calculated from the specified date.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `date` - A `Date` instance representing the base date for the calculation
|
||||
/// * `s` - A string slice representing the relative time.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use time::{Date, Duration, OffsetDateTime};
|
||||
/// use humantime_to_duration::{from_str_at_date, ParseDurationError};
|
||||
/// let today = OffsetDateTime::now_utc().date();
|
||||
/// let yesterday = today - Duration::days(1);
|
||||
/// assert_eq!(
|
||||
/// from_str_at_date(yesterday, "2 days").unwrap(),
|
||||
/// Duration::days(1) // 1 day from the specified date + 1 day from the input string
|
||||
/// );
|
||||
/// ```
|
||||
pub fn from_str_at_date(date: Date, s: &str) -> Result<Duration, ParseDurationError> {
|
||||
let time_now = OffsetDateTime::now_utc().date();
|
||||
let date_duration = date - time_now;
|
||||
|
||||
Ok(from_str(s)? + date_duration)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::from_str;
|
||||
use super::ParseDurationError;
|
||||
use time::Duration;
|
||||
use super::{from_str, from_str_at_date};
|
||||
use time::{Date, Duration, Month, OffsetDateTime};
|
||||
|
||||
#[test]
|
||||
fn test_years() {
|
||||
@@ -285,4 +338,30 @@ mod tests {
|
||||
_ => assert!(false),
|
||||
}*/
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_str_at_date() {
|
||||
let date = Date::from_calendar_date(2014, Month::September, 5).unwrap();
|
||||
let now = OffsetDateTime::now_utc().date();
|
||||
let days_diff = (date - now).whole_days();
|
||||
|
||||
assert_eq!(
|
||||
from_str_at_date(date, "1 day").unwrap(),
|
||||
Duration::days(days_diff + 1)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
from_str_at_date(date, "2 hours").unwrap(),
|
||||
Duration::days(days_diff) + Duration::hours(2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_input_at_date() {
|
||||
let date = Date::from_calendar_date(2014, Month::September, 5).unwrap();
|
||||
assert!(matches!(
|
||||
from_str_at_date(date, "invalid"),
|
||||
Err(ParseDurationError::InvalidInput)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
+58
-2
@@ -1,5 +1,5 @@
|
||||
use humantime_to_duration::{from_str, ParseDurationError};
|
||||
use time::Duration;
|
||||
use humantime_to_duration::{from_str, from_str_at_date, ParseDurationError};
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
#[test]
|
||||
fn test_invalid_input() {
|
||||
@@ -82,16 +82,23 @@ fn test_duration_parsing() {
|
||||
assert_eq!(from_str("day").unwrap(), Duration::seconds(86_400));
|
||||
|
||||
assert_eq!(from_str("1 hour").unwrap(), Duration::seconds(3_600));
|
||||
assert_eq!(from_str("1 h").unwrap(), Duration::seconds(3_600));
|
||||
assert_eq!(from_str("1 hour ago").unwrap(), Duration::seconds(-3_600));
|
||||
assert_eq!(from_str("-2 hours").unwrap(), Duration::seconds(-7_200));
|
||||
assert_eq!(from_str("hour").unwrap(), Duration::seconds(3_600));
|
||||
|
||||
assert_eq!(from_str("1 minute").unwrap(), Duration::seconds(60));
|
||||
assert_eq!(from_str("1 min").unwrap(), Duration::seconds(60));
|
||||
assert_eq!(from_str("2 minutes").unwrap(), Duration::seconds(120));
|
||||
assert_eq!(from_str("2 mins").unwrap(), Duration::seconds(120));
|
||||
assert_eq!(from_str("2m").unwrap(), Duration::seconds(120));
|
||||
assert_eq!(from_str("min").unwrap(), Duration::seconds(60));
|
||||
|
||||
assert_eq!(from_str("1 second").unwrap(), Duration::seconds(1));
|
||||
assert_eq!(from_str("1 s").unwrap(), Duration::seconds(1));
|
||||
assert_eq!(from_str("2 seconds").unwrap(), Duration::seconds(2));
|
||||
assert_eq!(from_str("2 secs").unwrap(), Duration::seconds(2));
|
||||
assert_eq!(from_str("2 sec").unwrap(), Duration::seconds(2));
|
||||
assert_eq!(from_str("sec").unwrap(), Duration::seconds(1));
|
||||
|
||||
assert_eq!(from_str("now").unwrap(), Duration::ZERO);
|
||||
@@ -106,3 +113,52 @@ fn test_duration_parsing() {
|
||||
Duration::seconds(-39_398_402)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_display_parse_duration_error_through_from_str() {
|
||||
let invalid_input = "9223372036854775807 seconds and 1 second";
|
||||
let error = from_str(invalid_input).unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
format!("{error}"),
|
||||
"Invalid input string: cannot be parsed as a relative time"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_display_should_fail() {
|
||||
let invalid_input = "Thu Jan 01 12:34:00 2015";
|
||||
let error = from_str(invalid_input).unwrap_err();
|
||||
|
||||
assert_eq!(
|
||||
format!("{error}"),
|
||||
"Invalid input string: cannot be parsed as a relative time"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_str_at_date_day() {
|
||||
let today = OffsetDateTime::now_utc().date();
|
||||
let yesterday = today - Duration::days(1);
|
||||
assert_eq!(
|
||||
from_str_at_date(yesterday, "2 days").unwrap(),
|
||||
Duration::days(1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_input_at_date() {
|
||||
let today = OffsetDateTime::now_utc().date();
|
||||
let result = from_str_at_date(today, "foobar");
|
||||
println!("{result:?}");
|
||||
match result {
|
||||
Err(ParseDurationError::InvalidInput) => assert!(true),
|
||||
_ => assert!(false),
|
||||
}
|
||||
|
||||
let result = from_str_at_date(today, "invalid 1r");
|
||||
match result {
|
||||
Err(ParseDurationError::InvalidInput) => assert!(true),
|
||||
_ => assert!(false),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user