git

Форк
0
/
blame.c 
1235 строк · 34.0 Кб
1
/*
2
 * Blame
3
 *
4
 * Copyright (c) 2006, 2014 by its authors
5
 * See COPYING for licensing conditions
6
 */
7

8
#include "builtin.h"
9
#include "config.h"
10
#include "color.h"
11
#include "builtin.h"
12
#include "environment.h"
13
#include "gettext.h"
14
#include "hex.h"
15
#include "repository.h"
16
#include "commit.h"
17
#include "diff.h"
18
#include "revision.h"
19
#include "quote.h"
20
#include "string-list.h"
21
#include "mailmap.h"
22
#include "parse-options.h"
23
#include "prio-queue.h"
24
#include "utf8.h"
25
#include "userdiff.h"
26
#include "line-range.h"
27
#include "line-log.h"
28
#include "progress.h"
29
#include "object-name.h"
30
#include "object-store-ll.h"
31
#include "pager.h"
32
#include "blame.h"
33
#include "refs.h"
34
#include "setup.h"
35
#include "tag.h"
36
#include "write-or-die.h"
37

38
static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
39
static char annotate_usage[] = N_("git annotate [<options>] [<rev-opts>] [<rev>] [--] <file>");
40

41
static const char *blame_opt_usage[] = {
42
	blame_usage,
43
	"",
44
	N_("<rev-opts> are documented in git-rev-list(1)"),
45
	NULL
46
};
47

48
static const char *annotate_opt_usage[] = {
49
	annotate_usage,
50
	"",
51
	N_("<rev-opts> are documented in git-rev-list(1)"),
52
	NULL
53
};
54

55
static int longest_file;
56
static int longest_author;
57
static int max_orig_digits;
58
static int max_digits;
59
static int max_score_digits;
60
static int show_root;
61
static int reverse;
62
static int blank_boundary;
63
static int incremental;
64
static int xdl_opts;
65
static int abbrev = -1;
66
static int no_whole_file_rename;
67
static int show_progress;
68
static char repeated_meta_color[COLOR_MAXLEN];
69
static int coloring_mode;
70
static struct string_list ignore_revs_file_list = STRING_LIST_INIT_DUP;
71
static int mark_unblamable_lines;
72
static int mark_ignored_lines;
73

74
static struct date_mode blame_date_mode = { DATE_ISO8601 };
75
static size_t blame_date_width;
76

77
static struct string_list mailmap = STRING_LIST_INIT_NODUP;
78

79
#ifndef DEBUG_BLAME
80
#define DEBUG_BLAME 0
81
#endif
82

83
static unsigned blame_move_score;
84
static unsigned blame_copy_score;
85

86
/* Remember to update object flag allocation in object.h */
87
#define METAINFO_SHOWN		(1u<<12)
88
#define MORE_THAN_ONE_PATH	(1u<<13)
89

90
struct progress_info {
91
	struct progress *progress;
92
	int blamed_lines;
93
};
94

95
static const char *nth_line_cb(void *data, long lno)
96
{
97
	return blame_nth_line((struct blame_scoreboard *)data, lno);
98
}
99

100
/*
101
 * Information on commits, used for output.
102
 */
103
struct commit_info {
104
	struct strbuf author;
105
	struct strbuf author_mail;
106
	timestamp_t author_time;
107
	struct strbuf author_tz;
108

109
	/* filled only when asked for details */
110
	struct strbuf committer;
111
	struct strbuf committer_mail;
112
	timestamp_t committer_time;
113
	struct strbuf committer_tz;
114

115
	struct strbuf summary;
116
};
117

118
#define COMMIT_INFO_INIT { \
119
	.author = STRBUF_INIT, \
120
	.author_mail = STRBUF_INIT, \
121
	.author_tz = STRBUF_INIT, \
122
	.committer = STRBUF_INIT, \
123
	.committer_mail = STRBUF_INIT, \
124
	.committer_tz = STRBUF_INIT, \
125
	.summary = STRBUF_INIT, \
126
}
127

128
/*
129
 * Parse author/committer line in the commit object buffer
130
 */
131
static void get_ac_line(const char *inbuf, const char *what,
132
	struct strbuf *name, struct strbuf *mail,
133
	timestamp_t *time, struct strbuf *tz)
134
{
135
	struct ident_split ident;
136
	size_t len, maillen, namelen;
137
	const char *tmp, *endp;
138
	const char *namebuf, *mailbuf;
139

140
	tmp = strstr(inbuf, what);
141
	if (!tmp)
142
		goto error_out;
143
	tmp += strlen(what);
144
	endp = strchr(tmp, '\n');
145
	if (!endp)
146
		len = strlen(tmp);
147
	else
148
		len = endp - tmp;
149

150
	if (split_ident_line(&ident, tmp, len)) {
151
	error_out:
152
		/* Ugh */
153
		tmp = "(unknown)";
154
		strbuf_addstr(name, tmp);
155
		strbuf_addstr(mail, tmp);
156
		strbuf_addstr(tz, tmp);
157
		*time = 0;
158
		return;
159
	}
160

161
	namelen = ident.name_end - ident.name_begin;
162
	namebuf = ident.name_begin;
163

164
	maillen = ident.mail_end - ident.mail_begin;
165
	mailbuf = ident.mail_begin;
166

167
	if (ident.date_begin && ident.date_end)
168
		*time = strtoul(ident.date_begin, NULL, 10);
169
	else
170
		*time = 0;
171

172
	if (ident.tz_begin && ident.tz_end)
173
		strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
174
	else
175
		strbuf_addstr(tz, "(unknown)");
176

177
	/*
178
	 * Now, convert both name and e-mail using mailmap
179
	 */
180
	map_user(&mailmap, &mailbuf, &maillen,
181
		 &namebuf, &namelen);
182

183
	strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
184
	strbuf_add(name, namebuf, namelen);
185
}
186

