date.c 26.9 KB
Newer Older
1 2 3 4 5 6
/*
 * GIT - The information manager from hell
 *
 * Copyright (C) Linus Torvalds, 2005
 */

Linus Torvalds's avatar
Linus Torvalds committed
7 8
#include "cache.h"

9 10 11
/*
 * This is like mktime, but without normalization of tm_wday and tm_yday.
 */
12
static time_t tm_to_time_t(const struct tm *tm)
13 14 15 16 17 18 19 20 21 22 23 24 25 26
{
	static const int mdays[] = {
	    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
	};
	int year = tm->tm_year - 70;
	int month = tm->tm_mon;
	int day = tm->tm_mday;

	if (year < 0 || year > 129) /* algo only works for 1970-2099 */
		return -1;
	if (month < 0 || month > 11) /* array bounds */
		return -1;
	if (month < 2 || (year + 2) % 4)
		day--;
27 28
	if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
		return -1;
29 30 31 32 33
	return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
		tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
}

static const char *month_names[] = {
34 35
	"January", "February", "March", "April", "May", "June",
	"July", "August", "September", "October", "November", "December"
36 37 38
};

static const char *weekday_names[] = {
39
	"Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays"
40 41
};

42 43 44 45 46 47 48 49 50 51
static time_t gm_time_t(unsigned long time, int tz)
{
	int minutes;

	minutes = tz < 0 ? -tz : tz;
	minutes = (minutes / 100)*60 + (minutes % 100);
	minutes = tz < 0 ? -minutes : minutes;
	return time + minutes * 60;
}

52 53 54 55 56
/*
 * The "tz" thing is passed in as this strange "decimal parse of tz"
 * thing, which means that tz -0100 is passed in as the integer -100,
 * even though it means "sixty minutes off"
 */
57
static struct tm *time_to_tm(unsigned long time, int tz)
58
{
59
	time_t t = gm_time_t(time, tz);
60 61 62
	return gmtime(&t);
}

63 64 65 66 67 68 69 70 71 72 73 74
/*
 * What value of "tz" was in effect back then at "time" in the
 * local timezone?
 */
static int local_tzoffset(unsigned long time)
{
	time_t t, t_local;
	struct tm tm;
	int offset, eastwest;

	t = time;
	localtime_r(&t, &tm);
75
	t_local = tm_to_time_t(&tm);
76 77 78 79 80 81 82 83 84 85 86 87 88

	if (t_local < t) {
		eastwest = -1;
		offset = t - t_local;
	} else {
		eastwest = 1;
		offset = t_local - t;
	}
	offset /= 60; /* in minutes */
	offset = (offset % 60) + ((offset / 60) * 100);
	return offset * eastwest;
}

89
void show_date_relative(unsigned long time, int tz,
90
			       const struct timeval *now,
91
			       struct strbuf *timebuf)
92 93
{
	unsigned long diff;
94 95 96 97
	if (now->tv_sec < time) {
		strbuf_addstr(timebuf, _("in the future"));
		return;
	}
98 99
	diff = now->tv_sec - time;
	if (diff < 90) {
100 101 102
		strbuf_addf(timebuf,
			 Q_("%lu second ago", "%lu seconds ago", diff), diff);
		return;
103 104 105 106
	}
	/* Turn it into minutes */
	diff = (diff + 30) / 60;
	if (diff < 90) {
107 108 109
		strbuf_addf(timebuf,
			 Q_("%lu minute ago", "%lu minutes ago", diff), diff);
		return;
110 111 112 113
	}
	/* Turn it into hours */
	diff = (diff + 30) / 60;
	if (diff < 36) {
114 115 116
		strbuf_addf(timebuf,
			 Q_("%lu hour ago", "%lu hours ago", diff), diff);
		return;
117 118 119 120
	}
	/* We deal with number of days from here on */
	diff = (diff + 12) / 24;
	if (diff < 14) {
121 122 123
		strbuf_addf(timebuf,
			 Q_("%lu day ago", "%lu days ago", diff), diff);
		return;
124 125 126
	}
	/* Say weeks for the past 10 weeks or so */
	if (diff < 70) {
127 128 129 130
		strbuf_addf(timebuf,
			 Q_("%lu week ago", "%lu weeks ago", (diff + 3) / 7),
			 (diff + 3) / 7);
		return;
131 132
	}
	/* Say months for the past 12 months or so */
Johan Sageryd's avatar
Johan Sageryd committed
133
	if (diff < 365) {
134 135 136 137
		strbuf_addf(timebuf,
			 Q_("%lu month ago", "%lu months ago", (diff + 15) / 30),
			 (diff + 15) / 30);
		return;
138 139 140
	}
	/* Give years and months for 5 years or so */
	if (diff < 1825) {
141 142 143
		unsigned long totalmonths = (diff * 12 * 2 + 365) / (365 * 2);
		unsigned long years = totalmonths / 12;
		unsigned long months = totalmonths % 12;
144 145 146 147
		if (months) {
			struct strbuf sb = STRBUF_INIT;
			strbuf_addf(&sb, Q_("%lu year", "%lu years", years), years);
			strbuf_addf(timebuf,
148
				 /* TRANSLATORS: "%s" is "<n> years" */
149 150 151 152 153 154 155
				 Q_("%s, %lu month ago", "%s, %lu months ago", months),
				 sb.buf, months);
			strbuf_release(&sb);
		} else
			strbuf_addf(timebuf,
				 Q_("%lu year ago", "%lu years ago", years), years);
		return;
156 157
	}
	/* Otherwise, just years. Centuries is probably overkill. */
158 159 160
	strbuf_addf(timebuf,
		 Q_("%lu year ago", "%lu years ago", (diff + 183) / 365),
		 (diff + 183) / 365);
161 162
}

