date.c: skip fractional second part of ISO-8601
[git] / date.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  */
6
7 #include "cache.h"
8
9 /*
10  * This is like mktime, but without normalization of tm_wday and tm_yday.
11  */
12 static time_t tm_to_time_t(const struct tm *tm)
13 {
14         static const int mdays[] = {
15             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
16         };
17         int year = tm->tm_year - 70;
18         int month = tm->tm_mon;
19         int day = tm->tm_mday;
20
21         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
22                 return -1;
23         if (month < 0 || month > 11) /* array bounds */
24                 return -1;
25         if (month < 2 || (year + 2) % 4)
26                 day--;
27         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
28                 return -1;
29         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
30                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
31 }
32
33 static const char *month_names[] = {
34         "January", "February", "March", "April", "May", "June",
35         "July", "August", "September", "October", "November", "December"
36 };
37
38 static const char *weekday_names[] = {
39         "Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays"
40 };
41
42 static time_t gm_time_t(timestamp_t time, int tz)
43 {
44         int minutes;
45
46         minutes = tz < 0 ? -tz : tz;
47         minutes = (minutes / 100)*60 + (minutes % 100);
48         minutes = tz < 0 ? -minutes : minutes;
49
50         if (minutes > 0) {
51                 if (unsigned_add_overflows(time, minutes * 60))
52                         die("Timestamp+tz too large: %"PRItime" +%04d",
53                             time, tz);
54         } else if (time < -minutes * 60)
55                 die("Timestamp before Unix epoch: %"PRItime" %04d", time, tz);
56         time += minutes * 60;
57         if (date_overflows(time))
58                 die("Timestamp too large for this system: %"PRItime, time);
59         return (time_t)time;
60 }
61
62 /*
63  * The "tz" thing is passed in as this strange "decimal parse of tz"
64  * thing, which means that tz -0100 is passed in as the integer -100,
65  * even though it means "sixty minutes off"
66  */
67 static struct tm *time_to_tm(timestamp_t time, int tz, struct tm *tm)
68 {
69         time_t t = gm_time_t(time, tz);
70         return gmtime_r(&t, tm);
71 }
72
73 static struct tm *time_to_tm_local(timestamp_t time, struct tm *tm)
74 {
75         time_t t = time;
76         return localtime_r(&t, tm);
77 }
78
79 /*
80  * Fill in the localtime 'struct tm' for the supplied time,
81  * and return the local tz.
82  */
83 static int local_time_tzoffset(time_t t, struct tm *tm)
84 {
85         time_t t_local;
86         int offset, eastwest;
87
88         localtime_r(&t, tm);
89         t_local = tm_to_time_t(tm);
90         if (t_local == -1)
91                 return 0; /* error; just use +0000 */
92         if (t_local < t) {
93                 eastwest = -1;
94                 offset = t - t_local;
95         } else {
96                 eastwest = 1;
97                 offset = t_local - t;
98         }
99         offset /= 60; /* in minutes */
100         offset = (offset % 60) + ((offset / 60) * 100);
101         return offset * eastwest;
102 }
103
104 /*
105  * What value of "tz" was in effect back then at "time" in the
106  * local timezone?
107  */
108 static int local_tzoffset(timestamp_t time)
109 {
110         struct tm tm;
111
112         if (date_overflows(time))
113                 die("Timestamp too large for this system: %"PRItime, time);
114
115         return local_time_tzoffset((time_t)time, &tm);
116 }
117
118 static void get_time(struct timeval *now)
119 {
120         const char *x;
121
122         x = getenv("GIT_TEST_DATE_NOW");
123         if (x) {
124                 now->tv_sec = atoi(x);
125                 now->tv_usec = 0;
126         }
127         else
128                 gettimeofday(now, NULL);
129 }
130
131 void show_date_relative(timestamp_t time, struct strbuf *timebuf)
132 {
133         struct timeval now;
134         timestamp_t diff;
135
136         get_time(&now);
137         if (now.tv_sec < time) {
138                 strbuf_addstr(timebuf, _("in the future"));
139                 return;
140         }
141         diff = now.tv_sec - time;
142         if (diff < 90) {
143                 strbuf_addf(timebuf,
144                          Q_("%"PRItime" second ago", "%"PRItime" seconds ago", diff), diff);
145                 return;
146         }
147         /* Turn it into minutes */
148         diff = (diff + 30) / 60;
149         if (diff < 90) {
150                 strbuf_addf(timebuf,
151                          Q_("%"PRItime" minute ago", "%"PRItime" minutes ago", diff), diff);
152                 return;
153         }
154         /* Turn it into hours */
155         diff = (diff + 30) / 60;
156         if (diff < 36) {
157                 strbuf_addf(timebuf,
158                          Q_("%"PRItime" hour ago", "%"PRItime" hours ago", diff), diff);
159                 return;
160         }
161         /* We deal with number of days from here on */
162         diff = (diff + 12) / 24;
163         if (diff < 14) {
164                 strbuf_addf(timebuf,
165                          Q_("%"PRItime" day ago", "%"PRItime" days ago", diff), diff);
166                 return;
167         }
168         /* Say weeks for the past 10 weeks or so */
169         if (diff < 70) {
170                 strbuf_addf(timebuf,
171                          Q_("%"PRItime" week ago", "%"PRItime" weeks ago", (diff + 3) / 7),
172                          (diff + 3) / 7);
173                 return;
174         }
175         /* Say months for the past 12 months or so */
176         if (diff < 365) {
177                 strbuf_addf(timebuf,
178                          Q_("%"PRItime" month ago", "%"PRItime" months ago", (diff + 15) / 30),
179                          (diff + 15) / 30);
180                 return;
181         }
182         /* Give years and months for 5 years or so */
183         if (diff < 1825) {
184                 timestamp_t totalmonths = (diff * 12 * 2 + 365) / (365 * 2);
185                 timestamp_t years = totalmonths / 12;
186                 timestamp_t months = totalmonths % 12;
187                 if (months) {
188                         struct strbuf sb = STRBUF_INIT;
189                         strbuf_addf(&sb, Q_("%"PRItime" year", "%"PRItime" years", years), years);
190                         strbuf_addf(timebuf,
191                                  /* TRANSLATORS: "%s" is "<n> years" */
192                                  Q_("%s, %"PRItime" month ago", "%s, %"PRItime" months ago", months),
193                                  sb.buf, months);
194                         strbuf_release(&sb);
195                 } else
196                         strbuf_addf(timebuf,
197                                  Q_("%"PRItime" year ago", "%"PRItime" years ago", years), years);
198                 return;
199         }
200         /* Otherwise, just years. Centuries is probably overkill. */
201         strbuf_addf(timebuf,
202                  Q_("%"PRItime" year ago", "%"PRItime" years ago", (diff + 183) / 365),
203                  (diff + 183) / 365);
204 }
205
206 struct date_mode *date_mode_from_type(enum date_mode_type type)
207 {
208         static struct date_mode mode;
209         if (type == DATE_STRFTIME)
210                 BUG("cannot create anonymous strftime date_mode struct");
211         mode.type = type;
212         mode.local = 0;
213         return &mode;
214 }
215
216 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)
217 {
218         struct {
219                 unsigned int    year:1,
220                                 date:1,
221                                 wday:1,
222                                 time:1,
223                                 seconds:1,
224                                 tz:1;
225         } hide = { 0 };
226
227         hide.tz = local || tz == human_tz;
228         hide.year = tm->tm_year == human_tm->tm_year;
229         if (hide.year) {
230                 if (tm->tm_mon == human_tm->tm_mon) {
231                         if (tm->tm_mday > human_tm->tm_mday) {
232                                 /* Future date: think timezones */
233                         } else if (tm->tm_mday == human_tm->tm_mday) {
234                                 hide.date = hide.wday = 1;
235                         } else if (tm->tm_mday + 5 > human_tm->tm_mday) {
236                                 /* Leave just weekday if it was a few days ago */
237                                 hide.date = 1;
238                         }
239                 }
240         }
241
242         /* Show "today" times as just relative times */
243         if (hide.wday) {
244                 show_date_relative(time, buf);
245                 return;
246         }
247
248         /*
249          * Always hide seconds for human-readable.
250          * Hide timezone if showing date.
251          * Hide weekday and time if showing year.
252          *
253          * The logic here is two-fold:
254          *  (a) only show details when recent enough to matter
255          *  (b) keep the maximum length "similar", and in check
256          */
257         if (human_tm->tm_year) {
258                 hide.seconds = 1;
259                 hide.tz |= !hide.date;
260                 hide.wday = hide.time = !hide.year;
261         }
262
263         if (!hide.wday)
264                 strbuf_addf(buf, "%.3s ", weekday_names[tm->tm_wday]);
265         if (!hide.date)
266                 strbuf_addf(buf, "%.3s %d ", month_names[tm->tm_mon], tm->tm_mday);
267
268         /* Do we want AM/PM depending on locale? */
269         if (!hide.time) {
270                 strbuf_addf(buf, "%02d:%02d", tm->tm_hour, tm->tm_min);
271                 if (!hide.seconds)
272                         strbuf_addf(buf, ":%02d", tm->tm_sec);
273         } else
274                 strbuf_rtrim(buf);
275
276         if (!hide.year)
277                 strbuf_addf(buf, " %d", tm->tm_year + 1900);
278
279         if (!hide.tz)
280                 strbuf_addf(buf, " %+05d", tz);
281 }
282
283 const char *show_date(timestamp_t time, int tz, const struct date_mode *mode)
284 {
285         struct tm *tm;
286         struct tm tmbuf = { 0 };
287         struct tm human_tm = { 0 };
288         int human_tz = -1;
289         static struct strbuf timebuf = STRBUF_INIT;
290
291         if (mode->type == DATE_UNIX) {
292                 strbuf_reset(&timebuf);
293                 strbuf_addf(&timebuf, "%"PRItime, time);
294                 return timebuf.buf;
295         }
296
297         if (mode->type == DATE_HUMAN) {
298                 struct timeval now;
299
300                 get_time(&now);
301
302                 /* Fill in the data for "current time" in human_tz and human_tm */
303                 human_tz = local_time_tzoffset(now.tv_sec, &human_tm);
304         }
305
306         if (mode->local)
307                 tz = local_tzoffset(time);
308
309         if (mode->type == DATE_RAW) {
310                 strbuf_reset(&timebuf);
311                 strbuf_addf(&timebuf, "%"PRItime" %+05d", time, tz);
312                 return timebuf.buf;
313         }
314
315         if (mode->type == DATE_RELATIVE) {
316                 strbuf_reset(&timebuf);
317                 show_date_relative(time, &timebuf);
318                 return timebuf.buf;
319         }
320
321         if (mode->local)
322                 tm = time_to_tm_local(time, &tmbuf);
323         else
324                 tm = time_to_tm(time, tz, &tmbuf);
325         if (!tm) {
326                 tm = time_to_tm(0, 0, &tmbuf);
327                 tz = 0;
328         }
329
330         strbuf_reset(&timebuf);
331         if (mode->type == DATE_SHORT)
332                 strbuf_addf(&timebuf, "%04d-%02d-%02d", tm->tm_year + 1900,
333                                 tm->tm_mon + 1, tm->tm_mday);
334         else if (mode->type == DATE_ISO8601)
335                 strbuf_addf(&timebuf, "%04d-%02d-%02d %02d:%02d:%02d %+05d",
336                                 tm->tm_year + 1900,
337                                 tm->tm_mon + 1,
338                                 tm->tm_mday,
339                                 tm->tm_hour, tm->tm_min, tm->tm_sec,
340                                 tz);
341         else if (mode->type == DATE_ISO8601_STRICT) {
342                 char sign = (tz >= 0) ? '+' : '-';
343                 tz = abs(tz);
344                 strbuf_addf(&timebuf, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
345                                 tm->tm_year + 1900,
346                                 tm->tm_mon + 1,
347                                 tm->tm_mday,
348                                 tm->tm_hour, tm->tm_min, tm->tm_sec,
349                                 sign, tz / 100, tz % 100);
350         } else if (mode->type == DATE_RFC2822)
351                 strbuf_addf(&timebuf, "%.3s, %d %.3s %d %02d:%02d:%02d %+05d",
352                         weekday_names[tm->tm_wday], tm->tm_mday,
353                         month_names[tm->tm_mon], tm->tm_year + 1900,
354                         tm->tm_hour, tm->tm_min, tm->tm_sec, tz);
355         else if (mode->type == DATE_STRFTIME)
356                 strbuf_addftime(&timebuf, mode->strftime_fmt, tm, tz,
357                                 !mode->local);
358         else
359                 show_date_normal(&timebuf, time, tm, tz, &human_tm, human_tz, mode->local);
360         return timebuf.buf;
361 }
362
363 /*
364  * Check these. And note how it doesn't do the summer-time conversion.
365  *
366  * In my world, it's always summer, and things are probably a bit off
367  * in other ways too.
368  */
369 static const struct {
370         const char *name;
371         int offset;
372         int dst;
373 } timezone_names[] = {
374         { "IDLW", -12, 0, },    /* International Date Line West */
375         { "NT",   -11, 0, },    /* Nome */
376         { "CAT",  -10, 0, },    /* Central Alaska */
377         { "HST",  -10, 0, },    /* Hawaii Standard */
378         { "HDT",  -10, 1, },    /* Hawaii Daylight */
379         { "YST",   -9, 0, },    /* Yukon Standard */
380         { "YDT",   -9, 1, },    /* Yukon Daylight */
381         { "PST",   -8, 0, },    /* Pacific Standard */
382         { "PDT",   -8, 1, },    /* Pacific Daylight */
383         { "MST",   -7, 0, },    /* Mountain Standard */
384         { "MDT",   -7, 1, },    /* Mountain Daylight */
385         { "CST",   -6, 0, },    /* Central Standard */
386         { "CDT",   -6, 1, },    /* Central Daylight */
387         { "EST",   -5, 0, },    /* Eastern Standard */
388         { "EDT",   -5, 1, },    /* Eastern Daylight */
389         { "AST",   -3, 0, },    /* Atlantic Standard */
390         { "ADT",   -3, 1, },    /* Atlantic Daylight */
391         { "WAT",   -1, 0, },    /* West Africa */
392
393         { "GMT",    0, 0, },    /* Greenwich Mean */
394         { "UTC",    0, 0, },    /* Universal (Coordinated) */
395         { "Z",      0, 0, },    /* Zulu, alias for UTC */
396
397         { "WET",    0, 0, },    /* Western European */
398         { "BST",    0, 1, },    /* British Summer */
399         { "CET",   +1, 0, },    /* Central European */
400         { "MET",   +1, 0, },    /* Middle European */
401         { "MEWT",  +1, 0, },    /* Middle European Winter */
402         { "MEST",  +1, 1, },    /* Middle European Summer */
403         { "CEST",  +1, 1, },    /* Central European Summer */
404         { "MESZ",  +1, 1, },    /* Middle European Summer */
405         { "FWT",   +1, 0, },    /* French Winter */
406         { "FST",   +1, 1, },    /* French Summer */
407         { "EET",   +2, 0, },    /* Eastern Europe, USSR Zone 1 */
408         { "EEST",  +2, 1, },    /* Eastern European Daylight */
409         { "WAST",  +7, 0, },    /* West Australian Standard */
410         { "WADT",  +7, 1, },    /* West Australian Daylight */
411         { "CCT",   +8, 0, },    /* China Coast, USSR Zone 7 */
412         { "JST",   +9, 0, },    /* Japan Standard, USSR Zone 8 */
413         { "EAST", +10, 0, },    /* Eastern Australian Standard */
414         { "EADT", +10, 1, },    /* Eastern Australian Daylight */
415         { "GST",  +10, 0, },    /* Guam Standard, USSR Zone 9 */
416         { "NZT",  +12, 0, },    /* New Zealand */
417         { "NZST", +12, 0, },    /* New Zealand Standard */
418         { "NZDT", +12, 1, },    /* New Zealand Daylight */
419         { "IDLE", +12, 0, },    /* International Date Line East */
420 };
421
422 static int match_string(const char *date, const char *str)
423 {
424         int i = 0;
425
426         for (i = 0; *date; date++, str++, i++) {
427                 if (*date == *str)
428                         continue;
429                 if (toupper(*date) == toupper(*str))
430                         continue;
431                 if (!isalnum(*date))
432                         break;
433                 return 0;
434         }
435         return i;
436 }
437
438 static int skip_alpha(const char *date)
439 {
440         int i = 0;
441         do {
442                 i++;
443         } while (isalpha(date[i]));
444         return i;
445 }
446
447 /*
448 * Parse month, weekday, or timezone name
449 */
450 static int match_alpha(const char *date, struct tm *tm, int *offset)
451 {
452         int i;
453
454         for (i = 0; i < 12; i++) {
455                 int match = match_string(date, month_names[i]);
456                 if (match >= 3) {
457                         tm->tm_mon = i;
458                         return match;
459                 }
460         }
461
462         for (i = 0; i < 7; i++) {
463                 int match = match_string(date, weekday_names[i]);
464                 if (match >= 3) {
465                         tm->tm_wday = i;
466                         return match;
467                 }
468         }
469
470         for (i = 0; i < ARRAY_SIZE(timezone_names); i++) {
471                 int match = match_string(date, timezone_names[i].name);
472                 if (match >= 3 || match == strlen(timezone_names[i].name)) {
473                         int off = timezone_names[i].offset;
474
475                         /* This is bogus, but we like summer */
476                         off += timezone_names[i].dst;
477
478                         /* Only use the tz name offset if we don't have anything better */
479                         if (*offset == -1)
480                                 *offset = 60*off;
481
482                         return match;
483                 }
484         }
485
486         if (match_string(date, "PM") == 2) {
487                 tm->tm_hour = (tm->tm_hour % 12) + 12;
488                 return 2;
489         }
490
491         if (match_string(date, "AM") == 2) {
492                 tm->tm_hour = (tm->tm_hour % 12) + 0;
493                 return 2;
494         }
495
496         /* BAD CRAP */
497         return skip_alpha(date);
498 }
499
500 static int set_date(int year, int month, int day, struct tm *now_tm, time_t now, struct tm *tm)
501 {
502         if (month > 0 && month < 13 && day > 0 && day < 32) {
503                 struct tm check = *tm;
504                 struct tm *r = (now_tm ? &check : tm);
505                 time_t specified;
506
507                 r->tm_mon = month - 1;
508                 r->tm_mday = day;
509                 if (year == -1) {
510                         if (!now_tm)
511                                 return 1;
512                         r->tm_year = now_tm->tm_year;
513                 }
514                 else if (year >= 1970 && year < 2100)
515                         r->tm_year = year - 1900;
516                 else if (year > 70 && year < 100)
517                         r->tm_year = year;
518                 else if (year < 38)
519                         r->tm_year = year + 100;
520                 else
521                         return -1;
522                 if (!now_tm)
523                         return 0;
524
525                 specified = tm_to_time_t(r);
526
527                 /* Be it commit time or author time, it does not make
528                  * sense to specify timestamp way into the future.  Make
529                  * sure it is not later than ten days from now...
530                  */
531                 if ((specified != -1) && (now + 10*24*3600 < specified))
532                         return -1;
533                 tm->tm_mon = r->tm_mon;
534                 tm->tm_mday = r->tm_mday;
535                 if (year != -1)
536                         tm->tm_year = r->tm_year;
537                 return 0;
538         }
539         return -1;
540 }
541
542 static int set_time(long hour, long minute, long second, struct tm *tm)
543 {
544         /* We accept 61st second because of leap second */
545         if (0 <= hour && hour <= 24 &&
546             0 <= minute && minute < 60 &&
547             0 <= second && second <= 60) {
548                 tm->tm_hour = hour;
549                 tm->tm_min = minute;
550                 tm->tm_sec = second;
551                 return 0;
552         }
553         return -1;
554 }
555
556 static int is_date_known(struct tm *tm)
557 {
558         return tm->tm_year != -1 && tm->tm_mon != -1 && tm->tm_mday != -1;
559 }
560
561 static int match_multi_number(timestamp_t num, char c, const char *date,
562                               char *end, struct tm *tm, time_t now)
563 {
564         struct tm now_tm;
565         struct tm *refuse_future;
566         long num2, num3;
567
568         num2 = strtol(end+1, &end, 10);
569         num3 = -1;
570         if (*end == c && isdigit(end[1]))
571                 num3 = strtol(end+1, &end, 10);
572
573         /* Time? Date? */
574         switch (c) {
575         case ':':
576                 if (num3 < 0)
577                         num3 = 0;
578                 if (set_time(num, num2, num3, tm) == 0) {
579                         /*
580                          * If %H:%M:%S was just parsed followed by: .<num4>
581                          * Consider (& discard) it as fractional second
582                          * if %Y%m%d is parsed before.
583                          */
584                         if (*end == '.' && isdigit(end[1]) && is_date_known(tm))
585                                 strtol(end + 1, &end, 10);
586                         break;
587                 }
588                 return 0;
589
590         case '-':
591         case '/':
592         case '.':
593                 if (!now)
594                         now = time(NULL);
595                 refuse_future = NULL;
596                 if (gmtime_r(&now, &now_tm))
597                         refuse_future = &now_tm;
598
599                 if (num > 70) {
600                         /* yyyy-mm-dd? */
601                         if (set_date(num, num2, num3, NULL, now, tm) == 0)
602                                 break;
603                         /* yyyy-dd-mm? */
604                         if (set_date(num, num3, num2, NULL, now, tm) == 0)
605                                 break;
606                 }
607                 /* Our eastern European friends say dd.mm.yy[yy]
608                  * is the norm there, so giving precedence to
609                  * mm/dd/yy[yy] form only when separator is not '.'
610                  */
611                 if (c != '.' &&
612                     set_date(num3, num, num2, refuse_future, now, tm) == 0)
613                         break;
614                 /* European dd.mm.yy[yy] or funny US dd/mm/yy[yy] */
615                 if (set_date(num3, num2, num, refuse_future, now, tm) == 0)
616                         break;
617                 /* Funny European mm.dd.yy */
618                 if (c == '.' &&
619                     set_date(num3, num, num2, refuse_future, now, tm) == 0)
620                         break;
621                 return 0;
622         }
623         return end - date;
624 }
625
626 /*
627  * Have we filled in any part of the time/date yet?
628  * We just do a binary 'and' to see if the sign bit
629  * is set in all the values.
630  */
631 static inline int nodate(struct tm *tm)
632 {
633         return (tm->tm_year &
634                 tm->tm_mon &
635                 tm->tm_mday &
636                 tm->tm_hour &
637                 tm->tm_min &
638                 tm->tm_sec) < 0;
639 }
640
641 /*
642  * We've seen a digit. Time? Year? Date?
643  */
644 static int match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt)
645 {
646         int n;
647         char *end;
648         timestamp_t num;
649
650         num = parse_timestamp(date, &end, 10);
651
652         /*
653          * Seconds since 1970? We trigger on that for any numbers with
654          * more than 8 digits. This is because we don't want to rule out
655          * numbers like 20070606 as a YYYYMMDD date.
656          */
657         if (num >= 100000000 && nodate(tm)) {
658                 time_t time = num;
659                 if (gmtime_r(&time, tm)) {
660                         *tm_gmt = 1;
661                         return end - date;
662                 }
663         }
664
665         /*
666          * Check for special formats: num[-.:/]num[same]num
667          */
668         switch (*end) {
669         case ':':
670         case '.':
671         case '/':
672         case '-':
673                 if (isdigit(end[1])) {
674                         int match = match_multi_number(num, *end, date, end, tm, 0);
675                         if (match)
676                                 return match;
677                 }
678         }
679
680         /*
681          * None of the special formats? Try to guess what
682          * the number meant. We use the number of digits
683          * to make a more educated guess..
684          */
685         n = 0;
686         do {
687                 n++;
688         } while (isdigit(date[n]));
689
690         /* Four-digit year or a timezone? */
691         if (n == 4) {
692                 if (num <= 1400 && *offset == -1) {
693                         unsigned int minutes = num % 100;
694                         unsigned int hours = num / 100;
695                         *offset = hours*60 + minutes;
696                 } else if (num > 1900 && num < 2100)
697                         tm->tm_year = num - 1900;
698                 return n;
699         }
700
701         /*
702          * Ignore lots of numerals. We took care of 4-digit years above.
703          * Days or months must be one or two digits.
704          */
705         if (n > 2)
706                 return n;
707
708         /*
709          * NOTE! We will give precedence to day-of-month over month or
710          * year numbers in the 1-12 range. So 05 is always "mday 5",
711          * unless we already have a mday..
712          *
713          * IOW, 01 Apr 05 parses as "April 1st, 2005".
714          */
715         if (num > 0 && num < 32 && tm->tm_mday < 0) {
716                 tm->tm_mday = num;
717                 return n;
718         }
719
720         /* Two-digit year? */
721         if (n == 2 && tm->tm_year < 0) {
722                 if (num < 10 && tm->tm_mday >= 0) {
723                         tm->tm_year = num + 100;
724                         return n;
725                 }
726                 if (num >= 70) {
727                         tm->tm_year = num;
728                         return n;
729                 }
730         }
731
732         if (num > 0 && num < 13 && tm->tm_mon < 0)
733                 tm->tm_mon = num-1;
734
735         return n;
736 }
737
738 static int match_tz(const char *date, int *offp)
739 {
740         char *end;
741         int hour = strtoul(date + 1, &end, 10);
742         int n = end - (date + 1);
743         int min = 0;
744
745         if (n == 4) {
746                 /* hhmm */
747                 min = hour % 100;
748                 hour = hour / 100;
749         } else if (n != 2) {
750                 min = 99; /* random crap */
751         } else if (*end == ':') {
752                 /* hh:mm? */
753                 min = strtoul(end + 1, &end, 10);
754                 if (end - (date + 1) != 5)
755                         min = 99; /* random crap */
756         } /* otherwise we parsed "hh" */
757
758         /*
759          * Don't accept any random crap. Even though some places have
760          * offset larger than 12 hours (e.g. Pacific/Kiritimati is at
761          * UTC+14), there is something wrong if hour part is much
762          * larger than that. We might also want to check that the
763          * minutes are divisible by 15 or something too. (Offset of
764          * Kathmandu, Nepal is UTC+5:45)
765          */
766         if (min < 60 && hour < 24) {
767                 int offset = hour * 60 + min;
768                 if (*date == '-')
769                         offset = -offset;
770                 *offp = offset;
771         }
772         return end - date;
773 }
774
775 static void date_string(timestamp_t date, int offset, struct strbuf *buf)
776 {
777         int sign = '+';
778
779         if (offset < 0) {
780                 offset = -offset;
781                 sign = '-';
782         }
783         strbuf_addf(buf, "%"PRItime" %c%02d%02d", date, sign, offset / 60, offset % 60);
784 }
785
786 /*
787  * Parse a string like "0 +0000" as ancient timestamp near epoch, but
788  * only when it appears not as part of any other string.
789  */
790 static int match_object_header_date(const char *date, timestamp_t *timestamp, int *offset)
791 {
792         char *end;
793         timestamp_t stamp;
794         int ofs;
795
796         if (*date < '0' || '9' < *date)
797                 return -1;
798         stamp = parse_timestamp(date, &end, 10);
799         if (*end != ' ' || stamp == TIME_MAX || (end[1] != '+' && end[1] != '-'))
800                 return -1;
801         date = end + 2;
802         ofs = strtol(date, &end, 10);
803         if ((*end != '\0' && (*end != '\n')) || end != date + 4)
804                 return -1;
805         ofs = (ofs / 100) * 60 + (ofs % 100);
806         if (date[-1] == '-')
807                 ofs = -ofs;
808         *timestamp = stamp;
809         *offset = ofs;
810         return 0;
811 }
812
813 /* Gr. strptime is crap for this; it doesn't have a way to require RFC2822
814    (i.e. English) day/month names, and it doesn't work correctly with %z. */
815 int parse_date_basic(const char *date, timestamp_t *timestamp, int *offset)
816 {
817         struct tm tm;
818         int tm_gmt;
819         timestamp_t dummy_timestamp;
820         int dummy_offset;
821
822         if (!timestamp)
823                 timestamp = &dummy_timestamp;
824         if (!offset)
825                 offset = &dummy_offset;
826
827         memset(&tm, 0, sizeof(tm));
828         tm.tm_year = -1;
829         tm.tm_mon = -1;
830         tm.tm_mday = -1;
831         tm.tm_isdst = -1;
832         tm.tm_hour = -1;
833         tm.tm_min = -1;
834         tm.tm_sec = -1;
835         *offset = -1;
836         tm_gmt = 0;
837
838         if (*date == '@' &&
839             !match_object_header_date(date + 1, timestamp, offset))
840                 return 0; /* success */
841         for (;;) {
842                 int match = 0;
843                 unsigned char c = *date;
844
845                 /* Stop at end of string or newline */
846                 if (!c || c == '\n')
847                         break;
848
849                 if (isalpha(c))
850                         match = match_alpha(date, &tm, offset);
851                 else if (isdigit(c))
852                         match = match_digit(date, &tm, offset, &tm_gmt);
853                 else if ((c == '-' || c == '+') && isdigit(date[1]))
854                         match = match_tz(date, offset);
855
856                 if (!match) {
857                         /* BAD CRAP */
858                         match = 1;
859                 }
860
861                 date += match;
862         }
863
864         /* do not use mktime(), which uses local timezone, here */
865         *timestamp = tm_to_time_t(&tm);
866         if (*timestamp == -1)
867                 return -1;
868
869         if (*offset == -1) {
870                 time_t temp_time;
871
872                 /* gmtime_r() in match_digit() may have clobbered it */
873                 tm.tm_isdst = -1;
874                 temp_time = mktime(&tm);
875                 if ((time_t)*timestamp > temp_time) {
876                         *offset = ((time_t)*timestamp - temp_time) / 60;
877                 } else {
878                         *offset = -(int)((temp_time - (time_t)*timestamp) / 60);
879                 }
880         }
881
882         if (!tm_gmt)
883                 *timestamp -= *offset * 60;
884         return 0; /* success */
885 }
886
887 int parse_expiry_date(const char *date, timestamp_t *timestamp)
888 {
889         int errors = 0;
890
891         if (!strcmp(date, "never") || !strcmp(date, "false"))
892                 *timestamp = 0;
893         else if (!strcmp(date, "all") || !strcmp(date, "now"))
894                 /*
895                  * We take over "now" here, which usually translates
896                  * to the current timestamp.  This is because the user
897                  * really means to expire everything she has done in
898                  * the past, and by definition reflogs are the record
899                  * of the past, and there is nothing from the future
900                  * to be kept.
901                  */
902                 *timestamp = TIME_MAX;
903         else
904                 *timestamp = approxidate_careful(date, &errors);
905
906         return errors;
907 }
908
909 int parse_date(const char *date, struct strbuf *result)
910 {
911         timestamp_t timestamp;
912         int offset;
913         if (parse_date_basic(date, &timestamp, &offset))
914                 return -1;
915         date_string(timestamp, offset, result);
916         return 0;
917 }
918
919 static enum date_mode_type parse_date_type(const char *format, const char **end)
920 {
921         if (skip_prefix(format, "relative", end))
922                 return DATE_RELATIVE;
923         if (skip_prefix(format, "iso8601-strict", end) ||
924             skip_prefix(format, "iso-strict", end))
925                 return DATE_ISO8601_STRICT;
926         if (skip_prefix(format, "iso8601", end) ||
927             skip_prefix(format, "iso", end))
928                 return DATE_ISO8601;
929         if (skip_prefix(format, "rfc2822", end) ||
930             skip_prefix(format, "rfc", end))
931                 return DATE_RFC2822;
932         if (skip_prefix(format, "short", end))
933                 return DATE_SHORT;
934         if (skip_prefix(format, "default", end))
935                 return DATE_NORMAL;
936         if (skip_prefix(format, "human", end))
937                 return DATE_HUMAN;
938         if (skip_prefix(format, "raw", end))
939                 return DATE_RAW;
940         if (skip_prefix(format, "unix", end))
941                 return DATE_UNIX;
942         if (skip_prefix(format, "format", end))
943                 return DATE_STRFTIME;
944         /*
945          * Please update $__git_log_date_formats in
946          * git-completion.bash when you add new formats.
947          */
948
949         die("unknown date format %s", format);
950 }
951
952 void parse_date_format(const char *format, struct date_mode *mode)
953 {
954         const char *p;
955
956         /* "auto:foo" is "if tty/pager, then foo, otherwise normal" */
957         if (skip_prefix(format, "auto:", &p)) {
958                 if (isatty(1) || pager_in_use())
959                         format = p;
960                 else
961                         format = "default";
962         }
963
964         /* historical alias */
965         if (!strcmp(format, "local"))
966                 format = "default-local";
967
968         mode->type = parse_date_type(format, &p);
969         mode->local = 0;
970
971         if (skip_prefix(p, "-local", &p))
972                 mode->local = 1;
973
974         if (mode->type == DATE_STRFTIME) {
975                 if (!skip_prefix(p, ":", &p))
976                         die("date format missing colon separator: %s", format);
977                 mode->strftime_fmt = xstrdup(p);
978         } else if (*p)
979                 die("unknown date format %s", format);
980 }
981
982 void datestamp(struct strbuf *out)
983 {
984         time_t now;
985         int offset;
986         struct tm tm = { 0 };
987
988         time(&now);
989
990         offset = tm_to_time_t(localtime_r(&now, &tm)) - now;
991         offset /= 60;
992
993         date_string(now, offset, out);
994 }
995
996 /*
997  * Relative time update (eg "2 days ago").  If we haven't set the time
998  * yet, we need to set it from current time.
999  */
1000 static time_t update_tm(struct tm *tm, struct tm *now, time_t sec)
1001 {
1002         time_t n;
1003
1004         if (tm->tm_mday < 0)
1005                 tm->tm_mday = now->tm_mday;
1006         if (tm->tm_mon < 0)
1007                 tm->tm_mon = now->tm_mon;
1008         if (tm->tm_year < 0) {
1009                 tm->tm_year = now->tm_year;
1010                 if (tm->tm_mon > now->tm_mon)
1011                         tm->tm_year--;
1012         }
1013
1014         n = mktime(tm) - sec;
1015         localtime_r(&n, tm);
1016         return n;
1017 }
1018
1019 /*
1020  * Do we have a pending number at the end, or when
1021  * we see a new one? Let's assume it's a month day,
1022  * as in "Dec 6, 1992"
1023  */
1024 static void pending_number(struct tm *tm, int *num)
1025 {
1026         int number = *num;
1027
1028         if (number) {
1029                 *num = 0;
1030                 if (tm->tm_mday < 0 && number < 32)
1031                         tm->tm_mday = number;
1032                 else if (tm->tm_mon < 0 && number < 13)
1033                         tm->tm_mon = number-1;
1034                 else if (tm->tm_year < 0) {
1035                         if (number > 1969 && number < 2100)
1036                                 tm->tm_year = number - 1900;
1037                         else if (number > 69 && number < 100)
1038                                 tm->tm_year = number;
1039                         else if (number < 38)
1040                                 tm->tm_year = 100 + number;
1041                         /* We screw up for number = 00 ? */
1042                 }
1043         }
1044 }
1045
1046 static void date_now(struct tm *tm, struct tm *now, int *num)
1047 {
1048         *num = 0;
1049         update_tm(tm, now, 0);
1050 }
1051
1052 static void date_yesterday(struct tm *tm, struct tm *now, int *num)
1053 {
1054         *num = 0;
1055         update_tm(tm, now, 24*60*60);
1056 }
1057
1058 static void date_time(struct tm *tm, struct tm *now, int hour)
1059 {
1060         if (tm->tm_hour < hour)
1061                 update_tm(tm, now, 24*60*60);
1062         tm->tm_hour = hour;
1063         tm->tm_min = 0;
1064         tm->tm_sec = 0;
1065 }
1066
1067 static void date_midnight(struct tm *tm, struct tm *now, int *num)
1068 {
1069         pending_number(tm, num);
1070         date_time(tm, now, 0);
1071 }
1072
1073 static void date_noon(struct tm *tm, struct tm *now, int *num)
1074 {
1075         pending_number(tm, num);
1076         date_time(tm, now, 12);
1077 }
1078
1079 static void date_tea(struct tm *tm, struct tm *now, int *num)
1080 {
1081         pending_number(tm, num);
1082         date_time(tm, now, 17);
1083 }
1084
1085 static void date_pm(struct tm *tm, struct tm *now, int *num)
1086 {
1087         int hour, n = *num;
1088         *num = 0;
1089
1090         hour = tm->tm_hour;
1091         if (n) {
1092                 hour = n;
1093                 tm->tm_min = 0;
1094                 tm->tm_sec = 0;
1095         }
1096         tm->tm_hour = (hour % 12) + 12;
1097 }
1098
1099 static void date_am(struct tm *tm, struct tm *now, int *num)
1100 {
1101         int hour, n = *num;
1102         *num = 0;
1103
1104         hour = tm->tm_hour;
1105         if (n) {
1106                 hour = n;
1107                 tm->tm_min = 0;
1108                 tm->tm_sec = 0;
1109         }
1110         tm->tm_hour = (hour % 12);
1111 }
1112
1113 static void date_never(struct tm *tm, struct tm *now, int *num)
1114 {
1115         time_t n = 0;
1116         localtime_r(&n, tm);
1117         *num = 0;
1118 }
1119
1120 static const struct special {
1121         const char *name;
1122         void (*fn)(struct tm *, struct tm *, int *);
1123 } special[] = {
1124         { "yesterday", date_yesterday },
1125         { "noon", date_noon },
1126         { "midnight", date_midnight },
1127         { "tea", date_tea },
1128         { "PM", date_pm },
1129         { "AM", date_am },
1130         { "never", date_never },
1131         { "now", date_now },
1132         { NULL }
1133 };
1134
1135 static const char *number_name[] = {
1136         "zero", "one", "two", "three", "four",
1137         "five", "six", "seven", "eight", "nine", "ten",
1138 };
1139
1140 static const struct typelen {
1141         const char *type;
1142         int length;
1143 } typelen[] = {
1144         { "seconds", 1 },
1145         { "minutes", 60 },
1146         { "hours", 60*60 },
1147         { "days", 24*60*60 },
1148         { "weeks", 7*24*60*60 },
1149         { NULL }
1150 };
1151
1152 static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm *now, int *num, int *touched)
1153 {
1154         const struct typelen *tl;
1155         const struct special *s;
1156         const char *end = date;
1157         int i;
1158
1159         while (isalpha(*++end))
1160                 ;
1161
1162         for (i = 0; i < 12; i++) {
1163                 int match = match_string(date, month_names[i]);
1164                 if (match >= 3) {
1165                         tm->tm_mon = i;
1166                         *touched = 1;
1167                         return end;
1168                 }
1169         }
1170
1171         for (s = special; s->name; s++) {
1172                 int len = strlen(s->name);
1173                 if (match_string(date, s->name) == len) {
1174                         s->fn(tm, now, num);
1175                         *touched = 1;
1176                         return end;
1177                 }
1178         }
1179
1180         if (!*num) {
1181                 for (i = 1; i < 11; i++) {
1182                         int len = strlen(number_name[i]);
1183                         if (match_string(date, number_name[i]) == len) {
1184                                 *num = i;
1185                                 *touched = 1;
1186                                 return end;
1187                         }
1188                 }
1189                 if (match_string(date, "last") == 4) {
1190                         *num = 1;
1191                         *touched = 1;
1192                 }
1193                 return end;
1194         }
1195
1196         tl = typelen;
1197         while (tl->type) {
1198                 int len = strlen(tl->type);
1199                 if (match_string(date, tl->type) >= len-1) {
1200                         update_tm(tm, now, tl->length * *num);
1201                         *num = 0;
1202                         *touched = 1;
1203                         return end;
1204                 }
1205                 tl++;
1206         }
1207
1208         for (i = 0; i < 7; i++) {
1209                 int match = match_string(date, weekday_names[i]);
1210                 if (match >= 3) {
1211                         int diff, n = *num -1;
1212                         *num = 0;
1213
1214                         diff = tm->tm_wday - i;
1215                         if (diff <= 0)
1216                                 n++;
1217                         diff += 7*n;
1218
1219                         update_tm(tm, now, diff * 24 * 60 * 60);
1220                         *touched = 1;
1221                         return end;
1222                 }
1223         }
1224
1225         if (match_string(date, "months") >= 5) {
1226                 int n;
1227                 update_tm(tm, now, 0); /* fill in date fields if needed */
1228                 n = tm->tm_mon - *num;
1229                 *num = 0;
1230                 while (n < 0) {
1231                         n += 12;
1232                         tm->tm_year--;
1233                 }
1234                 tm->tm_mon = n;
1235                 *touched = 1;
1236                 return end;
1237         }
1238
1239         if (match_string(date, "years") >= 4) {
1240                 update_tm(tm, now, 0); /* fill in date fields if needed */
1241                 tm->tm_year -= *num;
1242                 *num = 0;
1243                 *touched = 1;
1244                 return end;
1245         }
1246
1247         return end;
1248 }
1249
1250 static const char *approxidate_digit(const char *date, struct tm *tm, int *num,
1251                                      time_t now)
1252 {
1253         char *end;
1254         timestamp_t number = parse_timestamp(date, &end, 10);
1255
1256         switch (*end) {
1257         case ':':
1258         case '.':
1259         case '/':
1260         case '-':
1261                 if (isdigit(end[1])) {
1262                         int match = match_multi_number(number, *end, date, end,
1263                                                        tm, now);
1264                         if (match)
1265                                 return date + match;
1266                 }
1267         }
1268
1269         /* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
1270         if (date[0] != '0' || end - date <= 2)
1271                 *num = number;
1272         return end;
1273 }
1274
1275 static timestamp_t approxidate_str(const char *date,
1276                                    const struct timeval *tv,
1277                                    int *error_ret)
1278 {
1279         int number = 0;
1280         int touched = 0;
1281         struct tm tm, now;
1282         time_t time_sec;
1283
1284         time_sec = tv->tv_sec;
1285         localtime_r(&time_sec, &tm);
1286         now = tm;
1287
1288         tm.tm_year = -1;
1289         tm.tm_mon = -1;
1290         tm.tm_mday = -1;
1291
1292         for (;;) {
1293                 unsigned char c = *date;
1294                 if (!c)
1295                         break;
1296                 date++;
1297                 if (isdigit(c)) {
1298                         pending_number(&tm, &number);
1299                         date = approxidate_digit(date-1, &tm, &number, time_sec);
1300                         touched = 1;
1301                         continue;
1302                 }
1303                 if (isalpha(c))
1304                         date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
1305         }
1306         pending_number(&tm, &number);
1307         if (!touched)
1308                 *error_ret = 1;
1309         return (timestamp_t)update_tm(&tm, &now, 0);
1310 }
1311
1312 timestamp_t approxidate_relative(const char *date)
1313 {
1314         struct timeval tv;
1315         timestamp_t timestamp;
1316         int offset;
1317         int errors = 0;
1318
1319         if (!parse_date_basic(date, &timestamp, &offset))
1320                 return timestamp;
1321
1322         get_time(&tv);
1323         return approxidate_str(date, (const struct timeval *) &tv, &errors);
1324 }
1325
1326 timestamp_t approxidate_careful(const char *date, int *error_ret)
1327 {
1328         struct timeval tv;
1329         timestamp_t timestamp;
1330         int offset;
1331         int dummy = 0;
1332         if (!error_ret)
1333                 error_ret = &dummy;
1334
1335         if (!parse_date_basic(date, &timestamp, &offset)) {
1336                 *error_ret = 0;
1337                 return timestamp;
1338         }
1339
1340         get_time(&tv);
1341         return approxidate_str(date, &tv, error_ret);
1342 }
1343
1344 int date_overflows(timestamp_t t)
1345 {
1346         time_t sys;
1347
1348         /* If we overflowed our timestamp data type, that's bad... */
1349         if ((uintmax_t)t >= TIME_MAX)
1350                 return 1;
1351
1352         /*
1353          * ...but we also are going to feed the result to system
1354          * functions that expect time_t, which is often "signed long".
1355          * Make sure that we fit into time_t, as well.
1356          */
1357         sys = t;
1358         return t != sys || (t < 1) != (sys < 1);
1359 }