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