163 164 165
struct date_mode *date_mode_from_type(enum date_mode_type type)
{
	static struct date_mode mode;
Jeff King's avatar
Jeff King committed
166 167
	if (type == DATE_STRFTIME)
		die("BUG: cannot create anonymous strftime date_mode struct");
168
	mode.type = type;
169
	mode.local = 0;
170 171 172 173
	return &mode;
}

const 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 180
		tz = local_tzoffset(time);

181
	if (mode->type == DATE_RAW) {
182 183 184
		strbuf_reset(&timebuf);
		strbuf_addf(&timebuf, "%lu %+05d", time, tz);
		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 193
		show_date_relative(time, tz, &now, &timebuf);
		return timebuf.buf;
194 195
	}

196
	tm = time_to_tm(time, tz);
197 198 199 200
	if (!tm) {
		tm = time_to_tm(0, 0);
		tz = 0;
	}
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 209 210 211 212
				tm->tm_year + 1900,
				tm->tm_mon + 1,
				tm->tm_mday,
				tm->tm_hour, tm->tm_min, tm->tm_sec,
				tz);
213
	else if (mode->type == DATE_ISO8601_STRICT) {
214 215 216 217 218 219 220 221
		char sign = (tz >= 0) ? '+' : '-';
		tz = abs(tz);
		strbuf_addf(&timebuf, "%04d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
				tm->tm_year + 1900,
				tm->tm_mon + 1,
				tm->tm_mday,
				tm->tm_hour, tm->tm_min, tm->tm_sec,
				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 225 226
			weekday_names[tm->tm_wday], tm->tm_mday,
			month_names[tm->tm_mon], tm->tm_year + 1900,
			tm->tm_hour, tm->tm_min, tm->tm_sec, tz);
Jeff King's avatar
Jeff King committed
227 228
	else if (mode->type == DATE_STRFTIME)
		strbuf_addftime(&timebuf, mode->strftime_fmt, tm);
229
	else
230
		strbuf_addf(&timebuf, "%.3s %.3s %d %02d:%02d:%02d %d%c%+05d",
231 232 233 234
				weekday_names[tm->tm_wday],
				month_names[tm->tm_mon],
				tm->tm_mday,
				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 243 244 245 246 247 248 249
/*
 * Check these. And note how it doesn't do the summer-time conversion.
 *
 * In my world, it's always summer, and things are probably a bit off
 * in other ways too.
 */
static const struct {
	const char *name;
	int offset;
250
	int dst;
251
} timezone_names[] = {
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
	{ "IDLW", -12, 0, },	/* International Date Line West */
	{ "NT",   -11, 0, },	/* Nome */
	{ "CAT",  -10, 0, },	/* Central Alaska */
	{ "HST",  -10, 0, },	/* Hawaii Standard */
	{ "HDT",  -10, 1, },	/* Hawaii Daylight */
	{ "YST",   -9, 0, },	/* Yukon Standard */
	{ "YDT",   -9, 1, },	/* Yukon Daylight */
	{ "PST",   -8, 0, },	/* Pacific Standard */
	{ "PDT",   -8, 1, },	/* Pacific Daylight */
	{ "MST",   -7, 0, },	/* Mountain Standard */
	{ "MDT",   -7, 1, },	/* Mountain Daylight */
	{ "CST",   -6, 0, },	/* Central Standard */
	{ "CDT",   -6, 1, },	/* Central Daylight */
	{ "EST",   -5, 0, },	/* Eastern Standard */
	{ "EDT",   -5, 1, },	/* Eastern Daylight */
	{ "AST",   -3, 0, },	/* Atlantic Standard */
	{ "ADT",   -3, 1, },	/* Atlantic Daylight */
	{ "WAT",   -1, 0, },	/* West Africa */

	{ "GMT",    0, 0, },	/* Greenwich Mean */
	{ "UTC",    0, 0, },	/* Universal (Coordinated) */
273
	{ "Z",      0, 0, },    /* Zulu, alias for UTC */
274 275 276 277 278 279 280 281 282 283 284 285

	{ "WET",    0, 0, },	/* Western European */
	{ "BST",    0, 1, },	/* British Summer */
	{ "CET",   +1, 0, },	/* Central European */
	{ "MET",   +1, 0, },	/* Middle European */
	{ "MEWT",  +1, 0, },	/* Middle European Winter */
	{ "MEST",  +1, 1, },	/* Middle European Summer */
	{ "CEST",  +1, 1, },	/* Central European Summer */
	{ "MESZ",  +1, 1, },	/* Middle European Summer */
	{ "FWT",   +1, 0, },	/* French Winter */
	{ "FST",   +1, 1, },	/* French Summer */
	{ "EET",   +2, 0, },	/* Eastern Europe, USSR Zone 1 */
286
	{ "EEST",  +2, 1, },	/* Eastern European Daylight */
287 288 289 290 291 292 293
	{ "WAST",  +7, 0, },	/* West Australian Standard */
	{ "WADT",  +7, 1, },	/* West Australian Daylight */
	{ "CCT",   +8, 0, },	/* China Coast, USSR Zone 7 */
	{ "JST",   +9, 0, },	/* Japan Standard, USSR Zone 8 */
	{ "EAST", +10, 0, },	/* Eastern Australian Standard */
	{ "EADT", +10, 1, },	/* Eastern Australian Daylight */
	{ "GST",  +10, 0, },	/* Guam Standard, USSR Zone 9 */
294 295 296
	{ "NZT",  +12, 0, },	/* New Zealand */
	{ "NZST", +12, 0, },	/* New Zealand Standard */
	{ "NZDT", +12, 1, },	/* New Zealand Daylight */
297
	{ "IDLE", +12, 0, },	/* International Date Line East */
298
};
299

300
static int match_string(const char *date, const char *str)
301
{
302 303 304 305 306 307 308 309 310 311 312 313
	int i = 0;

	for (i = 0; *date; date++, str++, i++) {
		if (*date == *str)
			continue;
		if (toupper(*date) == toupper(*str))
			continue;
		if (!isalnum(*date))
			break;
		return 0;
	}
	return i;
314 315
}

316 317 318 319 320 321 322 323 324
static int skip_alpha(const char *date)
{
	int i = 0;
	do {
		i++;
	} while (isalpha(date[i]));
	return i;
}

325 326 327 328
/*
* Parse month, weekday, or timezone name
*/
static int match_alpha(const char *date, struct tm *tm, int *offset)
329
{
330
	int i;
331

332 333 334 335 336
	for (i = 0; i < 12; i++) {
		int match = match_string(date, month_names[i]);
		if (match >= 3) {
			tm->tm_mon = i;
			return match;
337
		}
338
	}
339

340 341 342 343 344 345 346
	for (i = 0; i < 7; i++) {
		int match = match_string(date, weekday_names[i]);
		if (match >= 3) {
			tm->tm_wday = i;
			return match;
		}
	}
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 352 353 354 355
			int off = timezone_names[i].offset;

			/* This is bogus, but we like summer */
			off += timezone_names[i].dst;

356 357 358 359
			/* Only use the tz name offset if we don't have anything better */
			if (*offset == -1)
				*offset = 60*off;

360
			return match;
361 362 363
		}
	}

364
	if (match_string(date, "PM") == 2) {
365 366 367 368 369 370
		tm->tm_hour = (tm->tm_hour % 12) + 12;
		return 2;
	}

	if (match_string(date, "AM") == 2) {
		tm->tm_hour = (tm->tm_hour % 12) + 0;
371 372 373
		return 2;
	}

374
	/* BAD CRAP */
375
	return skip_alpha(date);
376
}
377

