date.c 27.8 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
static time_t gm_time_t(timestamp_t time, int tz)
43 44 45 46 47 48
{
	int minutes;

	minutes = tz < 0 ? -tz : tz;
	minutes = (minutes / 100)*60 + (minutes % 100);
	minutes = tz < 0 ? -minutes : minutes;
49 50 51 52 53 54 55 56 57 58 59

	if (minutes > 0) {
		if (unsigned_add_overflows(time, minutes * 60))
			die("Timestamp+tz too large: %"PRItime" +%04d",
			    time, tz);
	} else if (time < -minutes * 60)
		die("Timestamp before Unix epoch: %"PRItime" %04d", time, tz);
	time += minutes * 60;
	if (date_overflows(time))
		die("Timestamp too large for this system: %"PRItime, time);
	return (time_t)time;
60 61
}

62 63 64 65 66
/*
 * 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"
 */
67
static struct tm *time_to_tm(timestamp_t time, int tz)
68
{
69
	time_t t = gm_time_t(time, tz);
70 71 72
	return gmtime(&t);
}

73
static struct tm *time_to_tm_local(timestamp_t time)
74 75 76 77 78
{
	time_t t = time;
	return localtime(&t);
}

79 80 81 82
/*
 * What value of "tz" was in effect back then at "time" in the
 * local timezone?
 */
83
static int local_tzoffset(timestamp_t time)
84 85 86 87 88
{
	time_t t, t_local;
	struct tm tm;
	int offset, eastwest;

89 90 91 92
	if (date_overflows(time))
		die("Timestamp too large for this system: %"PRItime, time);

	t = (time_t)time;
93
	localtime_r(&t, &tm);
94
	t_local = tm_to_time_t(&tm);
95

96 97
	if (t_local == -1)
		return 0; /* error; just use +0000 */
98 99 100 101 102 103 104 105 106 107 108 109
	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;
}

110
void show_date_relative(timestamp_t time, int tz,
111
			       const struct timeval *now,
112
			       struct strbuf *timebuf)
113
{
114
	timestamp_t diff;
115 116 117 118
	if (now->tv_sec < time) {
		strbuf_addstr(timebuf, _("in the future"));
		return;
	}
119 120
	diff = now->tv_sec - time;
	if (diff < 90) {
121
		strbuf_addf(timebuf,
122
			 Q_("%"PRItime" second ago", "%"PRItime" seconds ago", diff), diff);
123
		return;
124 125 126 127
	}
	/* Turn it into minutes */
	diff = (diff + 30) / 60;
	if (diff < 90) {
128
		strbuf_addf(timebuf,
129
			 Q_("%"PRItime" minute ago", "%"PRItime" minutes ago", diff), diff);
130
		return;
131 132 133 134
	}
	/* Turn it into hours */
	diff = (diff + 30) / 60;
	if (diff < 36) {
135
		strbuf_addf(timebuf,
136
			 Q_("%"PRItime" hour ago", "%"PRItime" hours ago", diff), diff);
137
		return;
138 139 140 141
	}
	/* We deal with number of days from here on */
	diff = (diff + 12) / 24;
	if (diff < 14) {
142
		strbuf_addf(timebuf,
143
			 Q_("%"PRItime" day ago", "%"PRItime" days ago", diff), diff);
144
		return;
145 146 147
	}
	/* Say weeks for the past 10 weeks or so */
	if (diff < 70) {
148
		strbuf_addf(timebuf,
149
			 Q_("%"PRItime" week ago", "%"PRItime" weeks ago", (diff + 3) / 7),
150 151
			 (diff + 3) / 7);
		return;
152 153
	}
	/* Say months for the past 12 months or so */
Johan Sageryd's avatar
Johan Sageryd committed
154
	if (diff < 365) {
155
		strbuf_addf(timebuf,
156
			 Q_("%"PRItime" month ago", "%"PRItime" months ago", (diff + 15) / 30),
157 158
			 (diff + 15) / 30);
		return;
159 160 161
	}
	/* Give years and months for 5 years or so */
	if (diff < 1825) {
162 163 164
		timestamp_t totalmonths = (diff * 12 * 2 + 365) / (365 * 2);
		timestamp_t years = totalmonths / 12;
		timestamp_t months = totalmonths % 12;
165 166
		if (months) {
			struct strbuf sb = STRBUF_INIT;
167
			strbuf_addf(&sb, Q_("%"PRItime" year", "%"PRItime" years", years), years);
168
			strbuf_addf(timebuf,
169
				 /* TRANSLATORS: "%s" is "<n> years" */
170
				 Q_("%s, %"PRItime" month ago", "%s, %"PRItime" months ago", months),
171 172 173 174
				 sb.buf, months);
			strbuf_release(&sb);
		} else
			strbuf_addf(timebuf,
175
				 Q_("%"PRItime" year ago", "%"PRItime" years ago", years), years);
176
		return;
177 178
	}
	/* Otherwise, just years. Centuries is probably overkill. */
179
	strbuf_addf(timebuf,
180
		 Q_("%"PRItime" year ago", "%"PRItime" years ago", (diff + 183) / 365),
181
		 (diff + 183) / 365);
182 183
}