187
static void commit_info_destroy(struct commit_info *ci)
188
{
189

190
	strbuf_release(&ci->author);
191
	strbuf_release(&ci->author_mail);
192
	strbuf_release(&ci->author_tz);
193
	strbuf_release(&ci->committer);
194
	strbuf_release(&ci->committer_mail);
195
	strbuf_release(&ci->committer_tz);
196
	strbuf_release(&ci->summary);
197
}
198

199
static void get_commit_info(struct commit *commit,
200
			    struct commit_info *ret,
201
			    int detailed)
202
{
203
	int len;
204
	const char *subject, *encoding;
205
	const char *message;
206

207
	encoding = get_log_output_encoding();
208
	message = repo_logmsg_reencode(the_repository, commit, NULL, encoding);
209
	get_ac_line(message, "\nauthor ",
210
		    &ret->author, &ret->author_mail,
211
		    &ret->author_time, &ret->author_tz);
212

213
	if (!detailed) {
214
		repo_unuse_commit_buffer(the_repository, commit, message);
215
		return;
216
	}
217

218
	get_ac_line(message, "\ncommitter ",
219
		    &ret->committer, &ret->committer_mail,
220
		    &ret->committer_time, &ret->committer_tz);
221

222
	len = find_commit_subject(message, &subject);
223
	if (len)
224
		strbuf_add(&ret->summary, subject, len);
225
	else
226
		strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
227

228
	repo_unuse_commit_buffer(the_repository, commit, message);
229
}
230

231
/*
232
 * Write out any suspect information which depends on the path. This must be
233
 * handled separately from emit_one_suspect_detail(), because a given commit
234
 * may have changes in multiple paths. So this needs to appear each time
235
 * we mention a new group.
236
 *
237
 * To allow LF and other nonportable characters in pathnames,
238
 * they are c-style quoted as needed.
239
 */
240
static void write_filename_info(struct blame_origin *suspect)
241
{
242
	if (suspect->previous) {
243
		struct blame_origin *prev = suspect->previous;
244
		printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
245
		write_name_quoted(prev->path, stdout, '\n');
246
	}
247
	printf("filename ");
248
	write_name_quoted(suspect->path, stdout, '\n');
249
}
250

251
/*
252
 * Porcelain/Incremental format wants to show a lot of details per
253
 * commit.  Instead of repeating this every line, emit it only once,
254
 * the first time each commit appears in the output (unless the
255
 * user has specifically asked for us to repeat).
256
 */
257
static int emit_one_suspect_detail(struct blame_origin *suspect, int repeat)
258
{
259
	struct commit_info ci = COMMIT_INFO_INIT;
260

261
	if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
262
		return 0;
263

264
	suspect->commit->object.flags |= METAINFO_SHOWN;
265
	get_commit_info(suspect->commit, &ci, 1);
266
	printf("author %s\n", ci.author.buf);
267
	printf("author-mail %s\n", ci.author_mail.buf);
268
	printf("author-time %"PRItime"\n", ci.author_time);
269
	printf("author-tz %s\n", ci.author_tz.buf);
270
	printf("committer %s\n", ci.committer.buf);
271
	printf("committer-mail %s\n", ci.committer_mail.buf);
272
	printf("committer-time %"PRItime"\n", ci.committer_time);
273
	printf("committer-tz %s\n", ci.committer_tz.buf);
274
	printf("summary %s\n", ci.summary.buf);
275
	if (suspect->commit->object.flags & UNINTERESTING)
276
		printf("boundary\n");
277

278
	commit_info_destroy(&ci);
279

280
	return 1;
281
}
282

283
/*
284
 * The blame_entry is found to be guilty for the range.
285
 * Show it in incremental output.
286
 */
287
static void found_guilty_entry(struct blame_entry *ent, void *data)
288
{
289
	struct progress_info *pi = (struct progress_info *)data;
290

291
	if (incremental) {
292
		struct blame_origin *suspect = ent->suspect;
293

294
		printf("%s %d %d %d\n",
295
		       oid_to_hex(&suspect->commit->object.oid),
296
		       ent->s_lno + 1, ent->lno + 1, ent->num_lines);
297
		emit_one_suspect_detail(suspect, 0);
298
		write_filename_info(suspect);
299
		maybe_flush_or_die(stdout, "stdout");
300
	}
301
	pi->blamed_lines += ent->num_lines;
302
	display_progress(pi->progress, pi->blamed_lines);
303
}
304

305
static const char *format_time(timestamp_t time, const char *tz_str,
306
			       int show_raw_time)
307
{
308
	static struct strbuf time_buf = STRBUF_INIT;
309

310
	strbuf_reset(&time_buf);
311
	if (show_raw_time) {
312
		strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);
313
	}
314
	else {
315
		const char *time_str;
316
		size_t time_width;
317
		int tz;
318
		tz = atoi(tz_str);
319
		time_str = show_date(time, tz, blame_date_mode);
320
		strbuf_addstr(&time_buf, time_str);
321
		/*
322
		 * Add space paddings to time_buf to display a fixed width
323
		 * string, and use time_width for display width calibration.
324
		 */
325
		for (time_width = utf8_strwidth(time_str);
326
		     time_width < blame_date_width;
327
		     time_width++)
328
			strbuf_addch(&time_buf, ' ');
329
	}
330
	return time_buf.buf;
331
}
332

333
#define OUTPUT_ANNOTATE_COMPAT      (1U<<0)
334
#define OUTPUT_LONG_OBJECT_NAME     (1U<<1)
335
#define OUTPUT_RAW_TIMESTAMP        (1U<<2)
336
#define OUTPUT_PORCELAIN            (1U<<3)
337
#define OUTPUT_SHOW_NAME            (1U<<4)
338
#define OUTPUT_SHOW_NUMBER          (1U<<5)
339
#define OUTPUT_SHOW_SCORE           (1U<<6)
340
#define OUTPUT_NO_AUTHOR            (1U<<7)
341
#define OUTPUT_SHOW_EMAIL           (1U<<8)
342
#define OUTPUT_LINE_PORCELAIN       (1U<<9)
343
#define OUTPUT_COLOR_LINE           (1U<<10)
344
#define OUTPUT_SHOW_AGE_WITH_COLOR  (1U<<11)
345