378
static 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 382 383 384 385 386
		struct tm check = *tm;
		struct tm *r = (now_tm ? &check : tm);
		time_t specified;

		r->tm_mon = month - 1;
		r->tm_mday = day;
387
		if (year == -1) {
388 389 390
			if (!now_tm)
				return 1;
			r->tm_year = now_tm->tm_year;
391
		}
392 393 394 395 396 397 398
		else if (year >= 1970 && year < 2100)
			r->tm_year = year - 1900;
		else if (year > 70 && year < 100)
			r->tm_year = year;
		else if (year < 38)
			r->tm_year = year + 100;
		else
399
			return 0;
400 401 402
		if (!now_tm)
			return 1;

403
		specified = tm_to_time_t(r);
404

405 406 407 408
		/* Be it commit time or author time, it does not make
		 * sense to specify timestamp way into the future.  Make
		 * sure it is not later than ten days from now...
		 */
409
		if ((specified != -1) && (now + 10*24*3600 < specified))
410 411 412 413 414
			return 0;
		tm->tm_mon = r->tm_mon;
		tm->tm_mday = r->tm_mday;
		if (year != -1)
			tm->tm_year = r->tm_year;
415
		return 1;
416
	}
417 418
	return 0;
}
419

420 421
static int match_multi_number(unsigned long num, char c, const char *date,
			      char *end, struct tm *tm, time_t now)