184 185 186
struct date_mode *date_mode_from_type(enum date_mode_type type)
{
	static struct date_mode mode;
Jeff King's avatar
Jeff King committed
187
	if (type == DATE_STRFTIME)
188
		BUG("cannot create anonymous strftime date_mode struct");
189
	mode.type = type;
190
	mode.local = 0;
191 192 193
	return &mode;
}

194
const char *show_date(timestamp_t time, int tz, const struct date_mode *mode)
195 196
{
	struct tm *tm;
197
	static struct strbuf timebuf = STRBUF_INIT;
198

Jeff King's avatar
Jeff King committed
199 200
	if (mode->type == DATE_UNIX) {
		strbuf_reset(&timebuf);
201
		strbuf_addf(&timebuf, "%"PRItime, time);
Jeff King's avatar
Jeff King committed
202 203 204
		return timebuf.buf;
	}

205
	if (mode->local)
206 207
		tz = local_tzoffset(time);

208
	if (mode->type == DATE_RAW) {
209
		strbuf_reset(&timebuf);
210
		strbuf_addf(&timebuf, "%"PRItime" %+05d", time, tz);
211
		return timebuf.buf;
Linus Torvalds's avatar
Linus Torvalds committed
212 213
	}

214
	if (mode->type == DATE_RELATIVE) {
215
		struct timeval now;
216 217

		strbuf_reset(&timebuf);
218
		gettimeofday(&now, NULL);
219 220
		show_date_relative(time, tz, &now, &timebuf);
		return timebuf.buf;
221 222
	}

223 224 225 226
	if (mode->local)
		tm = time_to_tm_local(time);
	else
		tm = time_to_tm(time, tz);
227 228 229 230
	if (!tm) {
		tm = time_to_tm(0, 0);
		tz = 0;
	}
231 232

	strbuf_reset(&timebuf);
233
	if (mode->type == DATE_SHORT)
234
		strbuf_addf(&timebuf, "%04d-%02d-%02d", tm->tm_year + 1900,
235
				tm->tm_mon + 1, tm->tm_mday);
236
	else if (mode->type == DATE_ISO8601)
237
		strbuf_addf(&timebuf, "%04d-%02d-%02d %02d:%02d:%02d %+05d",
238 239 240 241 242
				tm->tm_year + 1900,
				tm->tm_mon + 1,
				tm->tm_mday,
				tm->tm_hour, tm->tm_min, tm->tm_sec,
				tz);
243
	else if (mode->type == DATE_ISO8601_STRICT) {
244 245 246 247 248 249 250 251
		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);
252
	} else if (mode->type == DATE_RFC2822)
