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