422
{
423 424
	struct tm now_tm;
	struct tm *refuse_future;
425 426 427 428 429 430 431 432
	long num2, num3;

	num2 = strtol(end+1, &end, 10);
	num3 = -1;
	if (*end == c && isdigit(end[1]))
		num3 = strtol(end+1, &end, 10);

	/* Time? Date? */
433
	switch (c) {
434 435 436 437 438 439 440
	case ':':
		if (num3 < 0)
			num3 = 0;
		if (num < 25 && num2 >= 0 && num2 < 60 && num3 >= 0 && num3 <= 60) {
			tm->tm_hour = num;
			tm->tm_min = num2;
			tm->tm_sec = num3;
441 442
			break;
		}
443
		return 0;
444 445 446

	case '-':
	case '/':
447
	case '.':
448 449
		if (!now)
			now = time(NULL);
450 451 452 453
		refuse_future = NULL;
		if (gmtime_r(&now, &now_tm))
			refuse_future = &now_tm;

454 455
		if (num > 70) {
			/* yyyy-mm-dd? */
456
			if (is_date(num, num2, num3, NULL, now, tm))
457 458
				break;
			/* yyyy-dd-mm? */
459
			if (is_date(num, num3, num2, NULL, now, tm))
460
				break;
461
		}
462 463 464 465 466 467 468 469 470
		/* Our eastern European friends say dd.mm.yy[yy]
		 * is the norm there, so giving precedence to
		 * mm/dd/yy[yy] form only when separator is not '.'
		 */
		if (c != '.' &&
		    is_date(num3, num, num2, refuse_future, now, tm))
			break;
		/* European dd.mm.yy[yy] or funny US dd/mm/yy[yy] */
		if (is_date(num3, num2, num, refuse_future, now, tm))
471
			break;
472 473 474
		/* Funny European mm.dd.yy */
		if (c == '.' &&
		    is_date(num3, num, num2, refuse_future, now, tm))
475 476 477 478 479 480
			break;
		return 0;
	}
	return end - date;
}

481 482 483 484 485
/*
 * Have we filled in any part of the time/date yet?
 * We just do a binary 'and' to see if the sign bit
 * is set in all the values.
 */
486 487
static inline int nodate(struct tm *tm)
{
488 489 490 491 492 493
	return (tm->tm_year &
		tm->tm_mon &
		tm->tm_mday &
		tm->tm_hour &
		tm->tm_min &
		tm->tm_sec) < 0;
494 495
}

496
/*
Junio C Hamano's avatar
Junio C Hamano committed
497
 * We've seen a digit. Time? Year? Date?
498
 */