346
static void emit_porcelain_details(struct blame_origin *suspect, int repeat)
347
{
348
	if (emit_one_suspect_detail(suspect, repeat) ||
349
	    (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
350
		write_filename_info(suspect);
351
}
352

353
static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,
354
			   int opt)
355
{
356
	int repeat = opt & OUTPUT_LINE_PORCELAIN;
357
	int cnt;
358
	const char *cp;
359
	struct blame_origin *suspect = ent->suspect;
360
	char hex[GIT_MAX_HEXSZ + 1];
361

362
	oid_to_hex_r(hex, &suspect->commit->object.oid);
363
	printf("%s %d %d %d\n",
364
	       hex,
365
	       ent->s_lno + 1,
366
	       ent->lno + 1,
367
	       ent->num_lines);
368
	emit_porcelain_details(suspect, repeat);
369

370
	cp = blame_nth_line(sb, ent->lno);
371
	for (cnt = 0; cnt < ent->num_lines; cnt++) {
372
		char ch;
373
		if (cnt) {
374
			printf("%s %d %d\n", hex,
375
			       ent->s_lno + 1 + cnt,
376
			       ent->lno + 1 + cnt);
377
			if (repeat)
378
				emit_porcelain_details(suspect, 1);
379
		}
380
		putchar('\t');
381
		do {
382
			ch = *cp++;
383
			putchar(ch);
384
		} while (ch != '\n' &&
385
			 cp < sb->final_buf + sb->final_buf_size);
386
	}
387

388
	if (sb->final_buf_size && cp[-1] != '\n')
389
		putchar('\n');
390
}
391

392
static struct color_field {
393
	timestamp_t hop;
394
	char col[COLOR_MAXLEN];
395
} *colorfield;
396
static int colorfield_nr, colorfield_alloc;
397

398
static void parse_color_fields(const char *s)
399
{
400
	struct string_list l = STRING_LIST_INIT_DUP;
401
	struct string_list_item *item;
402
	enum { EXPECT_DATE, EXPECT_COLOR } next = EXPECT_COLOR;
403

404
	colorfield_nr = 0;
405

406
	/* Ideally this would be stripped and split at the same time? */
407
	string_list_split(&l, s, ',', -1);
408
	ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
409

410
	for_each_string_list_item(item, &l) {
411
		switch (next) {
412
		case EXPECT_DATE:
413
			colorfield[colorfield_nr].hop = approxidate(item->string);
414
			next = EXPECT_COLOR;
415
			colorfield_nr++;
416
			ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
417
			break;
418
		case EXPECT_COLOR:
419
			if (color_parse(item->string, colorfield[colorfield_nr].col))
420
				die(_("expecting a color: %s"), item->string);
421
			next = EXPECT_DATE;
422
			break;
423
		}
424
	}
425

426
	if (next == EXPECT_COLOR)
427
		die(_("must end with a color"));
428

429
	colorfield[colorfield_nr].hop = TIME_MAX;
430
	string_list_clear(&l, 0);
431
}
432

433
static void setup_default_color_by_age(void)
434
{
435
	parse_color_fields("blue,12 month ago,white,1 month ago,red");
436
}
437

438
static void determine_line_heat(struct commit_info *ci, const char **dest_color)
439
{
440
	int i = 0;
441

442
	while (i < colorfield_nr && ci->author_time > colorfield[i].hop)
443
		i++;
444

445
	*dest_color = colorfield[i].col;
446
}
447

448
static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int opt)
449
{
450
	int cnt;
451
	const char *cp;
452
	struct blame_origin *suspect = ent->suspect;
453
	struct commit_info ci = COMMIT_INFO_INIT;
454
	char hex[GIT_MAX_HEXSZ + 1];
455
	int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
456
	const char *default_color = NULL, *color = NULL, *reset = NULL;
457

458
	get_commit_info(suspect->commit, &ci, 1);
459
	oid_to_hex_r(hex, &suspect->commit->object.oid);
460

461
	cp = blame_nth_line(sb, ent->lno);
462

463
	if (opt & OUTPUT_SHOW_AGE_WITH_COLOR) {
464
		determine_line_heat(&ci, &default_color);
465
		color = default_color;
466
		reset = GIT_COLOR_RESET;
467
	}
468

469
	for (cnt = 0; cnt < ent->num_lines; cnt++) {
470
		char ch;
471
		int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? the_hash_algo->hexsz : abbrev;
472

473
		if (opt & OUTPUT_COLOR_LINE) {
474
			if (cnt > 0) {
475
				color = repeated_meta_color;
476
				reset = GIT_COLOR_RESET;
477
			} else  {
478
				color = default_color ? default_color : NULL;
479
				reset = default_color ? GIT_COLOR_RESET : NULL;
480
			}
481
		}
482
		if (color)
483
			fputs(color, stdout);
484

485
		if (suspect->commit->object.flags & UNINTERESTING) {
486
			if (blank_boundary)
487
				memset(hex, ' ', length);
488
			else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
489
				length--;
490
				putchar('^');
491
			}
492
		}
493

494
		if (mark_unblamable_lines && ent->unblamable) {
495
			length--;
496
			putchar('*');
497
		}
498
		if (mark_ignored_lines && ent->ignored) {
499
			length--;
500
			putchar('?');
501
		}
502
		printf("%.*s", length, hex);
503
		if (opt & OUTPUT_ANNOTATE_COMPAT) {
504
			const char *name;
505
			if (opt & OUTPUT_SHOW_EMAIL)
506
				name = ci.author_mail.buf;
507
			else
508
				name = ci.author.buf;
509
			printf("\t(%10s\t%10s\t%d)", name,
510
			       format_time(ci.author_time, ci.author_tz.buf,
511
					   show_raw_time),
512
			       ent->lno + 1 + cnt);
513
		} else {
514
			if (opt & OUTPUT_SHOW_SCORE)
515
				printf(" %*d %02d",
516
				       max_score_digits, ent->score,
517
				       ent->suspect->refcnt);
518
			if (opt & OUTPUT_SHOW_NAME)
519
				printf(" %-*.*s", longest_file, longest_file,
520
				       suspect->path);
521
			if (opt & OUTPUT_SHOW_NUMBER)
522
				printf(" %*d", max_orig_digits,
523
				       ent->s_lno + 1 + cnt);
524

525
			if (!(opt & OUTPUT_NO_AUTHOR)) {
526
				const char *name;
527
				int pad;
528
				if (opt & OUTPUT_SHOW_EMAIL)
529
					name = ci.author_mail.buf;
530
				else
531
					name = ci.author.buf;
532
				pad = longest_author - utf8_strwidth(name);
533
				printf(" (%s%*s %10s",
534
				       name, pad, "",
535
				       format_time(ci.author_time,
536
						   ci.author_tz.buf,
537
						   show_raw_time));
538
			}
539
			printf(" %*d) ",
540
			       max_digits, ent->lno + 1 + cnt);
541
		}
542
		if (reset)
543
			fputs(reset, stdout);
544
		do {
545
			ch = *cp++;
546
			putchar(ch);
547
		} while (ch != '\n' &&
548
			 cp < sb->final_buf + sb->final_buf_size);
549
	}
