See commit_processor.h for the contract. `now` is injected so the parser is deterministic and unit-testable.
| 100 | // See commit_processor.h for the contract. `now` is injected so the parser is |
| 101 | // deterministic and unit-testable. |
| 102 | time_t ParseRelativeTimespan(const std::string ×pan, time_t now) { |
| 103 | // Tokenize on whitespace, lower-casing as we go. |
| 104 | std::vector<std::string> tokens; |
| 105 | std::string current; |
| 106 | for (size_t i = 0; i < timespan.size(); ++i) { |
| 107 | const unsigned char c = static_cast<unsigned char>(timespan[i]); |
| 108 | if (isspace(c)) { |
| 109 | if (!current.empty()) { |
| 110 | tokens.push_back(current); |
| 111 | current.clear(); |
| 112 | } |
| 113 | } else { |
| 114 | current += static_cast<char>(tolower(c)); |
| 115 | } |
| 116 | } |
| 117 | if (!current.empty()) { |
| 118 | tokens.push_back(current); |
| 119 | } |
| 120 | |
| 121 | // Expect exactly "<number> <unit> ago". |
| 122 | if (tokens.size() != 3 || tokens[2] != "ago") { |
| 123 | return 0; |
| 124 | } |
| 125 | const std::string &number = tokens[0]; |
| 126 | if (number.empty()) { |
| 127 | return 0; |
| 128 | } |
| 129 | for (size_t i = 0; i < number.size(); ++i) { |
| 130 | if (!isdigit(static_cast<unsigned char>(number[i]))) { |
| 131 | return 0; |
| 132 | } |
| 133 | } |
| 134 | const int64_t count = String2Int64(number); |
| 135 | |
| 136 | // De-pluralize the unit. |
| 137 | std::string unit = tokens[1]; |
| 138 | if (!unit.empty() && unit[unit.size() - 1] == 's') { |
| 139 | unit.resize(unit.size() - 1); |
| 140 | } |
| 141 | |
| 142 | // Fixed-length units can be subtracted directly. |
| 143 | int64_t factor = 0; |
| 144 | if (unit == "sec" || unit == "second") { |
| 145 | factor = 1; |
| 146 | } else if (unit == "min" || unit == "minute") { |
| 147 | factor = 60; |
| 148 | } else if (unit == "hour") { |
| 149 | factor = 3600; |
| 150 | } else if (unit == "day") { |
| 151 | factor = 86400; |
| 152 | } else if (unit == "week") { |
| 153 | factor = 604800; |
| 154 | } |
| 155 | if (factor > 0) { |
| 156 | return now - static_cast<time_t>(count * factor); |
| 157 | } |
| 158 | |
| 159 | // Calendar units: let mktime() normalize the broken-down time. |
no test coverage detected