499
static int match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt)
500 501 502 503 504 505 506 507
{
	int n;
	char *end;
	unsigned long num;

	num = strtoul(date, &end, 10);

	/*
508 509 510
	 * Seconds since 1970? We trigger on that for any numbers with
	 * more than 8 digits. This is because we don't want to rule out
	 * numbers like 20070606 as a YYYYMMDD date.
511
	 */
512
	if (num >= 100000000 && nodate(tm)) {
513
		time_t time = num;
514 515
		if (gmtime_r(&time, tm)) {
			*tm_gmt = 1;
516
			return end - date;
517
		}
518 519 520
	}

	/*
521
	 * Check for special formats: num[-.:/]num[same]num
522 523 524
	 */
	switch (*end) {
	case ':':
525
	case '.':
526 527 528
	case '/':
	case '-':
		if (isdigit(end[1])) {
529
			int match = match_multi_number(num, *end, date, end, tm, 0);
530 531
			if (match)
				return match;
532 533
		}
	}
534 535 536 537 538 539 540 541 542 543 544 545 546

	/*
	 * None of the special formats? Try to guess what
	 * the number meant. We use the number of digits
	 * to make a more educated guess..
	 */
	n = 0;
	do {
		n++;
	} while (isdigit(date[n]));

	/* Four-digit year or a timezone? */
	if (n == 4) {
547
		if (num <= 1400 && *offset == -1) {
548 549 550 551 552 553 554 555
			unsigned int minutes = num % 100;
			unsigned int hours = num / 100;
			*offset = hours*60 + minutes;
		} else if (num > 1900 && num < 2100)
			tm->tm_year = num - 1900;
		return n;
	}

556 557 558 559 560 561 562
	/*
	 * Ignore lots of numerals. We took care of 4-digit years above.
	 * Days or months must be one or two digits.
	 */
	if (n > 2)
		return n;

563 564
	/*
	 * NOTE! We will give precedence to day-of-month over month or
Junio C Hamano's avatar
Junio C Hamano committed
565
	 * year numbers in the 1-12 range. So 05 is always "mday 5",
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
	 * unless we already have a mday..
	 *
	 * IOW, 01 Apr 05 parses as "April 1st, 2005".
	 */
	if (num > 0 && num < 32 && tm->tm_mday < 0) {
		tm->tm_mday = num;
		return n;
	}

	/* Two-digit year? */
	if (n == 2 && tm->tm_year < 0) {
		if (num < 10 && tm->tm_mday >= 0) {
			tm->tm_year = num + 100;
			return n;
		}
		if (num >= 70) {
			tm->tm_year = num;
			return n;
		}
	}

587
	if (num > 0 && num < 13 && tm->tm_mon < 0)
588
		tm->tm_mon = num-1;
Junio C Hamano's avatar
Junio C Hamano committed
589

590
	return n;
591
}
592

593
static int match_tz(const char *date, int *offp)
594 595
{
	char *end;
596 597 598
	int hour = strtoul(date + 1, &end, 10);
	int n = end - (date + 1);
	int min = 0;
599

600 601 602 603 604 605 606 607 608 609 610 611
	if (n == 4) {
		/* hhmm */
		min = hour % 100;
		hour = hour / 100;
	} else if (n != 2) {
		min = 99; /* random crap */
	} else if (*end == ':') {
		/* hh:mm? */
		min = strtoul(end + 1, &end, 10);
		if (end - (date + 1) != 5)
			min = 99; /* random crap */
	} /* otherwise we parsed "hh" */
612

613
	/*
614 615 616 617 618 619
	 * Don't accept any random crap. Even though some places have
	 * offset larger than 12 hours (e.g. Pacific/Kiritimati is at
	 * UTC+14), there is something wrong if hour part is much
	 * larger than that. We might also want to check that the
	 * minutes are divisible by 15 or something too. (Offset of
	 * Kathmandu, Nepal is UTC+5:45)
620
	 */
621 622
	if (min < 60 && hour < 24) {
		int offset = hour * 60 + min;
623 624 625 626
		if (*date == '-')
			offset = -offset;
		*offp = offset;
	}
627 628
	return end - date;
}
629

630
static void date_string(unsigned long date, int offset, struct strbuf *buf)
631 632 633 634 635 636 637
{
	int sign = '+';

	if (offset < 0) {
		offset = -offset;
		sign = '-';
	}
638
	strbuf_addf(buf, "%lu %c%02d%02d", date, sign, offset / 60, offset % 60);
639 640
}

641 642 643 644 645 646 647 648 649 650
/*
 * Parse a string like "0 +0000" as ancient timestamp near epoch, but
 * only when it appears not as part of any other string.
 */
static int match_object_header_date(const char *date, unsigned long *timestamp, int *offset)
{
	char *end;
	unsigned long stamp;
	int ofs;

651
	if (*date < '0' || '9' < *date)
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
		return -1;
	stamp = strtoul(date, &end, 10);
	if (*end != ' ' || stamp == ULONG_MAX || (end[1] != '+' && end[1] != '-'))
		return -1;
	date = end + 2;
	ofs = strtol(date, &end, 10);
	if ((*end != '\0' && (*end != '\n')) || end != date + 4)
		return -1;
	ofs = (ofs / 100) * 60 + (ofs % 100);
	if (date[-1] == '-')
		ofs = -ofs;
	*timestamp = stamp;
	*offset = ofs;
	return 0;
}

668 669
/* Gr. strptime is crap for this; it doesn't have a way to require RFC2822
   (i.e. English) day/month names, and it doesn't work correctly with %z. */