550

551
	if (sb->final_buf_size && cp[-1] != '\n')
552
		putchar('\n');
553

554
	commit_info_destroy(&ci);
555
}
556

557
static void output(struct blame_scoreboard *sb, int option)
558
{
559
	struct blame_entry *ent;
560

561
	if (option & OUTPUT_PORCELAIN) {
562
		for (ent = sb->ent; ent; ent = ent->next) {
563
			int count = 0;
564
			struct blame_origin *suspect;
565
			struct commit *commit = ent->suspect->commit;
566
			if (commit->object.flags & MORE_THAN_ONE_PATH)
567
				continue;
568
			for (suspect = get_blame_suspects(commit); suspect; suspect = suspect->next) {
569
				if (suspect->guilty && count++) {
570
					commit->object.flags |= MORE_THAN_ONE_PATH;
571
					break;
572
				}
573
			}
574
		}
575
	}
576

577
	for (ent = sb->ent; ent; ent = ent->next) {
578
		if (option & OUTPUT_PORCELAIN)
579
			emit_porcelain(sb, ent, option);
580
		else {
581
			emit_other(sb, ent, option);
582
		}
583
	}
584
}
585

586
/*
587
 * Add phony grafts for use with -S; this is primarily to
588
 * support git's cvsserver that wants to give a linear history
589
 * to its clients.
590
 */
591
static int read_ancestry(const char *graft_file)
592
{
593
	FILE *fp = fopen_or_warn(graft_file, "r");
594
	struct strbuf buf = STRBUF_INIT;
595
	if (!fp)
596
		return -1;
597
	while (!strbuf_getwholeline(&buf, fp, '\n')) {
598
		/* The format is just "Commit Parent1 Parent2 ...\n" */
599
		struct commit_graft *graft = read_graft_line(&buf);
600
		if (graft)
601
			register_commit_graft(the_repository, graft, 0);
602
	}
603
	fclose(fp);
604
	strbuf_release(&buf);
605
	return 0;
606
}
607

608
static int update_auto_abbrev(int auto_abbrev, struct blame_origin *suspect)
609
{
610
	const char *uniq = repo_find_unique_abbrev(the_repository,
611
						   &suspect->commit->object.oid,
612
						   auto_abbrev);
613
	int len = strlen(uniq);
614
	if (auto_abbrev < len)
615
		return len;
616
	return auto_abbrev;
617
}
618

619
/*
620
 * How many columns do we need to show line numbers, authors,
621
 * and filenames?
622
 */
623
static void find_alignment(struct blame_scoreboard *sb, int *option)
624
{
625
	int longest_src_lines = 0;
626
	int longest_dst_lines = 0;
627
	unsigned largest_score = 0;
628
	struct blame_entry *e;
629
	int compute_auto_abbrev = (abbrev < 0);
630
	int auto_abbrev = DEFAULT_ABBREV;
631

632
	for (e = sb->ent; e; e = e->next) {
633
		struct blame_origin *suspect = e->suspect;
634
		int num;
635

636
		if (compute_auto_abbrev)
637
			auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
638
		if (strcmp(suspect->path, sb->path))
639
			*option |= OUTPUT_SHOW_NAME;
640
		num = strlen(suspect->path);
641
		if (longest_file < num)
642
			longest_file = num;
643
		if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
644
			struct commit_info ci = COMMIT_INFO_INIT;
645
			suspect->commit->object.flags |= METAINFO_SHOWN;
646
			get_commit_info(suspect->commit, &ci, 1);
647
			if (*option & OUTPUT_SHOW_EMAIL)
648
				num = utf8_strwidth(ci.author_mail.buf);
649
			else
650
				num = utf8_strwidth(ci.author.buf);
651
			if (longest_author < num)
652
				longest_author = num;
653
			commit_info_destroy(&ci);
654
		}
655
		num = e->s_lno + e->num_lines;
656
		if (longest_src_lines < num)
657
			longest_src_lines = num;
658
		num = e->lno + e->num_lines;
659
		if (longest_dst_lines < num)
660
			longest_dst_lines = num;
661
		if (largest_score < blame_entry_score(sb, e))
662
			largest_score = blame_entry_score(sb, e);
663
	}
664
	max_orig_digits = decimal_width(longest_src_lines);
