Throw in case date can't be parsed instead of returning -1 as date

This commit is contained in:
Geert Janssens 2017-01-14 15:56:34 +01:00 committed by Geert Janssens
parent bbac6aa1c5
commit b9e73d923e
2 changed files with 17 additions and 12 deletions

View File

@ -149,20 +149,21 @@ std::map<GncTransPropType, const char*> gnc_csv_col_type_strs = {
* 01/02/2003.
* @param date_str The string containing a date being parsed
* @param format An index specifying a format in date_format_user
* @return The parsed value of date_str on success or -1 on failure
* @exception std::invalid_argument if the string can't be parsed into a date.
* @return The parsed value of date_str on success, throws on failure
*/
time64 parse_date (const std::string &date_str, int format)
{
boost::regex r(date_regex[format]);
boost::smatch what;
if(!boost::regex_search(date_str, what, r))
return -1; // regex didn't find a match
throw std::invalid_argument ("String doesn't appear to be formatted as a date."); // regex didn't find a match
// Attention: different behavior from 2.6.x series !
// If date format without year was selected, the match
// should NOT have found a year.
if ((format >= 3) && (what.length("YEAR") != 0))
return -1;
throw std::invalid_argument ("String appears to contain a year while the selected format forbids this.");
auto day = std::stoi (what.str("DAY"));
auto month = std::stoi (what.str("MONTH"));
@ -351,15 +352,17 @@ int GncTxImport::parse (bool guessColTypes, GError** error)
*/
static time64* convert_date_col_str (const std::string &str, int date_format)
{
auto parsed_date = parse_date (str.c_str(), date_format);
if (parsed_date == -1)
return nullptr;
else
try
{
auto parsed_date = parse_date (str.c_str(), date_format);
auto mydate = new time64;
*mydate = parsed_date;
return mydate;
}
catch (std::invalid_argument)
{
return nullptr;
}
}

View File

@ -69,7 +69,7 @@ time64 parse_date (const char* date_str, int format)// C: 14 in 7 SCM: 9 in 2 Lo
*/
TEST(GncTxImportTest, parse_date)
{
time64 rawtime = gnc_time (NULL);
time64 rawtime = gnc_time (nullptr);
struct tm *tm = gnc_gmtime (&rawtime);
int curr_year = tm->tm_year;
@ -177,17 +177,19 @@ TEST(GncTxImportTest, parse_date)
gboolean success = TRUE;
int got_year = 0, got_month = 0, got_day = 0;
rawtime = parse_date (std::string(test_dates[i].date_str), test_dates[i].date_fmt);
if (rawtime == -1)
got_year = got_month = got_day = -1;
else
try
{
rawtime = parse_date (std::string(test_dates[i].date_str), test_dates[i].date_fmt);
tm = gnc_gmtime (&rawtime);
got_year = tm->tm_year;
got_month = tm->tm_mon;
got_day = tm->tm_mday;
gnc_tm_free(tm);
}
catch (std::invalid_argument)
{
got_year = got_month = got_day = -1;
}
if ((got_year != test_dates[i].exp_year) ||
(got_month != test_dates[i].exp_month) ||