253
		strbuf_addf(&timebuf, "%.3s, %d %.3s %d %02d:%02d:%02d %+05d",
254 255 256
			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
257
	else if (mode->type == DATE_STRFTIME)
258
		strbuf_addftime(&timebuf, mode->strftime_fmt, tm, tz,
259
				!mode->local);
260
	else
261
		strbuf_addf(&timebuf, "%.3s %.3s %d %02d:%02d:%02d %d%c%+05d",
262 263 264 265
				weekday_names[tm->tm_wday],
				month_names[tm->tm_mon],
				tm->tm_mday,
				tm->tm_hour, tm->tm_min, tm->tm_sec,
266
				tm->tm_year + 1900,
267
				mode->local ? 0 : ' ',
268
				tz);
269
	return timebuf.buf;
270 271
}

272 273 274 275 276 277 278 279 280
/*
 * 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;
281
	int dst;
282
} timezone_names[] = {
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	{ "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) */
304
	{ "Z",      0, 0, },    /* Zulu, alias for UTC */
305 306 307 308 309 310 311 312 313 314 315 316

	{ "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 */
317
	{ "EEST",  +2, 1, },	/* Eastern European Daylight */
318 319 320 321 322 323 324
	{ "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 */
325 326 327
	{ "NZT",  +12, 0, },	/* New Zealand */
	{ "NZST", +12, 0, },	/* New Zealand Standard */
	{ "NZDT", +12, 1, },	/* New Zealand Daylight */
328
	{ "IDLE", +12, 0, },	/* International Date Line East */
329
};
330

331
static int match_string(const char *date, const char *str)
332
{
333 334 335 336 337 338 339 340 341 342 343 344
	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;
345 346
}

347 348 349 350 351 352 353 354 355
static int skip_alpha(const char *date)
{
	int i = 0;
	do {
		i++;
	} while (isalpha(date[i]));
	return i;
}

356 357 358 359
/*
* Parse month, weekday, or timezone name
*/
static int match_alpha(const char *date, struct tm *tm, int *offset)
360
{
361
	int i;
362

363 364 365 366 367
	for (i = 0; i < 12; i++) {
		int match = match_string(date, month_names[i]);
		if (match >= 3) {
			tm->tm_mon = i;
			return match;
368
		}
369
	}
370

371 372 373 374 375 376 377
	for (i = 0; i < 7; i++) {
		int match = match_string(date, weekday_names[i]);
		if (match >= 3) {
			tm->tm_wday = i;
			return match;
		}
	}
378

379
	for (i = 0; i < ARRAY_SIZE(timezone_names); i++) {
380
		int match = match_string(date, timezone_names[i].name);
381
		if (match >= 3 || match == strlen(timezone_names[i].name)) {
382 383 384 385 386
			int off = timezone_names[i].offset;

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

387 388 389 390
			/* Only use the tz name offset if we don't have anything better */
			if (*offset == -1)
				*offset = 60*off;

391
			return match;
392 393 394
		}
	}

395
	if (match_string(date, "PM") == 2) {
396 397 398 399 400 401
		tm->tm_hour = (tm->tm_hour % 12) + 12;
		return 2;
	}

	if (match_string(date, "AM") == 2) {
		tm->tm_hour = (tm->tm_hour % 12) + 0;
402 403 404
		return 2;
	}

405
	/* BAD CRAP */
406
	return skip_alpha(date);
407
}
408

409
static int is_date(int year, int month, int day, struct tm *now_tm, time_t now, struct tm *tm)
410
{
411
	if (month > 0 && month < 13 && day > 0 && day < 32) {
412 413 414 415 416 417
		struct tm check = *tm;
		struct tm *r = (now_tm ? &check : tm);
		time_t specified;

		r->tm_mon = month - 1;
		r->tm_mday = day;
418
		if (year == -1) {
419 420 421
			if (!now_tm)
				return 1;
			r->tm_year = now_tm->tm_year;
422
		}
423 424 425 426 427 428 429
		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
430
			return 0;
431 432 433
		if (!now_tm)
			return 1;

434
		specified = tm_to_time_t(r);
435

436 437 438 439
		/* 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...
		 */
440
		if ((specified != -1) && (now + 10*24*3600 < specified))
441 442 443 444 445
			return 0;
		tm->tm_mon = r->tm_mon;
		tm->tm_mday = r->tm_mday;
		if (year != -1)
			tm->tm_year = r->tm_year;
446
		return 1;
447
	}
448 449
	return 0;
}
450

451
static int match_multi_number(timestamp_t num, char c, const char *date,
452
			      char *end, struct tm *tm, time_t now)
453
{
454 455
	struct tm now_tm;
	struct tm *refuse_future;
456 457 458 459 460 461 462 463
	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? */
464
	switch (c) {
465 466 467 468 469 470 471
	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;
472 473
			break;
		}
474
		return 0;
475 476 477

	case '-':
	case '/':
478
	case '.':
479 480
		if (!now)
			now = time(NULL);
481 482 483 484
		refuse_future = NULL;
		if (gmtime_r(&now, &now_tm))
			refuse_future = &now_tm;

485 486
		if (num > 70) {
			/* yyyy-mm-dd? */
487
			if (is_date(num, num2, num3, NULL, now, tm))
488 489
				break;
			/* yyyy-dd-mm? */
490
			if (is_date(num, num3, num2, NULL, now, tm))
491
				break;
492
		}
493 494 495 496 497 498 499 500 501
		/* 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))
502
			break;
503 504 505
		/* Funny European mm.dd.yy */
		if (c == '.' &&
		    is_date(num3, num, num2, refuse_future, now, tm))
506 507 508 509 510 511
			break;
		return 0;
	}
	return end - date;
}

