From 3382bf7a661ab7e48c6cf2fc838ba04789794bd5 Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Tue, 14 Jun 2022 10:19:36 -0300 Subject: [PATCH 1/2] Time.parse!: better error message when end of input is reached --- spec/std/time/format_spec.cr | 6 ++++++ src/time/format/parser.cr | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/spec/std/time/format_spec.cr b/spec/std/time/format_spec.cr index 3a95d50d0eea..08baa2e910fd 100644 --- a/spec/std/time/format_spec.cr +++ b/spec/std/time/format_spec.cr @@ -204,6 +204,12 @@ describe Time::Format do Time.parse!("2017-12-01 20:15:13 +01:00", "%F %T %:z").to_s("%F %T %:z").should eq "2017-12-01 20:15:13 +01:00" end + it "gives nice error message when end of input is reached (#12047)" do + expect_raises(Time::Format::Error, "Expected '-' but the end of the input was reached") do + Time.parse!("2021-01", "%F") + end + end + it "parses" do parse_time("2014", "%Y").year.should eq(2014) parse_time("19", "%C").year.should eq(1900) diff --git a/src/time/format/parser.cr b/src/time/format/parser.cr index e5587d55e753..3007b61feb3d 100644 --- a/src/time/format/parser.cr +++ b/src/time/format/parser.cr @@ -502,6 +502,14 @@ struct Time::Format end def char(char, *alternatives) + unless @reader.has_next? + if alternatives.empty? + raise "Expected #{char.inspect} but the end of the input was reached" + else + raise "Expected one of #{({char} + alternatives).join(", ", &.inspect)} but reached the input end" + end + end + unless char?(char, *alternatives) raise "Unexpected char: #{current_char.inspect}" end From beaec549aadef58d04896bfc1474aa99a140cd21 Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Tue, 14 Jun 2022 17:01:05 -0300 Subject: [PATCH 2/2] Update src/time/format/parser.cr MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Johannes Müller --- src/time/format/parser.cr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/time/format/parser.cr b/src/time/format/parser.cr index 3007b61feb3d..95bac1a5799d 100644 --- a/src/time/format/parser.cr +++ b/src/time/format/parser.cr @@ -506,7 +506,7 @@ struct Time::Format if alternatives.empty? raise "Expected #{char.inspect} but the end of the input was reached" else - raise "Expected one of #{({char} + alternatives).join(", ", &.inspect)} but reached the input end" + raise "Expected one of #{char.inspect}, #{alternatives.join(", ", &.inspect)} but reached the input end" end end