670
int parse_date_basic(const char *date, unsigned long *timestamp, int *offset)
671 672
{
	struct tm tm;
673 674 675 676 677 678 679 680
	int tm_gmt;
	unsigned long dummy_timestamp;
	int dummy_offset;

	if (!timestamp)
		timestamp = &dummy_timestamp;
	if (!offset)
		offset = &dummy_offset;
681

682 683 684 685
	memset(&tm, 0, sizeof(tm));
	tm.tm_year = -1;
	tm.tm_mon = -1;
	tm.tm_mday = -1;
686
	tm.tm_isdst = -1;
687 688 689
	tm.tm_hour = -1;
	tm.tm_min = -1;
	tm.tm_sec = -1;
690
	*offset = -1;
691
	tm_gmt = 0;
692

693 694
	if (*date == '@' &&
	    !match_object_header_date(date + 1, timestamp, offset))
695
		return 0; /* success */
696 697 698 699 700 701 702 703 704
	for (;;) {
		int match = 0;
		unsigned char c = *date;

		/* Stop at end of string or newline */
		if (!c || c == '\n')
			break;

		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 712 713

		if (!match) {
			/* BAD CRAP */
			match = 1;
Junio C Hamano's avatar
Junio C Hamano committed
714
		}
715 716 717

		date += match;
	}
718

719
	/* do not use mktime(), which uses local timezone, here */
720
	*timestamp = tm_to_time_t(&tm);
721 722 723
	if (*timestamp == -1)
		return -1;

724
	if (*offset == -1) {
725 726 727 728 729
		time_t temp_time;

		/* gmtime_r() in match_digit() may have clobbered it */
		tm.tm_isdst = -1;
		temp_time = mktime(&tm);
730 731 732 733 734 735
		if ((time_t)*timestamp > temp_time) {
			*offset = ((time_t)*timestamp - temp_time) / 60;
		} else {
			*offset = -(int)((temp_time - (time_t)*timestamp) / 60);
		}
	}
736

737
	if (!tm_gmt)
738
		*timestamp -= *offset * 60;
739
	return 0; /* success */
740 741
}

742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
int parse_expiry_date(const char *date, unsigned long *timestamp)
{
	int errors = 0;

	if (!strcmp(date, "never") || !strcmp(date, "false"))
		*timestamp = 0;
	else if (!strcmp(date, "all") || !strcmp(date, "now"))
		/*
		 * We take over "now" here, which usually translates
		 * to the current timestamp.  This is because the user
		 * really means to expire everything she has done in
		 * the past, and by definition reflogs are the record
		 * of the past, and there is nothing from the future
		 * to be kept.
		 */
		*timestamp = ULONG_MAX;
	else
		*timestamp = approxidate_careful(date, &errors);

	return errors;
}

764
int parse_date(const char *date, struct strbuf *result)
765 766 767
{
	unsigned long timestamp;
	int offset;
768
	if (parse_date_basic(date, &timestamp, &offset))
769
		return -1;
770 771
	date_string(timestamp, offset, result);
	return 0;
772 773
}

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
static enum date_mode_type parse_date_type(const char *format, const char **end)
{
	if (skip_prefix(format, "relative", end))
		return DATE_RELATIVE;
	if (skip_prefix(format, "iso8601-strict", end) ||
	    skip_prefix(format, "iso-strict", end))
		return DATE_ISO8601_STRICT;
	if (skip_prefix(format, "iso8601", end) ||
	    skip_prefix(format, "iso", end))
		return DATE_ISO8601;
	if (skip_prefix(format, "rfc2822", end) ||
	    skip_prefix(format, "rfc", end))
		return DATE_RFC2822;
	if (skip_prefix(format, "short", end))
		return DATE_SHORT;
	if (skip_prefix(format, "default", end))
		return DATE_NORMAL;
	if (skip_prefix(format, "raw", end))
		return DATE_RAW;
	if (skip_prefix(format, "format", end))
		return DATE_STRFTIME;

	die("unknown date format %s", format);
}

799
void parse_date_format(const char *format, struct date_mode *mode)
800
{
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
	const char *p;

	/* historical alias */
	if (!strcmp(format, "local"))
		format = "default-local";

	mode->type = parse_date_type(format, &p);
	mode->local = 0;

	if (skip_prefix(p, "-local", &p))
		mode->local = 1;

	if (mode->type == DATE_STRFTIME) {
		if (!skip_prefix(p, ":", &p))
			die("date format missing colon separator: %s", format);
		mode->strftime_fmt = xstrdup(p);
	} else if (*p)
818 819 820
		die("unknown date format %s", format);
}

821
void datestamp(struct strbuf *out)
822 823 824 825 826 827
{
	time_t now;
	int offset;

	time(&now);

828
	offset = tm_to_time_t(localtime(&now)) - now;
829 830
	offset /= 60;

831
	date_string(now, offset, out);
832
}
833

834 835 836 837 838
/*
 * Relative time update (eg "2 days ago").  If we haven't set the time
 * yet, we need to set it from current time.
 */