512 513 514 515 516
/*
 * 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.
 */
517 518
static inline int nodate(struct tm *tm)
{
519 520 521 522 523 524
	return (tm->tm_year &
		tm->tm_mon &
		tm->tm_mday &
		tm->tm_hour &
		tm->tm_min &
		tm->tm_sec) < 0;
525 526
}

527
/*
Junio C Hamano's avatar
Junio C Hamano committed
528
 * We've seen a digit. Time? Year? Date?
529
 */
530
static int match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt)
531 532 533
{
	int n;
	char *end;
534
	timestamp_t num;
535

536
	num = parse_timestamp(date, &end, 10);
537 538

	/*
539 540 541
	 * 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.
542
	 */
543
	if (num >= 100000000 && nodate(tm)) {
544
		time_t time = num;
545 546
		if (gmtime_r(&time, tm)) {
			*tm_gmt = 1;
547
			return end - date;
548
		}
549 550 551
	}

	/*
552
	 * Check for special formats: num[-.:/]num[same]num
553 554 555
	 */
	switch (*end) {
	case ':':
556
	case '.':
557 558 559
	case '/':
	case '-':
		if (isdigit(end[1])) {
560
			int match = match_multi_number(num, *end, date, end, tm, 0);
561 562
			if (match)
				return match;
563 564
		}
	}
565 566 567 568 569 570 571 572 573 574 575 576 577

	/*
	 * 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) {
578
		if (num <= 1400 && *offset == -1) {
579 580 581 582 583 584 585 586
			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;
	}

587 588 589 590 591 592 593
	/*
	 * 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;

594 595
	/*
	 * NOTE! We will give precedence to day-of-month over month or
Junio C Hamano's avatar
Junio C Hamano committed
596
	 * year numbers in the 1-12 range. So 05 is always "mday 5",
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
	 * 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;
		}
	}

Linus Torvalds's avatar
Linus Torvalds committed
618
	if (num > 0 && num < 13 && tm->tm_mon < 0)
619
		tm->tm_mon = num-1;
Junio C Hamano's avatar
Junio C Hamano committed
620

621
	return n;
622
}
623

624
static int match_tz(const char *date, int *offp)
625 626
{
	char *end;
627 628 629
	int hour = strtoul(date + 1, &end, 10);
	int n = end - (date + 1);
	int min = 0;
630

631 632 633 634 635 636 637 638 639 640 641 642
	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" */
643

644
	/*
645 646 647 648 649 650
	 * 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)
651
	 */
652 653
	if (min < 60 && hour < 24) {
		int offset = hour * 60 + min;
654 655 656 657
		if (*date == '-')
			offset = -offset;
		*offp = offset;
	}
658 659
	return end - date;
}
660