665
	max_digits = decimal_width(longest_dst_lines);
666
	max_score_digits = decimal_width(largest_score);
667

668
	if (compute_auto_abbrev)
669
		/* one more abbrev length is needed for the boundary commit */
670
		abbrev = auto_abbrev + 1;
671
}
672

673
static void sanity_check_on_fail(struct blame_scoreboard *sb, int baa)
674
{
675
	int opt = OUTPUT_SHOW_SCORE | OUTPUT_SHOW_NUMBER | OUTPUT_SHOW_NAME;
676
	find_alignment(sb, &opt);
677
	output(sb, opt);
678
	die("Baa %d!", baa);
679
}
680

681
static unsigned parse_score(const char *arg)
682
{
683
	char *end;
684
	unsigned long score = strtoul(arg, &end, 10);
685
	if (*end)
686
		return 0;
687
	return score;
688
}
689

690
static char *add_prefix(const char *prefix, const char *path)
691
{
692
	return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
693
}
694

695
static int git_blame_config(const char *var, const char *value,
696
			    const struct config_context *ctx, void *cb)
697
{
698
	if (!strcmp(var, "blame.showroot")) {
699
		show_root = git_config_bool(var, value);
700
		return 0;
701
	}
702
	if (!strcmp(var, "blame.blankboundary")) {
703
		blank_boundary = git_config_bool(var, value);
704
		return 0;
705
	}
706
	if (!strcmp(var, "blame.showemail")) {
707
		int *output_option = cb;
708
		if (git_config_bool(var, value))
709
			*output_option |= OUTPUT_SHOW_EMAIL;
710
		else
711
			*output_option &= ~OUTPUT_SHOW_EMAIL;
712
		return 0;
713
	}
714
	if (!strcmp(var, "blame.date")) {
715
		if (!value)
716
			return config_error_nonbool(var);
717
		parse_date_format(value, &blame_date_mode);
718
		return 0;
719
	}
720
	if (!strcmp(var, "blame.ignorerevsfile")) {
721
		char *str;
722
		int ret;
723

724
		ret = git_config_pathname(&str, var, value);
725
		if (ret)
726
			return ret;
727
		string_list_insert(&ignore_revs_file_list, str);
728
		free(str);
729
		return 0;
730
	}
731
	if (!strcmp(var, "blame.markunblamablelines")) {
732
		mark_unblamable_lines = git_config_bool(var, value);
733
		return 0;
734
	}
735
	if (!strcmp(var, "blame.markignoredlines")) {
736
		mark_ignored_lines = git_config_bool(var, value);
737
		return 0;
738
	}
739
	if (!strcmp(var, "color.blame.repeatedlines")) {
740
		if (color_parse_mem(value, strlen(value), repeated_meta_color))
741
			warning(_("invalid value for '%s': '%s'"),
742
				"color.blame.repeatedLines", value);
743
		return 0;
744
	}
745
	if (!strcmp(var, "color.blame.highlightrecent")) {
746
		parse_color_fields(value);
747
		return 0;
748
	}
749

750
	if (!strcmp(var, "blame.coloring")) {
751
		if (!value)
752
			return config_error_nonbool(var);
753
		if (!strcmp(value, "repeatedLines")) {
754
			coloring_mode |= OUTPUT_COLOR_LINE;
755
		} else if (!strcmp(value, "highlightRecent")) {
756
			coloring_mode |= OUTPUT_SHOW_AGE_WITH_COLOR;
757
		} else if (!strcmp(value, "none")) {
758
			coloring_mode &= ~(OUTPUT_COLOR_LINE |
759
					    OUTPUT_SHOW_AGE_WITH_COLOR);
760
		} else {
761
			warning(_("invalid value for '%s': '%s'"),
762
				"blame.coloring", value);
763
			return 0;
764
		}
765
	}
766

767
	if (git_diff_heuristic_config(var, value, cb) < 0)
768
		return -1;
769
	if (userdiff_config(var, value) < 0)
770
		return -1;
771

772
	return git_default_config(var, value, ctx, cb);
773
}
774

775
static int blame_copy_callback(const struct option *option, const char *arg, int unset)
776
{
777
	int *opt = option->value;
778

779
	BUG_ON_OPT_NEG(unset);
780

781
	/*
782
	 * -C enables copy from removed files;
783
	 * -C -C enables copy from existing files, but only
784
	 *       when blaming a new file;
785
	 * -C -C -C enables copy from existing files for
786
	 *          everybody
787
	 */
788
	if (*opt & PICKAXE_BLAME_COPY_HARDER)
789
		*opt |= PICKAXE_BLAME_COPY_HARDEST;
790
	if (*opt & PICKAXE_BLAME_COPY)
791
		*opt |= PICKAXE_BLAME_COPY_HARDER;
792
	*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
793

794
	if (arg)
795
		blame_copy_score = parse_score(arg);
796
	return 0;
797
}
798

799
static int blame_move_callback(const struct option *option, const char *arg, int unset)
800
{
801
	int *opt = option->value;
802

803
	BUG_ON_OPT_NEG(unset);
804

805
	*opt |= PICKAXE_BLAME_MOVE;
806

807
	if (arg)
808
		blame_move_score = parse_score(arg);
809
	return 0;
810
}
811

812
static int is_a_rev(const char *name)
813
{
814
	struct object_id oid;
815

816
	if (repo_get_oid(the_repository, name, &oid))
817
		return 0;
818
	return OBJ_NONE < oid_object_info(the_repository, &oid, NULL);
819
}
820

821
static int peel_to_commit_oid(struct object_id *oid_ret, void *cbdata)
822
{
823
	struct repository *r = ((struct blame_scoreboard *)cbdata)->repo;
824
	struct object_id oid;
825

826
	oidcpy(&oid, oid_ret);
827
	while (1) {
828
		struct object *obj;
829
		int kind = oid_object_info(r, &oid, NULL);
830
		if (kind == OBJ_COMMIT) {
831
			oidcpy(oid_ret, &oid);
832
			return 0;
833
		}
834
		if (kind != OBJ_TAG)
835
			return -1;
836
		obj = deref_tag(r, parse_object(r, &oid), NULL, 0);
837
		if (!obj)
838
			return -1;
839
		oidcpy(&oid, &obj->oid);
840
	}
841
}
842

