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