661
static void date_string(timestamp_t date, int offset, struct strbuf *buf)
662 663 664 665 666 667 668
{
	int sign = '+';

	if (offset < 0) {
		offset = -offset;
		sign = '-';
	}
669
	strbuf_addf(buf, "%"PRItime" %c%02d%02d", date, sign, offset / 60, offset % 60);
670 671
}

672 673 674 675
/*
 * Parse a string like "0 +0000" as ancient timestamp near epoch, but
 * only when it appears not as part of any other string.
 */
676
static int match_object_header_date(const char *date, timestamp_t *timestamp, int *offset)
677 678
{
	char *end;
679
	timestamp_t stamp;
680 681
	int ofs;

682
	if (*date < '0' || '9' < *date)
683
		return -1;
684
	stamp = parse_timestamp(date, &end, 10);
685
	if (*end != ' ' || stamp == TIME_MAX || (end[1] != '+' && end[1] != '-'))
686 687 688 689 690 691 692 693 694 695 696 697 698
		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;
}

699 700
/* 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. */
701
int parse_date_basic(const char *date, timestamp_t *timestamp, int *offset)
702 703
{
	struct tm tm;
704
	int tm_gmt;
705
	timestamp_t dummy_timestamp;
706 707 708 709 710 711
	int dummy_offset;

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

713 714 715 716
	memset(&tm, 0, sizeof(tm));
	tm.tm_year = -1;
	tm.tm_mon = -1;
	tm.tm_mday = -1;
717
	tm.tm_isdst = -1;
718 719 720
	tm.tm_hour = -1;
	tm.tm_min = -1;
	tm.tm_sec = -1;
721
	*offset = -1;
722
	tm_gmt = 0;
723

724 725
	if (*date == '@' &&
	    !match_object_header_date(date + 1, timestamp, offset))
726
		return 0; /* success */
727 728 729 730 731 732 733 734 735
	for (;;) {
		int match = 0;
		unsigned char c = *date;

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

		if (isalpha(c))
736
			match = match_alpha(date, &tm, offset);
737
		else if (isdigit(c))
738
			match = match_digit(date, &tm, offset, &tm_gmt);
739
		else if ((c == '-' || c == '+') && isdigit(date[1]))
740
			match = match_tz(date, offset);
741 742 743 744

		if (!match) {
			/* BAD CRAP */
			match = 1;
Junio C Hamano's avatar
Junio C Hamano committed
745
		}
746 747 748

		date += match;
	}
749

750
	/* do not use mktime(), which uses local timezone, here */
751
	*timestamp = tm_to_time_t(&tm);
752 753 754
	if (*timestamp == -1)
		return -1;

755
	if (*offset == -1) {
756 757 758 759 760
		time_t temp_time;

		/* gmtime_r() in match_digit() may have clobbered it */
		tm.tm_isdst = -1;
		temp_time = mktime(&tm);
761 762 763 764 765 766
		if ((time_t)*timestamp > temp_time) {
			*offset = ((time_t)*timestamp - temp_time) / 60;
		} else {
			*offset = -(int)((temp_time - (time_t)*timestamp) / 60);
		}
	}
767

768
	if (!tm_gmt)
769
		*timestamp -= *offset * 60;
770
	return 0; /* success */
771 772
}

773
int parse_expiry_date(const char *date, timestamp_t *timestamp)
774 775 776 777 778 779 780 781 782 783 784 785 786 787
{
	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.
		 */
788
		*timestamp = TIME_MAX;
789 790 791 792 793 794
	else
		*timestamp = approxidate_careful(date, &errors);

	return errors;
}