843
static void build_ignorelist(struct blame_scoreboard *sb,
844
			     struct string_list *ignore_revs_file_list,
845
			     struct string_list *ignore_rev_list)
846
{
847
	struct string_list_item *i;
848
	struct object_id oid;
849

850
	oidset_init(&sb->ignore_list, 0);
851
	for_each_string_list_item(i, ignore_revs_file_list) {
852
		if (!strcmp(i->string, ""))
853
			oidset_clear(&sb->ignore_list);
854
		else
855
			oidset_parse_file_carefully(&sb->ignore_list, i->string,
856
						    the_repository->hash_algo,
857
						    peel_to_commit_oid, sb);
858
	}
859
	for_each_string_list_item(i, ignore_rev_list) {
860
		if (repo_get_oid_committish(the_repository, i->string, &oid) ||
861
		    peel_to_commit_oid(&oid, sb))
862
			die(_("cannot find revision %s to ignore"), i->string);
863
		oidset_insert(&sb->ignore_list, &oid);
864
	}
865
}
866

867
int cmd_blame(int argc, const char **argv, const char *prefix)
868
{
869
	struct rev_info revs;
870
	char *path = NULL;
871
	struct blame_scoreboard sb;
872
	struct blame_origin *o;
873
	struct blame_entry *ent = NULL;
874
	long dashdash_pos, lno;
875
	struct progress_info pi = { NULL, 0 };
876

877
	struct string_list range_list = STRING_LIST_INIT_NODUP;
878
	struct string_list ignore_rev_list = STRING_LIST_INIT_NODUP;
879
	int output_option = 0, opt = 0;
880
	int show_stats = 0;
881
	const char *revs_file = NULL;
882
	const char *contents_from = NULL;
883
	const struct option options[] = {
884
		OPT_BOOL(0, "incremental", &incremental, N_("show blame entries as we find them, incrementally")),
885
		OPT_BOOL('b', NULL, &blank_boundary, N_("do not show object names of boundary commits (Default: off)")),
886
		OPT_BOOL(0, "root", &show_root, N_("do not treat root commits as boundaries (Default: off)")),
887
		OPT_BOOL(0, "show-stats", &show_stats, N_("show work cost statistics")),
888
		OPT_BOOL(0, "progress", &show_progress, N_("force progress reporting")),
889
		OPT_BIT(0, "score-debug", &output_option, N_("show output score for blame entries"), OUTPUT_SHOW_SCORE),
890
		OPT_BIT('f', "show-name", &output_option, N_("show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
891
		OPT_BIT('n', "show-number", &output_option, N_("show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
892
		OPT_BIT('p', "porcelain", &output_option, N_("show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
893
		OPT_BIT(0, "line-porcelain", &output_option, N_("show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
894
		OPT_BIT('c', NULL, &output_option, N_("use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
895
		OPT_BIT('t', NULL, &output_option, N_("show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
896
		OPT_BIT('l', NULL, &output_option, N_("show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
897
		OPT_BIT('s', NULL, &output_option, N_("suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
898
		OPT_BIT('e', "show-email", &output_option, N_("show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
899
		OPT_BIT('w', NULL, &xdl_opts, N_("ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
900
		OPT_STRING_LIST(0, "ignore-rev", &ignore_rev_list, N_("rev"), N_("ignore <rev> when blaming")),
901
		OPT_STRING_LIST(0, "ignore-revs-file", &ignore_revs_file_list, N_("file"), N_("ignore revisions from <file>")),
902
		OPT_BIT(0, "color-lines", &output_option, N_("color redundant metadata from previous line differently"), OUTPUT_COLOR_LINE),
903
		OPT_BIT(0, "color-by-age", &output_option, N_("color lines by age"), OUTPUT_SHOW_AGE_WITH_COLOR),
904
		OPT_BIT(0, "minimal", &xdl_opts, N_("spend extra cycles to find better match"), XDF_NEED_MINIMAL),
905
		OPT_STRING('S', NULL, &revs_file, N_("file"), N_("use revisions from <file> instead of calling git-rev-list")),
906
		OPT_STRING(0, "contents", &contents_from, N_("file"), N_("use <file>'s contents as the final image")),
907
		OPT_CALLBACK_F('C', NULL, &opt, N_("score"), N_("find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback),
908
		OPT_CALLBACK_F('M', NULL, &opt, N_("score"), N_("find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback),
909
		OPT_STRING_LIST('L', NULL, &range_list, N_("range"),
910
				N_("process only line range <start>,<end> or function :<funcname>")),
911
		OPT__ABBREV(&abbrev),
912
		OPT_END()
913
	};
914

915
	struct parse_opt_ctx_t ctx;
916
	int cmd_is_annotate = !strcmp(argv[0], "annotate");
917
	struct range_set ranges;
918
	unsigned int range_i;
919
	long anchor;
920
	long num_lines = 0;
921
	const char *str_usage = cmd_is_annotate ? annotate_usage : blame_usage;
922
	const char **opt_usage = cmd_is_annotate ? annotate_opt_usage : blame_opt_usage;
923

924
	setup_default_color_by_age();
925
	git_config(git_blame_config, &output_option);
926
	repo_init_revisions(the_repository, &revs, NULL);
927
	revs.date_mode = blame_date_mode;
928
	revs.diffopt.flags.allow_textconv = 1;
929
	revs.diffopt.flags.follow_renames = 1;
930

931
	save_commit_buffer = 0;
932
	dashdash_pos = 0;
933
	show_progress = -1;
934

935
	parse_options_start(&ctx, argc, argv, prefix, options,
936
			    PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
937
	for (;;) {
938
		switch (parse_options_step(&ctx, options, opt_usage)) {
939
		case PARSE_OPT_NON_OPTION:
940
		case PARSE_OPT_UNKNOWN:
941
			break;
942
		case PARSE_OPT_HELP:
943
		case PARSE_OPT_ERROR:
944
		case PARSE_OPT_SUBCOMMAND:
945
			exit(129);
946
		case PARSE_OPT_COMPLETE:
947
			exit(0);
948
		case PARSE_OPT_DONE:
949
			if (ctx.argv[0])
950
				dashdash_pos = ctx.cpidx;
951
			goto parse_done;
952
		}
953

954
		if (!strcmp(ctx.argv[0], "--reverse")) {
955
			ctx.argv[0] = "--children";
956
			reverse = 1;
957
		}
958
		parse_revision_opt(&revs, &ctx, options, opt_usage);
959
	}
960
parse_done:
961
	revision_opts_finish(&revs);
962
	no_whole_file_rename = !revs.diffopt.flags.follow_renames;
963
	xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;
964
	revs.diffopt.flags.follow_renames = 0;
965
	argc = parse_options_end(&ctx);
966

967
	prepare_repo_settings(the_repository);
968
	the_repository->settings.command_requires_full_index = 0;
969

970
	if (incremental || (output_option & OUTPUT_PORCELAIN)) {
971
		if (show_progress > 0)
972
			die(_("--progress can't be used with --incremental or porcelain formats"));
973
		show_progress = 0;
974
	} else if (show_progress < 0)
975
		show_progress = isatty(2);
976

977
	if (0 < abbrev && abbrev < (int)the_hash_algo->hexsz)
978
		/* one more abbrev length is needed for the boundary commit */
979
		abbrev++;
980
	else if (!abbrev)
981
		abbrev = the_hash_algo->hexsz;
982

983
	if (revs_file && read_ancestry(revs_file))
984
		die_errno("reading graft file '%s' failed", revs_file);
985

986
	if (cmd_is_annotate) {
987
		output_option |= OUTPUT_ANNOTATE_COMPAT;
988
		blame_date_mode.type = DATE_ISO8601;
989
	} else {
990
		blame_date_mode = revs.date_mode;
991
	}
992

993
	/* The maximum width used to show the dates */
994
	switch (blame_date_mode.type) {
995
	case DATE_RFC2822:
996
		blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
997
		break;
998
	case DATE_ISO8601_STRICT:
999
		blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
1000
		break;
1001
	case DATE_ISO8601:
1002
		blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
1003
		break;
1004
	case DATE_RAW:
1005
		blame_date_width = sizeof("1161298804 -0700");
1006
		break;
1007
	case DATE_UNIX:
1008
		blame_date_width = sizeof("1161298804");
1009
		break;
1010
	case DATE_SHORT:
1011
		blame_date_width = sizeof("2006-10-19");
1012
		break;
1013
	case DATE_RELATIVE:
1014
		/*
1015
		 * TRANSLATORS: This string is used to tell us the
1016
		 * maximum display width for a relative timestamp in
1017
		 * "git blame" output.  For C locale, "4 years, 11
1018
		 * months ago", which takes 22 places, is the longest
1019
		 * among various forms of relative timestamps, but
1020
		 * your language may need more or fewer display
1021
		 * columns.
1022
		 */
1023
		blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
1024
		break;
1025
	case DATE_HUMAN:
1026
		/* If the year is shown, no time is shown */
1027
		blame_date_width = sizeof("Thu Oct 19 16:00");
1028
		break;
1029
	case DATE_NORMAL:
1030
		blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
1031
		break;
1032
	case DATE_STRFTIME:
1033
		blame_date_width = strlen(show_date(0, 0, blame_date_mode)) + 1; /* add the null */
1034
		break;
1035
	}
1036
	blame_date_width -= 1; /* strip the null */
1037

1038
	if (revs.diffopt.flags.find_copies_harder)
1039
		opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
1040
			PICKAXE_BLAME_COPY_HARDER);
1041

1042
	/*
1043
	 * We have collected options unknown to us in argv[1..unk]
1044
	 * which are to be passed to revision machinery if we are
1045
	 * going to do the "bottom" processing.
1046
	 *
1047
	 * The remaining are:
1048
	 *
1049
	 * (1) if dashdash_pos != 0, it is either
1050
	 *     "blame [revisions] -- <path>" or
1051
	 *     "blame -- <path> <rev>"
1052
	 *
1053
	 * (2) otherwise, it is one of the two:
1054
	 *     "blame [revisions] <path>"
1055
	 *     "blame <path> <rev>"
1056
	 *
1057
	 * Note that we must strip out <path> from the arguments: we do not
1058
	 * want the path pruning but we may want "bottom" processing.
1059
	 */
1060
	if (dashdash_pos) {
1061
		switch (argc - dashdash_pos - 1) {
1062
		case 2: /* (1b) */
1063
			if (argc != 4)
1064
				usage_with_options(opt_usage, options);
1065
			/* reorder for the new way: <rev> -- <path> */
1066
			argv[1] = argv[3];
1067
			argv[3] = argv[2];
1068
			argv[2] = "--";
1069
			/* FALLTHROUGH */
1070
		case 1: /* (1a) */
1071
			path = add_prefix(prefix, argv[--argc]);
1072
			argv[argc] = NULL;
1073
			break;
1074
		default:
1075
			usage_with_options(opt_usage, options);
1076
		}
1077
	} else {
1078
		if (argc < 2)
1079
			usage_with_options(opt_usage, options);
1080
		if (argc == 3 && is_a_rev(argv[argc - 1])) { /* (2b) */
1081
			path = add_prefix(prefix, argv[1]);
1082
			argv[1] = argv[2];
1083
		} else {	/* (2a) */
1084
			if (argc == 2 && is_a_rev(argv[1]) && !get_git_work_tree())
1085
				die("missing <path> to blame");
1086
			path = add_prefix(prefix, argv[argc - 1]);
1087
		}
1088
		argv[argc - 1] = "--";
1089
	}
1090

1091
	revs.disable_stdin = 1;
1092
	setup_revisions(argc, argv, &revs, NULL);
1093
	if (!revs.pending.nr && is_bare_repository()) {
1094
		struct commit *head_commit;
1095
		struct object_id head_oid;
1096

1097
		if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING,
1098
					     &head_oid, NULL) ||
1099
		    !(head_commit = lookup_commit_reference_gently(revs.repo,
1100
							     &head_oid, 1)))
1101
			die("no such ref: HEAD");
1102

1103
		add_pending_object(&revs, &head_commit->object, "HEAD");
1104
	}
1105

1106
	init_scoreboard(&sb);
1107
	sb.revs = &revs;
1108
	sb.contents_from = contents_from;
1109
	sb.reverse = reverse;
1110
	sb.repo = the_repository;
1111
	sb.path = path;
1112
	build_ignorelist(&sb, &ignore_revs_file_list, &ignore_rev_list);
1113
	string_list_clear(&ignore_revs_file_list, 0);
1114
	string_list_clear(&ignore_rev_list, 0);
1115
	setup_scoreboard(&sb, &o);
1116

1117
	/*
1118
	 * Changed-path Bloom filters are disabled when looking
1119
	 * for copies.
1120
	 */
1121
	if (!(opt & PICKAXE_BLAME_COPY))
1122
		setup_blame_bloom_data(&sb);
1123

1124
	lno = sb.num_lines;
1125

1126
	if (lno && !range_list.nr)
1127
		string_list_append(&range_list, "1");
1128

1129
	anchor = 1;
1130
	range_set_init(&ranges, range_list.nr);
1131
	for (range_i = 0; range_i < range_list.nr; ++range_i) {
1132
		long bottom, top;
1133
		if (parse_range_arg(range_list.items[range_i].string,
1134
				    nth_line_cb, &sb, lno, anchor,
1135
				    &bottom, &top, sb.path,
1136
				    the_repository->index))
1137
			usage(str_usage);
1138
		if ((!lno && (top || bottom)) || lno < bottom)
1139
			die(Q_("file %s has only %lu line",
1140
			       "file %s has only %lu lines",
1141
			       lno), sb.path, lno);
1142
		if (bottom < 1)
1143
			bottom = 1;
1144
		if (top < 1 || lno < top)
1145
			top = lno;
1146
		bottom--;
1147
		range_set_append_unsafe(&ranges, bottom, top);
1148
		anchor = top + 1;
1149
	}
1150
	sort_and_merge_range_set(&ranges);
1151

1152
	for (range_i = ranges.nr; range_i > 0; --range_i) {
1153
		const struct range *r = &ranges.ranges[range_i - 1];
1154
		ent = blame_entry_prepend(ent, r->start, r->end, o);
1155
		num_lines += (r->end - r->start);
1156
	}
1157
	if (!num_lines)
1158
		num_lines = sb.num_lines;
1159

1160
	o->suspects = ent;
1161
	prio_queue_put(&sb.commits, o->commit);
1162

1163
	blame_origin_decref(o);
1164

1165
	range_set_release(&ranges);
1166
	string_list_clear(&range_list, 0);
1167

1168
	sb.ent = NULL;
1169

1170
	if (blame_move_score)
1171
		sb.move_score = blame_move_score;
1172
	if (blame_copy_score)
1173
		sb.copy_score = blame_copy_score;
1174

1175
	sb.debug = DEBUG_BLAME;
1176
	sb.on_sanity_fail = &sanity_check_on_fail;
1177

1178
	sb.show_root = show_root;
1179
	sb.xdl_opts = xdl_opts;
1180
	sb.no_whole_file_rename = no_whole_file_rename;
1181

1182
	read_mailmap(&mailmap);
1183

1184
	sb.found_guilty_entry = &found_guilty_entry;
1185
	sb.found_guilty_entry_data = &pi;
1186
	if (show_progress)
1187
		pi.progress = start_delayed_progress(_("Blaming lines"), num_lines);
1188

1189
	assign_blame(&sb, opt);
1190

1191
	stop_progress(&pi.progress);
1192

1193
	if (!incremental)
1194
		setup_pager();
1195
	else
1196
		goto cleanup;
1197

1198
	blame_sort_final(&sb);
1199

1200
	blame_coalesce(&sb);
1201

1202
	if (!(output_option & (OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR)))
1203
		output_option |= coloring_mode;
1204

1205
	if (!(output_option & OUTPUT_PORCELAIN)) {
1206
		find_alignment(&sb, &output_option);
1207
		if (!*repeated_meta_color &&
1208
		    (output_option & OUTPUT_COLOR_LINE))
1209
			xsnprintf(repeated_meta_color,
1210
				  sizeof(repeated_meta_color),
1211
				  "%s", GIT_COLOR_CYAN);
1212
	}
1213
	if (output_option & OUTPUT_ANNOTATE_COMPAT)
1214
		output_option &= ~(OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR);
1215

1216
	output(&sb, output_option);
1217
	free((void *)sb.final_buf);
1218
	for (ent = sb.ent; ent; ) {
1219
		struct blame_entry *e = ent->next;
1220
		free(ent);
1221
		ent = e;
1222
	}
1223

1224
	if (show_stats) {
1225
		printf("num read blob: %d\n", sb.num_read_blob);
1226
		printf("num get patch: %d\n", sb.num_get_patch);
1227
		printf("num commits: %d\n", sb.num_commits);
1228
	}
1229

1230
cleanup:
1231
	free(path);
1232
	cleanup_scoreboard(&sb);
1233
	release_revisions(&revs);
1234
	return 0;
1235
}
1236

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.