static unsigned long update_tm(struct tm *tm, struct tm *now, unsigned long sec)
839
{
840 841 842 843 844 845 846 847 848 849 850 851 852
	time_t n;

	if (tm->tm_mday < 0)
		tm->tm_mday = now->tm_mday;
	if (tm->tm_mon < 0)
		tm->tm_mon = now->tm_mon;
	if (tm->tm_year < 0) {
		tm->tm_year = now->tm_year;
		if (tm->tm_mon > now->tm_mon)
			tm->tm_year--;
	}

	n = mktime(tm) - sec;
853
	localtime_r(&n, tm);
854
	return n;
855 856
}

857 858 859 860 861
static void date_now(struct tm *tm, struct tm *now, int *num)
{
	update_tm(tm, now, 0);
}

862
static void date_yesterday(struct tm *tm, struct tm *now, int *num)
863
{
864
	update_tm(tm, now, 24*60*60);
865 866
}

867
static 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 872 873 874 875
	tm->tm_hour = hour;
	tm->tm_min = 0;
	tm->tm_sec = 0;
}

876
static void date_midnight(struct tm *tm, struct tm *now, int *num)
877
{
878
	date_time(tm, now, 0);
879 880
}

881
static void date_noon(struct tm *tm, struct tm *now, int *num)
882
{
883
	date_time(tm, now, 12);
884 885
}

886
static void date_tea(struct tm *tm, struct tm *now, int *num)
887
{
888
	date_time(tm, now, 17);
889 890
}

891
static void date_pm(struct tm *tm, struct tm *now, int *num)
892
{
893
	int hour, n = *num;
894 895
	*num = 0;

896 897 898
	hour = tm->tm_hour;
	if (n) {
		hour = n;
899 900 901
		tm->tm_min = 0;
		tm->tm_sec = 0;
	}
902
	tm->tm_hour = (hour % 12) + 12;
903 904
}

905
static void date_am(struct tm *tm, struct tm *now, int *num)
906
{
907
	int hour, n = *num;
908 909
	*num = 0;

910 911 912
	hour = tm->tm_hour;
	if (n) {
		hour = n;
913 914 915
		tm->tm_min = 0;
		tm->tm_sec = 0;
	}
916
	tm->tm_hour = (hour % 12);
917 918
}

919
static void date_never(struct tm *tm, struct tm *now, int *num)
920
{
921 922
	time_t n = 0;
	localtime_r(&n, tm);
923 924
}

925 926
static const struct special {
	const char *name;
927
	void (*fn)(struct tm *, struct tm *, int *);
928 929 930 931 932
} special[] = {
	{ "yesterday", date_yesterday },
	{ "noon", date_noon },
	{ "midnight", date_midnight },
	{ "tea", date_tea },
933 934
	{ "PM", date_pm },
	{ "AM", date_am },
935
	{ "never", date_never },
936
	{ "now", date_now },
937 938 939
	{ NULL }
};

940 941 942 943 944
static const char *number_name[] = {
	"zero", "one", "two", "three", "four",
	"five", "six", "seven", "eight", "nine", "ten",
};

945
static const struct typelen {
946 947 948 949 950 951 952 953 954
	const char *type;
	int length;
} typelen[] = {
	{ "seconds", 1 },
	{ "minutes", 60 },
	{ "hours", 60*60 },
	{ "days", 24*60*60 },
	{ "weeks", 7*24*60*60 },
	{ NULL }
Junio C Hamano's avatar
Junio C Hamano committed
955
};
956