795
int parse_date(const char *date, struct strbuf *result)
796
{
797
	timestamp_t timestamp;
798
	int offset;
799
	if (parse_date_basic(date, &timestamp, &offset))
800
		return -1;
801 802
	date_string(timestamp, offset, result);
	return 0;
803 804
}

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
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;
Jeff King's avatar
Jeff King committed
824 825
	if (skip_prefix(format, "unix", end))
		return DATE_UNIX;
826 827 828 829 830 831
	if (skip_prefix(format, "format", end))
		return DATE_STRFTIME;

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

832
void parse_date_format(const char *format, struct date_mode *mode)
833
{
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
	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)
851 852 853
		die("unknown date format %s", format);
}

854
void datestamp(struct strbuf *out)
855 856 857 858 859 860
{
	time_t now;
	int offset;

	time(&now);

861
	offset = tm_to_time_t(localtime(&now)) - now;
862 863
	offset /= 60;

864
	date_string(now, offset, out);
865
}
866

Linus Torvalds's avatar
Linus Torvalds committed
867 868 869 870
/*
 * Relative time update (eg "2 days ago").  If we haven't set the time
 * yet, we need to set it from current time.
 */
871
static time_t update_tm(struct tm *tm, struct tm *now, time_t sec)
872
{
Linus Torvalds's avatar
Linus Torvalds committed
873 874 875 876 877 878 879 880 881 882 883 884 885
	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;
886
	localtime_r(&n, tm);
Linus Torvalds's avatar
Linus Torvalds committed
887
	return n;
888 889
}

890 891 892 893 894
static void date_now(struct tm *tm, struct tm *now, int *num)
{
	update_tm(tm, now, 0);
}

Linus Torvalds's avatar
Linus Torvalds committed
895
static void date_yesterday(struct tm *tm, struct tm *now, int *num)
896
{
Linus Torvalds's avatar
Linus Torvalds committed
897
	update_tm(tm, now, 24*60*60);
898 899
}

Linus Torvalds's avatar
Linus Torvalds committed
900
static void date_time(struct tm *tm, struct tm *now, int hour)
901 902
{
	if (tm->tm_hour < hour)
Linus Torvalds's avatar
Linus Torvalds committed
903
		date_yesterday(tm, now, NULL);
904 905 906 907 908
	tm->tm_hour = hour;
	tm->tm_min = 0;
	tm->tm_sec = 0;
}

Linus Torvalds's avatar
Linus Torvalds committed
909
static void date_midnight(struct tm *tm, struct tm *now, int *num)
910
{
Linus Torvalds's avatar
Linus Torvalds committed
911
	date_time(tm, now, 0);
912 913
}

Linus Torvalds's avatar
Linus Torvalds committed
914
static void date_noon(struct tm *tm, struct tm *now, int *num)
915
{
Linus Torvalds's avatar
Linus Torvalds committed
916
	date_time(tm, now, 12);
917 918
}

Linus Torvalds's avatar
Linus Torvalds committed
919
static void date_tea(struct tm *tm, struct tm *now, int *num)
920
{
Linus Torvalds's avatar
Linus Torvalds committed
921
	date_time(tm, now, 17);
922 923
}

Linus Torvalds's avatar
Linus Torvalds committed
924
static void date_pm(struct tm *tm, struct tm *now, int *num)
925
{
926
	int hour, n = *num;
927 928
	*num = 0;

929 930 931
	hour = tm->tm_hour;
	if (n) {
		hour = n;
932 933 934
		tm->tm_min = 0;
		tm->tm_sec = 0;
	}
935
	tm->tm_hour = (hour % 12) + 12;
936 937
}

Linus Torvalds's avatar
Linus Torvalds committed
938
static void date_am(struct tm *tm, struct tm *now, int *num)
939
{
940
	int hour, n = *num;
941 942
	*num = 0;

943 944 945
	hour = tm->tm_hour;
	if (n) {
		hour = n;
946 947 948
		tm->tm_min = 0;
		tm->tm_sec = 0;
	}
949
	tm->tm_hour = (hour % 12);
950 951
}

