notes.c: append separator instead of insert by pos
[alt-git.git] / date.c
blob7c8650f79967a32d16f4e2a133b43ef0358eacb0
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 */
7 #include "cache.h"
8 #include "date.h"
9 #include "gettext.h"
12 * This is like mktime, but without normalization of tm_wday and tm_yday.
14 time_t tm_to_time_t(const struct tm *tm)
16 static const int mdays[] = {
17 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
19 int year = tm->tm_year - 70;
20 int month = tm->tm_mon;
21 int day = tm->tm_mday;
23 if (year < 0 || year > 129) /* algo only works for 1970-2099 */
24 return -1;
25 if (month < 0 || month > 11) /* array bounds */
26 return -1;
27 if (month < 2 || (year + 2) % 4)
28 day--;
29 if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
30 return -1;
31 return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
32 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
35 static const char *month_names[] = {
36 "January", "February", "March", "April", "May", "June",
37 "July", "August", "September", "October", "November", "December"
40 static const char *weekday_names[] = {
41 "Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays"
44 static time_t gm_time_t(timestamp_t time, int tz)
46 int minutes;
48 minutes = tz < 0 ? -tz : tz;
49 minutes = (minutes / 100)*60 + (minutes % 100);
50 minutes = tz < 0 ? -minutes : minutes;
52 if (minutes > 0) {
53 if (unsigned_add_overflows(time, minutes * 60))
54 die("Timestamp+tz too large: %"PRItime" +%04d",
55 time, tz);
56 } else if (time < -minutes * 60)
57 die("Timestamp before Unix epoch: %"PRItime" %04d", time, tz);
58 time += minutes * 60;
59 if (date_overflows(time))
60 die("Timestamp too large for this system: %"PRItime, time);
61 return (time_t)time;
65 * The "tz" thing is passed in as this strange "decimal parse of tz"
66 * thing, which means that tz -0100 is passed in as the integer -100,
67 * even though it means "sixty minutes off"
69 static struct tm *time_to_tm(timestamp_t time, int tz, struct tm *tm)
71 time_t t = gm_time_t(time, tz);
72 return gmtime_r(&t, tm);
75 static struct tm *time_to_tm_local(timestamp_t time, struct tm *tm)
77 time_t t = time;
78 return localtime_r(&t, tm);
82 * Fill in the localtime 'struct tm' for the supplied time,
83 * and return the local tz.
85 static int local_time_tzoffset(time_t t, struct tm *tm)
87 time_t t_local;
88 int offset, eastwest;
90 localtime_r(&t, tm);
91 t_local = tm_to_time_t(tm);
92 if (t_local == -1)
93 return 0; /* error; just use +0000 */
94 if (t_local < t) {
95 eastwest = -1;
96 offset = t - t_local;
97 } else {
98 eastwest = 1;
99 offset = t_local - t;
101 offset /= 60; /* in minutes */
102 offset = (offset % 60) + ((offset / 60) * 100);
103 return offset * eastwest;
107 * What value of "tz" was in effect back then at "time" in the
108 * local timezone?
110 static int local_tzoffset(timestamp_t time)
112 struct tm tm;
114 if (date_overflows(time))
115 die("Timestamp too large for this system: %"PRItime, time);
117 return local_time_tzoffset((time_t)time, &tm);
120 static void get_time(struct timeval *now)
122 const char *x;
124 x = getenv("GIT_TEST_DATE_NOW");
125 if (x) {
126 now->tv_sec = atoi(x);
127 now->tv_usec = 0;
129 else
130 gettimeofday(now, NULL);
133 void show_date_relative(timestamp_t time, struct strbuf *timebuf)
135 struct timeval now;
136 timestamp_t diff;
138 get_time(&now);
139 if (now.tv_sec < time) {
140 strbuf_addstr(timebuf, _("in the future"));
141 return;
143 diff = now.tv_sec - time;
144 if (diff < 90) {
145 strbuf_addf(timebuf,
146 Q_("%"PRItime" second ago", "%"PRItime" seconds ago", diff), diff);
147 return;
149 /* Turn it into minutes */
150 diff = (diff + 30) / 60;
151 if (diff < 90) {
152 strbuf_addf(timebuf,
153 Q_("%"PRItime" minute ago", "%"PRItime" minutes ago", diff), diff);
154 return;
156 /* Turn it into hours */
157 diff = (diff + 30) / 60;
158 if (diff < 36) {
159 strbuf_addf(timebuf,
160 Q_("%"PRItime" hour ago", "%"PRItime" hours ago", diff), diff);
161 return;
163 /* We deal with number of days from here on */
164 diff = (diff + 12) / 24;
165 if (diff < 14) {
166 strbuf_addf(timebuf,
167 Q_("%"PRItime" day ago", "%"PRItime" days ago", diff), diff);
168 return;
170 /* Say weeks for the past 10 weeks or so */
171 if (diff < 70) {
172 strbuf_addf(timebuf,
173 Q_("%"PRItime" week ago", "%"PRItime" weeks ago", (diff + 3) / 7),
174 (diff + 3) / 7);
175 return;
177 /* Say months for the past 12 months or so */
178 if (diff < 365) {
179 strbuf_addf(timebuf,
180 Q_("%"PRItime" month ago", "%"PRItime" months ago", (diff + 15) / 30),
181 (diff + 15) / 30);
182 return;
184 /* Give years and months for 5 years or so */
185 if (diff < 1825) {
186 timestamp_t totalmonths = (diff * 12 * 2 + 365) / (365 * 2);
187 timestamp_t years = totalmonths / 12;
188 timestamp_t months = totalmonths % 12;
189 if (months) {
190 struct strbuf sb = STRBUF_INIT;
191 strbuf_addf(&sb, Q_("%"PRItime" year", "%"PRItime" years", years), years);
192 strbuf_addf(timebuf,
193 /* TRANSLATORS: "%s" is "<n> years" */
194 Q_("%s, %"PRItime" month ago", "%s, %"PRItime" months ago", months),
195 sb.buf, months);
196 strbuf_release(&sb);
197 } else
198 strbuf_addf(timebuf,
199 Q_("%"PRItime" year ago", "%"PRItime" years ago", years), years);
200 return;
202 /* Otherwise, just years. Centuries is probably overkill. */
203 strbuf_addf(timebuf,
204 Q_("%"PRItime" year ago", "%"PRItime" years ago", (diff + 183) / 365),
205 (diff + 183) / 365);
208 struct date_mode *date_mode_from_type(enum date_mode_type type)
210 static struct date_mode mode = DATE_MODE_INIT;
211 if (type == DATE_STRFTIME)
212 BUG("cannot create anonymous strftime date_mode struct");
213 mode.type = type;
214 return &mode;
217 static void show_date_normal(struct strbuf *buf, timestamp_t time, struct tm *tm, int tz, struct tm *human_tm, int human_tz, int local)
219 struct {
220 unsigned int year:1,
221 date:1,
222 wday:1,
223 time:1,
224 seconds:1,
225 tz:1;
226 } hide = { 0 };
228 hide.tz = local || tz == human_tz;
229 hide.year = tm->tm_year == human_tm->tm_year;
230 if (hide.year) {
231 if (tm->tm_mon == human_tm->tm_mon) {
232 if (tm->tm_mday > human_tm->tm_mday) {
233 /* Future date: think timezones */
234 } else if (tm->tm_mday == human_tm->tm_mday) {
235 hide.date = hide.wday = 1;
236 } else if (tm->tm_mday + 5 > human_tm->tm_mday) {
237 /* Leave just weekday if it was a few days ago */
238 hide.date = 1;
243 /* Show "today" times as just relative times */
244 if (hide.wday) {
245 show_date_relative(time, buf);
246 return;
250 * Always hide seconds for human-readable.
251 * Hide timezone if showing date.
252 * Hide weekday and time if showing year.
254 * The logic here is two-fold:
255 * (a) only show details when recent enough to matter
256 * (b) keep the maximum length "similar", and in check
258 if (human_tm->tm_year) {
259 hide.seconds = 1;
260 hide.tz |= !hide.date;
261 hide.wday = hide.time = !hide.year;
264 if (!hide.wday)
265 strbuf_addf(buf, "%.3s ", weekday_names[tm->tm_wday]);
266 if (!hide.date)
267 strbuf_addf(buf, "%.3s %d ", month_names[tm->tm_mon], tm->tm_mday);
269 /* Do we want AM/PM depending on locale? */
270 if (!hide.time) {
271 strbuf_addf(buf, "%02d:%02d", tm->tm_hour, tm->tm_min);
272 if (!hide.seconds)
273 strbuf_addf(buf, ":%02d", tm->tm_sec);
274 } else
275 strbuf_rtrim(buf);
277 if (!hide.year)
278 strbuf_addf(buf, " %d", tm->tm_year + 1900);
280 if (!hide.tz)
281 strbuf_addf(buf, " %+05d", tz);
284 const char *show_date(timestamp_t time, int tz, const struct date_mode *mode)
286 struct tm *tm;
287 struct tm tmbuf = { 0 };
288 struct tm human_tm = { 0 };
289 int human_tz = -1;
290 static struct strbuf timebuf = STRBUF_INIT;
292 if (mode->type == DATE_UNIX) {
293 strbuf_reset(&timebuf);
294 strbuf_addf(&timebuf, "%"PRItime, time);
295 return timebuf.buf;
298 if (mode->type == DATE_HUMAN) {
299 struct timeval now;
301 get_time(&now);
303 /* Fill in the data for "current time" in human_tz and human_tm */
304 human_tz = local_time_tzoffset(now.tv_sec, &human_tm);
307 if (mode->local)
308 tz = local_tzoffset(time);
310 if (mode->type == DATE_RAW) {
311 strbuf_reset(&timebuf);
312 strbuf_addf(&timebuf, "%"PRItime" %+05d", time, tz);
313 return timebuf.buf;
316 if (mode->type == DATE_RELATIVE) {
317 strbuf_reset(&timebuf);
318 show_date_relative(time, &timebuf);
319 return timebuf.buf;
322 if (mode->local)
323 tm = time_to_tm_local(time, &tmbuf);
324 else
325 tm = time_to_tm(time, tz, &tmbuf);
326 if (!tm) {
327 tm = time_to_tm(0, 0, &tmbuf);
328 tz = 0;
331 strbuf_reset(&timebuf);
332 if (mode->type == DATE_SHORT)
333 strbuf_addf(&timebuf, "%04d-%02d-%02d", tm->tm_year + 1900,
334 tm->tm_mon + 1, tm->tm_mday);
335 else if (mode->type == DATE_ISO8601)
336 strbuf_addf(&timebuf, "%04d-%02d-%02d %02d:%02d:%02d %+05d",
337 tm->tm_year + 1900,
338 tm->tm_mon + 1,
339 tm->tm_mday,
340 tm->tm_hour, tm->tm_min, tm->tm_sec,
341 tz);
342 else if (mode->type == DATE_ISO8601_STRICT) {
343 char sign = (tz >= 0) ? '+' : '-';
344 tz = abs(tz);
345 strbuf_addf(&timebuf, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
346 tm->tm_year + 1900,
347 tm->tm_mon + 1,
348 tm->tm_mday,
349 tm->tm_hour, tm->tm_min, tm->tm_sec,
350 sign, tz / 100, tz % 100);
351 } else if (mode->type == DATE_RFC2822)
352 strbuf_addf(&timebuf, "%.3s, %d %.3s %d %02d:%02d:%02d %+05d",
353 weekday_names[tm->tm_wday], tm->tm_mday,
354 month_names[tm->tm_mon], tm->tm_year + 1900,
355 tm->tm_hour, tm->tm_min, tm->tm_sec, tz);
356 else if (mode->type == DATE_STRFTIME)
357 strbuf_addftime(&timebuf, mode->strftime_fmt, tm, tz,
358 !mode->local);
359 else
360 show_date_normal(&timebuf, time, tm, tz, &human_tm, human_tz, mode->local);
361 return timebuf.buf;
365 * Check these. And note how it doesn't do the summer-time conversion.
367 * In my world, it's always summer, and things are probably a bit off
368 * in other ways too.
370 static const struct {
371 const char *name;
372 int offset;
373 int dst;
374 } timezone_names[] = {
375 { "IDLW", -12, 0, }, /* International Date Line West */
376 { "NT", -11, 0, }, /* Nome */
377 { "CAT", -10, 0, }, /* Central Alaska */
378 { "HST", -10, 0, }, /* Hawaii Standard */
379 { "HDT", -10, 1, }, /* Hawaii Daylight */
380 { "YST", -9, 0, }, /* Yukon Standard */
381 { "YDT", -9, 1, }, /* Yukon Daylight */
382 { "PST", -8, 0, }, /* Pacific Standard */
383 { "PDT", -8, 1, }, /* Pacific Daylight */
384 { "MST", -7, 0, }, /* Mountain Standard */
385 { "MDT", -7, 1, }, /* Mountain Daylight */
386 { "CST", -6, 0, }, /* Central Standard */
387 { "CDT", -6, 1, }, /* Central Daylight */
388 { "EST", -5, 0, }, /* Eastern Standard */
389 { "EDT", -5, 1, }, /* Eastern Daylight */
390 { "AST", -3, 0, }, /* Atlantic Standard */
391 { "ADT", -3, 1, }, /* Atlantic Daylight */
392 { "WAT", -1, 0, }, /* West Africa */
394 { "GMT", 0, 0, }, /* Greenwich Mean */
395 { "UTC", 0, 0, }, /* Universal (Coordinated) */
396 { "Z", 0, 0, }, /* Zulu, alias for UTC */
398 { "WET", 0, 0, }, /* Western European */
399 { "BST", 0, 1, }, /* British Summer */
400 { "CET", +1, 0, }, /* Central European */
401 { "MET", +1, 0, }, /* Middle European */
402 { "MEWT", +1, 0, }, /* Middle European Winter */
403 { "MEST", +1, 1, }, /* Middle European Summer */
404 { "CEST", +1, 1, }, /* Central European Summer */
405 { "MESZ", +1, 1, }, /* Middle European Summer */
406 { "FWT", +1, 0, }, /* French Winter */
407 { "FST", +1, 1, }, /* French Summer */
408 { "EET", +2, 0, }, /* Eastern Europe, USSR Zone 1 */
409 { "EEST", +2, 1, }, /* Eastern European Daylight */
410 { "WAST", +7, 0, }, /* West Australian Standard */
411 { "WADT", +7, 1, }, /* West Australian Daylight */
412 { "CCT", +8, 0, }, /* China Coast, USSR Zone 7 */
413 { "JST", +9, 0, }, /* Japan Standard, USSR Zone 8 */
414 { "EAST", +10, 0, }, /* Eastern Australian Standard */
415 { "EADT", +10, 1, }, /* Eastern Australian Daylight */
416 { "GST", +10, 0, }, /* Guam Standard, USSR Zone 9 */
417 { "NZT", +12, 0, }, /* New Zealand */
418 { "NZST", +12, 0, }, /* New Zealand Standard */
419 { "NZDT", +12, 1, }, /* New Zealand Daylight */
420 { "IDLE", +12, 0, }, /* International Date Line East */
423 static int match_string(const char *date, const char *str)
425 int i = 0;
427 for (i = 0; *date; date++, str++, i++) {
428 if (*date == *str)
429 continue;
430 if (toupper(*date) == toupper(*str))
431 continue;
432 if (!isalnum(*date))
433 break;
434 return 0;
436 return i;
439 static int skip_alpha(const char *date)
441 int i = 0;
442 do {
443 i++;
444 } while (isalpha(date[i]));
445 return i;
449 * Parse month, weekday, or timezone name
451 static int match_alpha(const char *date, struct tm *tm, int *offset)
453 int i;
455 for (i = 0; i < 12; i++) {
456 int match = match_string(date, month_names[i]);
457 if (match >= 3) {
458 tm->tm_mon = i;
459 return match;
463 for (i = 0; i < 7; i++) {
464 int match = match_string(date, weekday_names[i]);
465 if (match >= 3) {
466 tm->tm_wday = i;
467 return match;
471 for (i = 0; i < ARRAY_SIZE(timezone_names); i++) {
472 int match = match_string(date, timezone_names[i].name);
473 if (match >= 3 || match == strlen(timezone_names[i].name)) {
474 int off = timezone_names[i].offset;
476 /* This is bogus, but we like summer */
477 off += timezone_names[i].dst;
479 /* Only use the tz name offset if we don't have anything better */
480 if (*offset == -1)
481 *offset = 60*off;
483 return match;
487 if (match_string(date, "PM") == 2) {
488 tm->tm_hour = (tm->tm_hour % 12) + 12;
489 return 2;
492 if (match_string(date, "AM") == 2) {
493 tm->tm_hour = (tm->tm_hour % 12) + 0;
494 return 2;
497 /* ISO-8601 allows yyyymmDD'T'HHMMSS, with less precision */
498 if (*date == 'T' && isdigit(date[1]) && tm->tm_hour == -1) {
499 tm->tm_min = tm->tm_sec = 0;
500 return 1;
503 /* BAD CRAP */
504 return skip_alpha(date);
507 static int set_date(int year, int month, int day, struct tm *now_tm, time_t now, struct tm *tm)
509 if (month > 0 && month < 13 && day > 0 && day < 32) {
510 struct tm check = *tm;
511 struct tm *r = (now_tm ? &check : tm);
512 time_t specified;
514 r->tm_mon = month - 1;
515 r->tm_mday = day;
516 if (year == -1) {
517 if (!now_tm)
518 return 1;
519 r->tm_year = now_tm->tm_year;
521 else if (year >= 1970 && year < 2100)
522 r->tm_year = year - 1900;
523 else if (year > 70 && year < 100)
524 r->tm_year = year;
525 else if (year < 38)
526 r->tm_year = year + 100;
527 else
528 return -1;
529 if (!now_tm)
530 return 0;
532 specified = tm_to_time_t(r);
534 /* Be it commit time or author time, it does not make
535 * sense to specify timestamp way into the future. Make
536 * sure it is not later than ten days from now...
538 if ((specified != -1) && (now + 10*24*3600 < specified))
539 return -1;
540 tm->tm_mon = r->tm_mon;
541 tm->tm_mday = r->tm_mday;
542 if (year != -1)
543 tm->tm_year = r->tm_year;
544 return 0;
546 return -1;
549 static int set_time(long hour, long minute, long second, struct tm *tm)
551 /* We accept 61st second because of leap second */
552 if (0 <= hour && hour <= 24 &&
553 0 <= minute && minute < 60 &&
554 0 <= second && second <= 60) {
555 tm->tm_hour = hour;
556 tm->tm_min = minute;
557 tm->tm_sec = second;
558 return 0;
560 return -1;
563 static int is_date_known(struct tm *tm)
565 return tm->tm_year != -1 && tm->tm_mon != -1 && tm->tm_mday != -1;
568 static int match_multi_number(timestamp_t num, char c, const char *date,
569 char *end, struct tm *tm, time_t now)
571 struct tm now_tm;
572 struct tm *refuse_future;
573 long num2, num3;
575 num2 = strtol(end+1, &end, 10);
576 num3 = -1;
577 if (*end == c && isdigit(end[1]))
578 num3 = strtol(end+1, &end, 10);
580 /* Time? Date? */
581 switch (c) {
582 case ':':
583 if (num3 < 0)
584 num3 = 0;
585 if (set_time(num, num2, num3, tm) == 0) {
587 * If %H:%M:%S was just parsed followed by: .<num4>
588 * Consider (& discard) it as fractional second
589 * if %Y%m%d is parsed before.
591 if (*end == '.' && isdigit(end[1]) && is_date_known(tm))
592 strtol(end + 1, &end, 10);
593 break;
595 return 0;
597 case '-':
598 case '/':
599 case '.':
600 if (!now)
601 now = time(NULL);
602 refuse_future = NULL;
603 if (gmtime_r(&now, &now_tm))
604 refuse_future = &now_tm;
606 if (num > 70) {
607 /* yyyy-mm-dd? */
608 if (set_date(num, num2, num3, NULL, now, tm) == 0)
609 break;
610 /* yyyy-dd-mm? */
611 if (set_date(num, num3, num2, NULL, now, tm) == 0)
612 break;
614 /* Our eastern European friends say dd.mm.yy[yy]
615 * is the norm there, so giving precedence to
616 * mm/dd/yy[yy] form only when separator is not '.'
618 if (c != '.' &&
619 set_date(num3, num, num2, refuse_future, now, tm) == 0)
620 break;
621 /* European dd.mm.yy[yy] or funny US dd/mm/yy[yy] */
622 if (set_date(num3, num2, num, refuse_future, now, tm) == 0)
623 break;
624 /* Funny European mm.dd.yy */
625 if (c == '.' &&
626 set_date(num3, num, num2, refuse_future, now, tm) == 0)
627 break;
628 return 0;
630 return end - date;
634 * Have we filled in any part of the time/date yet?
635 * We just do a binary 'and' to see if the sign bit
636 * is set in all the values.
638 static inline int nodate(struct tm *tm)
640 return (tm->tm_year &
641 tm->tm_mon &
642 tm->tm_mday &
643 tm->tm_hour &
644 tm->tm_min &
645 tm->tm_sec) < 0;
649 * Have we seen an ISO-8601-alike date, i.e. 20220101T0,
650 * In which, hour is still unset,
651 * and minutes and second has been set to 0.
653 static inline int maybeiso8601(struct tm *tm)
655 return tm->tm_hour == -1 &&
656 tm->tm_min == 0 &&
657 tm->tm_sec == 0;
661 * We've seen a digit. Time? Year? Date?
663 static int match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt)
665 int n;
666 char *end;
667 timestamp_t num;
669 num = parse_timestamp(date, &end, 10);
672 * Seconds since 1970? We trigger on that for any numbers with
673 * more than 8 digits. This is because we don't want to rule out
674 * numbers like 20070606 as a YYYYMMDD date.
676 if (num >= 100000000 && nodate(tm)) {
677 time_t time = num;
678 if (gmtime_r(&time, tm)) {
679 *tm_gmt = 1;
680 return end - date;
685 * Check for special formats: num[-.:/]num[same]num
687 switch (*end) {
688 case ':':
689 case '.':
690 case '/':
691 case '-':
692 if (isdigit(end[1])) {
693 int match = match_multi_number(num, *end, date, end, tm, 0);
694 if (match)
695 return match;
700 * None of the special formats? Try to guess what
701 * the number meant. We use the number of digits
702 * to make a more educated guess..
704 n = 0;
705 do {
706 n++;
707 } while (isdigit(date[n]));
709 /* 8 digits, compact style of ISO-8601's date: YYYYmmDD */
710 /* 6 digits, compact style of ISO-8601's time: HHMMSS */
711 if (n == 8 || n == 6) {
712 unsigned int num1 = num / 10000;
713 unsigned int num2 = (num % 10000) / 100;
714 unsigned int num3 = num % 100;
715 if (n == 8)
716 set_date(num1, num2, num3, NULL, time(NULL), tm);
717 else if (n == 6 && set_time(num1, num2, num3, tm) == 0 &&
718 *end == '.' && isdigit(end[1]))
719 strtoul(end + 1, &end, 10);
720 return end - date;
723 /* reduced precision of ISO-8601's time: HHMM or HH */
724 if (maybeiso8601(tm)) {
725 unsigned int num1 = num;
726 unsigned int num2 = 0;
727 if (n == 4) {
728 num1 = num / 100;
729 num2 = num % 100;
731 if ((n == 4 || n == 2) && !nodate(tm) &&
732 set_time(num1, num2, 0, tm) == 0)
733 return n;
735 * We thought this is an ISO-8601 time string,
736 * we set minutes and seconds to 0,
737 * turn out it isn't, rollback the change.
739 tm->tm_min = tm->tm_sec = -1;
742 /* Four-digit year or a timezone? */
743 if (n == 4) {
744 if (num <= 1400 && *offset == -1) {
745 unsigned int minutes = num % 100;
746 unsigned int hours = num / 100;
747 *offset = hours*60 + minutes;
748 } else if (num > 1900 && num < 2100)
749 tm->tm_year = num - 1900;
750 return n;
754 * Ignore lots of numerals. We took care of 4-digit years above.
755 * Days or months must be one or two digits.
757 if (n > 2)
758 return n;
761 * NOTE! We will give precedence to day-of-month over month or
762 * year numbers in the 1-12 range. So 05 is always "mday 5",
763 * unless we already have a mday..
765 * IOW, 01 Apr 05 parses as "April 1st, 2005".
767 if (num > 0 && num < 32 && tm->tm_mday < 0) {
768 tm->tm_mday = num;
769 return n;
772 /* Two-digit year? */
773 if (n == 2 && tm->tm_year < 0) {
774 if (num < 10 && tm->tm_mday >= 0) {
775 tm->tm_year = num + 100;
776 return n;
778 if (num >= 70) {
779 tm->tm_year = num;
780 return n;
784 if (num > 0 && num < 13 && tm->tm_mon < 0)
785 tm->tm_mon = num-1;
787 return n;
790 static int match_tz(const char *date, int *offp)
792 char *end;
793 int hour = strtoul(date + 1, &end, 10);
794 int n = end - (date + 1);
795 int min = 0;
797 if (n == 4) {
798 /* hhmm */
799 min = hour % 100;
800 hour = hour / 100;
801 } else if (n != 2) {
802 min = 99; /* random crap */
803 } else if (*end == ':') {
804 /* hh:mm? */
805 min = strtoul(end + 1, &end, 10);
806 if (end - (date + 1) != 5)
807 min = 99; /* random crap */
808 } /* otherwise we parsed "hh" */
811 * Don't accept any random crap. Even though some places have
812 * offset larger than 12 hours (e.g. Pacific/Kiritimati is at
813 * UTC+14), there is something wrong if hour part is much
814 * larger than that. We might also want to check that the
815 * minutes are divisible by 15 or something too. (Offset of
816 * Kathmandu, Nepal is UTC+5:45)
818 if (min < 60 && hour < 24) {
819 int offset = hour * 60 + min;
820 if (*date == '-')
821 offset = -offset;
822 *offp = offset;
824 return end - date;
827 static void date_string(timestamp_t date, int offset, struct strbuf *buf)
829 int sign = '+';
831 if (offset < 0) {
832 offset = -offset;
833 sign = '-';
835 strbuf_addf(buf, "%"PRItime" %c%02d%02d", date, sign, offset / 60, offset % 60);
839 * Parse a string like "0 +0000" as ancient timestamp near epoch, but
840 * only when it appears not as part of any other string.
842 static int match_object_header_date(const char *date, timestamp_t *timestamp, int *offset)
844 char *end;
845 timestamp_t stamp;
846 int ofs;
848 if (*date < '0' || '9' < *date)
849 return -1;
850 stamp = parse_timestamp(date, &end, 10);
851 if (*end != ' ' || stamp == TIME_MAX || (end[1] != '+' && end[1] != '-'))
852 return -1;
853 date = end + 2;
854 ofs = strtol(date, &end, 10);
855 if ((*end != '\0' && (*end != '\n')) || end != date + 4)
856 return -1;
857 ofs = (ofs / 100) * 60 + (ofs % 100);
858 if (date[-1] == '-')
859 ofs = -ofs;
860 *timestamp = stamp;
861 *offset = ofs;
862 return 0;
865 /* Gr. strptime is crap for this; it doesn't have a way to require RFC2822
866 (i.e. English) day/month names, and it doesn't work correctly with %z. */
867 int parse_date_basic(const char *date, timestamp_t *timestamp, int *offset)
869 struct tm tm;
870 int tm_gmt;
871 timestamp_t dummy_timestamp;
872 int dummy_offset;
874 if (!timestamp)
875 timestamp = &dummy_timestamp;
876 if (!offset)
877 offset = &dummy_offset;
879 memset(&tm, 0, sizeof(tm));
880 tm.tm_year = -1;
881 tm.tm_mon = -1;
882 tm.tm_mday = -1;
883 tm.tm_isdst = -1;
884 tm.tm_hour = -1;
885 tm.tm_min = -1;
886 tm.tm_sec = -1;
887 *offset = -1;
888 tm_gmt = 0;
890 if (*date == '@' &&
891 !match_object_header_date(date + 1, timestamp, offset))
892 return 0; /* success */
893 for (;;) {
894 int match = 0;
895 unsigned char c = *date;
897 /* Stop at end of string or newline */
898 if (!c || c == '\n')
899 break;
901 if (isalpha(c))
902 match = match_alpha(date, &tm, offset);
903 else if (isdigit(c))
904 match = match_digit(date, &tm, offset, &tm_gmt);
905 else if ((c == '-' || c == '+') && isdigit(date[1]))
906 match = match_tz(date, offset);
908 if (!match) {
909 /* BAD CRAP */
910 match = 1;
913 date += match;
916 /* do not use mktime(), which uses local timezone, here */
917 *timestamp = tm_to_time_t(&tm);
918 if (*timestamp == -1)
919 return -1;
921 if (*offset == -1) {
922 time_t temp_time;
924 /* gmtime_r() in match_digit() may have clobbered it */
925 tm.tm_isdst = -1;
926 temp_time = mktime(&tm);
927 if ((time_t)*timestamp > temp_time) {
928 *offset = ((time_t)*timestamp - temp_time) / 60;
929 } else {
930 *offset = -(int)((temp_time - (time_t)*timestamp) / 60);
934 if (!tm_gmt)
935 *timestamp -= *offset * 60;
936 return 0; /* success */
939 int parse_expiry_date(const char *date, timestamp_t *timestamp)
941 int errors = 0;
943 if (!strcmp(date, "never") || !strcmp(date, "false"))
944 *timestamp = 0;
945 else if (!strcmp(date, "all") || !strcmp(date, "now"))
947 * We take over "now" here, which usually translates
948 * to the current timestamp. This is because the user
949 * really means to expire everything that was done in
950 * the past, and by definition reflogs are the record
951 * of the past, and there is nothing from the future
952 * to be kept.
954 *timestamp = TIME_MAX;
955 else
956 *timestamp = approxidate_careful(date, &errors);
958 return errors;
961 int parse_date(const char *date, struct strbuf *result)
963 timestamp_t timestamp;
964 int offset;
965 if (parse_date_basic(date, &timestamp, &offset))
966 return -1;
967 date_string(timestamp, offset, result);
968 return 0;
971 static enum date_mode_type parse_date_type(const char *format, const char **end)
973 if (skip_prefix(format, "relative", end))
974 return DATE_RELATIVE;
975 if (skip_prefix(format, "iso8601-strict", end) ||
976 skip_prefix(format, "iso-strict", end))
977 return DATE_ISO8601_STRICT;
978 if (skip_prefix(format, "iso8601", end) ||
979 skip_prefix(format, "iso", end))
980 return DATE_ISO8601;
981 if (skip_prefix(format, "rfc2822", end) ||
982 skip_prefix(format, "rfc", end))
983 return DATE_RFC2822;
984 if (skip_prefix(format, "short", end))
985 return DATE_SHORT;
986 if (skip_prefix(format, "default", end))
987 return DATE_NORMAL;
988 if (skip_prefix(format, "human", end))
989 return DATE_HUMAN;
990 if (skip_prefix(format, "raw", end))
991 return DATE_RAW;
992 if (skip_prefix(format, "unix", end))
993 return DATE_UNIX;
994 if (skip_prefix(format, "format", end))
995 return DATE_STRFTIME;
997 * Please update $__git_log_date_formats in
998 * git-completion.bash when you add new formats.
1001 die("unknown date format %s", format);
1004 void parse_date_format(const char *format, struct date_mode *mode)
1006 const char *p;
1008 /* "auto:foo" is "if tty/pager, then foo, otherwise normal" */
1009 if (skip_prefix(format, "auto:", &p)) {
1010 if (isatty(1) || pager_in_use())
1011 format = p;
1012 else
1013 format = "default";
1016 /* historical alias */
1017 if (!strcmp(format, "local"))
1018 format = "default-local";
1020 mode->type = parse_date_type(format, &p);
1021 mode->local = 0;
1023 if (skip_prefix(p, "-local", &p))
1024 mode->local = 1;
1026 if (mode->type == DATE_STRFTIME) {
1027 if (!skip_prefix(p, ":", &p))
1028 die("date format missing colon separator: %s", format);
1029 mode->strftime_fmt = xstrdup(p);
1030 } else if (*p)
1031 die("unknown date format %s", format);
1034 void date_mode_release(struct date_mode *mode)
1036 free((char *)mode->strftime_fmt);
1039 void datestamp(struct strbuf *out)
1041 time_t now;
1042 int offset;
1043 struct tm tm = { 0 };
1045 time(&now);
1047 offset = tm_to_time_t(localtime_r(&now, &tm)) - now;
1048 offset /= 60;
1050 date_string(now, offset, out);
1054 * Relative time update (eg "2 days ago"). If we haven't set the time
1055 * yet, we need to set it from current time.
1057 static time_t update_tm(struct tm *tm, struct tm *now, time_t sec)
1059 time_t n;
1061 if (tm->tm_mday < 0)
1062 tm->tm_mday = now->tm_mday;
1063 if (tm->tm_mon < 0)
1064 tm->tm_mon = now->tm_mon;
1065 if (tm->tm_year < 0) {
1066 tm->tm_year = now->tm_year;
1067 if (tm->tm_mon > now->tm_mon)
1068 tm->tm_year--;
1071 n = mktime(tm) - sec;
1072 localtime_r(&n, tm);
1073 return n;
1077 * Do we have a pending number at the end, or when
1078 * we see a new one? Let's assume it's a month day,
1079 * as in "Dec 6, 1992"
1081 static void pending_number(struct tm *tm, int *num)
1083 int number = *num;
1085 if (number) {
1086 *num = 0;
1087 if (tm->tm_mday < 0 && number < 32)
1088 tm->tm_mday = number;
1089 else if (tm->tm_mon < 0 && number < 13)
1090 tm->tm_mon = number-1;
1091 else if (tm->tm_year < 0) {
1092 if (number > 1969 && number < 2100)
1093 tm->tm_year = number - 1900;
1094 else if (number > 69 && number < 100)
1095 tm->tm_year = number;
1096 else if (number < 38)
1097 tm->tm_year = 100 + number;
1098 /* We screw up for number = 00 ? */
1103 static void date_now(struct tm *tm, struct tm *now, int *num)
1105 *num = 0;
1106 update_tm(tm, now, 0);
1109 static void date_yesterday(struct tm *tm, struct tm *now, int *num)
1111 *num = 0;
1112 update_tm(tm, now, 24*60*60);
1115 static void date_time(struct tm *tm, struct tm *now, int hour)
1117 if (tm->tm_hour < hour)
1118 update_tm(tm, now, 24*60*60);
1119 tm->tm_hour = hour;
1120 tm->tm_min = 0;
1121 tm->tm_sec = 0;
1124 static void date_midnight(struct tm *tm, struct tm *now, int *num)
1126 pending_number(tm, num);
1127 date_time(tm, now, 0);
1130 static void date_noon(struct tm *tm, struct tm *now, int *num)
1132 pending_number(tm, num);
1133 date_time(tm, now, 12);
1136 static void date_tea(struct tm *tm, struct tm *now, int *num)
1138 pending_number(tm, num);
1139 date_time(tm, now, 17);
1142 static void date_pm(struct tm *tm, struct tm *now UNUSED, int *num)
1144 int hour, n = *num;
1145 *num = 0;
1147 hour = tm->tm_hour;
1148 if (n) {
1149 hour = n;
1150 tm->tm_min = 0;
1151 tm->tm_sec = 0;
1153 tm->tm_hour = (hour % 12) + 12;
1156 static void date_am(struct tm *tm, struct tm *now UNUSED, int *num)
1158 int hour, n = *num;
1159 *num = 0;
1161 hour = tm->tm_hour;
1162 if (n) {
1163 hour = n;
1164 tm->tm_min = 0;
1165 tm->tm_sec = 0;
1167 tm->tm_hour = (hour % 12);
1170 static void date_never(struct tm *tm, struct tm *now UNUSED, int *num)
1172 time_t n = 0;
1173 localtime_r(&n, tm);
1174 *num = 0;
1177 static const struct special {
1178 const char *name;
1179 void (*fn)(struct tm *, struct tm *, int *);
1180 } special[] = {
1181 { "yesterday", date_yesterday },
1182 { "noon", date_noon },
1183 { "midnight", date_midnight },
1184 { "tea", date_tea },
1185 { "PM", date_pm },
1186 { "AM", date_am },
1187 { "never", date_never },
1188 { "now", date_now },
1189 { NULL }
1192 static const char *number_name[] = {
1193 "zero", "one", "two", "three", "four",
1194 "five", "six", "seven", "eight", "nine", "ten",
1197 static const struct typelen {
1198 const char *type;
1199 int length;
1200 } typelen[] = {
1201 { "seconds", 1 },
1202 { "minutes", 60 },
1203 { "hours", 60*60 },
1204 { "days", 24*60*60 },
1205 { "weeks", 7*24*60*60 },
1206 { NULL }
1209 static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm *now, int *num, int *touched)
1211 const struct typelen *tl;
1212 const struct special *s;
1213 const char *end = date;
1214 int i;
1216 while (isalpha(*++end))
1219 for (i = 0; i < 12; i++) {
1220 int match = match_string(date, month_names[i]);
1221 if (match >= 3) {
1222 tm->tm_mon = i;
1223 *touched = 1;
1224 return end;
1228 for (s = special; s->name; s++) {
1229 int len = strlen(s->name);
1230 if (match_string(date, s->name) == len) {
1231 s->fn(tm, now, num);
1232 *touched = 1;
1233 return end;
1237 if (!*num) {
1238 for (i = 1; i < 11; i++) {
1239 int len = strlen(number_name[i]);
1240 if (match_string(date, number_name[i]) == len) {
1241 *num = i;
1242 *touched = 1;
1243 return end;
1246 if (match_string(date, "last") == 4) {
1247 *num = 1;
1248 *touched = 1;
1250 return end;
1253 tl = typelen;
1254 while (tl->type) {
1255 int len = strlen(tl->type);
1256 if (match_string(date, tl->type) >= len-1) {
1257 update_tm(tm, now, tl->length * *num);
1258 *num = 0;
1259 *touched = 1;
1260 return end;
1262 tl++;
1265 for (i = 0; i < 7; i++) {
1266 int match = match_string(date, weekday_names[i]);
1267 if (match >= 3) {
1268 int diff, n = *num -1;
1269 *num = 0;
1271 diff = tm->tm_wday - i;
1272 if (diff <= 0)
1273 n++;
1274 diff += 7*n;
1276 update_tm(tm, now, diff * 24 * 60 * 60);
1277 *touched = 1;
1278 return end;
1282 if (match_string(date, "months") >= 5) {
1283 int n;
1284 update_tm(tm, now, 0); /* fill in date fields if needed */
1285 n = tm->tm_mon - *num;
1286 *num = 0;
1287 while (n < 0) {
1288 n += 12;
1289 tm->tm_year--;
1291 tm->tm_mon = n;
1292 *touched = 1;
1293 return end;
1296 if (match_string(date, "years") >= 4) {
1297 update_tm(tm, now, 0); /* fill in date fields if needed */
1298 tm->tm_year -= *num;
1299 *num = 0;
1300 *touched = 1;
1301 return end;
1304 return end;
1307 static const char *approxidate_digit(const char *date, struct tm *tm, int *num,
1308 time_t now)
1310 char *end;
1311 timestamp_t number = parse_timestamp(date, &end, 10);
1313 switch (*end) {
1314 case ':':
1315 case '.':
1316 case '/':
1317 case '-':
1318 if (isdigit(end[1])) {
1319 int match = match_multi_number(number, *end, date, end,
1320 tm, now);
1321 if (match)
1322 return date + match;
1326 /* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
1327 if (date[0] != '0' || end - date <= 2)
1328 *num = number;
1329 return end;
1332 static timestamp_t approxidate_str(const char *date,
1333 const struct timeval *tv,
1334 int *error_ret)
1336 int number = 0;
1337 int touched = 0;
1338 struct tm tm, now;
1339 time_t time_sec;
1341 time_sec = tv->tv_sec;
1342 localtime_r(&time_sec, &tm);
1343 now = tm;
1345 tm.tm_year = -1;
1346 tm.tm_mon = -1;
1347 tm.tm_mday = -1;
1349 for (;;) {
1350 unsigned char c = *date;
1351 if (!c)
1352 break;
1353 date++;
1354 if (isdigit(c)) {
1355 pending_number(&tm, &number);
1356 date = approxidate_digit(date-1, &tm, &number, time_sec);
1357 touched = 1;
1358 continue;
1360 if (isalpha(c))
1361 date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
1363 pending_number(&tm, &number);
1364 if (!touched)
1365 *error_ret = 1;
1366 return (timestamp_t)update_tm(&tm, &now, 0);
1369 timestamp_t approxidate_careful(const char *date, int *error_ret)
1371 struct timeval tv;
1372 timestamp_t timestamp;
1373 int offset;
1374 int dummy = 0;
1375 if (!error_ret)
1376 error_ret = &dummy;
1378 if (!parse_date_basic(date, &timestamp, &offset)) {
1379 *error_ret = 0;
1380 return timestamp;
1383 get_time(&tv);
1384 return approxidate_str(date, &tv, error_ret);
1387 int date_overflows(timestamp_t t)
1389 time_t sys;
1391 /* If we overflowed our timestamp data type, that's bad... */
1392 if ((uintmax_t)t >= TIME_MAX)
1393 return 1;
1396 * ...but we also are going to feed the result to system
1397 * functions that expect time_t, which is often "signed long".
1398 * Make sure that we fit into time_t, as well.
1400 sys = t;
1401 return t != sys || (t < 1) != (sys < 1);