957
static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm *now, int *num, int *touched)
958
{
959 960
	const struct typelen *tl;
	const struct special *s;
961
	const char *end = date;
962
	int i;
963

964
	while (isalpha(*++end))
965
		;
966 967 968 969 970

	for (i = 0; i < 12; i++) {
		int match = match_string(date, month_names[i]);
		if (match >= 3) {
			tm->tm_mon = i;
971
			*touched = 1;
972 973 974 975
			return end;
		}
	}

976 977 978
	for (s = special; s->name; s++) {
		int len = strlen(s->name);
		if (match_string(date, s->name) == len) {
979
			s->fn(tm, now, num);
980
			*touched = 1;
981 982
			return end;
		}
983 984 985 986 987 988 989
	}

	if (!*num) {
		for (i = 1; i < 11; i++) {
			int len = strlen(number_name[i]);
			if (match_string(date, number_name[i]) == len) {
				*num = i;
990
				*touched = 1;
991 992 993
				return end;
			}
		}
994
		if (match_string(date, "last") == 4) {
995
			*num = 1;
996 997
			*touched = 1;
		}
998 999 1000 1001 1002 1003 1004
		return end;
	}

	tl = typelen;
	while (tl->type) {
		int len = strlen(tl->type);
		if (match_string(date, tl->type) >= len-1) {
1005
			update_tm(tm, now, tl->length * *num);
1006
			*num = 0;
1007
			*touched = 1;
1008 1009 1010 1011 1012
			return end;
		}
		tl++;
	}

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	for (i = 0; i < 7; i++) {
		int match = match_string(date, weekday_names[i]);
		if (match >= 3) {
			int diff, n = *num -1;
			*num = 0;

			diff = tm->tm_wday - i;
			if (diff <= 0)
				n++;
			diff += 7*n;

1024
			update_tm(tm, now, diff * 24 * 60 * 60);
1025
			*touched = 1;
1026 1027 1028 1029
			return end;
		}
	}

1030
	if (match_string(date, "months") >= 5) {
1031 1032 1033
		int n;
		update_tm(tm, now, 0); /* fill in date fields if needed */
		n = tm->tm_mon - *num;
1034 1035 1036 1037 1038 1039
		*num = 0;
		while (n < 0) {
			n += 12;
			tm->tm_year--;
		}
		tm->tm_mon = n;
1040
		*touched = 1;
1041 1042 1043 1044
		return end;
	}

	if (match_string(date, "years") >= 4) {
1045
		update_tm(tm, now, 0); /* fill in date fields if needed */
1046 1047
		tm->tm_year -= *num;
		*num = 0;
1048
		*touched = 1;
1049 1050 1051 1052 1053 1054
		return end;
	}

	return end;
}

1055 1056
static const char *approxidate_digit(const char *date, struct tm *tm, int *num,
				     time_t now)
1057 1058 1059 1060
{
	char *end;
	unsigned long number = strtoul(date, &end, 10);

1061 1062 1063 1064 1065 1066
	switch (*end) {
	case ':':
	case '.':
	case '/':
	case '-':
		if (isdigit(end[1])) {
1067 1068
			int match = match_multi_number(number, *end, date, end,
						       tm, now);
1069 1070 1071 1072 1073
			if (match)
				return date + match;
		}
	}

1074 1075 1076
	/* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */
	if (date[0] != '0' || end - date <= 2)
		*num = number;
1077 1078 1079
	return end;
}

1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
/*
 * Do we have a pending number at the end, or when
 * we see a new one? Let's assume it's a month day,
 * as in "Dec 6, 1992"
 */
static void pending_number(struct tm *tm, int *num)
{
	int number = *num;

	if (number) {
		*num = 0;
		if (tm->tm_mday < 0 && number < 32)
			tm->tm_mday = number;
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
		else if (tm->tm_mon < 0 && number < 13)
			tm->tm_mon = number-1;
		else if (tm->tm_year < 0) {
			if (number > 1969 && number < 2100)
				tm->tm_year = number - 1900;
			else if (number > 69 && number < 100)
				tm->tm_year = number;
			else if (number < 38)
				tm->tm_year = 100 + number;
			/* We screw up for number = 00 ? */
		}
1104 1105 1106
	}
}

1107 1108 1109
static unsigned long approxidate_str(const char *date,
				     const struct timeval *tv,
				     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 1121 1122 1123

	tm.tm_year = -1;
	tm.tm_mon = -1;
	tm.tm_mday = -1;

1124 1125 1126 1127 1128 1129
	for (;;) {
		unsigned char c = *date;
		if (!c)
			break;
		date++;
		if (isdigit(c)) {
1130
			pending_number(&tm, &number);
1131
			date = approxidate_digit(date-1, &tm, &number, time_sec);
1132
			touched = 1;
1133 1134 1135
			continue;
		}
		if (isalpha(c))
1136
			date = approxidate_alpha(date-1, &tm, &now, &number, &touched);
1137
	}
1138
	pending_number(&tm, &number);
1139 1140
	if (!touched)
		*error_ret = 1;
1141
	return update_tm(&tm, &now, 0);
1142
}
1143 1144 1145

unsigned long approxidate_relative(const char *date, const struct timeval *tv)
{
1146 1147
	unsigned long timestamp;
	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
}

1155
unsigned long approxidate_careful(const char *date, int *error_ret)
1156 1157
{
	struct timeval tv;
1158 1159
	unsigned long timestamp;
	int offset;
1160 1161 1162
	int dummy = 0;
	if (!error_ret)
		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 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

int date_overflows(unsigned long t)
{
	time_t sys;

	/* If we overflowed our unsigned long, that's bad... */
	if (t == ULONG_MAX)
		return 1;

	/*
	 * ...but we also are going to feed the result to system
	 * functions that expect time_t, which is often "signed long".
	 * Make sure that we fit into time_t, as well.
	 */
	sys = t;
	return t != sys || (t < 1) != (sys < 1);
}