14 Commits

Author SHA1 Message Date
Sylvestre Ledru 6d6b0c39e3 update of the version to 0.1.2 2023-04-24 21:16:26 +02:00
Sylvestre Ledru 7decfeeb7f lower the regex dep. we don't need 1.8 2023-04-24 21:15:44 +02:00
Sylvestre Ledru 9ac69eef7d update of the version 2023-04-24 00:16:53 +02:00
Sylvestre Ledru 4bd207f6fc update of the version 2023-04-24 00:14:30 +02:00
Sylvestre Ledru 3b05dabf54 update of the version 2023-04-24 00:11:58 +02:00
Sylvestre Ledru a68f15e034 from_str('Thu Jan 01 12:34:00 2015') should fail 2023-04-24 00:07:34 +02:00
Sylvestre Ledru 492c6f76f4 fix the link to cov 2023-04-23 22:56:52 +02:00
Sylvestre Ledru 306e1e21a9 add a test to check InvalidInput 2023-04-23 22:51:47 +02:00
Sylvestre Ledru 87372718f1 Fix readme syntax 2023-04-23 22:12:41 +02:00
Sylvestre Ledru 112b7bf86d improve the coverage 2023-04-23 22:10:56 +02:00
Sylvestre Ledru 8a7f4ec8cc add more badges 2023-04-23 22:08:43 +02:00
Sylvestre Ledru b3dbb3cb50 extend the CI 2023-04-23 21:22:45 +02:00
Sylvestre Ledru 50212c6d04 rename the action 2023-04-23 21:21:31 +02:00
Sylvestre Ledru 89cd5a2d54 add badges 2023-04-23 20:39:08 +02:00
7 changed files with 223 additions and 31 deletions
+166
View File
@@ -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
-22
View File
@@ -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
View File
@@ -13,7 +13,7 @@ dependencies = [
[[package]]
name = "humantime_to_duration"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"regex",
"time",
+2 -2
View File
@@ -1,11 +1,11 @@
[package]
name = "humantime_to_duration"
description = " parsing human-readable relative time strings and converting them to a Duration"
version = "0.1.0"
version = "0.1.2"
edition = "2021"
license = "MIT"
repository = "https://github.com/uutils/humantime_to_duration"
[dependencies]
regex = "1.8.1"
regex = "1.7"
time = "0.3.20"
+6 -2
View File
@@ -1,5 +1,9 @@
# humantime_to_duration
[![Crates.io](https://img.shields.io/crates/v/humantime_to_duration.svg)](https://crates.io/crates/humantime_to_duration)
[![License](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/uutils/humantime_to_duration/blob/main/LICENSE)
[![CodeCov](https://codecov.io/gh/uutils/humantime_to_duration/branch/main/graph/badge.svg)](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
@@ -14,7 +18,7 @@ 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:
@@ -51,7 +55,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:
```
+19 -4
View File
@@ -80,15 +80,20 @@ impl From<RegexError> for ParseDurationError {
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,9 +134,19 @@ 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)
+29
View File
@@ -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,25 @@ 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"
);
}