Linus Torvalds's avatar
Linus Torvalds committed
952
static void date_never(struct tm *tm, struct tm *now, int *num)
953
{
954 955
	time_t n = 0;
	localtime_r(&n, tm);
956 957
}

958 959
static const struct special {
	const char *name;
Linus Torvalds's avatar
Linus Torvalds committed
960
	void (*fn)(struct tm *, struct tm *, int *);
961 962 963 964 965
} special[] = {
	{ "yesterday", date_yesterday },
	{ "noon", date_noon },
	{ "midnight", date_midnight },
	{ "tea", date_tea },
966 967
	{ "PM", date_pm },
	{ "AM", date_am },
968
	{ "never", date_never },
969
	{ "now", date_now },
970 971 972
	{ NULL }
};

973 974 975 976 977
static const char *number_name[] = {
	"zero", "one", "two", "three", "four",
	"five", "six", "seven", "eight", "nine", "ten",
};

978
static const struct typelen {
979 980 981 982 983 984 985 986 987
	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
988
};
989

990
static const char *approxidate_alpha(const char *date, struct tm *tm, struct tm *now, int *num, int *touched)
991
{
992 993
	const struct typelen *tl;
	const struct special *s;
994
	const char *end = date;
995
	int i;
996

997
	while (isalpha(*++end))
998
		;
999 1000 1001 1002 1003

	for (i = 0; i < 12; i++) {
		int match = match_string(date, month_names[i]);
		if (match >= 3) {
			tm->tm_mon = i;
1004
			*touched = 1;
1005 1006 1007 1008
			return end;
		}
	}

1009 1010 1011
	for (s = special; s->name; s++) {
		int len = strlen(s->name);
		if (match_string(date, s->name) == len) {
Linus Torvalds's avatar
Linus Torvalds committed
1012
			s->fn(tm, now, num);
1013
			*touched = 1;
1014 1015
			return end;
		}
1016 1017 1018 1019 1020 1021 1022
	}

	if (!*num) {
		for (i = 1; i < 11; i++) {
			int len = strlen(number_name[i]);
			if (match_string(date, number_name[i]) == len) {
				*num = i;
1023
				*touched = 1;
1024 1025 1026
				return end;
			}
		}
1027
		if (match_string(date, "last") == 4) {
1028
			*num = 1;
1029 1030
			*touched = 1;
		}
1031 1032 1033 1034 1035 1036 1037
		return end;
	}

	tl = typelen;
	while (tl->type) {
		int len = strlen(tl->type);
		if (match_string(date, tl->type) >= len-1) {
Linus Torvalds's avatar
Linus Torvalds committed
1038
			update_tm(tm, now, tl->length * *num);
1039
			*num = 0;
1040
			*touched = 1;
1041 1042 1043 1044 1045
			return end;
		}
		tl++;
	}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
	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;

Linus Torvalds's avatar
Linus Torvalds committed
1057
			update_tm(tm, now, diff * 24 * 60 * 60);
1058
			*touched = 1;
1059 1060 1061 1062
			return end;
		}
	}

1063
	if (match_string(date, "months") >= 5) {
1064 1065 1066
		int n;
		update_tm(tm, now, 0); /* fill in date fields if needed */
		n = tm->tm_mon - *num;
1067 1068 1069 1070 1071 1072
		*num = 0;
		while (n < 0) {
			n += 12;
			tm->tm_year--;
		}
		tm->tm_mon = n;
1073
		*touched = 1;
1074 1075 1076 1077
		return end;
	}

	if (match_string(date, "years") >= 4) {
1078
		update_tm(tm, now, 0); /* fill in date fields if needed */
1079 1080
		tm->tm_year -= *num;
		*num = 0;
1081
		*touched = 1;
1082 1083 1084