323 Commits

Author SHA1 Message Date
Sylvestre Ledru 46a5ef89c9 Merge pull request #195 from cakebaker/bump_version_to_0_11
Bump version to `0.11.0`
2025-08-01 09:05:34 +02:00
Daniel Hofstetter 226d6a0588 Bump version to 0.11.0 2025-08-01 08:38:55 +02:00
Sylvestre Ledru 28b9f11f2e Merge pull request #179 from cakebaker/remove_unnecessary_option
chore: remove unnecessary `Option` as return value
2025-08-01 08:25:34 +02:00
Sylvestre Ledru b68c325abd Merge pull request #162 from cakebaker/set_timezone_for_tests
tests: set timezone to `UTC0` in integration tests
2025-08-01 08:25:18 +02:00
Daniel Hofstetter 27a626d3d5 Merge pull request #194 from uutils/renovate/rstest-0.x-lockfile
chore(deps): update rust crate rstest to v0.26.1
2025-07-27 16:43:53 +02:00
renovate[bot] 1630fd025e chore(deps): update rust crate rstest to v0.26.1 2025-07-27 14:39:43 +00:00
Daniel Hofstetter cf5770838c Merge pull request #193 from uutils/renovate/rstest-0.x
chore(deps): update rust crate rstest to 0.26
2025-07-27 10:26:19 +02:00
renovate[bot] db9ff29c02 chore(deps): update rust crate rstest to 0.26 2025-07-26 21:25:06 +00:00
Daniel Hofstetter 4cfe8db9be Merge pull request #192 from yuankunzhang/update-readme
Update readme
2025-07-24 16:26:03 +02:00
yuankunzhang 1e7a541528 docs: update readme 2025-07-24 14:21:24 +00:00
Daniel Hofstetter b2bb6dfe91 Merge pull request #191 from yuankunzhang/update-comments
docs: update comments
2025-07-24 16:20:22 +02:00
yuankunzhang d71c6ea41c docs: update comments 2025-07-24 14:09:45 +00:00
Daniel Hofstetter 3b6362e7c8 Merge pull request #190 from yuankunzhang/fix-base-datetime-handling
fix base datetime handling in the builder
2025-07-24 10:21:28 +02:00
yuankunzhang 897a50f4d5 fix base datetime handling in the builder 2025-07-24 10:09:25 +02:00
Daniel Hofstetter 96f477121f Merge pull request #189 from yuankunzhang/support-float-timestamp
fix: support float timestamp values
2025-07-24 10:03:56 +02:00
yuankunzhang c47ce6870a fix: support float timestamp values 2025-07-24 09:34:02 +02:00
Daniel Hofstetter 77e1ab2d00 Merge pull request #188 from yuankunzhang/update-comments
Update comments
2025-07-23 17:35:43 +02:00
yuankunzhang a48ad6aec3 chore: update comments 2025-07-23 17:30:32 +02:00
Daniel Hofstetter 0ddeec70b4 Merge pull request #187 from yuankunzhang/year-module
feat: add a year module
2025-07-23 17:26:43 +02:00
yuankunzhang 2bb8ac8203 feat: add a year module 2025-07-23 13:53:46 +00:00
Daniel Hofstetter 5b52929c91 Merge pull request #186 from yuankunzhang/improve-literal-date-parser
feat: improve the literal date parsers
2025-07-23 14:42:54 +02:00
yuankunzhang 3d6f79d826 feat: improve the literal date parsers 2025-07-23 12:31:33 +00:00
Daniel Hofstetter 324d0bca34 Merge pull request #184 from yuankunzhang/improve-us-date-parser
Improve the `us()` date parser
2025-07-22 15:35:14 +02:00
yuankunzhang 9f75f895e0 feat: improve the us() date parser 2025-07-22 15:30:13 +02:00
Yuankun Zhang 5ba4b18655 Improve the iso1() and iso2() date parsers (#183)
* feat: improve date parsing with GNU compatibility and validation

- Add `TryFrom<(&str, u32, u32)>` implementation for `Date` struct
  with validation.
- Add comprehensive date validation for months, days, taking leap
  year into account.
- Refactor `iso1()` and `iso2()` date parsers to use the new
  validation logic.

* fix typo

Co-authored-by: Daniel Hofstetter <daniel.hofstetter@42dh.com>

* remove unnecessary if condition

Co-authored-by: Daniel Hofstetter <daniel.hofstetter@42dh.com>

---------

Co-authored-by: Daniel Hofstetter <daniel.hofstetter@42dh.com>
2025-07-22 14:49:36 +02:00
Daniel Hofstetter 5d869b5264 Merge pull request #182 from yuankunzhang/add-ctx-err
feat: add a `ctx_err` util function
2025-07-20 14:07:21 +02:00
yuankunzhang 793d18dce7 feat: add a ctx_err util function 2025-07-20 03:28:52 +00:00
Daniel Hofstetter 7182760266 Merge pull request #181 from yuankunzhang/support-leading-zeros-in-timezone-colonless
feat: support leading zeros in `timezone_colonless()`
2025-07-19 17:30:07 +02:00
yuankunzhang e7a8a52a21 feat: support leading zeros in timezone_colonless() 2025-07-19 17:18:39 +02:00
Daniel Hofstetter 0674254bc6 Merge pull request #180 from yuankunzhang/fix-time-offset
fix: time offset can only appear after time or timezone
2025-07-19 16:16:17 +02:00
yuankunzhang 8bebfab576 fix: time offset can only appear after time or timezone 2025-07-19 13:57:46 +00:00
Daniel Hofstetter 6feeddfea1 chore: remove unnecessary Option as return value 2025-07-17 10:12:03 +02:00
Daniel Hofstetter 6499842e15 Merge pull request #178 from yuankunzhang/improve-items-mod
chore: re-organize items/mod.rs
2025-07-17 09:44:47 +02:00
yuankunzhang 949e0613d6 chore: re-organize items/mod.rs 2025-07-17 09:54:24 +08:00
Daniel Hofstetter 6e6ffc2dff tests: set timezone to UTC0 in integration tests 2025-07-16 10:13:20 +02:00
Daniel Hofstetter 67364fc6ba Merge pull request #174 from yuankunzhang/exclusive-timestamp
fix: timestamp cannot be combined with other items
2025-07-16 10:09:47 +02:00
Daniel Hofstetter d92f5eeb27 Merge pull request #176 from uutils/renovate/winnow-0.x-lockfile
fix(deps): update rust crate winnow to v0.7.12
2025-07-16 10:07:03 +02:00
renovate[bot] 5c4a60fadf fix(deps): update rust crate winnow to v0.7.12 2025-07-16 08:01:37 +00:00
Daniel Hofstetter 45bda33a6b Merge pull request #175 from uutils/renovate/libfuzzer-sys-0.x-lockfile
fix(deps): update rust crate libfuzzer-sys to v0.4.10
2025-07-04 08:06:44 +02:00
renovate[bot] 64069cdbf2 fix(deps): update rust crate libfuzzer-sys to v0.4.10 2025-07-03 23:25:47 +00:00
yuankunzhang 4d6568b326 fix: timestamp cannot be combined with other items 2025-07-01 13:40:04 +00:00
Daniel Hofstetter f5c1a5e399 Merge pull request #173 from yuankunzhang/date-time-builder
refactor: introduce a builder and simplify the date time composition
2025-07-01 14:52:49 +02:00
yuankunzhang 706ab45937 refactor: introduce a builder and simplify the date time composition 2025-06-30 13:51:25 +00:00
Daniel Hofstetter 4d9afba2d4 Merge pull request #172 from yuankunzhang/minor-refactor
refactor: put the epoch and timezone module into separate files
2025-06-30 15:10:34 +02:00
yuankunzhang 05677a803d refactor: put the epoch and timezone module into separate files 2025-06-30 13:05:10 +00:00
Daniel Hofstetter 98d4931b53 Merge pull request #169 from yuankunzhang/hour-with-meridiem
fix: hour must be greater than 0 when meridiem is specified
2025-06-28 17:03:48 +02:00
yuankunzhang 0b5d3ffdf3 fix: hour must be greater than 0 when meridiem is specified 2025-06-28 16:48:09 +02:00
Daniel Hofstetter 24fa78a927 Merge pull request #168 from yuankunzhang/nanoseconds
feat: support nanoseconds
2025-06-28 16:45:22 +02:00
yuankunzhang c0ada32ce1 feat: support nanoseconds 2025-06-28 16:30:24 +02:00
Daniel Hofstetter b5b1fd2b5e Merge pull request #171 from yuankunzhang/check-overflows
fix: check overflows during date time composition
2025-06-28 16:18:41 +02:00
yuankunzhang 8d78de85a5 fix: check overflows during date time composition 2025-06-27 15:24:00 +00:00
Sylvestre Ledru 33ac3b75cc Merge pull request #170 from cakebaker/clippy_fix_warning
clippy: fix warning from `uninlined_format_args`
2025-06-27 09:54:14 +02:00
Daniel Hofstetter 832942c019 clippy: fix warning from uninlined_format_args 2025-06-27 09:45:11 +02:00
Daniel Hofstetter e031c8ce49 Merge pull request #167 from Maximkaaa/integration_tests
test: Integration tests for time parsing
2025-06-26 16:59:28 +02:00
Maxim 856a13ddb2 test: Integration tests for date parsing 2025-06-25 05:15:41 +00:00
Sylvestre Ledru f1f2c47120 Merge pull request #163 from cakebaker/tests_fix_typos
tests: fix typos
2025-06-24 14:47:21 +02:00
Sylvestre Ledru 2c0fa5a264 Merge pull request #164 from cakebaker/tests_add_license_header
tests: add license header to integration tests
2025-06-24 14:47:08 +02:00
Daniel Hofstetter 937572d557 tests: add license header to integration tests 2025-06-24 14:43:56 +02:00
Daniel Hofstetter a7d9d1ab59 tests: fix typos
aphabetical -> alphabetical, ommititing -> omitting
2025-06-24 13:55:37 +02:00
Sylvestre Ledru 3be37c4d82 Merge pull request #161 from Maximkaaa/integration_tests
Integration tests for date parsing
2025-06-24 12:36:55 +02:00
Daniel Hofstetter 95897465b2 Merge pull request #159 from yuankunzhang/weekday-optional-comma
fix: weekday may be followed by an optional comma
2025-06-21 07:42:03 +02:00
Maxim 7260b0ae73 test: Integration tests for date parsing 2025-06-20 09:16:48 +00:00
Maxim 92daee09de chore: Remove empty source file 2025-06-20 15:31:40 +09:00
yuankunzhang 73f69b1da0 fix: weekday may be followed by an optional comma 2025-06-17 22:08:35 +08:00
Daniel Hofstetter 30cb26d75c Merge pull request #157 from yuankunzhang/simplify-mod-rs
Simplify items/mod.rs by moving the fundamental combinators to their own module
2025-06-15 17:04:49 +02:00
yuankunzhang 6e64f21967 refactor: move fundamental combinators from mod.rs to the primitive module 2025-06-15 21:15:28 +08:00
yuankunzhang 9b67307512 fix: relative date time handling 2025-06-15 21:13:31 +08:00
Sylvestre Ledru 76d8f17350 Merge pull request #155 from yuankunzhang/main
fix: use custom dec_uint in ordinal parsing
2025-06-15 11:05:09 +02:00
Yuankun Zhang c05b8217e0 Merge branch 'main' into main 2025-06-15 12:22:16 +08:00
yuankunzhang 41a53a2610 fix: use custom dec_uint in ordinal parsing 2025-06-15 12:21:07 +08:00
Daniel Hofstetter 03cff2ce1e Merge pull request #150 from yuankunzhang/minor-fix
fix: check whether the parsed time contains timezone
2025-06-14 15:10:44 +02:00
Daniel Hofstetter 12f73c3d57 Merge pull request #153 from uutils/renovate/winnow-0.x-lockfile
fix(deps): update rust crate winnow to v0.7.11
2025-06-10 18:47:50 +02:00
renovate[bot] c694587fdd fix(deps): update rust crate winnow to v0.7.11 2025-06-10 16:41:00 +00:00
yuankunzhang 3fe06c0b94 fix: check whether the parsed time contains timezone 2025-06-04 16:42:32 +08:00
Sylvestre Ledru 1a6a6f688a Merge pull request #143 from yuankunzhang/main
use proper error mode in items::parse()
2025-06-04 09:11:30 +02:00
yuankunzhang 294bd5eeb2 use proper error mode in items::parse() 2025-05-28 23:21:41 +08:00
yuankunzhang 60745300ad use a custom float parser 2025-05-28 23:19:10 +08:00
Sylvestre Ledru 1552608bce Merge pull request #145 from yuankunzhang/fallible-offset-conversion
fallible offset conversion
2025-05-26 18:08:50 +02:00
Sylvestre Ledru ee9beb07d3 prepare release 0.10.0 2025-05-26 16:50:31 +02:00
Daniel Hofstetter 6f073addf5 Merge pull request #146 from drinkcat/fix-tests
Fix/improve tests
2025-05-26 13:59:44 +02:00
Nicolas Boichat a9676626be src/items: Fix timezone tests
The current tests look wrong ("%Z" shouldn't print an offset, but
this accidentally works due to the way the parsing logic operates),
fix that.
2025-05-25 21:34:22 +02:00
Nicolas Boichat da0af495e8 test: Replace %+ format with explicit one
%+ is an extension that jiff doesn't support (if we still want to
convert parse_datetime in the future, and since these are tests,
it's probably better to use an explicit format.
2025-05-25 21:34:22 +02:00
Nicolas Boichat e00555cd96 src/lib: Add end-to-end timezone test
Also make the offset test a little bit smarter.
2025-05-25 21:34:22 +02:00
yuankunzhang ab91b2b6d7 fallible offset conversion 2025-05-20 21:30:35 +08:00
Terts Diepraam cc7c143b21 Merge pull request #141 from yuankunzhang/main
Upgrade winnow to 0.7.10
2025-05-19 15:05:43 +02:00
Daniel Hofstetter 7721ae2cd8 Merge pull request #142 from yanganto/msrv
Specify MSRV 1.71.1
2025-05-14 16:06:27 +02:00
Antonio Yang 557c3a3ae3 Specify MSRV 1.71.1 2025-05-14 00:59:47 +08:00
yuankunzhang bea8ec2641 upgrade winnow to 0.7.10 2025-05-12 19:46:33 +08:00
Terts Diepraam 852e49e224 Merge pull request #138 from yuankunzhang/code-cleanup
Code cleanup
2025-05-09 13:31:02 +02:00
yuankunzhang 2390ef0b25 code cleanup 2025-05-09 18:55:10 +08:00
Terts Diepraam 77156f46d2 Merge pull request #137 from yuankunzhang/replace-the-regex-parser
Replace the regex parser with winnow-based parse
2025-05-09 11:35:48 +02:00
yuankunzhang bc6b70bc9e code fixup to pass all tests 2025-05-07 21:54:42 +08:00
Daniel Hilst 2479c61dd5 Find a compatibility intersection between chrono and GNU 2025-04-30 19:53:34 +08:00
Daniel Hilst 4c3d2221da Restore the old API and add the missing combinators 2025-04-30 19:53:34 +08:00
Terts Diepraam 07d4b80ea5 start parsing date with winnow 2025-04-30 19:53:34 +08:00
Daniel Hofstetter b481a2bdec Merge pull request #136 from uutils/renovate/chrono-0.x-lockfile
fix(deps): update rust crate chrono to v0.4.41
2025-04-29 18:28:41 +02:00
renovate[bot] a387463373 fix(deps): update rust crate chrono to v0.4.41 2025-04-29 15:59:06 +00:00
Daniel Hofstetter b6795d9b2e Merge pull request #134 from dan-hipschman/handle-uppercase
Allow uppercase for words like "today", "next", etc.
2025-04-26 17:56:24 +02:00
Dan Hipschman 3bdafeb2cf Allow uppercase for words like "today", "next", etc. 2025-04-26 08:07:10 -07:00
Daniel Hofstetter b9630d4bd3 Merge pull request #128 from dan-hipschman/parse-relative-weekdays
Parse relative weekdays like "next monday"
2025-04-25 09:24:49 +02:00
Dan Hipschman 65fb9140d2 Parse relative weekdays like "next monday" 2025-04-22 10:00:13 -07:00
Sylvestre Ledru 9b22a18bce Merge pull request #130 from cakebaker/fix_some_clippy_pedantic_issues
clippy: fix some warnings from clippy::pedantic
2025-04-22 10:42:20 +02:00
Daniel Hofstetter 28b788a300 clippy: fix warnings from redundant_else lint 2025-04-22 10:34:39 +02:00
Daniel Hofstetter f6b6b3e4ea clippy: fix warning from manual_let_else lint 2025-04-22 10:31:02 +02:00
Daniel Hofstetter 1a93bb4e3e clippy: fix warning from needless_continue lint 2025-04-22 10:27:13 +02:00
Daniel Hofstetter 9fc966308e clippy: remove unnecessary semicolon 2025-04-22 10:12:20 +02:00
Sylvestre Ledru 7119769488 Merge pull request #121 from cakebaker/rename_const
Rename `TWELVEHOUR` to `TWELVE_HOUR`
2025-04-22 09:56:39 +02:00
Daniel Hofstetter 46a82b70b3 Rename TWELVEHOUR to TWELVE_HOUR 2025-04-22 09:52:19 +02:00
Dan Hipschman e7ed14e8a4 Allow spaces between +/- and number (#129)
* Allow spaces between +/- and number

* Remove space to make fmt job pass

---------

Co-authored-by: Daniel Hofstetter <daniel.hofstetter@42dh.com>
2025-04-22 09:44:09 +02:00
Daniel Hofstetter 9184428407 Merge pull request #126 from uutils/renovate/chrono-0.x-lockfile
Update Rust crate chrono to v0.4.40
2025-02-26 13:44:20 +01:00
renovate[bot] 25825df8b7 Update Rust crate chrono to v0.4.40 2025-02-26 11:56:48 +00:00
Sylvestre Ledru 0dbce58014 Merge pull request #120 from cakebaker/readme_fix_sentence
README.md: fix incorrect sentence
2025-02-17 20:31:53 +01:00
Daniel Hofstetter 0c0a054f70 README.md: fix incorrect sentence 2025-02-17 14:51:34 +01:00
Sylvestre Ledru 52dca03c56 README.md: adjust the doc to avoid the hardcoded version 2025-02-17 11:24:36 +01:00
Daniel Hofstetter d4384ceec9 Merge pull request #119 from sylvestre/new-release
Prepare the new relase + clippy
2025-02-17 08:58:27 +01:00
Sylvestre Ledru 46cc4147c7 fix clippy pedantic 2025-02-16 21:52:29 +01:00
Sylvestre Ledru 93e1c9bfe7 prepare 0.8.0 2025-02-16 21:32:13 +01:00
Daniel Hofstetter e7a7a0b07f Merge pull request #110 from jfinkels/parse-ref-date-and-delta
Parse reference datetime and timedelta from the same string
2025-02-16 17:20:29 +01:00
jfinkels d4353d0888 Use str.ends_with for patterns ending in Z
Co-authored-by: Daniel Hofstetter <daniel.hofstetter@42dh.com>
2025-02-16 11:16:23 -05:00
Jeffrey Finkelstein 8aee979de5 Parse reference date and delta from same string
Change the `parse_datetime()` function so that it parses both a
reference date and a time delta from one string. The new implementation
attempts to parse the datetime from the longest possible prefix of the
string. The remainder of the string is parsed as the time delta. This
allows us to parse more combinations of reference dates and time deltas
more easily.

Fixes #104
2025-02-14 22:00:09 -05:00
Jeffrey Finkelstein f1fada62a6 Add additional pattern for datetime w/o timezone 2025-02-14 22:00:09 -05:00
Daniel Hofstetter ca6a39c0a7 Merge pull request #117 from jfinkels/add-time-to-date-after-parsing
Add time to parsed date after parsing not before
2025-02-14 10:10:14 +01:00
Jeffrey Finkelstein db18db4e1d Add time to parsed date after parsing not before
Change the way dates without times are parsed by just parsing the date
as-is and applying the placeholder time (00:00:00) after parsing
instead of before.
2025-02-13 18:48:47 -05:00
Sylvestre Ledru c337aba9cb Merge pull request #116 from jfinkels/remove-add-zero-months
Remove more useless calls to add zero months to date
2025-02-13 07:55:18 +01:00
Sylvestre Ledru 63cfc01e80 Merge pull request #111 from cakebaker/fuzz_remove_rand_dependency
fuzz: remove `rand` dependency
2025-02-13 07:54:53 +01:00
Sylvestre Ledru 1daaeb42a2 Merge pull request #118 from jfinkels/add-more-tests
Add a lot more unit tests
2025-02-13 07:54:36 +01:00
Jeffrey Finkelstein 3fcbac6fae Add a lot more unit tests
Add more unit tests for `parse_datetime()` when given an input without
a time delta (like "+1 year" or similar).
2025-02-12 22:04:09 -05:00
Jeffrey Finkelstein 65cd15dba9 Remove useless call to add zero months to date 2025-02-12 21:49:23 -05:00
Daniel Hofstetter 65c88f3586 Merge pull request #115 from jfinkels/patterns-with-length
Greedy parsing of datetime before time delta
2025-02-12 07:15:23 +01:00
jfinkels 2c55db21fa Avoid unnecessary slicing when parsing offset
Co-authored-by: Daniel Hofstetter <daniel.hofstetter@42dh.com>
2025-02-11 20:05:55 -05:00
Jeffrey Finkelstein badc887606 Greedy parsing of datetime before time delta
Simulate greedy parsing of an absolute datetime in the prefix of a
string before parsing a subsequent time delta in the suffix of the
string. This does not change the behavior of `parse_datetime`, it just
prepares the code for a future change that allows parsing both the
absolute datetime and the time delta from the same string.

Greedy parsing is implemented by iterating over a list of patterns in
decreasing order of length so that longer patterns are tried before
shorter patterns. This guarantees that if there is an absolute datetime
present at the beginning of the string, then it will definitely be
parsed and the remaining part of the string is assumed to contain a time
delta.
2025-02-09 17:31:25 -05:00
Jeffrey Finkelstein f8adcb6c88 Add passing test for parsing datetime ending in Z
Add a passing unit test for parsing a datetime ending in the letter Z,
as in

    2023-06-03 12:00:01Z

This is treated as a datetime in the UTC time zone.
2025-02-09 17:31:25 -05:00
Daniel Hofstetter d0dceb6eaf Merge pull request #114 from jfinkels/parse-empty-string
Allow empty string in parse_relative_time_at_date
2025-02-09 16:18:43 +01:00
Jeffrey Finkelstein 45b9d9f09a Allow empty string in parse_relative_time_at_date
Allow the empty string when parsing the relative time in
`parse_relative_time_at_date()`. The empty string represents zero time
delta.
2025-02-08 15:05:50 -05:00
Daniel Hofstetter 0965130c1b fuzz: remove rand dependency 2025-02-08 20:59:19 +01:00
Sylvestre Ledru 51ddcb793f Merge pull request #113 from jfinkels/set-utc-tz-in-test
Explicitly set timezone UTC0 in a unit test
2025-02-08 20:59:03 +01:00
Sylvestre Ledru 7985aa04ba Merge pull request #112 from jfinkels/fix-add-months-tests
Make tests of adding months more resilient
2025-02-08 20:58:39 +01:00
Jeffrey Finkelstein 5c0c9c4405 Explicitly set timezone UTC0 in a unit test 2025-02-08 14:48:06 -05:00
Jeffrey Finkelstein 8dd8051eb7 Make tests of adding months more resilient
Protect against a situation where adding one month to the current day
would cause an overflow in the next month in some unit tests of
`parse_relative_time`. For example, adding one month to March 31
should overflow to May 1 because April only has 30 days. This is a
difference in the behavior we want for our library compared with the
behavior of `chrono`.
2025-02-08 14:42:38 -05:00
Daniel Hofstetter 073b9f7b70 Merge pull request #109 from uutils/renovate/libfuzzer-sys-0.x-lockfile
fix(deps): update rust crate libfuzzer-sys to v0.4.9
2025-01-29 07:16:20 +01:00
renovate[bot] 0318dabe3a fix(deps): update rust crate libfuzzer-sys to v0.4.9 2025-01-28 18:33:49 +00:00
Sylvestre Ledru 57fe123e21 Merge pull request #107 from cakebaker/bump_nom
Bump `nom` & adapt to API changes
2025-01-27 11:14:31 +01:00
Daniel Hofstetter 2fe83cabf1 Adapt to API changes in nom 8.0.0 2025-01-27 10:53:08 +01:00
Daniel Hofstetter 94d4112707 Bump nom from 7.1.3 to 8.0.0 2025-01-27 10:48:23 +01:00
Sylvestre Ledru eda2422bb3 Merge pull request #103 from jfinkels/parse-datetime-with-single-digit-offset-t-sep
Parse datetime with T separator and single digit offset
2025-01-19 23:07:12 +01:00
Jeffrey Finkelstein c948274c42 Parse datetime with T separator and digit offset
Parse a datetime with T separator between date and time, single digit
timezone offset, and no space between time and offset.
2025-01-19 16:38:06 -05:00
Sylvestre Ledru b209341259 Merge pull request #105 from sylvestre/0.7.0
prepare new release 0.7.0
2025-01-19 22:29:25 +01:00
Sylvestre Ledru 9cd22afa29 prepare new release 0.7.0 2025-01-19 22:25:25 +01:00
Sylvestre Ledru a7061bce12 Merge pull request #102 from jfinkels/parse-datetime-with-single-digit-offset
Parse datetimes with single digit timezone offset
2025-01-19 22:25:10 +01:00
Jeffrey Finkelstein ea49dc94f0 Parse datetimes with single digit timezone offset
Parse full datetimes with single digit timezone offsets like +3 or -5.
2025-01-18 18:45:22 -05:00
Sylvestre Ledru 938aa9694b Merge pull request #100 from jfinkels/add-months-overflow-surplus-days
Overflow surplus days when adding months to a date
2025-01-18 23:30:10 +01:00
Sylvestre Ledru 51e294724c Merge pull request #99 from jfinkels/parse-dates-with-slashes
Parse calendar dates with slashes, like 2/29/1996
2025-01-18 23:27:22 +01:00
Sylvestre Ledru fa53ec79bd Merge pull request #78 from cakebaker/readme_bump_version
readme: bump version to 0.6.0
2025-01-18 23:27:02 +01:00
Jeffrey Finkelstein 90d22a2c37 Overflow surplus days when adding months to a date
Change the behavior of `parse_relative_time_at_date()` so that adding
months to a given date causes surplus days to overflow to the next
month. For example, adding 1 month to 1996-03-31 would be 1996-04-31,
but April only has 30 days, so the surplus day rolls over to the next
month, resulting in 1996-05-01.

Closes #98
2025-01-18 23:23:37 +01:00
Jeffrey Finkelstein 06aac3f56f Parse calendar dates with slashes, like 2/29/1996 2025-01-18 23:23:34 +01:00
Sylvestre Ledru 240abf791e Merge pull request #101 from jfinkels/single-digit-tz-offset
Parse single digit timezone offsets
2025-01-18 23:22:50 +01:00
Jeffrey Finkelstein 34f226fd98 Parse single digit timezone offsets
Add parsing for timezone offsets of the form +N or -N. As a side effect
of this change, parsing timezone offsets like +0700, UTC+2, and Z-1 are
now supported.
2025-01-18 14:49:16 -05:00
Sylvestre Ledru 00dc90dd10 Merge pull request #97 from jfinkels/military-time-zones
Add support for military time zones
2025-01-09 07:51:39 +01:00
Jeffrey Finkelstein 3c67f4b5c9 Add support for military time zones
Fixes #39
2025-01-08 21:38:46 -05:00
Daniel Hofstetter faf363c2e6 Merge pull request #96 from uutils/renovate/chrono-0.x-lockfile
fix(deps): update rust crate chrono to v0.4.39
2024-12-09 13:34:01 +01:00
renovate[bot] 56410cebcf fix(deps): update rust crate chrono to v0.4.39 2024-12-09 12:12:42 +00:00
Daniel Hofstetter d777be1bb6 Merge pull request #94 from uutils/renovate/migrate-config
chore(config): migrate renovate config
2024-11-29 16:05:53 +01:00
Daniel Hofstetter 6429ef26c5 Merge pull request #93 from uutils/renovate/codecov-codecov-action-5.x
chore(deps): update codecov/codecov-action action to v5
2024-11-29 16:03:30 +01:00
Daniel Hofstetter fa311c0dd4 ci: fix deprecated codecov argument 2024-11-29 15:59:28 +01:00
renovate[bot] 7ab9a02761 chore(deps): update codecov/codecov-action action to v5 2024-11-29 14:49:20 +00:00
Sylvestre Ledru 78877a1b98 Merge pull request #92 from cakebaker/ci_fix_code_coverage
ci: use `-Cinstrument-coverage` instead of `-Zprofile`
2024-11-29 15:49:10 +01:00
Sylvestre Ledru 623c626b3a Merge pull request #95 from cakebaker/clippy_fix_warning
clippy: fix warning from `needless_return` lint
2024-11-29 09:53:27 +01:00
Daniel Hofstetter a9bccfa20a clippy: fix warning from needless_return lint 2024-11-29 09:44:40 +01:00
renovate[bot] dba1374f8e chore(config): migrate config renovate.json 2024-11-18 14:38:21 +00:00
Daniel Hofstetter 9b266bcb17 ci: use -Cinstrument-coverage instead of -Zprofile
Support for -Zprofile has been removed: https://github.com/rust-lang/rust/pull/131829
2024-11-11 09:48:09 +01:00
Sylvestre Ledru 5e3fc539a3 Merge pull request #88 from cakebaker/bump_iana_time_zone_in_fuzz
Bump `iana-time-zone` in `fuzz` from `0.1.56` to `0.1.61`
2024-11-08 10:28:05 +01:00
Sylvestre Ledru c26d83fd6e Merge pull request #91 from uutils/renovate/libfuzzer-sys-0.x-lockfile
fix(deps): update rust crate libfuzzer-sys to v0.4.8
2024-11-08 10:27:56 +01:00
renovate[bot] a841ad0fc4 fix(deps): update rust crate libfuzzer-sys to v0.4.8 2024-11-08 01:44:41 +00:00
Daniel Hofstetter 8ca89bdb55 Merge pull request #90 from uutils/renovate/regex-1.x-lockfile
fix(deps): update rust crate regex to v1.11.1
2024-10-25 07:06:26 +02:00
renovate[bot] 48852068de fix(deps): update rust crate regex to v1.11.1 2024-10-24 17:07:28 +00:00
Daniel Hofstetter 3813a3bae9 Merge pull request #89 from uutils/renovate/regex-1.x-lockfile
fix(deps): update rust crate regex to v1.11.0
2024-09-30 06:59:39 +02:00
renovate[bot] 313de7ba7c fix(deps): update rust crate regex to v1.11.0 2024-09-29 16:46:09 +00:00
Daniel Hofstetter 7913ecd888 Merge pull request #87 from jetlime/main
`parse_relative_time`: Include 'this' direction
2024-09-17 16:11:30 +02:00
Paul Houssel 8a528468ae include 'this' direction 2024-09-17 15:31:00 +02:00
Daniel Hofstetter 212c6f7c24 Merge pull request #85 from ysthakur/fix-relative-time
Don't use Durations for calculating relative times
2024-09-17 11:06:59 +02:00
Daniel Hofstetter cd7020f038 Bump iana-time-zone in fuzz from 0.1.56 to 0.1.61 2024-09-17 09:49:38 +02:00
Daniel Hofstetter e543ee64a7 Merge pull request #75 from uutils/renovate/chrono-0.x-lockfile
fix(deps): update rust crate chrono to v0.4.38
2024-09-17 09:43:55 +02:00
renovate[bot] 19d49cfe73 fix(deps): update rust crate chrono to v0.4.38 2024-09-17 07:39:50 +00:00
Sylvestre Ledru 86d72fc867 Merge pull request #74 from cakebaker/bump_chrono
Bump `chrono` and `iana-time-zone`; fix use of deprecated function
2024-09-17 09:38:40 +02:00
Daniel Hofstetter bbcafc42f9 Replace use of NativeDateTime::from_timestamp_opt
with DateTime::from_timestamp due to deprecation
2024-09-17 09:34:25 +02:00
Daniel Hofstetter 1570d92fc5 Bump chrono and iana-time-zone
chrono: 0.4.26 -> 0.4.38
iana-time-zone: 0.1.56 -> 0.1.61
2024-09-17 09:34:14 +02:00
ysthakur e41e26fef1 Replace unnecessary return with None 2024-09-04 23:55:47 -04:00
ysthakur d5015a641e Format 2024-08-28 02:24:49 -04:00
ysthakur 5e6bddb6f5 Get rid of parse_relative_time 2024-08-27 22:13:47 -04:00
ysthakur ced645a4f4 Make helpers timezone-generic 2024-08-27 21:46:49 -04:00
ysthakur d75338a51b Make tests for months without 30 days and leap years 2024-08-27 19:02:08 -04:00
ysthakur d4f67bbde0 Don't use Durations for calculating relative times 2024-08-27 18:51:10 -04:00
Daniel Hofstetter ba19b94acd Merge pull request #81 from uutils/renovate/regex-1.x-lockfile
fix(deps): update rust crate regex to v1.10.6
2024-08-02 18:32:25 +02:00
renovate[bot] f7f789913a fix(deps): update rust crate regex to v1.10.6 2024-08-02 16:04:11 +00:00
Daniel Hofstetter 7e84a62b9e Merge pull request #79 from uutils/renovate/regex-1.x-lockfile
fix(deps): update rust crate regex to v1.10.5
2024-06-09 15:59:12 +02:00
renovate[bot] db8c1d364f fix(deps): update rust crate regex to v1.10.5 2024-06-09 13:29:07 +00:00
Daniel Hofstetter e1aa18d263 readme: bump version to 0.6.0 2024-05-21 07:22:43 +02:00
Sylvestre Ledru a05bd1d06e Merge pull request #77 from cakebaker/release_0_6_0
Bump version to 0.6.0
2024-05-20 18:50:45 +02:00
Daniel Hofstetter a75107c69d Bump version to 0.6.0 2024-05-20 18:40:34 +02:00
Daniel Hofstetter 0f5b6bf16e Merge pull request #76 from RenjiSann/main
Fix single digit date parsing
2024-05-20 17:32:41 +02:00
Dorian Péron 1bb93d7fe9 Fix single digit date parsing 2024-05-20 17:24:33 +02:00
Sylvestre Ledru 138999131b Merge pull request #73 from cakebaker/ci_use_clippy_all_targets
ci: use `clippy --all-targets`
2024-05-03 15:52:55 +02:00
Daniel Hofstetter fc14854394 clippy: fix warnings from zero_prefixed_literal 2024-05-03 15:35:24 +02:00
Daniel Hofstetter be45c2734d ci: use clippy --all-targets 2024-05-03 15:33:11 +02:00
Daniel Hofstetter acf9b9c76e Merge pull request #72 from uutils/renovate/regex-1.x
fix(deps): update rust crate regex to 1.10.4
2024-05-01 13:47:54 +02:00
renovate[bot] 04494f6ddb fix(deps): update rust crate regex to 1.10.4 2024-05-01 11:32:23 +00:00
Daniel Hofstetter 20a39748f0 Merge pull request #71 from uutils/renovate/libfuzzer-sys-0.x
fix(deps): update rust crate libfuzzer-sys to 0.4.7
2024-05-01 13:31:17 +02:00
renovate[bot] 113100e669 fix(deps): update rust crate libfuzzer-sys to 0.4.7 2024-05-01 10:08:38 +00:00
Terts Diepraam ff2113eabe Merge pull request #67 from matrixhead/main
epoch timezone fix
2024-03-24 18:51:36 +01:00
Sylvestre Ledru ad9a056826 Merge pull request #64 from cakebaker/ci_use_codecov_token
ci: use codecov token
2024-03-24 17:09:56 +01:00
Sylvestre Ledru d1263e0e7e Merge pull request #69 from cakebaker/clippy_fix_warnings
clippy: fix warnings
2024-03-24 17:05:35 +01:00
Daniel Hofstetter 5b81981a8a clippy: fix warning from bool_assert_comparison 2024-03-24 16:54:43 +01:00
Daniel Hofstetter 85957480b3 clippy: fix warnings from zero_prefixed_literal 2024-03-24 16:52:29 +01:00
Daniel Hofstetter 0d04eeb08d Merge pull request #68 from uutils/renovate/regex-1.x
fix(deps): update rust crate regex to 1.10.4
2024-03-23 07:12:53 +01:00
renovate[bot] 0dddb4b726 fix(deps): update rust crate regex to 1.10.4 2024-03-23 05:16:50 +00:00
mhead deffff9803 epoch timezone fix 2024-03-04 21:23:25 +05:30
Terts Diepraam 96d8c7c294 Merge pull request #65 from matrixhead/main
support for parsing date string with only time
2024-03-03 23:10:44 +01:00
mhead 249c079790 parse time only strings 2024-03-03 22:54:01 +05:30
Daniel Hofstetter 261b28db22 ci: use codecov token 2024-02-06 09:58:43 +01:00
Terts Diepraam cdc1b64fcf Merge pull request #63 from drmorr0/drmorr/fix_readme
fix readme
2024-02-01 15:41:47 +01:00
Daniel Hofstetter 9e27be1e1a Merge pull request #62 from uutils/renovate/codecov-codecov-action-4.x
chore(deps): update codecov/codecov-action action to v4
2024-02-01 07:06:07 +01:00
David Morrison 9bb047eeab fix readme 2024-01-31 15:13:23 -08:00
renovate[bot] 040561c235 chore(deps): update codecov/codecov-action action to v4 2024-01-31 19:43:11 +00:00
Sylvestre Ledru 9009bfc4ed Merge pull request #60 from cakebaker/ci_replace_actions_rs_cargo
ci: remove actions-rs/cargo & use cargo directly
2024-01-22 09:42:42 +01:00
Daniel Hofstetter c39e01748c ci: remove actions-rs/cargo & use cargo directly 2024-01-22 09:26:32 +01:00
Sylvestre Ledru 325ae3a408 Merge pull request #59 from cakebaker/ci_use_dtolnay_rust_toolchain
ci: use dtolnay/rust-toolchain instead of action_rs/toolchain
2024-01-22 08:52:34 +01:00
Daniel Hofstetter 1ded0a062c ci: use dtolnay/rust-toolchain instead of
action_rs/toolchain to get rid of some CI warnings
2024-01-22 08:46:20 +01:00
Daniel Hofstetter 0047868a35 Merge pull request #58 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.10.3
2024-01-21 17:00:08 +01:00
renovate[bot] 5d11c142b5 Update Rust crate regex to 1.10.3 2024-01-21 15:53:29 +00:00
Sylvestre Ledru 8ef448acb5 Update of the version in the readme 2023-11-26 15:58:00 +01:00
Daniel Hofstetter 0ad9ef3e6b Merge pull request #54 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.10.2
2023-10-17 07:10:05 +02:00
renovate[bot] 4dfa20c7b0 Update Rust crate regex to 1.10.2 2023-10-16 17:22:22 +00:00
Daniel Hofstetter e8ab1a46e2 Merge pull request #53 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.10.1
2023-10-15 10:32:42 +02:00
renovate[bot] 57d3527d81 Update Rust crate regex to 1.10.1 2023-10-14 16:17:34 +00:00
Daniel Hofstetter 48255280aa Merge pull request #52 from uutils/renovate/regex-1.x
Update Rust crate regex to v1.10.0
2023-10-10 06:52:42 +02:00
renovate[bot] bddcc6067f Update Rust crate regex to v1.10.0 2023-10-09 21:57:23 +00:00
Daniel Hofstetter be7fe1dc12 Merge pull request #51 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.9.6
2023-09-30 16:18:10 +02:00
renovate[bot] 70fde9fa18 Update Rust crate regex to 1.9.6 2023-09-30 13:41:06 +00:00
Sylvestre Ledru 2d05b14a2d Merge pull request #34 from philolo1/fix/23-weekday
Support weekdays in parse_datetime
2023-09-19 11:44:14 +02:00
Patrick Klitzke 96db1a281e Support weekdays in parse_datetime
This commit resolves issue #23.

Adds parse_weekday function that uses chrono weekday parser with a map for edge cases.
Adds tests cases to make sure it works correctly.
Use nom for parsing.
2023-09-19 17:47:18 +09:00
Patrick Klitzke 93c02dc0b7 Fixes Negative numbers for @ not being recognized (#43)
* Fixes Negative numbers for @ not being recognized

This commit resolves #40.
Adds new file and functions parse_timestamp.
Adds tests for handling negative numbers.
2023-09-15 11:40:27 +02:00
Daniel Hofstetter 29d641389d Merge pull request #49 from uutils/revert-48-renovate/codecov-codecov-action-4.x
Revert "Update codecov/codecov-action action to v4"
2023-09-15 10:11:25 +02:00
Daniel Hofstetter adb5fabfa7 Revert "Update codecov/codecov-action action to v4" 2023-09-15 09:30:33 +02:00
Sylvestre Ledru 02e5c22985 Merge pull request #46 from philolo1/feature/update-version
update version to 0.5.0
2023-09-14 17:51:04 +02:00
Daniel Hofstetter c6feb9a251 Merge pull request #48 from uutils/renovate/codecov-codecov-action-4.x
Update codecov/codecov-action action to v4
2023-09-14 17:44:30 +02:00
renovate[bot] 852638fef0 Update codecov/codecov-action action to v4 2023-09-14 15:32:52 +00:00
Daniel Hofstetter 5c34517469 Merge pull request #47 from uutils/renovate/actions-checkout-4.x
Update actions/checkout action to v4
2023-09-04 17:10:51 +02:00
renovate[bot] 47c5f3620b Update actions/checkout action to v4 2023-09-04 14:54:00 +00:00
Patrick Klitzke 1e43cc945f update parse_datetime to version to 0.5.0
update fuzz to version to 0.2.0
2023-09-04 17:50:42 +09:00
Sylvestre Ledru f9ce5047a5 Merge pull request #45 from cakebaker/use_rust_2021_edition
Use Rust 2021 edition for fuzzing
2023-09-02 18:05:41 +02:00
Daniel Hofstetter 4c3fd2b1ed Merge pull request #44 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.9.5
2023-09-02 17:54:09 +02:00
Daniel Hofstetter 9a7f87ac09 Use Rust 2021 edition for fuzzing 2023-09-02 17:49:26 +02:00
renovate[bot] 0b0aa70193 Update Rust crate regex to 1.9.5 2023-09-02 15:29:56 +00:00
Daniel Hofstetter 0c44becec8 Merge pull request #42 from cakebaker/remove_time_crate
Adapt chrono settings to remove old time crate
2023-08-30 11:38:15 +02:00
Daniel Hofstetter 64dfea4b47 Adapt chrono settings to remove old time crate 2023-08-30 08:12:18 +02:00
Terts Diepraam 0bdabd5303 Merge pull request #41 from philolo1/fix/spelling
Fix small smelling error in readme
2023-08-30 07:46:09 +02:00
Patrick Klitzke 2112830d8b Fix small smelling error in readme 2023-08-30 14:39:34 +09:00
Terts Diepraam 2737b4a0f2 Merge pull request #33 from philolo1/fix/datetime-should-parse-relative
Make parse_datetime::parse_datetime::from_str accept relative time
2023-08-29 10:06:09 +02:00
Patrick Klitzke f10749eade Refactor parse_datetime to only expose parse_datetime function
Create new file parse_relative_time.rs with the relative time helper function.
Renames from_str to parse_datetime and parse_relative time.
Adds function parse_datetime_at_date.
2023-08-29 09:03:17 +09:00
Terts Diepraam a7380508bc Merge pull request #38 from cakebaker/use_timestamp_opt_instead_of_timestamp
Use timestamp_opt() instead of timestamp() in test
2023-08-28 10:06:16 +02:00
Daniel Hofstetter 7f0a909752 Use timestamp_opt() instead of timestamp() in test 2023-08-28 09:34:38 +02:00
Daniel Hofstetter ff0f99bea5 Merge pull request #35 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.9.4
2023-08-27 11:30:45 +02:00
renovate[bot] dc0d8a3aa0 Update Rust crate regex to 1.9.4 2023-08-26 17:26:24 +00:00
Sylvestre Ledru b615effc4e Merge pull request #32 from philolo1/fix/add-unix-timestamp-test
Add tests for unix timestamp
2023-08-22 13:25:05 -04:00
Patrick Klitzke cebf55cf82 Add a unix timestamp
This pr adds tests to support the @ unix timestamp.
2023-08-21 19:40:43 +09:00
Sylvestre Ledru efee20bf01 Merge pull request #29 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.9.3
2023-08-21 07:10:25 +02:00
Sylvestre Ledru c084001056 Merge pull request #31 from Benjscho/main
Add test for parsing epoch seconds
2023-08-21 07:10:15 +02:00
Ben Schofield a35530ed4a Add test for parsing epoch seconds
Add test to verify epoch seconds can be parsed by `parse_datetime`.
2023-08-20 18:41:39 -07:00
renovate[bot] 6cfcc985a8 Update Rust crate regex to 1.9.3 2023-08-06 00:15:26 +00:00
Sylvestre Ledru 497bebb9e7 Merge pull request #27 from uutils/renovate/regex-1.x
Update Rust crate regex to v1.9.1
2023-07-08 14:21:03 +02:00
renovate[bot] dfd43a6d65 Update Rust crate regex to v1.9.1 2023-07-07 20:20:30 +00:00
Sylvestre Ledru 51dd843ded Merge pull request #26 from undali/f19
add 'next' and 'last' support
2023-07-02 22:10:16 +02:00
undali c24d593821 add 'next' and 'last' support 2023-06-26 16:00:57 +04:00
Sylvestre Ledru bed2d16e67 Release version 0.4.0 2023-06-09 13:43:54 +02:00
Sylvestre Ledru 7ab1ad2f0e document the old name 2023-06-09 13:43:04 +02:00
Sylvestre Ledru c1a2bef4a6 Merge pull request #22 from sylvestre/rename
rename from humantime_to_duration to parse_datetime
2023-06-09 13:41:17 +02:00
Sylvestre Ledru 673d5b600e rename from humantime_to_duration to parse_datetime 2023-06-09 10:16:26 +02:00
Sylvestre Ledru 83e1431db0 Merge pull request #21 from sylvestre/fuzz
Also fuzz fuzz_parse_datetime_from_str for a minute
2023-06-08 11:27:07 +02:00
Sylvestre Ledru 80f8fdf883 README: syntax highlighting 2023-06-07 15:01:25 +02:00
Sylvestre Ledru 22bdd8f49c run the fuzzers in the CI 2023-06-07 13:52:00 +02:00
Sylvestre Ledru dc508c469b add a fuzzer for parse_datetime_from_str 2023-06-07 13:51:40 +02:00
Sylvestre Ledru e503de7559 Merge pull request #12 from Benjscho/main
add datetime parser
2023-06-07 10:03:17 +02:00
Ben Schofield 7ee33d1fb1 cargo fmt 2023-06-06 10:26:05 -07:00
Ben Schofield bc33770075 Update README
Update the README and add a test module to parse_datetime for any
examples presented in the README.
2023-06-06 10:05:14 -07:00
Sylvestre Ledru 70d3e53604 new release 2023-06-06 11:46:45 +02:00
Sylvestre Ledru 1ba787d1c3 Merge pull request #17 from cakebaker/downgrade_libc
Downgrade libc from 0.2.145 to 0.2.144
2023-06-06 08:02:47 +02:00
Daniel Hofstetter 33cefd7db2 Downgrade libc from 0.2.145 to 0.2.144 2023-06-06 07:49:14 +02:00
Sylvestre Ledru d0d913e161 Merge pull request #16 from uutils/renovate/regex-1.x
Update Rust crate regex to 1.8.4
2023-06-05 19:40:31 +02:00
renovate[bot] c784a721ee Update Rust crate regex to 1.8.4 2023-06-05 16:52:25 +00:00
Ben Schofield 29e7a5c335 Update src/parse_datetime.rs
Co-authored-by: Sylvestre Ledru <sledru@mozilla.com>
2023-06-05 08:04:22 -07:00
Ben Schofield 8d797fcbcb typo fix 2023-06-05 08:00:07 -07:00
Ben Schofield c177117428 Fixes for comments 2023-06-05 07:58:44 -07:00
Sylvestre Ledru 03c8e81a10 Merge pull request #15 from Redfire75369/patch-1
Added Syntax Highlighting to Example in ReadME
2023-06-05 14:32:06 +02:00
Redfire 7547f31b76 Added Syntax Highlighting to Example in ReadME 2023-06-05 20:22:57 +08:00
Sylvestre Ledru 1c32733f38 Merge pull request #14 from cakebaker/remove_time_crate
Adapt chrono settings to remove old time crate
2023-06-05 09:53:01 +02:00
Daniel Hofstetter 5278394b7c Adapt chrono settings to remove old time crate 2023-06-05 09:18:54 +02:00
Ben Schofield e53aabd914 add datetime parser
Add a relaxed datetime parser. This datetime parser functions by using `chrono`s
own parsing utilities and a try/succeed approach to parsing.

This implementation of the datetime parser has some drawbacks and some
positives. On the positive side:
- it was easy to implement
- it is easy to add more datetime formats to

In order to add additionally supported formats, a developer can add the
required format string to the `format` mod in `parse_datetime.rs`, and
then add it as a potential format to the relevant `fmts` vec.

On the negative:
- It is not easily customiseable beyond the supported `chrono` parsing
  formats. E.g., `chrono` does not currently support parsing offsets
  without trailing zeros. `from_str("UTC+1")` should return a valid response
  but `chrono` fails to parse this.
- Because it is an attempt driven parser, it is likely not that
  performant. I have not done any performance testing as part of this
change, but I would expect a custom parser to perform much better.
2023-06-03 09:58:36 -07:00
Sylvestre Ledru e5d7fbcece We moved from time to chrono 2023-06-03 16:39:58 +02:00
Sylvestre Ledru 060998e90e refresh the fuzz lock 2023-06-03 16:38:42 +02:00
Sylvestre Ledru a272f55948 update of the doc 2023-06-03 16:38:21 +02:00
Sylvestre Ledru 9c5da7959c new release 2023-06-03 16:34:51 +02:00
Sylvestre Ledru a60f1d89f5 Merge pull request #11 from sylvestre/chrono
Port the crate to use chrono instead of time
2023-06-03 16:33:51 +02:00
Sylvestre Ledru 1d78cc5a3f Simplify the check 2023-06-03 16:31:37 +02:00
Sylvestre Ledru 6ba55a075b Fix the various warnings 2023-06-03 14:38:30 +02:00
Sylvestre Ledru b439960eb1 Port the crate to use chrono instead of time 2023-06-03 13:14:00 +02:00
Sylvestre Ledru f1a15ab2b3 Merge pull request #8 from uutils/renovate/regex-1.x
Update Rust crate regex to v1.8.3
2023-05-29 16:09:02 +02:00
Sylvestre Ledru 0bd4dd716a Merge pull request #7 from uutils/renovate/rand-0.x
Update Rust crate rand to 0.8.5
2023-05-29 15:58:18 +02:00
renovate[bot] 674909c0f9 Update Rust crate regex to v1.8.3 2023-05-29 13:33:54 +00:00
renovate[bot] 57bcf7f433 Update Rust crate rand to 0.8.5 2023-05-29 13:33:48 +00:00
Sylvestre Ledru 2e80358014 Merge pull request #6 from uutils/renovate/configure
Configure Renovate
2023-05-29 15:31:52 +02:00
renovate[bot] 15fb185d95 Add renovate.json 2023-05-29 00:16:49 +00:00
Sylvestre Ledru e64c163f47 adjust the license for Debian 2023-05-27 09:43:52 +02:00
Sylvestre Ledru 86378bc326 version 0.2.1 2023-05-12 13:58:33 +02:00
Sylvestre Ledru 6a52551dea Merge pull request #5 from cakebaker/simplify_test
Simplify tests
2023-05-12 13:54:39 +02:00
Sylvestre Ledru 21e7e01fc8 Merge pull request #4 from sylvestre/reverse
Reverse the two functions
2023-05-12 13:54:31 +02:00
Daniel Hofstetter 1359dc9349 Simplify tests 2023-05-12 09:59:31 +02:00
Sylvestre Ledru daec32d5c4 describe the error 2023-05-11 22:15:29 +02:00
Sylvestre Ledru 7a3d0bafca Reverse the two functions 2023-05-11 22:15:07 +02:00
Sylvestre Ledru 537df73bdd Fix a doc warning 2023-05-11 21:57:28 +02:00
Daniel Hofstetter 3e4c6e3b6c Add .gitignore (#3) 2023-05-11 17:29:08 +02:00
Sylvestre Ledru 29e64c3cda version 0.2.0 2023-05-11 17:20:24 +02:00
Sylvestre Ledru db00d0686f add a new from_str_at_date(date, string) function (#2)
Co-authored-by: Daniel Hofstetter <daniel.hofstetter@42dh.com>
2023-05-11 17:16:02 +02:00
Sylvestre Ledru 1f0eae3536 add the README 2023-04-25 09:00:51 +02:00
28 changed files with 4796 additions and 584 deletions
+54 -55
View File
@@ -4,6 +4,7 @@ name: Basic CI
env:
CARGO_TERM_COLOR: always
RUST_MIN_SRV: "1.71.1"
jobs:
check:
@@ -13,15 +14,9 @@ jobs:
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
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo check
test:
name: cargo test
@@ -30,31 +25,18 @@ jobs:
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
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo 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
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: rustup component add rustfmt
- uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check
- run: cargo fmt --all -- --check
clippy:
name: cargo clippy -- -D warnings
@@ -63,17 +45,23 @@ jobs:
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/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: rustup component add clippy
- uses: actions-rs/cargo@v1
- run: cargo clippy --all-targets -- -D warnings
min_version:
name: Minimum Supported Rust Version
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macOS-latest, windows-latest]
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
command: clippy
args: -- -D warnings
toolchain: ${{ env.RUST_MIN_SRV }}
- run: cargo test
coverage:
name: Code Coverage
@@ -86,7 +74,7 @@ jobs:
- { os: macos-latest , features: macos }
- { os: windows-latest , features: windows }
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Initialize workflow variables
id: vars
shell: bash
@@ -101,28 +89,22 @@ jobs:
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
uses: dtolnay/rust-toolchain@nightly
with:
toolchain: ${{ steps.vars.outputs.TOOLCHAIN }}
default: true
profile: minimal # minimal component installation (ie, no documentation)
components: llvm-tools-preview
- name: Test
uses: actions-rs/cargo@v1
with:
command: test
args: ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} --no-fail-fast
run: cargo test --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"
RUSTFLAGS: "-Cinstrument-coverage -Zcoverage-options=branch -Ccodegen-units=1 -Copt-level=0 -Coverflow-checks=off -Zpanic_abort_tests -Cpanic=abort"
RUSTDOCFLAGS: "-Cpanic=abort"
LLVM_PROFILE_FILE: "parse_datetime-%p-%m.profraw"
- name: "`grcov` ~ install"
id: build_grcov
shell: bash
@@ -150,17 +132,34 @@ jobs:
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
grcov . --binary-path="${COVERAGE_REPORT_DIR}" --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\()"
grcov . --binary-path="${COVERAGE_REPORT_DIR}" --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
uses: codecov/codecov-action@v5
with:
# token: ${{ secrets.CODECOV_TOKEN }}
file: ${{ steps.coverage.outputs.report }}
token: ${{ secrets.CODECOV_TOKEN }}
files: ${{ 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
fuzz:
name: Run the fuzzers
runs-on: ubuntu-latest
env:
RUN_FOR: 60
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
- name: Install `cargo-fuzz`
run: cargo install cargo-fuzz
- uses: Swatinem/rust-cache@v2
- name: Run from_str for XX seconds
shell: bash
run: |
## Run it
cd fuzz
cargo +nightly fuzz run fuzz_parse_datetime -- -max_total_time=${{ env.RUN_FOR }} -detect_leaks=0
+1
View File
@@ -0,0 +1 @@
target/
Generated
+476 -24
View File
File diff suppressed because it is too large Load Diff
+13 -6
View File
@@ -1,11 +1,18 @@
[package]
name = "humantime_to_duration"
description = " parsing human-readable relative time strings and converting them to a Duration"
version = "0.1.2"
name = "parse_datetime"
description = "parsing human-readable time strings and converting them to a DateTime"
version = "0.11.0"
edition = "2021"
license = "MIT"
repository = "https://github.com/uutils/humantime_to_duration"
repository = "https://github.com/uutils/parse_datetime"
readme = "README.md"
rust-version = "1.71.1"
[dependencies]
regex = "1.7"
time = "0.3.20"
regex = "1.10.4"
chrono = { version="0.4.38", default-features=false, features=["std", "alloc", "clock"] }
winnow = "0.7.10"
num-traits = "0.2.19"
[dev-dependencies]
rstest = "0.26"
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2023 uutils
Copyright (c) 2023 Sylvestre Ledru and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+50 -25
View File
@@ -1,38 +1,55 @@
# humantime_to_duration
# parse_datetime
[![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)
[![Crates.io](https://img.shields.io/crates/v/parse_datetime.svg)](https://crates.io/crates/parse_datetime)
[![License](http://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/uutils/parse_datetime/blob/main/LICENSE)
[![CodeCov](https://codecov.io/gh/uutils/parse_datetime/branch/main/graph/badge.svg)](https://codecov.io/gh/uutils/parse_datetime)
A Rust crate for parsing human-readable relative time strings and converting them to a `Duration`.
A Rust crate for parsing human-readable relative time strings and human-readable datetime strings and converting them to a `DateTime`.
## Features
- Parses a variety of human-readable time formats.
- Parses a variety of human-readable and standard time formats.
- Supports positive and negative durations.
- Allows for chaining time units (e.g., "1 hour 2 minutes" or "2 days and 2 hours").
- Allows for chaining time units (e.g., "1 hour 2 minutes" or "2 days 2 hours ago").
- Calculate durations relative to a specified date.
- Relies on Chrono
## Usage
Add this to your `Cargo.toml`:
Add `parse_datetime` to your `Cargo.toml` with:
```toml
[dependencies]
humantime_to_duration = "0.1.1"
```
cargo add parse_datetime
```
Then, import the crate and use the from_str function:
```
use humantime_to_duration::from_str;
use time::Duration;
Then, import the crate and use the `parse_datetime_at_date` function:
let duration = from_str("+3 days");
assert_eq!(duration.unwrap(), Duration::days(3));
```rs
use chrono::{Duration, Local};
use parse_datetime::parse_datetime_at_date;
let now = Local::now();
let after = parse_datetime_at_date(now, "+3 days");
assert_eq!(
(now + Duration::days(3)).naive_utc(),
after.unwrap().naive_utc()
);
```
For DateTime parsing, import the `parse_datetime` function:
```rs
use parse_datetime::parse_datetime;
use chrono::{Local, TimeZone};
let dt = parse_datetime("2021-02-14 06:37:47");
assert_eq!(dt.unwrap(), Local.with_ymd_and_hms(2021, 2, 14, 6, 37, 47).unwrap());
```
### Supported Formats
The `from_str` function supports the following formats for relative time:
The `parse_datetime` and `parse_datetime_at_date` functions support absolute datetime and the following relative times:
- `num` `unit` (e.g., "-1 hour", "+3 days")
- `unit` (e.g., "hour", "day")
@@ -40,28 +57,36 @@ The `from_str` function supports the following formats for relative time:
- "yesterday"
- "tomorrow"
- use "ago" for the past
- combined units with "and" or "," (e.g., "2 years and 1 month", "1 day, 2 hours" or "2 weeks 1 second")
- use "next" or "last" with `unit` (e.g., "next week", "last year")
- unix timestamps (for example "@0" "@1344000")
`num` can be a positive or negative integer.
`unit` can be one of the following: "fortnight", "week", "day", "hour", "minute", "min", "second", "sec" and their plural forms.
## Return Values
The `from_str` function returns:
### parse_datetime and parse_datetime_at_date
- `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
The `parse_datetime` and `parse_datetime_at_date` function return:
This function will return `Err(ParseDurationError::InvalidInput)` if the input string
cannot be parsed as a relative time.
- `Ok(DateTime<FixedOffset>)` - If the input string can be parsed as a datetime
- `Err(ParseDateTimeError::InvalidInput)` - If the input string cannot be parsed
## Fuzzer
To run the fuzzer:
```
$ cargo fuzz run fuzz_from_str
$ cd fuzz
$ cargo install cargo-fuzz
$ cargo +nightly fuzz run fuzz_parse_datetime
```
## License
This project is licensed under the [MIT License](LICENSE).
## Note
At some point, this crate was called humantime_to_duration.
It has been renamed to cover more cases.
+1
View File
@@ -0,0 +1 @@
corpus
+287 -72
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "aho-corasick"
@@ -11,6 +11,21 @@ dependencies = [
"memchr",
]
[[package]]
name = "android-tzdata"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "arbitrary"
version = "1.3.0"
@@ -18,12 +33,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2d098ff73c1ca148721f37baad5ea6a465a13f9573aba8641fbbbae8164a54e"
[[package]]
name = "cc"
version = "1.0.79"
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "bumpalo"
version = "3.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1"
[[package]]
name = "cc"
version = "1.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13208fcbb66eaeffe09b99fffbe1af420f00a7b35aa99ad683dfc1aa76145229"
dependencies = [
"jobserver",
"libc",
"shlex",
]
[[package]]
@@ -33,44 +62,74 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "fuzz_from_str"
version = "0.1.0"
dependencies = [
"humantime_to_duration",
"libfuzzer-sys",
"rand",
"regex",
"time",
]
[[package]]
name = "getrandom"
version = "0.2.9"
name = "chrono"
version = "0.4.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4"
checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d"
dependencies = [
"cfg-if",
"libc",
"wasi",
"android-tzdata",
"iana-time-zone",
"num-traits",
"windows-link",
]
[[package]]
name = "humantime_to_duration"
version = "0.1.0"
name = "core-foundation-sys"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa"
[[package]]
name = "fuzz_parse_datetime"
version = "0.2.0"
dependencies = [
"chrono",
"libfuzzer-sys",
"parse_datetime",
"regex",
"time",
]
[[package]]
name = "iana-time-zone"
version = "0.1.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "jobserver"
version = "0.1.26"
version = "0.1.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2"
checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0"
dependencies = [
"libc",
]
[[package]]
name = "js-sys"
version = "0.3.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.142"
@@ -79,20 +138,34 @@ checksum = "6a987beff54b60ffa6d51982e1aa1146bc42f19bd26be28b0586f252fccf5317"
[[package]]
name = "libfuzzer-sys"
version = "0.4.6"
version = "0.4.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "beb09950ae85a0a94b27676cccf37da5ff13f27076aa1adbc6545dd0d0e1bd4e"
checksum = "5037190e1f70cbeef565bd267599242926f724d3b8a9f510fd7e0b540cfa4404"
dependencies = [
"arbitrary",
"cc",
"once_cell",
]
[[package]]
name = "memchr"
version = "2.5.0"
name = "log"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
checksum = "518ef76f2f87365916b142844c16d8fefd85039bc5699050210a7778ee1cd1de"
[[package]]
name = "memchr"
version = "2.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5486aed0026218e61b8a01d5fbd5a0a134649abb71a0e53b7bc088529dced86e"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
@@ -101,46 +174,50 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
name = "parse_datetime"
version = "0.10.0"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
"chrono",
"num-traits",
"regex",
"winnow",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
name = "proc-macro2"
version = "1.0.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
checksum = "6aeca18b86b413c660b781aa319e4e2648a3e6f9eadc9b47e9038e6fe9f3451b"
dependencies = [
"ppv-lite86",
"rand_core",
"unicode-ident",
]
[[package]]
name = "rand_core"
version = "0.6.4"
name = "quote"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
dependencies = [
"getrandom",
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.8.1"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af83e617f331cc6ae2da5443c602dfa5af81e517212d9d611a5b3ba1777b5370"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3"
dependencies = [
"aho-corasick",
"memchr",
@@ -149,34 +226,172 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.7.1"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5996294f19bd3aae0453a862ad728f60e6600695733dd5df01da90c54363a3c"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "serde"
version = "1.0.160"
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "time"
version = "0.3.20"
name = "syn"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890"
checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e"
dependencies = [
"serde",
"time-core",
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "time-core"
version = "0.1.0"
name = "unicode-ident"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
name = "wasm-bindgen"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5"
dependencies = [
"cfg-if",
"once_cell",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484"
[[package]]
name = "windows-core"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-link"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dccfd733ce2b1753b03b6d3c65edf020262ea35e20ccdf3e288043e6dd620e3"
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c06928c8748d81b05c9be96aad92e1b6ff01833332f281e8cfca3be4b35fc9ec"
dependencies = [
"memchr",
]
+9 -10
View File
@@ -1,22 +1,21 @@
[package]
name = "fuzz_from_str"
version = "0.1.0"
edition = "2018"
name = "fuzz_parse_datetime"
version = "0.2.0"
edition = "2021"
[package.metadata]
cargo-fuzz = true
[dependencies]
rand = "0.8.4"
libfuzzer-sys = "0.4"
regex = "1.8.1"
time = "0.3.20"
libfuzzer-sys = "0.4.7"
regex = "1.10.4"
chrono = { version="0.4", default-features=false, features=["std", "alloc", "clock"] }
[dependencies.humantime_to_duration]
[dependencies.parse_datetime]
path = "../"
[[bin]]
name = "fuzz_from_str"
path = "fuzz_targets/from_str.rs"
name = "fuzz_parse_datetime"
path = "fuzz_targets/parse_datetime.rs"
test = false
doc = false
@@ -4,5 +4,5 @@ use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let s = std::str::from_utf8(data).unwrap_or("");
let _ = humantime_to_duration::from_str(s);
let _ = parse_datetime::parse_datetime(s);
});
+6
View File
@@ -0,0 +1,6 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:recommended"
]
}
+320
View File
@@ -0,0 +1,320 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use chrono::{DateTime, Datelike, FixedOffset, NaiveDate, TimeZone, Timelike};
use super::{date, relative, time, weekday};
/// The builder is used to construct a DateTime object from various components.
/// The parser creates a `DateTimeBuilder` object with the parsed components,
/// but without the baseline date and time. So you normally need to set the base
/// date and time using the `set_base()` method before calling `build()`, or
/// leave it unset to use the current date and time as the base.
#[derive(Debug, Default)]
pub struct DateTimeBuilder {
base: Option<DateTime<FixedOffset>>,
timestamp: Option<f64>,
date: Option<date::Date>,
time: Option<time::Time>,
weekday: Option<weekday::Weekday>,
timezone: Option<time::Offset>,
relative: Vec<relative::Relative>,
}
impl DateTimeBuilder {
pub(super) fn new() -> Self {
Self::default()
}
/// Sets the base date and time for the builder. If not set, the current
/// date and time will be used.
pub(super) fn set_base(mut self, base: DateTime<FixedOffset>) -> Self {
self.base = Some(base);
self
}
/// Timestamp value is exclusive to other date/time components. Caller of
/// the builder must ensure that it is not combined with other items.
pub(super) fn set_timestamp(mut self, ts: f64) -> Result<Self, &'static str> {
self.timestamp = Some(ts);
Ok(self)
}
pub(super) fn set_year(mut self, year: u32) -> Result<Self, &'static str> {
if let Some(date) = self.date.as_mut() {
if date.year.is_some() {
Err("year cannot appear more than once")
} else {
date.year = Some(year);
Ok(self)
}
} else {
self.date = Some(date::Date {
day: 1,
month: 1,
year: Some(year),
});
Ok(self)
}
}
pub(super) fn set_date(mut self, date: date::Date) -> Result<Self, &'static str> {
if self.date.is_some() || self.timestamp.is_some() {
Err("date cannot appear more than once")
} else {
self.date = Some(date);
Ok(self)
}
}
pub(super) fn set_time(mut self, time: time::Time) -> Result<Self, &'static str> {
if self.time.is_some() || self.timestamp.is_some() {
Err("time cannot appear more than once")
} else if self.timezone.is_some() && time.offset.is_some() {
Err("time offset and timezone are mutually exclusive")
} else {
self.time = Some(time);
Ok(self)
}
}
pub(super) fn set_weekday(mut self, weekday: weekday::Weekday) -> Result<Self, &'static str> {
if self.weekday.is_some() {
Err("weekday cannot appear more than once")
} else {
self.weekday = Some(weekday);
Ok(self)
}
}
pub(super) fn set_timezone(mut self, timezone: time::Offset) -> Result<Self, &'static str> {
if self.timezone.is_some() {
Err("timezone cannot appear more than once")
} else if self.time.as_ref().and_then(|t| t.offset.as_ref()).is_some() {
Err("time offset and timezone are mutually exclusive")
} else {
self.timezone = Some(timezone);
Ok(self)
}
}
pub(super) fn push_relative(mut self, relative: relative::Relative) -> Self {
self.relative.push(relative);
self
}
pub(super) fn build(self) -> Option<DateTime<FixedOffset>> {
let base = self.base.unwrap_or_else(|| chrono::Local::now().into());
// If any of the following items are set, we truncate the time portion
// of the base date to zero; otherwise, we use the base date as is.
let mut dt = if self.timestamp.is_none()
&& self.date.is_none()
&& self.time.is_none()
&& self.weekday.is_none()
&& self.timezone.is_none()
{
base
} else {
new_date(
base.year(),
base.month(),
base.day(),
0,
0,
0,
0,
*base.offset(),
)?
};
if let Some(ts) = self.timestamp {
// TODO: How to make the fract -> nanosecond conversion more precise?
// Maybe considering using the
// [rust_decimal](https://crates.io/crates/rust_decimal) crate?
match chrono::Utc.timestamp_opt(ts as i64, (ts.fract() * 10f64.powi(9)).round() as u32)
{
chrono::MappedLocalTime::Single(t) => {
// If the timestamp is valid, we can use it directly.
dt = t.with_timezone(&dt.timezone());
}
chrono::MappedLocalTime::Ambiguous(earliest, _latest) => {
// TODO: When there is a fold in the local time, which value
// do we choose? For now, we use the earliest one.
dt = earliest.with_timezone(&dt.timezone());
}
chrono::MappedLocalTime::None => {
return None; // Invalid timestamp
}
}
}
if let Some(date::Date { year, month, day }) = self.date {
dt = new_date(
year.map(|x| x as i32).unwrap_or(dt.year()),
month,
day,
dt.hour(),
dt.minute(),
dt.second(),
dt.nanosecond(),
*dt.offset(),
)?;
}
if let Some(time::Time {
hour,
minute,
second,
ref offset,
}) = self.time
{
let offset = offset
.clone()
.and_then(|o| chrono::FixedOffset::try_from(o).ok())
.unwrap_or(*dt.offset());
dt = new_date(
dt.year(),
dt.month(),
dt.day(),
hour,
minute,
second as u32,
(second.fract() * 10f64.powi(9)).round() as u32,
offset,
)?;
}
if let Some(weekday::Weekday { offset, day }) = self.weekday {
if self.time.is_none() {
dt = new_date(dt.year(), dt.month(), dt.day(), 0, 0, 0, 0, *dt.offset())?;
}
let mut offset = offset;
let day = day.into();
// If the current day is not the target day, we need to adjust
// the x value to ensure we find the correct day.
//
// Consider this:
// Assuming today is Monday, next Friday is actually THIS Friday;
// but next Monday is indeed NEXT Monday.
if dt.weekday() != day && offset > 0 {
offset -= 1;
}
// Calculate the delta to the target day.
//
// Assuming today is Thursday, here are some examples:
//
// Example 1: last Thursday (x = -1, day = Thursday)
// delta = (3 - 3) % 7 + (-1) * 7 = -7
//
// Example 2: last Monday (x = -1, day = Monday)
// delta = (0 - 3) % 7 + (-1) * 7 = -3
//
// Example 3: next Monday (x = 1, day = Monday)
// delta = (0 - 3) % 7 + (0) * 7 = 4
// (Note that we have adjusted the x value above)
//
// Example 4: next Thursday (x = 1, day = Thursday)
// delta = (3 - 3) % 7 + (1) * 7 = 7
let delta = (day.num_days_from_monday() as i32
- dt.weekday().num_days_from_monday() as i32)
.rem_euclid(7)
+ offset.checked_mul(7)?;
dt = if delta < 0 {
dt.checked_sub_days(chrono::Days::new((-delta) as u64))?
} else {
dt.checked_add_days(chrono::Days::new(delta as u64))?
}
}
for rel in self.relative {
// TODO: Handle potential overflows in the addition operations.
match rel {
relative::Relative::Years(x) => {
dt = dt.with_year(dt.year() + x)?;
}
relative::Relative::Months(x) => {
// *NOTE* This is done in this way to conform to
// GNU behavior.
let days = last_day_of_month(dt.year(), dt.month());
if x >= 0 {
dt += dt
.date_naive()
.checked_add_days(chrono::Days::new((days * x as u32) as u64))?
.signed_duration_since(dt.date_naive());
} else {
dt += dt
.date_naive()
.checked_sub_days(chrono::Days::new((days * -x as u32) as u64))?
.signed_duration_since(dt.date_naive());
}
}
relative::Relative::Days(x) => dt += chrono::Duration::days(x.into()),
relative::Relative::Hours(x) => dt += chrono::Duration::hours(x.into()),
relative::Relative::Minutes(x) => {
dt += chrono::Duration::try_minutes(x.into())?;
}
// Seconds are special because they can be given as a float.
relative::Relative::Seconds(x) => {
dt += chrono::Duration::try_seconds(x as i64)?;
}
}
}
if let Some(offset) = self.timezone {
dt = with_timezone_restore(offset, dt)?;
}
Some(dt)
}
}
#[allow(clippy::too_many_arguments)]
fn new_date(
year: i32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
nano: u32,
offset: FixedOffset,
) -> Option<DateTime<FixedOffset>> {
let newdate = NaiveDate::from_ymd_opt(year, month, day)
.and_then(|naive| naive.and_hms_nano_opt(hour, minute, second, nano))?;
Some(DateTime::<FixedOffset>::from_local(newdate, offset))
}
/// Restores year, month, day, etc after applying the timezone
/// returns None if timezone overflows the date
fn with_timezone_restore(
offset: time::Offset,
at: DateTime<FixedOffset>,
) -> Option<DateTime<FixedOffset>> {
let offset: FixedOffset = chrono::FixedOffset::try_from(offset).ok()?;
let copy = at;
let x = at
.with_timezone(&offset)
.with_day(copy.day())?
.with_month(copy.month())?
.with_year(copy.year())?
.with_hour(copy.hour())?
.with_minute(copy.minute())?
.with_second(copy.second())?
.with_nanosecond(copy.nanosecond())?;
Some(x)
}
fn last_day_of_month(year: i32, month: u32) -> u32 {
NaiveDate::from_ymd_opt(year, month + 1, 1)
.unwrap_or(NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap())
.pred_opt()
.unwrap()
.day()
}
+79
View File
@@ -0,0 +1,79 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Parse an ISO 8601 date and time item
//!
//! The GNU docs state:
//!
//! > The ISO 8601 date and time of day extended format consists of an ISO 8601
//! > date, a T character separator, and an ISO 8601 time of day. This format
//! > is also recognized if the T is replaced by a space.
//! >
//! > In this format, the time of day should use 24-hour notation. Fractional
//! > seconds are allowed, with either comma or period preceding the fraction.
//! > ISO 8601 fractional minutes and hours are not supported. Typically, hosts
//! > support nanosecond timestamp resolution; excess precision is silently
//! > discarded.
use winnow::{
combinator::{alt, trace},
seq, ModalResult, Parser,
};
use crate::items::space;
use super::{
date::{self, Date},
primitive::s,
time::{self, Time},
};
#[derive(PartialEq, Debug, Clone, Default)]
pub(crate) struct DateTime {
pub(crate) date: Date,
pub(crate) time: Time,
}
pub(crate) fn parse(input: &mut &str) -> ModalResult<DateTime> {
seq!(DateTime {
date: trace("iso_date", alt((date::iso1, date::iso2))),
// Note: the `T` is lowercased by the main parse function
_: alt((s('t').void(), (' ', space).void())),
time: trace("iso_time", time::iso),
})
.parse_next(input)
}
#[cfg(test)]
mod tests {
use super::{parse, DateTime};
use crate::items::{date::Date, time::Time};
#[test]
fn some_date() {
let reference = Some(DateTime {
date: Date {
day: 10,
month: 10,
year: Some(2022),
},
time: Time {
hour: 10,
minute: 10,
second: 55.0,
offset: None,
},
});
for mut s in [
"2022-10-10t10:10:55",
"2022-10-10 10:10:55",
"2022-10-10 t 10:10:55",
"2022-10-10 10:10:55",
"2022-10-10 (A comment!) t 10:10:55",
"2022-10-10 (A comment!) 10:10:55",
] {
let old_s = s.to_owned();
assert_eq!(parse(&mut s).ok(), reference, "Failed string: {old_s}")
}
}
}
+583
View File
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use winnow::{combinator::preceded, ModalResult, Parser};
use super::primitive::{float, s};
/// Parse a timestamp in the form of `@1234567890`.
pub fn parse(input: &mut &str) -> ModalResult<f64> {
s(preceded("@", float)).parse_next(input)
}
#[cfg(test)]
mod tests {
use super::parse;
fn float_eq(a: f64, b: f64) -> bool {
(a - b).abs() < f64::EPSILON
}
#[test]
fn float() {
let mut input = "@1234567890";
assert!(float_eq(parse(&mut input).unwrap(), 1234567890.0));
let mut input = "@1234567890.12345";
assert!(float_eq(parse(&mut input).unwrap(), 1234567890.12345));
let mut input = "@1234567890,12345";
assert!(float_eq(parse(&mut input).unwrap(), 1234567890.12345));
let mut input = "@-1234567890.12345";
assert_eq!(parse(&mut input).unwrap(), -1234567890.12345);
}
}
+501
View File
File diff suppressed because it is too large Load Diff
+47
View File
@@ -0,0 +1,47 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use winnow::{
ascii::alpha1,
combinator::{alt, opt},
ModalResult, Parser,
};
use super::primitive::{dec_uint, s};
pub(super) fn ordinal(input: &mut &str) -> ModalResult<i32> {
alt((text_ordinal, number_ordinal)).parse_next(input)
}
fn number_ordinal(input: &mut &str) -> ModalResult<i32> {
let sign = opt(alt(('+'.value(1), '-'.value(-1)))).map(|s| s.unwrap_or(1));
(s(sign), s(dec_uint))
.verify_map(|(s, u): (i32, u32)| {
let i: i32 = u.try_into().ok()?;
Some(s * i)
})
.parse_next(input)
}
fn text_ordinal(input: &mut &str) -> ModalResult<i32> {
s(alpha1)
.verify_map(|s: &str| {
Some(match s {
"last" => -1,
"this" => 0,
"next" | "first" => 1,
"third" => 3,
"fourth" => 4,
"fifth" => 5,
"sixth" => 6,
"seventh" => 7,
"eight" => 8,
"ninth" => 9,
"tenth" => 10,
"eleventh" => 11,
"twelfth" => 12,
_ => return None,
})
})
.parse_next(input)
}
+140
View File
@@ -0,0 +1,140 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Primitive combinators.
use winnow::{
ascii::{digit1, multispace0},
combinator::{alt, delimited, not, opt, peek, preceded, repeat, separated},
error::{ContextError, ParserError, StrContext, StrContextValue},
stream::AsChar,
token::{none_of, one_of, take_while},
Parser,
};
/// Allow spaces and comments before a parser
///
/// Every token parser should be wrapped in this to allow spaces and comments.
/// It is only preceding, because that allows us to check mandatory whitespace
/// after running the parser.
pub(super) fn s<'a, O, E>(p: impl Parser<&'a str, O, E>) -> impl Parser<&'a str, O, E>
where
E: ParserError<&'a str>,
{
preceded(space, p)
}
/// Parse the space in-between tokens
///
/// You probably want to use the [`s`] combinator instead.
pub(super) fn space<'a, E>(input: &mut &'a str) -> winnow::Result<(), E>
where
E: ParserError<&'a str>,
{
separated(0.., multispace0, alt((comment, ignored_hyphen_or_plus))).parse_next(input)
}
/// A hyphen or plus is ignored when it is not followed by a digit
///
/// This includes being followed by a comment! Compare these inputs:
/// ```txt
/// - 12 weeks
/// - (comment) 12 weeks
/// ```
/// The last comment should be ignored.
///
/// The plus is undocumented, but it seems to be ignored.
fn ignored_hyphen_or_plus<'a, E>(input: &mut &'a str) -> winnow::Result<(), E>
where
E: ParserError<&'a str>,
{
(
alt(('-', '+')),
multispace0,
peek(not(take_while(1, AsChar::is_dec_digit))),
)
.void()
.parse_next(input)
}
/// Parse a comment
///
/// A comment is given between parentheses, which must be balanced. Any other
/// tokens can be within the comment.
fn comment<'a, E>(input: &mut &'a str) -> winnow::Result<(), E>
where
E: ParserError<&'a str>,
{
delimited(
'(',
repeat(0.., alt((none_of(['(', ')']).void(), comment))),
')',
)
.parse_next(input)
}
/// Parse a signed decimal integer.
///
/// Rationale for not using `winnow::ascii::dec_int`: When upgrading winnow from
/// 0.5 to 0.7, we discovered that `winnow::ascii::dec_int` now accepts only the
/// following two forms:
///
/// - 0
/// - [+-]?[1-9][0-9]*
///
/// Inputs like [+-]?0[0-9]* (e.g., `+012`) are therefore rejected. We provide a
/// custom implementation to support such zero-prefixed integers.
#[allow(unused)]
pub(super) fn dec_int<'a, E>(input: &mut &'a str) -> winnow::Result<i32, E>
where
E: ParserError<&'a str>,
{
(opt(one_of(['+', '-'])), digit1)
.void()
.take()
.verify_map(|s: &str| s.parse().ok())
.parse_next(input)
}
/// Parse an unsigned decimal integer.
///
/// See the rationale for `dec_int` for why we don't use
/// `winnow::ascii::dec_uint`.
pub(super) fn dec_uint<'a, E>(input: &mut &'a str) -> winnow::Result<u32, E>
where
E: ParserError<&'a str>,
{
digit1
.void()
.take()
.verify_map(|s: &str| s.parse().ok())
.parse_next(input)
}
/// Parse a float number.
///
/// Rationale for not using `winnow::ascii::float`: the `float` parser provided
/// by winnow accepts E-notation numbers (e.g., `1.23e4`), whereas GNU date
/// rejects such numbers. To remain compatible with GNU date, we provide a
/// custom implementation that only accepts inputs like [+-]?[0-9]+(\.[0-9]+)?.
pub(super) fn float<'a, E>(input: &mut &'a str) -> winnow::Result<f64, E>
where
E: ParserError<&'a str>,
{
(
opt(one_of(['+', '-'])),
digit1,
opt(preceded(one_of(['.', ',']), digit1)),
)
.void()
.take()
.verify_map(|s: &str| s.replace(",", ".").parse().ok())
.parse_next(input)
}
/// Create a context error with a reason.
pub(super) fn ctx_err(reason: &'static str) -> ContextError {
let mut err = ContextError::new();
err.push(StrContext::Expected(StrContextValue::Description(reason)));
err
}
+195
View File
@@ -0,0 +1,195 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Parse a relative datetime item
//!
//! The GNU docs state:
//!
//! > The unit of time displacement may be selected by the string year or
//! > month for moving by whole years or months. These are fuzzy units, as
//! > years and months are not all of equal duration. More precise units are
//! > fortnight which is worth 14 days, week worth 7 days, day worth 24
//! > hours, hour worth 60 minutes, minute or min worth 60 seconds, and
//! > second or sec worth one second. An s suffix on these units is
//! > accepted and ignored.
//! >
//! > The unit of time may be preceded by a multiplier, given as an optionally
//! > signed number. Unsigned numbers are taken as positively signed. No number
//! > at all implies 1 for a multiplier. Following a relative item by the
//! > string ago is equivalent to preceding the unit by a multiplier with
//! > value -1.
//! >
//! > The string tomorrow is worth one day in the future (equivalent to
//! > day), the string yesterday is worth one day in the past (equivalent
//! > to day ago).
//! >
//! > The strings now or today are relative items corresponding to
//! > zero-valued time displacement, these strings come from the fact a
//! > zero-valued time displacement represents the current time when not
//! > otherwise changed by previous items. They may be used to stress other
//! > items, like in 12:00 today. The string this also has the meaning of a
//! > zero-valued time displacement, but is preferred in date strings like
//! > this thursday.
use winnow::{
ascii::alpha1,
combinator::{alt, opt},
ModalResult, Parser,
};
use super::{
ordinal::ordinal,
primitive::{float, s},
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Relative {
Years(i32),
Months(i32),
Days(i32),
Hours(i32),
Minutes(i32),
// Seconds are special because they can be given as a float
Seconds(f64),
}
impl Relative {
// TODO: determine how to handle multiplication overflows,
// using saturating_mul for now.
fn mul(self, n: i32) -> Self {
match self {
Self::Years(x) => Self::Years(n.saturating_mul(x)),
Self::Months(x) => Self::Months(n.saturating_mul(x)),
Self::Days(x) => Self::Days(n.saturating_mul(x)),
Self::Hours(x) => Self::Hours(n.saturating_mul(x)),
Self::Minutes(x) => Self::Minutes(n.saturating_mul(x)),
Self::Seconds(x) => Self::Seconds(f64::from(n) * x),
}
}
}
pub fn parse(input: &mut &str) -> ModalResult<Relative> {
alt((
s("tomorrow").value(Relative::Days(1)),
s("yesterday").value(Relative::Days(-1)),
// For "today" and "now", the unit is arbitrary
s("today").value(Relative::Days(0)),
s("now").value(Relative::Days(0)),
seconds,
other,
))
.parse_next(input)
}
fn seconds(input: &mut &str) -> ModalResult<Relative> {
(
opt(alt((s(float), ordinal.map(|x| x as f64)))),
s(alpha1).verify(|s: &str| matches!(s, "seconds" | "second" | "sec" | "secs")),
ago,
)
.map(|(n, _, ago)| Relative::Seconds(n.unwrap_or(1.0) * if ago { -1.0 } else { 1.0 }))
.parse_next(input)
}
fn other(input: &mut &str) -> ModalResult<Relative> {
(opt(ordinal), integer_unit, ago)
.map(|(n, unit, ago)| unit.mul(n.unwrap_or(1) * if ago { -1 } else { 1 }))
.parse_next(input)
}
fn ago(input: &mut &str) -> ModalResult<bool> {
opt(s("ago")).map(|o| o.is_some()).parse_next(input)
}
fn integer_unit(input: &mut &str) -> ModalResult<Relative> {
s(alpha1)
.verify_map(|s: &str| {
Some(match s.strip_suffix('s').unwrap_or(s) {
"year" => Relative::Years(1),
"month" => Relative::Months(1),
"fortnight" => Relative::Days(14),
"week" => Relative::Days(7),
"day" => Relative::Days(1),
"hour" => Relative::Hours(1),
"minute" | "min" => Relative::Minutes(1),
_ => return None,
})
})
.parse_next(input)
}
#[cfg(test)]
mod tests {
use super::{parse, Relative};
#[test]
fn all() {
for (s, rel) in [
// Seconds
("second", Relative::Seconds(1.0)),
("sec", Relative::Seconds(1.0)),
("seconds", Relative::Seconds(1.0)),
("secs", Relative::Seconds(1.0)),
("second ago", Relative::Seconds(-1.0)),
("3 seconds", Relative::Seconds(3.0)),
("3.5 seconds", Relative::Seconds(3.5)),
// ("+3.5 seconds", Relative::Seconds(3.5)),
("3.5 seconds ago", Relative::Seconds(-3.5)),
("-3.5 seconds ago", Relative::Seconds(3.5)),
// Minutes
("minute", Relative::Minutes(1)),
("minutes", Relative::Minutes(1)),
("min", Relative::Minutes(1)),
("mins", Relative::Minutes(1)),
("10 minutes", Relative::Minutes(10)),
("-10 minutes", Relative::Minutes(-10)),
("10 minutes ago", Relative::Minutes(-10)),
("-10 minutes ago", Relative::Minutes(10)),
// Hours
("hour", Relative::Hours(1)),
("hours", Relative::Hours(1)),
("10 hours", Relative::Hours(10)),
("+10 hours", Relative::Hours(10)),
("-10 hours", Relative::Hours(-10)),
("10 hours ago", Relative::Hours(-10)),
("-10 hours ago", Relative::Hours(10)),
// Days
("day", Relative::Days(1)),
("days", Relative::Days(1)),
("10 days", Relative::Days(10)),
("+10 days", Relative::Days(10)),
("-10 days", Relative::Days(-10)),
("10 days ago", Relative::Days(-10)),
("-10 days ago", Relative::Days(10)),
// Multiple days
("fortnight", Relative::Days(14)),
("fortnights", Relative::Days(14)),
("2 fortnights ago", Relative::Days(-28)),
("+2 fortnights ago", Relative::Days(-28)),
("week", Relative::Days(7)),
("weeks", Relative::Days(7)),
("2 weeks ago", Relative::Days(-14)),
// Other
("year", Relative::Years(1)),
("years", Relative::Years(1)),
("month", Relative::Months(1)),
("months", Relative::Months(1)),
// Special
("yesterday", Relative::Days(-1)),
("tomorrow", Relative::Days(1)),
("today", Relative::Days(0)),
("now", Relative::Days(0)),
// This something
("this day", Relative::Days(0)),
("this second", Relative::Seconds(0.0)),
("this year", Relative::Years(0)),
// Weird stuff
("next week ago", Relative::Days(-7)),
("last week ago", Relative::Days(7)),
("this week ago", Relative::Days(0)),
] {
let mut t = s;
assert_eq!(parse(&mut t).ok(), Some(rel), "Failed string: {s}")
}
}
}
+865
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More