1/* 2 * Blame 3 * 4 * Copyright (c) 2006, 2014 by its authors 5 * See COPYING for licensing conditions 6 */ 7 8#include "cache.h" 9#include "refs.h" 10#include "builtin.h" 11#include "commit.h" 12#include "tag.h" 13#include "tree-walk.h" 14#include "diff.h" 15#include "diffcore.h" 16#include "revision.h" 17#include "quote.h" 18#include "xdiff-interface.h" 19#include "cache-tree.h" 20#include "string-list.h" 21#include "mailmap.h" 22#include "mergesort.h" 23#include "parse-options.h" 24#include "prio-queue.h" 25#include "utf8.h" 26#include "userdiff.h" 27#include "line-range.h" 28#include "line-log.h" 29#include "dir.h" 30#include "progress.h" 31 32static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>"); 33 34static const char *blame_opt_usage[] = { 35 blame_usage, 36 "", 37 N_("<rev-opts> are documented in git-rev-list(1)"), 38 NULL 39}; 40 41static int longest_file; 42static int longest_author; 43static int max_orig_digits; 44static int max_digits; 45static int max_score_digits; 46static int show_root; 47static int reverse; 48static int blank_boundary; 49static int incremental; 50static int xdl_opts; 51static int abbrev = -1; 52static int no_whole_file_rename; 53static int show_progress; 54 55static struct date_mode blame_date_mode = { DATE_ISO8601 }; 56static size_t blame_date_width; 57 58static struct string_list mailmap = STRING_LIST_INIT_NODUP; 59 60#ifndef DEBUG 61#define DEBUG 0 62#endif 63 64#define PICKAXE_BLAME_MOVE 01 65#define PICKAXE_BLAME_COPY 02 66#define PICKAXE_BLAME_COPY_HARDER 04 67#define PICKAXE_BLAME_COPY_HARDEST 010 68 69static unsigned blame_move_score; 70static unsigned blame_copy_score; 71#define BLAME_DEFAULT_MOVE_SCORE 20 72#define BLAME_DEFAULT_COPY_SCORE 40 73 74/* Remember to update object flag allocation in object.h */ 75#define METAINFO_SHOWN (1u<<12) 76#define MORE_THAN_ONE_PATH (1u<<13) 77 78/* 79 * One blob in a commit that is being suspected 80 */ 81struct blame_origin { 82 int refcnt; 83 /* Record preceding blame record for this blob */ 84 struct blame_origin *previous; 85 /* origins are put in a list linked via `next' hanging off the 86 * corresponding commit's util field in order to make finding 87 * them fast. The presence in this chain does not count 88 * towards the origin's reference count. It is tempting to 89 * let it count as long as the commit is pending examination, 90 * but even under circumstances where the commit will be 91 * present multiple times in the priority queue of unexamined 92 * commits, processing the first instance will not leave any 93 * work requiring the origin data for the second instance. An 94 * interspersed commit changing that would have to be 95 * preexisting with a different ancestry and with the same 96 * commit date in order to wedge itself between two instances 97 * of the same commit in the priority queue _and_ produce 98 * blame entries relevant for it. While we don't want to let 99 * us get tripped up by this case, it certainly does not seem 100 * worth optimizing for. 101 */ 102 struct blame_origin *next; 103 struct commit *commit; 104 /* `suspects' contains blame entries that may be attributed to 105 * this origin's commit or to parent commits. When a commit 106 * is being processed, all suspects will be moved, either by 107 * assigning them to an origin in a different commit, or by 108 * shipping them to the scoreboard's ent list because they 109 * cannot be attributed to a different commit. 110 */ 111 struct blame_entry *suspects; 112 mmfile_t file; 113 struct object_id blob_oid; 114 unsigned mode; 115 /* guilty gets set when shipping any suspects to the final 116 * blame list instead of other commits 117 */ 118 char guilty; 119 char path[FLEX_ARRAY]; 120}; 121 122struct progress_info { 123 struct progress *progress; 124 int blamed_lines; 125}; 126 127static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b, 128 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data) 129{ 130 xpparam_t xpp = {0}; 131 xdemitconf_t xecfg = {0}; 132 xdemitcb_t ecb = {NULL}; 133 134 xpp.flags = xdl_opts; 135 xecfg.hunk_func = hunk_func; 136 ecb.priv = cb_data; 137 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 138} 139 140/* 141 * Given an origin, prepare mmfile_t structure to be used by the 142 * diff machinery 143 */ 144static void fill_origin_blob(struct diff_options *opt, 145 struct blame_origin *o, mmfile_t *file, int *num_read_blob) 146{ 147 if (!o->file.ptr) { 148 enum object_type type; 149 unsigned long file_size; 150 151 (*num_read_blob)++; 152 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 153 textconv_object(o->path, o->mode, &o->blob_oid, 1, &file->ptr, &file_size)) 154 ; 155 else 156 file->ptr = read_sha1_file(o->blob_oid.hash, &type, 157 &file_size); 158 file->size = file_size; 159 160 if (!file->ptr) 161 die("Cannot read blob %s for path %s", 162 oid_to_hex(&o->blob_oid), 163 o->path); 164 o->file = *file; 165 } 166 else 167 *file = o->file; 168} 169 170/* 171 * Origin is refcounted and usually we keep the blob contents to be 172 * reused. 173 */ 174static inline struct blame_origin *blame_origin_incref(struct blame_origin *o) 175{ 176 if (o) 177 o->refcnt++; 178 return o; 179} 180 181static void blame_origin_decref(struct blame_origin *o) 182{ 183 if (o && --o->refcnt <= 0) { 184 struct blame_origin *p, *l = NULL; 185 if (o->previous) 186 blame_origin_decref(o->previous); 187 free(o->file.ptr); 188 /* Should be present exactly once in commit chain */ 189 for (p = o->commit->util; p; l = p, p = p->next) { 190 if (p == o) { 191 if (l) 192 l->next = p->next; 193 else 194 o->commit->util = p->next; 195 free(o); 196 return; 197 } 198 } 199 die("internal error in blame_origin_decref"); 200 } 201} 202 203static void drop_origin_blob(struct blame_origin *o) 204{ 205 if (o->file.ptr) { 206 free(o->file.ptr); 207 o->file.ptr = NULL; 208 } 209} 210 211/* 212 * Each group of lines is described by a blame_entry; it can be split 213 * as we pass blame to the parents. They are arranged in linked lists 214 * kept as `suspects' of some unprocessed origin, or entered (when the 215 * blame origin has been finalized) into the scoreboard structure. 216 * While the scoreboard structure is only sorted at the end of 217 * processing (according to final image line number), the lists 218 * attached to an origin are sorted by the target line number. 219 */ 220struct blame_entry { 221 struct blame_entry *next; 222 223 /* the first line of this group in the final image; 224 * internally all line numbers are 0 based. 225 */ 226 int lno; 227 228 /* how many lines this group has */ 229 int num_lines; 230 231 /* the commit that introduced this group into the final image */ 232 struct blame_origin *suspect; 233 234 /* the line number of the first line of this group in the 235 * suspect's file; internally all line numbers are 0 based. 236 */ 237 int s_lno; 238 239 /* how significant this entry is -- cached to avoid 240 * scanning the lines over and over. 241 */ 242 unsigned score; 243}; 244 245/* 246 * Any merge of blames happens on lists of blames that arrived via 247 * different parents in a single suspect. In this case, we want to 248 * sort according to the suspect line numbers as opposed to the final 249 * image line numbers. The function body is somewhat longish because 250 * it avoids unnecessary writes. 251 */ 252 253static struct blame_entry *blame_merge(struct blame_entry *list1, 254 struct blame_entry *list2) 255{ 256 struct blame_entry *p1 = list1, *p2 = list2, 257 **tail = &list1; 258 259 if (!p1) 260 return p2; 261 if (!p2) 262 return p1; 263 264 if (p1->s_lno <= p2->s_lno) { 265 do { 266 tail = &p1->next; 267 if ((p1 = *tail) == NULL) { 268 *tail = p2; 269 return list1; 270 } 271 } while (p1->s_lno <= p2->s_lno); 272 } 273 for (;;) { 274 *tail = p2; 275 do { 276 tail = &p2->next; 277 if ((p2 = *tail) == NULL) { 278 *tail = p1; 279 return list1; 280 } 281 } while (p1->s_lno > p2->s_lno); 282 *tail = p1; 283 do { 284 tail = &p1->next; 285 if ((p1 = *tail) == NULL) { 286 *tail = p2; 287 return list1; 288 } 289 } while (p1->s_lno <= p2->s_lno); 290 } 291} 292 293static void *get_next_blame(const void *p) 294{ 295 return ((struct blame_entry *)p)->next; 296} 297 298static void set_next_blame(void *p1, void *p2) 299{ 300 ((struct blame_entry *)p1)->next = p2; 301} 302 303/* 304 * Final image line numbers are all different, so we don't need a 305 * three-way comparison here. 306 */ 307 308static int compare_blame_final(const void *p1, const void *p2) 309{ 310 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 311 ? 1 : -1; 312} 313 314static int compare_blame_suspect(const void *p1, const void *p2) 315{ 316 const struct blame_entry *s1 = p1, *s2 = p2; 317 /* 318 * to allow for collating suspects, we sort according to the 319 * respective pointer value as the primary sorting criterion. 320 * The actual relation is pretty unimportant as long as it 321 * establishes a total order. Comparing as integers gives us 322 * that. 323 */ 324 if (s1->suspect != s2->suspect) 325 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1; 326 if (s1->s_lno == s2->s_lno) 327 return 0; 328 return s1->s_lno > s2->s_lno ? 1 : -1; 329} 330 331static struct blame_entry *blame_sort(struct blame_entry *head, 332 int (*compare_fn)(const void *, const void *)) 333{ 334 return llist_mergesort (head, get_next_blame, set_next_blame, compare_fn); 335} 336 337static int compare_commits_by_reverse_commit_date(const void *a, 338 const void *b, 339 void *c) 340{ 341 return -compare_commits_by_commit_date(a, b, c); 342} 343 344/* 345 * The current state of the blame assignment. 346 */ 347struct blame_scoreboard { 348 /* the final commit (i.e. where we started digging from) */ 349 struct commit *final; 350 /* Priority queue for commits with unassigned blame records */ 351 struct prio_queue commits; 352 struct rev_info *revs; 353 const char *path; 354 355 /* 356 * The contents in the final image. 357 * Used by many functions to obtain contents of the nth line, 358 * indexed with scoreboard.lineno[blame_entry.lno]. 359 */ 360 const char *final_buf; 361 unsigned long final_buf_size; 362 363 /* linked list of blames */ 364 struct blame_entry *ent; 365 366 /* look-up a line in the final buffer */ 367 int num_lines; 368 int *lineno; 369 370 /* stats */ 371 int num_read_blob; 372 int num_get_patch; 373 int num_commits; 374 375 /* 376 * blame for a blame_entry with score lower than these thresholds 377 * is not passed to the parent using move/copy logic. 378 */ 379 unsigned move_score; 380 unsigned copy_score; 381 382 /* use this file's contents as the final image */ 383 const char *contents_from; 384}; 385 386static void sanity_check_refcnt(struct blame_scoreboard *); 387 388/* 389 * If two blame entries that are next to each other came from 390 * contiguous lines in the same origin (i.e. <commit, path> pair), 391 * merge them together. 392 */ 393static void blame_coalesce(struct blame_scoreboard *sb) 394{ 395 struct blame_entry *ent, *next; 396 397 for (ent = sb->ent; ent && (next = ent->next); ent = next) { 398 if (ent->suspect == next->suspect && 399 ent->s_lno + ent->num_lines == next->s_lno) { 400 ent->num_lines += next->num_lines; 401 ent->next = next->next; 402 blame_origin_decref(next->suspect); 403 free(next); 404 ent->score = 0; 405 next = ent; /* again */ 406 } 407 } 408 409 if (DEBUG) /* sanity */ 410 sanity_check_refcnt(sb); 411} 412 413/* 414 * Merge the given sorted list of blames into a preexisting origin. 415 * If there were no previous blames to that commit, it is entered into 416 * the commit priority queue of the score board. 417 */ 418 419static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin, 420 struct blame_entry *sorted) 421{ 422 if (porigin->suspects) 423 porigin->suspects = blame_merge(porigin->suspects, sorted); 424 else { 425 struct blame_origin *o; 426 for (o = porigin->commit->util; o; o = o->next) { 427 if (o->suspects) { 428 porigin->suspects = sorted; 429 return; 430 } 431 } 432 porigin->suspects = sorted; 433 prio_queue_put(&sb->commits, porigin->commit); 434 } 435} 436 437/* 438 * Given a commit and a path in it, create a new origin structure. 439 * The callers that add blame to the scoreboard should use 440 * get_origin() to obtain shared, refcounted copy instead of calling 441 * this function directly. 442 */ 443static struct blame_origin *make_origin(struct commit *commit, const char *path) 444{ 445 struct blame_origin *o; 446 FLEX_ALLOC_STR(o, path, path); 447 o->commit = commit; 448 o->refcnt = 1; 449 o->next = commit->util; 450 commit->util = o; 451 return o; 452} 453 454/* 455 * Locate an existing origin or create a new one. 456 * This moves the origin to front position in the commit util list. 457 */ 458static struct blame_origin *get_origin(struct commit *commit, const char *path) 459{ 460 struct blame_origin *o, *l; 461 462 for (o = commit->util, l = NULL; o; l = o, o = o->next) { 463 if (!strcmp(o->path, path)) { 464 /* bump to front */ 465 if (l) { 466 l->next = o->next; 467 o->next = commit->util; 468 commit->util = o; 469 } 470 return blame_origin_incref(o); 471 } 472 } 473 return make_origin(commit, path); 474} 475 476/* 477 * Fill the blob_sha1 field of an origin if it hasn't, so that later 478 * call to fill_origin_blob() can use it to locate the data. blob_sha1 479 * for an origin is also used to pass the blame for the entire file to 480 * the parent to detect the case where a child's blob is identical to 481 * that of its parent's. 482 * 483 * This also fills origin->mode for corresponding tree path. 484 */ 485static int fill_blob_sha1_and_mode(struct blame_origin *origin) 486{ 487 if (!is_null_oid(&origin->blob_oid)) 488 return 0; 489 if (get_tree_entry(origin->commit->object.oid.hash, 490 origin->path, 491 origin->blob_oid.hash, &origin->mode)) 492 goto error_out; 493 if (sha1_object_info(origin->blob_oid.hash, NULL) != OBJ_BLOB) 494 goto error_out; 495 return 0; 496 error_out: 497 oidclr(&origin->blob_oid); 498 origin->mode = S_IFINVALID; 499 return -1; 500} 501 502/* 503 * We have an origin -- check if the same path exists in the 504 * parent and return an origin structure to represent it. 505 */ 506static struct blame_origin *find_origin(struct commit *parent, 507 struct blame_origin *origin) 508{ 509 struct blame_origin *porigin; 510 struct diff_options diff_opts; 511 const char *paths[2]; 512 513 /* First check any existing origins */ 514 for (porigin = parent->util; porigin; porigin = porigin->next) 515 if (!strcmp(porigin->path, origin->path)) { 516 /* 517 * The same path between origin and its parent 518 * without renaming -- the most common case. 519 */ 520 return blame_origin_incref (porigin); 521 } 522 523 /* See if the origin->path is different between parent 524 * and origin first. Most of the time they are the 525 * same and diff-tree is fairly efficient about this. 526 */ 527 diff_setup(&diff_opts); 528 DIFF_OPT_SET(&diff_opts, RECURSIVE); 529 diff_opts.detect_rename = 0; 530 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 531 paths[0] = origin->path; 532 paths[1] = NULL; 533 534 parse_pathspec(&diff_opts.pathspec, 535 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 536 PATHSPEC_LITERAL_PATH, "", paths); 537 diff_setup_done(&diff_opts); 538 539 if (is_null_oid(&origin->commit->object.oid)) 540 do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 541 else 542 diff_tree_sha1(parent->tree->object.oid.hash, 543 origin->commit->tree->object.oid.hash, 544 "", &diff_opts); 545 diffcore_std(&diff_opts); 546 547 if (!diff_queued_diff.nr) { 548 /* The path is the same as parent */ 549 porigin = get_origin(parent, origin->path); 550 oidcpy(&porigin->blob_oid, &origin->blob_oid); 551 porigin->mode = origin->mode; 552 } else { 553 /* 554 * Since origin->path is a pathspec, if the parent 555 * commit had it as a directory, we will see a whole 556 * bunch of deletion of files in the directory that we 557 * do not care about. 558 */ 559 int i; 560 struct diff_filepair *p = NULL; 561 for (i = 0; i < diff_queued_diff.nr; i++) { 562 const char *name; 563 p = diff_queued_diff.queue[i]; 564 name = p->one->path ? p->one->path : p->two->path; 565 if (!strcmp(name, origin->path)) 566 break; 567 } 568 if (!p) 569 die("internal error in blame::find_origin"); 570 switch (p->status) { 571 default: 572 die("internal error in blame::find_origin (%c)", 573 p->status); 574 case 'M': 575 porigin = get_origin(parent, origin->path); 576 oidcpy(&porigin->blob_oid, &p->one->oid); 577 porigin->mode = p->one->mode; 578 break; 579 case 'A': 580 case 'T': 581 /* Did not exist in parent, or type changed */ 582 break; 583 } 584 } 585 diff_flush(&diff_opts); 586 clear_pathspec(&diff_opts.pathspec); 587 return porigin; 588} 589 590/* 591 * We have an origin -- find the path that corresponds to it in its 592 * parent and return an origin structure to represent it. 593 */ 594static struct blame_origin *find_rename(struct commit *parent, 595 struct blame_origin *origin) 596{ 597 struct blame_origin *porigin = NULL; 598 struct diff_options diff_opts; 599 int i; 600 601 diff_setup(&diff_opts); 602 DIFF_OPT_SET(&diff_opts, RECURSIVE); 603 diff_opts.detect_rename = DIFF_DETECT_RENAME; 604 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 605 diff_opts.single_follow = origin->path; 606 diff_setup_done(&diff_opts); 607 608 if (is_null_oid(&origin->commit->object.oid)) 609 do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 610 else 611 diff_tree_sha1(parent->tree->object.oid.hash, 612 origin->commit->tree->object.oid.hash, 613 "", &diff_opts); 614 diffcore_std(&diff_opts); 615 616 for (i = 0; i < diff_queued_diff.nr; i++) { 617 struct diff_filepair *p = diff_queued_diff.queue[i]; 618 if ((p->status == 'R' || p->status == 'C') && 619 !strcmp(p->two->path, origin->path)) { 620 porigin = get_origin(parent, p->one->path); 621 oidcpy(&porigin->blob_oid, &p->one->oid); 622 porigin->mode = p->one->mode; 623 break; 624 } 625 } 626 diff_flush(&diff_opts); 627 clear_pathspec(&diff_opts.pathspec); 628 return porigin; 629} 630 631/* 632 * Append a new blame entry to a given output queue. 633 */ 634static void add_blame_entry(struct blame_entry ***queue, 635 const struct blame_entry *src) 636{ 637 struct blame_entry *e = xmalloc(sizeof(*e)); 638 memcpy(e, src, sizeof(*e)); 639 blame_origin_incref(e->suspect); 640 641 e->next = **queue; 642 **queue = e; 643 *queue = &e->next; 644} 645 646/* 647 * src typically is on-stack; we want to copy the information in it to 648 * a malloced blame_entry that gets added to the given queue. The 649 * origin of dst loses a refcnt. 650 */ 651static void dup_entry(struct blame_entry ***queue, 652 struct blame_entry *dst, struct blame_entry *src) 653{ 654 blame_origin_incref(src->suspect); 655 blame_origin_decref(dst->suspect); 656 memcpy(dst, src, sizeof(*src)); 657 dst->next = **queue; 658 **queue = dst; 659 *queue = &dst->next; 660} 661 662static const char *blame_nth_line(struct blame_scoreboard *sb, long lno) 663{ 664 return sb->final_buf + sb->lineno[lno]; 665} 666 667static const char *nth_line_cb(void *data, long lno) 668{ 669 return blame_nth_line((struct blame_scoreboard *)data, lno); 670} 671 672/* 673 * It is known that lines between tlno to same came from parent, and e 674 * has an overlap with that range. it also is known that parent's 675 * line plno corresponds to e's line tlno. 676 * 677 * <---- e -----> 678 * <------> 679 * <------------> 680 * <------------> 681 * <------------------> 682 * 683 * Split e into potentially three parts; before this chunk, the chunk 684 * to be blamed for the parent, and after that portion. 685 */ 686static void split_overlap(struct blame_entry *split, 687 struct blame_entry *e, 688 int tlno, int plno, int same, 689 struct blame_origin *parent) 690{ 691 int chunk_end_lno; 692 memset(split, 0, sizeof(struct blame_entry [3])); 693 694 if (e->s_lno < tlno) { 695 /* there is a pre-chunk part not blamed on parent */ 696 split[0].suspect = blame_origin_incref(e->suspect); 697 split[0].lno = e->lno; 698 split[0].s_lno = e->s_lno; 699 split[0].num_lines = tlno - e->s_lno; 700 split[1].lno = e->lno + tlno - e->s_lno; 701 split[1].s_lno = plno; 702 } 703 else { 704 split[1].lno = e->lno; 705 split[1].s_lno = plno + (e->s_lno - tlno); 706 } 707 708 if (same < e->s_lno + e->num_lines) { 709 /* there is a post-chunk part not blamed on parent */ 710 split[2].suspect = blame_origin_incref(e->suspect); 711 split[2].lno = e->lno + (same - e->s_lno); 712 split[2].s_lno = e->s_lno + (same - e->s_lno); 713 split[2].num_lines = e->s_lno + e->num_lines - same; 714 chunk_end_lno = split[2].lno; 715 } 716 else 717 chunk_end_lno = e->lno + e->num_lines; 718 split[1].num_lines = chunk_end_lno - split[1].lno; 719 720 /* 721 * if it turns out there is nothing to blame the parent for, 722 * forget about the splitting. !split[1].suspect signals this. 723 */ 724 if (split[1].num_lines < 1) 725 return; 726 split[1].suspect = blame_origin_incref(parent); 727} 728 729/* 730 * split_overlap() divided an existing blame e into up to three parts 731 * in split. Any assigned blame is moved to queue to 732 * reflect the split. 733 */ 734static void split_blame(struct blame_entry ***blamed, 735 struct blame_entry ***unblamed, 736 struct blame_entry *split, 737 struct blame_entry *e) 738{ 739 if (split[0].suspect && split[2].suspect) { 740 /* The first part (reuse storage for the existing entry e) */ 741 dup_entry(unblamed, e, &split[0]); 742 743 /* The last part -- me */ 744 add_blame_entry(unblamed, &split[2]); 745 746 /* ... and the middle part -- parent */ 747 add_blame_entry(blamed, &split[1]); 748 } 749 else if (!split[0].suspect && !split[2].suspect) 750 /* 751 * The parent covers the entire area; reuse storage for 752 * e and replace it with the parent. 753 */ 754 dup_entry(blamed, e, &split[1]); 755 else if (split[0].suspect) { 756 /* me and then parent */ 757 dup_entry(unblamed, e, &split[0]); 758 add_blame_entry(blamed, &split[1]); 759 } 760 else { 761 /* parent and then me */ 762 dup_entry(blamed, e, &split[1]); 763 add_blame_entry(unblamed, &split[2]); 764 } 765} 766 767/* 768 * After splitting the blame, the origins used by the 769 * on-stack blame_entry should lose one refcnt each. 770 */ 771static void decref_split(struct blame_entry *split) 772{ 773 int i; 774 775 for (i = 0; i < 3; i++) 776 blame_origin_decref(split[i].suspect); 777} 778 779/* 780 * reverse_blame reverses the list given in head, appending tail. 781 * That allows us to build lists in reverse order, then reverse them 782 * afterwards. This can be faster than building the list in proper 783 * order right away. The reason is that building in proper order 784 * requires writing a link in the _previous_ element, while building 785 * in reverse order just requires placing the list head into the 786 * _current_ element. 787 */ 788 789static struct blame_entry *reverse_blame(struct blame_entry *head, 790 struct blame_entry *tail) 791{ 792 while (head) { 793 struct blame_entry *next = head->next; 794 head->next = tail; 795 tail = head; 796 head = next; 797 } 798 return tail; 799} 800 801/* 802 * Process one hunk from the patch between the current suspect for 803 * blame_entry e and its parent. This first blames any unfinished 804 * entries before the chunk (which is where target and parent start 805 * differing) on the parent, and then splits blame entries at the 806 * start and at the end of the difference region. Since use of -M and 807 * -C options may lead to overlapping/duplicate source line number 808 * ranges, all we can rely on from sorting/merging is the order of the 809 * first suspect line number. 810 */ 811static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq, 812 int tlno, int offset, int same, 813 struct blame_origin *parent) 814{ 815 struct blame_entry *e = **srcq; 816 struct blame_entry *samep = NULL, *diffp = NULL; 817 818 while (e && e->s_lno < tlno) { 819 struct blame_entry *next = e->next; 820 /* 821 * current record starts before differing portion. If 822 * it reaches into it, we need to split it up and 823 * examine the second part separately. 824 */ 825 if (e->s_lno + e->num_lines > tlno) { 826 /* Move second half to a new record */ 827 int len = tlno - e->s_lno; 828 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry)); 829 n->suspect = e->suspect; 830 n->lno = e->lno + len; 831 n->s_lno = e->s_lno + len; 832 n->num_lines = e->num_lines - len; 833 e->num_lines = len; 834 e->score = 0; 835 /* Push new record to diffp */ 836 n->next = diffp; 837 diffp = n; 838 } else 839 blame_origin_decref(e->suspect); 840 /* Pass blame for everything before the differing 841 * chunk to the parent */ 842 e->suspect = blame_origin_incref(parent); 843 e->s_lno += offset; 844 e->next = samep; 845 samep = e; 846 e = next; 847 } 848 /* 849 * As we don't know how much of a common stretch after this 850 * diff will occur, the currently blamed parts are all that we 851 * can assign to the parent for now. 852 */ 853 854 if (samep) { 855 **dstq = reverse_blame(samep, **dstq); 856 *dstq = &samep->next; 857 } 858 /* 859 * Prepend the split off portions: everything after e starts 860 * after the blameable portion. 861 */ 862 e = reverse_blame(diffp, e); 863 864 /* 865 * Now retain records on the target while parts are different 866 * from the parent. 867 */ 868 samep = NULL; 869 diffp = NULL; 870 while (e && e->s_lno < same) { 871 struct blame_entry *next = e->next; 872 873 /* 874 * If current record extends into sameness, need to split. 875 */ 876 if (e->s_lno + e->num_lines > same) { 877 /* 878 * Move second half to a new record to be 879 * processed by later chunks 880 */ 881 int len = same - e->s_lno; 882 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry)); 883 n->suspect = blame_origin_incref(e->suspect); 884 n->lno = e->lno + len; 885 n->s_lno = e->s_lno + len; 886 n->num_lines = e->num_lines - len; 887 e->num_lines = len; 888 e->score = 0; 889 /* Push new record to samep */ 890 n->next = samep; 891 samep = n; 892 } 893 e->next = diffp; 894 diffp = e; 895 e = next; 896 } 897 **srcq = reverse_blame(diffp, reverse_blame(samep, e)); 898 /* Move across elements that are in the unblamable portion */ 899 if (diffp) 900 *srcq = &diffp->next; 901} 902 903struct blame_chunk_cb_data { 904 struct blame_origin *parent; 905 long offset; 906 struct blame_entry **dstq; 907 struct blame_entry **srcq; 908}; 909 910/* diff chunks are from parent to target */ 911static int blame_chunk_cb(long start_a, long count_a, 912 long start_b, long count_b, void *data) 913{ 914 struct blame_chunk_cb_data *d = data; 915 if (start_a - start_b != d->offset) 916 die("internal error in blame::blame_chunk_cb"); 917 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 918 start_b + count_b, d->parent); 919 d->offset = start_a + count_a - (start_b + count_b); 920 return 0; 921} 922 923/* 924 * We are looking at the origin 'target' and aiming to pass blame 925 * for the lines it is suspected to its parent. Run diff to find 926 * which lines came from parent and pass blame for them. 927 */ 928static void pass_blame_to_parent(struct blame_scoreboard *sb, 929 struct blame_origin *target, 930 struct blame_origin *parent) 931{ 932 mmfile_t file_p, file_o; 933 struct blame_chunk_cb_data d; 934 struct blame_entry *newdest = NULL; 935 936 if (!target->suspects) 937 return; /* nothing remains for this target */ 938 939 d.parent = parent; 940 d.offset = 0; 941 d.dstq = &newdest; d.srcq = &target->suspects; 942 943 fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob); 944 fill_origin_blob(&sb->revs->diffopt, target, &file_o, &sb->num_read_blob); 945 sb->num_get_patch++; 946 947 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d)) 948 die("unable to generate diff (%s -> %s)", 949 oid_to_hex(&parent->commit->object.oid), 950 oid_to_hex(&target->commit->object.oid)); 951 /* The rest are the same as the parent */ 952 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 953 *d.dstq = NULL; 954 queue_blames(sb, parent, newdest); 955 956 return; 957} 958 959/* 960 * The lines in blame_entry after splitting blames many times can become 961 * very small and trivial, and at some point it becomes pointless to 962 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 963 * ordinary C program, and it is not worth to say it was copied from 964 * totally unrelated file in the parent. 965 * 966 * Compute how trivial the lines in the blame_entry are. 967 */ 968static unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e) 969{ 970 unsigned score; 971 const char *cp, *ep; 972 973 if (e->score) 974 return e->score; 975 976 score = 1; 977 cp = blame_nth_line(sb, e->lno); 978 ep = blame_nth_line(sb, e->lno + e->num_lines); 979 while (cp < ep) { 980 unsigned ch = *((unsigned char *)cp); 981 if (isalnum(ch)) 982 score++; 983 cp++; 984 } 985 e->score = score; 986 return score; 987} 988 989/* 990 * best_so_far[] and this[] are both a split of an existing blame_entry 991 * that passes blame to the parent. Maintain best_so_far the best split 992 * so far, by comparing this and best_so_far and copying this into 993 * bst_so_far as needed. 994 */ 995static void copy_split_if_better(struct blame_scoreboard *sb, 996 struct blame_entry *best_so_far, 997 struct blame_entry *this) 998{ 999 int i;10001001 if (!this[1].suspect)1002 return;1003 if (best_so_far[1].suspect) {1004 if (blame_entry_score(sb, &this[1]) < blame_entry_score(sb, &best_so_far[1]))1005 return;1006 }10071008 for (i = 0; i < 3; i++)1009 blame_origin_incref(this[i].suspect);1010 decref_split(best_so_far);1011 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));1012}10131014/*1015 * We are looking at a part of the final image represented by1016 * ent (tlno and same are offset by ent->s_lno).1017 * tlno is where we are looking at in the final image.1018 * up to (but not including) same match preimage.1019 * plno is where we are looking at in the preimage.1020 *1021 * <-------------- final image ---------------------->1022 * <------ent------>1023 * ^tlno ^same1024 * <---------preimage----->1025 * ^plno1026 *1027 * All line numbers are 0-based.1028 */1029static void handle_split(struct blame_scoreboard *sb,1030 struct blame_entry *ent,1031 int tlno, int plno, int same,1032 struct blame_origin *parent,1033 struct blame_entry *split)1034{1035 if (ent->num_lines <= tlno)1036 return;1037 if (tlno < same) {1038 struct blame_entry this[3];1039 tlno += ent->s_lno;1040 same += ent->s_lno;1041 split_overlap(this, ent, tlno, plno, same, parent);1042 copy_split_if_better(sb, split, this);1043 decref_split(this);1044 }1045}10461047struct handle_split_cb_data {1048 struct blame_scoreboard *sb;1049 struct blame_entry *ent;1050 struct blame_origin *parent;1051 struct blame_entry *split;1052 long plno;1053 long tlno;1054};10551056static int handle_split_cb(long start_a, long count_a,1057 long start_b, long count_b, void *data)1058{1059 struct handle_split_cb_data *d = data;1060 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1061 d->split);1062 d->plno = start_a + count_a;1063 d->tlno = start_b + count_b;1064 return 0;1065}10661067/*1068 * Find the lines from parent that are the same as ent so that1069 * we can pass blames to it. file_p has the blob contents for1070 * the parent.1071 */1072static void find_copy_in_blob(struct blame_scoreboard *sb,1073 struct blame_entry *ent,1074 struct blame_origin *parent,1075 struct blame_entry *split,1076 mmfile_t *file_p)1077{1078 const char *cp;1079 mmfile_t file_o;1080 struct handle_split_cb_data d;10811082 memset(&d, 0, sizeof(d));1083 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1084 /*1085 * Prepare mmfile that contains only the lines in ent.1086 */1087 cp = blame_nth_line(sb, ent->lno);1088 file_o.ptr = (char *) cp;1089 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;10901091 /*1092 * file_o is a part of final image we are annotating.1093 * file_p partially may match that image.1094 */1095 memset(split, 0, sizeof(struct blame_entry [3]));1096 if (diff_hunks(file_p, &file_o, handle_split_cb, &d))1097 die("unable to generate diff (%s)",1098 oid_to_hex(&parent->commit->object.oid));1099 /* remainder, if any, all match the preimage */1100 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1101}11021103/* Move all blame entries from list *source that have a score smaller1104 * than score_min to the front of list *small.1105 * Returns a pointer to the link pointing to the old head of the small list.1106 */11071108static struct blame_entry **filter_small(struct blame_scoreboard *sb,1109 struct blame_entry **small,1110 struct blame_entry **source,1111 unsigned score_min)1112{1113 struct blame_entry *p = *source;1114 struct blame_entry *oldsmall = *small;1115 while (p) {1116 if (blame_entry_score(sb, p) <= score_min) {1117 *small = p;1118 small = &p->next;1119 p = *small;1120 } else {1121 *source = p;1122 source = &p->next;1123 p = *source;1124 }1125 }1126 *small = oldsmall;1127 *source = NULL;1128 return small;1129}11301131/*1132 * See if lines currently target is suspected for can be attributed to1133 * parent.1134 */1135static void find_move_in_parent(struct blame_scoreboard *sb,1136 struct blame_entry ***blamed,1137 struct blame_entry **toosmall,1138 struct blame_origin *target,1139 struct blame_origin *parent)1140{1141 struct blame_entry *e, split[3];1142 struct blame_entry *unblamed = target->suspects;1143 struct blame_entry *leftover = NULL;1144 mmfile_t file_p;11451146 if (!unblamed)1147 return; /* nothing remains for this target */11481149 fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);1150 if (!file_p.ptr)1151 return;11521153 /* At each iteration, unblamed has a NULL-terminated list of1154 * entries that have not yet been tested for blame. leftover1155 * contains the reversed list of entries that have been tested1156 * without being assignable to the parent.1157 */1158 do {1159 struct blame_entry **unblamedtail = &unblamed;1160 struct blame_entry *next;1161 for (e = unblamed; e; e = next) {1162 next = e->next;1163 find_copy_in_blob(sb, e, parent, split, &file_p);1164 if (split[1].suspect &&1165 sb->move_score < blame_entry_score(sb, &split[1])) {1166 split_blame(blamed, &unblamedtail, split, e);1167 } else {1168 e->next = leftover;1169 leftover = e;1170 }1171 decref_split(split);1172 }1173 *unblamedtail = NULL;1174 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);1175 } while (unblamed);1176 target->suspects = reverse_blame(leftover, NULL);1177}11781179struct blame_list {1180 struct blame_entry *ent;1181 struct blame_entry split[3];1182};11831184/*1185 * Count the number of entries the target is suspected for,1186 * and prepare a list of entry and the best split.1187 */1188static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1189 int *num_ents_p)1190{1191 struct blame_entry *e;1192 int num_ents, i;1193 struct blame_list *blame_list = NULL;11941195 for (e = unblamed, num_ents = 0; e; e = e->next)1196 num_ents++;1197 if (num_ents) {1198 blame_list = xcalloc(num_ents, sizeof(struct blame_list));1199 for (e = unblamed, i = 0; e; e = e->next)1200 blame_list[i++].ent = e;1201 }1202 *num_ents_p = num_ents;1203 return blame_list;1204}12051206/*1207 * For lines target is suspected for, see if we can find code movement1208 * across file boundary from the parent commit. porigin is the path1209 * in the parent we already tried.1210 */1211static void find_copy_in_parent(struct blame_scoreboard *sb,1212 struct blame_entry ***blamed,1213 struct blame_entry **toosmall,1214 struct blame_origin *target,1215 struct commit *parent,1216 struct blame_origin *porigin,1217 int opt)1218{1219 struct diff_options diff_opts;1220 int i, j;1221 struct blame_list *blame_list;1222 int num_ents;1223 struct blame_entry *unblamed = target->suspects;1224 struct blame_entry *leftover = NULL;12251226 if (!unblamed)1227 return; /* nothing remains for this target */12281229 diff_setup(&diff_opts);1230 DIFF_OPT_SET(&diff_opts, RECURSIVE);1231 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12321233 diff_setup_done(&diff_opts);12341235 /* Try "find copies harder" on new path if requested;1236 * we do not want to use diffcore_rename() actually to1237 * match things up; find_copies_harder is set only to1238 * force diff_tree_sha1() to feed all filepairs to diff_queue,1239 * and this code needs to be after diff_setup_done(), which1240 * usually makes find-copies-harder imply copy detection.1241 */1242 if ((opt & PICKAXE_BLAME_COPY_HARDEST)1243 || ((opt & PICKAXE_BLAME_COPY_HARDER)1244 && (!porigin || strcmp(target->path, porigin->path))))1245 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12461247 if (is_null_oid(&target->commit->object.oid))1248 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1249 else1250 diff_tree_sha1(parent->tree->object.oid.hash,1251 target->commit->tree->object.oid.hash,1252 "", &diff_opts);12531254 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1255 diffcore_std(&diff_opts);12561257 do {1258 struct blame_entry **unblamedtail = &unblamed;1259 blame_list = setup_blame_list(unblamed, &num_ents);12601261 for (i = 0; i < diff_queued_diff.nr; i++) {1262 struct diff_filepair *p = diff_queued_diff.queue[i];1263 struct blame_origin *norigin;1264 mmfile_t file_p;1265 struct blame_entry this[3];12661267 if (!DIFF_FILE_VALID(p->one))1268 continue; /* does not exist in parent */1269 if (S_ISGITLINK(p->one->mode))1270 continue; /* ignore git links */1271 if (porigin && !strcmp(p->one->path, porigin->path))1272 /* find_move already dealt with this path */1273 continue;12741275 norigin = get_origin(parent, p->one->path);1276 oidcpy(&norigin->blob_oid, &p->one->oid);1277 norigin->mode = p->one->mode;1278 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p, &sb->num_read_blob);1279 if (!file_p.ptr)1280 continue;12811282 for (j = 0; j < num_ents; j++) {1283 find_copy_in_blob(sb, blame_list[j].ent,1284 norigin, this, &file_p);1285 copy_split_if_better(sb, blame_list[j].split,1286 this);1287 decref_split(this);1288 }1289 blame_origin_decref(norigin);1290 }12911292 for (j = 0; j < num_ents; j++) {1293 struct blame_entry *split = blame_list[j].split;1294 if (split[1].suspect &&1295 sb->copy_score < blame_entry_score(sb, &split[1])) {1296 split_blame(blamed, &unblamedtail, split,1297 blame_list[j].ent);1298 } else {1299 blame_list[j].ent->next = leftover;1300 leftover = blame_list[j].ent;1301 }1302 decref_split(split);1303 }1304 free(blame_list);1305 *unblamedtail = NULL;1306 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);1307 } while (unblamed);1308 target->suspects = reverse_blame(leftover, NULL);1309 diff_flush(&diff_opts);1310 clear_pathspec(&diff_opts.pathspec);1311}13121313/*1314 * The blobs of origin and porigin exactly match, so everything1315 * origin is suspected for can be blamed on the parent.1316 */1317static void pass_whole_blame(struct blame_scoreboard *sb,1318 struct blame_origin *origin, struct blame_origin *porigin)1319{1320 struct blame_entry *e, *suspects;13211322 if (!porigin->file.ptr && origin->file.ptr) {1323 /* Steal its file */1324 porigin->file = origin->file;1325 origin->file.ptr = NULL;1326 }1327 suspects = origin->suspects;1328 origin->suspects = NULL;1329 for (e = suspects; e; e = e->next) {1330 blame_origin_incref(porigin);1331 blame_origin_decref(e->suspect);1332 e->suspect = porigin;1333 }1334 queue_blames(sb, porigin, suspects);1335}13361337/*1338 * We pass blame from the current commit to its parents. We keep saying1339 * "parent" (and "porigin"), but what we mean is to find scapegoat to1340 * exonerate ourselves.1341 */1342static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)1343{1344 if (!reverse) {1345 if (revs->first_parent_only &&1346 commit->parents &&1347 commit->parents->next) {1348 free_commit_list(commit->parents->next);1349 commit->parents->next = NULL;1350 }1351 return commit->parents;1352 }1353 return lookup_decoration(&revs->children, &commit->object);1354}13551356static int num_scapegoats(struct rev_info *revs, struct commit *commit)1357{1358 struct commit_list *l = first_scapegoat(revs, commit);1359 return commit_list_count(l);1360}13611362/* Distribute collected unsorted blames to the respected sorted lists1363 * in the various origins.1364 */1365static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)1366{1367 blamed = blame_sort(blamed, compare_blame_suspect);1368 while (blamed)1369 {1370 struct blame_origin *porigin = blamed->suspect;1371 struct blame_entry *suspects = NULL;1372 do {1373 struct blame_entry *next = blamed->next;1374 blamed->next = suspects;1375 suspects = blamed;1376 blamed = next;1377 } while (blamed && blamed->suspect == porigin);1378 suspects = reverse_blame(suspects, NULL);1379 queue_blames(sb, porigin, suspects);1380 }1381}13821383#define MAXSG 1613841385static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)1386{1387 struct rev_info *revs = sb->revs;1388 int i, pass, num_sg;1389 struct commit *commit = origin->commit;1390 struct commit_list *sg;1391 struct blame_origin *sg_buf[MAXSG];1392 struct blame_origin *porigin, **sg_origin = sg_buf;1393 struct blame_entry *toosmall = NULL;1394 struct blame_entry *blames, **blametail = &blames;13951396 num_sg = num_scapegoats(revs, commit);1397 if (!num_sg)1398 goto finish;1399 else if (num_sg < ARRAY_SIZE(sg_buf))1400 memset(sg_buf, 0, sizeof(sg_buf));1401 else1402 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));14031404 /*1405 * The first pass looks for unrenamed path to optimize for1406 * common cases, then we look for renames in the second pass.1407 */1408 for (pass = 0; pass < 2 - no_whole_file_rename; pass++) {1409 struct blame_origin *(*find)(struct commit *, struct blame_origin *);1410 find = pass ? find_rename : find_origin;14111412 for (i = 0, sg = first_scapegoat(revs, commit);1413 i < num_sg && sg;1414 sg = sg->next, i++) {1415 struct commit *p = sg->item;1416 int j, same;14171418 if (sg_origin[i])1419 continue;1420 if (parse_commit(p))1421 continue;1422 porigin = find(p, origin);1423 if (!porigin)1424 continue;1425 if (!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {1426 pass_whole_blame(sb, origin, porigin);1427 blame_origin_decref(porigin);1428 goto finish;1429 }1430 for (j = same = 0; j < i; j++)1431 if (sg_origin[j] &&1432 !oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {1433 same = 1;1434 break;1435 }1436 if (!same)1437 sg_origin[i] = porigin;1438 else1439 blame_origin_decref(porigin);1440 }1441 }14421443 sb->num_commits++;1444 for (i = 0, sg = first_scapegoat(revs, commit);1445 i < num_sg && sg;1446 sg = sg->next, i++) {1447 struct blame_origin *porigin = sg_origin[i];1448 if (!porigin)1449 continue;1450 if (!origin->previous) {1451 blame_origin_incref(porigin);1452 origin->previous = porigin;1453 }1454 pass_blame_to_parent(sb, origin, porigin);1455 if (!origin->suspects)1456 goto finish;1457 }14581459 /*1460 * Optionally find moves in parents' files.1461 */1462 if (opt & PICKAXE_BLAME_MOVE) {1463 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);1464 if (origin->suspects) {1465 for (i = 0, sg = first_scapegoat(revs, commit);1466 i < num_sg && sg;1467 sg = sg->next, i++) {1468 struct blame_origin *porigin = sg_origin[i];1469 if (!porigin)1470 continue;1471 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1472 if (!origin->suspects)1473 break;1474 }1475 }1476 }14771478 /*1479 * Optionally find copies from parents' files.1480 */1481 if (opt & PICKAXE_BLAME_COPY) {1482 if (sb->copy_score > sb->move_score)1483 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);1484 else if (sb->copy_score < sb->move_score) {1485 origin->suspects = blame_merge(origin->suspects, toosmall);1486 toosmall = NULL;1487 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);1488 }1489 if (!origin->suspects)1490 goto finish;14911492 for (i = 0, sg = first_scapegoat(revs, commit);1493 i < num_sg && sg;1494 sg = sg->next, i++) {1495 struct blame_origin *porigin = sg_origin[i];1496 find_copy_in_parent(sb, &blametail, &toosmall,1497 origin, sg->item, porigin, opt);1498 if (!origin->suspects)1499 goto finish;1500 }1501 }15021503finish:1504 *blametail = NULL;1505 distribute_blame(sb, blames);1506 /*1507 * prepend toosmall to origin->suspects1508 *1509 * There is no point in sorting: this ends up on a big1510 * unsorted list in the caller anyway.1511 */1512 if (toosmall) {1513 struct blame_entry **tail = &toosmall;1514 while (*tail)1515 tail = &(*tail)->next;1516 *tail = origin->suspects;1517 origin->suspects = toosmall;1518 }1519 for (i = 0; i < num_sg; i++) {1520 if (sg_origin[i]) {1521 drop_origin_blob(sg_origin[i]);1522 blame_origin_decref(sg_origin[i]);1523 }1524 }1525 drop_origin_blob(origin);1526 if (sg_buf != sg_origin)1527 free(sg_origin);1528}15291530/*1531 * Information on commits, used for output.1532 */1533struct commit_info {1534 struct strbuf author;1535 struct strbuf author_mail;1536 timestamp_t author_time;1537 struct strbuf author_tz;15381539 /* filled only when asked for details */1540 struct strbuf committer;1541 struct strbuf committer_mail;1542 timestamp_t committer_time;1543 struct strbuf committer_tz;15441545 struct strbuf summary;1546};15471548/*1549 * Parse author/committer line in the commit object buffer1550 */1551static void get_ac_line(const char *inbuf, const char *what,1552 struct strbuf *name, struct strbuf *mail,1553 timestamp_t *time, struct strbuf *tz)1554{1555 struct ident_split ident;1556 size_t len, maillen, namelen;1557 char *tmp, *endp;1558 const char *namebuf, *mailbuf;15591560 tmp = strstr(inbuf, what);1561 if (!tmp)1562 goto error_out;1563 tmp += strlen(what);1564 endp = strchr(tmp, '\n');1565 if (!endp)1566 len = strlen(tmp);1567 else1568 len = endp - tmp;15691570 if (split_ident_line(&ident, tmp, len)) {1571 error_out:1572 /* Ugh */1573 tmp = "(unknown)";1574 strbuf_addstr(name, tmp);1575 strbuf_addstr(mail, tmp);1576 strbuf_addstr(tz, tmp);1577 *time = 0;1578 return;1579 }15801581 namelen = ident.name_end - ident.name_begin;1582 namebuf = ident.name_begin;15831584 maillen = ident.mail_end - ident.mail_begin;1585 mailbuf = ident.mail_begin;15861587 if (ident.date_begin && ident.date_end)1588 *time = strtoul(ident.date_begin, NULL, 10);1589 else1590 *time = 0;15911592 if (ident.tz_begin && ident.tz_end)1593 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1594 else1595 strbuf_addstr(tz, "(unknown)");15961597 /*1598 * Now, convert both name and e-mail using mailmap1599 */1600 map_user(&mailmap, &mailbuf, &maillen,1601 &namebuf, &namelen);16021603 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);1604 strbuf_add(name, namebuf, namelen);1605}16061607static void commit_info_init(struct commit_info *ci)1608{16091610 strbuf_init(&ci->author, 0);1611 strbuf_init(&ci->author_mail, 0);1612 strbuf_init(&ci->author_tz, 0);1613 strbuf_init(&ci->committer, 0);1614 strbuf_init(&ci->committer_mail, 0);1615 strbuf_init(&ci->committer_tz, 0);1616 strbuf_init(&ci->summary, 0);1617}16181619static void commit_info_destroy(struct commit_info *ci)1620{16211622 strbuf_release(&ci->author);1623 strbuf_release(&ci->author_mail);1624 strbuf_release(&ci->author_tz);1625 strbuf_release(&ci->committer);1626 strbuf_release(&ci->committer_mail);1627 strbuf_release(&ci->committer_tz);1628 strbuf_release(&ci->summary);1629}16301631static void get_commit_info(struct commit *commit,1632 struct commit_info *ret,1633 int detailed)1634{1635 int len;1636 const char *subject, *encoding;1637 const char *message;16381639 commit_info_init(ret);16401641 encoding = get_log_output_encoding();1642 message = logmsg_reencode(commit, NULL, encoding);1643 get_ac_line(message, "\nauthor ",1644 &ret->author, &ret->author_mail,1645 &ret->author_time, &ret->author_tz);16461647 if (!detailed) {1648 unuse_commit_buffer(commit, message);1649 return;1650 }16511652 get_ac_line(message, "\ncommitter ",1653 &ret->committer, &ret->committer_mail,1654 &ret->committer_time, &ret->committer_tz);16551656 len = find_commit_subject(message, &subject);1657 if (len)1658 strbuf_add(&ret->summary, subject, len);1659 else1660 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));16611662 unuse_commit_buffer(commit, message);1663}16641665/*1666 * Write out any suspect information which depends on the path. This must be1667 * handled separately from emit_one_suspect_detail(), because a given commit1668 * may have changes in multiple paths. So this needs to appear each time1669 * we mention a new group.1670 *1671 * To allow LF and other nonportable characters in pathnames,1672 * they are c-style quoted as needed.1673 */1674static void write_filename_info(struct blame_origin *suspect)1675{1676 if (suspect->previous) {1677 struct blame_origin *prev = suspect->previous;1678 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));1679 write_name_quoted(prev->path, stdout, '\n');1680 }1681 printf("filename ");1682 write_name_quoted(suspect->path, stdout, '\n');1683}16841685/*1686 * Porcelain/Incremental format wants to show a lot of details per1687 * commit. Instead of repeating this every line, emit it only once,1688 * the first time each commit appears in the output (unless the1689 * user has specifically asked for us to repeat).1690 */1691static int emit_one_suspect_detail(struct blame_origin *suspect, int repeat)1692{1693 struct commit_info ci;16941695 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1696 return 0;16971698 suspect->commit->object.flags |= METAINFO_SHOWN;1699 get_commit_info(suspect->commit, &ci, 1);1700 printf("author %s\n", ci.author.buf);1701 printf("author-mail %s\n", ci.author_mail.buf);1702 printf("author-time %"PRItime"\n", ci.author_time);1703 printf("author-tz %s\n", ci.author_tz.buf);1704 printf("committer %s\n", ci.committer.buf);1705 printf("committer-mail %s\n", ci.committer_mail.buf);1706 printf("committer-time %"PRItime"\n", ci.committer_time);1707 printf("committer-tz %s\n", ci.committer_tz.buf);1708 printf("summary %s\n", ci.summary.buf);1709 if (suspect->commit->object.flags & UNINTERESTING)1710 printf("boundary\n");17111712 commit_info_destroy(&ci);17131714 return 1;1715}17161717/*1718 * The blame_entry is found to be guilty for the range.1719 * Show it in incremental output.1720 */1721static void found_guilty_entry(struct blame_entry *ent,1722 struct progress_info *pi)1723{1724 if (incremental) {1725 struct blame_origin *suspect = ent->suspect;17261727 printf("%s %d %d %d\n",1728 oid_to_hex(&suspect->commit->object.oid),1729 ent->s_lno + 1, ent->lno + 1, ent->num_lines);1730 emit_one_suspect_detail(suspect, 0);1731 write_filename_info(suspect);1732 maybe_flush_or_die(stdout, "stdout");1733 }1734 pi->blamed_lines += ent->num_lines;1735 display_progress(pi->progress, pi->blamed_lines);1736}17371738/*1739 * The main loop -- while we have blobs with lines whose true origin1740 * is still unknown, pick one blob, and allow its lines to pass blames1741 * to its parents. */1742static void assign_blame(struct blame_scoreboard *sb, int opt)1743{1744 struct rev_info *revs = sb->revs;1745 struct commit *commit = prio_queue_get(&sb->commits);1746 struct progress_info pi = { NULL, 0 };17471748 if (show_progress)1749 pi.progress = start_progress_delay(_("Blaming lines"),1750 sb->num_lines, 50, 1);17511752 while (commit) {1753 struct blame_entry *ent;1754 struct blame_origin *suspect = commit->util;17551756 /* find one suspect to break down */1757 while (suspect && !suspect->suspects)1758 suspect = suspect->next;17591760 if (!suspect) {1761 commit = prio_queue_get(&sb->commits);1762 continue;1763 }17641765 assert(commit == suspect->commit);17661767 /*1768 * We will use this suspect later in the loop,1769 * so hold onto it in the meantime.1770 */1771 blame_origin_incref(suspect);1772 parse_commit(commit);1773 if (reverse ||1774 (!(commit->object.flags & UNINTERESTING) &&1775 !(revs->max_age != -1 && commit->date < revs->max_age)))1776 pass_blame(sb, suspect, opt);1777 else {1778 commit->object.flags |= UNINTERESTING;1779 if (commit->object.parsed)1780 mark_parents_uninteresting(commit);1781 }1782 /* treat root commit as boundary */1783 if (!commit->parents && !show_root)1784 commit->object.flags |= UNINTERESTING;17851786 /* Take responsibility for the remaining entries */1787 ent = suspect->suspects;1788 if (ent) {1789 suspect->guilty = 1;1790 for (;;) {1791 struct blame_entry *next = ent->next;1792 found_guilty_entry(ent, &pi);1793 if (next) {1794 ent = next;1795 continue;1796 }1797 ent->next = sb->ent;1798 sb->ent = suspect->suspects;1799 suspect->suspects = NULL;1800 break;1801 }1802 }1803 blame_origin_decref(suspect);18041805 if (DEBUG) /* sanity */1806 sanity_check_refcnt(sb);1807 }18081809 stop_progress(&pi.progress);1810}18111812static const char *format_time(timestamp_t time, const char *tz_str,1813 int show_raw_time)1814{1815 static struct strbuf time_buf = STRBUF_INIT;18161817 strbuf_reset(&time_buf);1818 if (show_raw_time) {1819 strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);1820 }1821 else {1822 const char *time_str;1823 size_t time_width;1824 int tz;1825 tz = atoi(tz_str);1826 time_str = show_date(time, tz, &blame_date_mode);1827 strbuf_addstr(&time_buf, time_str);1828 /*1829 * Add space paddings to time_buf to display a fixed width1830 * string, and use time_width for display width calibration.1831 */1832 for (time_width = utf8_strwidth(time_str);1833 time_width < blame_date_width;1834 time_width++)1835 strbuf_addch(&time_buf, ' ');1836 }1837 return time_buf.buf;1838}18391840#define OUTPUT_ANNOTATE_COMPAT 0011841#define OUTPUT_LONG_OBJECT_NAME 0021842#define OUTPUT_RAW_TIMESTAMP 0041843#define OUTPUT_PORCELAIN 0101844#define OUTPUT_SHOW_NAME 0201845#define OUTPUT_SHOW_NUMBER 0401846#define OUTPUT_SHOW_SCORE 01001847#define OUTPUT_NO_AUTHOR 02001848#define OUTPUT_SHOW_EMAIL 04001849#define OUTPUT_LINE_PORCELAIN 0100018501851static void emit_porcelain_details(struct blame_origin *suspect, int repeat)1852{1853 if (emit_one_suspect_detail(suspect, repeat) ||1854 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))1855 write_filename_info(suspect);1856}18571858static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,1859 int opt)1860{1861 int repeat = opt & OUTPUT_LINE_PORCELAIN;1862 int cnt;1863 const char *cp;1864 struct blame_origin *suspect = ent->suspect;1865 char hex[GIT_MAX_HEXSZ + 1];18661867 oid_to_hex_r(hex, &suspect->commit->object.oid);1868 printf("%s %d %d %d\n",1869 hex,1870 ent->s_lno + 1,1871 ent->lno + 1,1872 ent->num_lines);1873 emit_porcelain_details(suspect, repeat);18741875 cp = blame_nth_line(sb, ent->lno);1876 for (cnt = 0; cnt < ent->num_lines; cnt++) {1877 char ch;1878 if (cnt) {1879 printf("%s %d %d\n", hex,1880 ent->s_lno + 1 + cnt,1881 ent->lno + 1 + cnt);1882 if (repeat)1883 emit_porcelain_details(suspect, 1);1884 }1885 putchar('\t');1886 do {1887 ch = *cp++;1888 putchar(ch);1889 } while (ch != '\n' &&1890 cp < sb->final_buf + sb->final_buf_size);1891 }18921893 if (sb->final_buf_size && cp[-1] != '\n')1894 putchar('\n');1895}18961897static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int opt)1898{1899 int cnt;1900 const char *cp;1901 struct blame_origin *suspect = ent->suspect;1902 struct commit_info ci;1903 char hex[GIT_MAX_HEXSZ + 1];1904 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19051906 get_commit_info(suspect->commit, &ci, 1);1907 oid_to_hex_r(hex, &suspect->commit->object.oid);19081909 cp = blame_nth_line(sb, ent->lno);1910 for (cnt = 0; cnt < ent->num_lines; cnt++) {1911 char ch;1912 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? GIT_SHA1_HEXSZ : abbrev;19131914 if (suspect->commit->object.flags & UNINTERESTING) {1915 if (blank_boundary)1916 memset(hex, ' ', length);1917 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {1918 length--;1919 putchar('^');1920 }1921 }19221923 printf("%.*s", length, hex);1924 if (opt & OUTPUT_ANNOTATE_COMPAT) {1925 const char *name;1926 if (opt & OUTPUT_SHOW_EMAIL)1927 name = ci.author_mail.buf;1928 else1929 name = ci.author.buf;1930 printf("\t(%10s\t%10s\t%d)", name,1931 format_time(ci.author_time, ci.author_tz.buf,1932 show_raw_time),1933 ent->lno + 1 + cnt);1934 } else {1935 if (opt & OUTPUT_SHOW_SCORE)1936 printf(" %*d %02d",1937 max_score_digits, ent->score,1938 ent->suspect->refcnt);1939 if (opt & OUTPUT_SHOW_NAME)1940 printf(" %-*.*s", longest_file, longest_file,1941 suspect->path);1942 if (opt & OUTPUT_SHOW_NUMBER)1943 printf(" %*d", max_orig_digits,1944 ent->s_lno + 1 + cnt);19451946 if (!(opt & OUTPUT_NO_AUTHOR)) {1947 const char *name;1948 int pad;1949 if (opt & OUTPUT_SHOW_EMAIL)1950 name = ci.author_mail.buf;1951 else1952 name = ci.author.buf;1953 pad = longest_author - utf8_strwidth(name);1954 printf(" (%s%*s %10s",1955 name, pad, "",1956 format_time(ci.author_time,1957 ci.author_tz.buf,1958 show_raw_time));1959 }1960 printf(" %*d) ",1961 max_digits, ent->lno + 1 + cnt);1962 }1963 do {1964 ch = *cp++;1965 putchar(ch);1966 } while (ch != '\n' &&1967 cp < sb->final_buf + sb->final_buf_size);1968 }19691970 if (sb->final_buf_size && cp[-1] != '\n')1971 putchar('\n');19721973 commit_info_destroy(&ci);1974}19751976static void output(struct blame_scoreboard *sb, int option)1977{1978 struct blame_entry *ent;19791980 if (option & OUTPUT_PORCELAIN) {1981 for (ent = sb->ent; ent; ent = ent->next) {1982 int count = 0;1983 struct blame_origin *suspect;1984 struct commit *commit = ent->suspect->commit;1985 if (commit->object.flags & MORE_THAN_ONE_PATH)1986 continue;1987 for (suspect = commit->util; suspect; suspect = suspect->next) {1988 if (suspect->guilty && count++) {1989 commit->object.flags |= MORE_THAN_ONE_PATH;1990 break;1991 }1992 }1993 }1994 }19951996 for (ent = sb->ent; ent; ent = ent->next) {1997 if (option & OUTPUT_PORCELAIN)1998 emit_porcelain(sb, ent, option);1999 else {2000 emit_other(sb, ent, option);2001 }2002 }2003}20042005static const char *get_next_line(const char *start, const char *end)2006{2007 const char *nl = memchr(start, '\n', end - start);2008 return nl ? nl + 1 : end;2009}20102011/*2012 * To allow quick access to the contents of nth line in the2013 * final image, prepare an index in the scoreboard.2014 */2015static int prepare_lines(struct blame_scoreboard *sb)2016{2017 const char *buf = sb->final_buf;2018 unsigned long len = sb->final_buf_size;2019 const char *end = buf + len;2020 const char *p;2021 int *lineno;2022 int num = 0;20232024 for (p = buf; p < end; p = get_next_line(p, end))2025 num++;20262027 ALLOC_ARRAY(sb->lineno, num + 1);2028 lineno = sb->lineno;20292030 for (p = buf; p < end; p = get_next_line(p, end))2031 *lineno++ = p - buf;20322033 *lineno = len;20342035 sb->num_lines = num;2036 return sb->num_lines;2037}20382039/*2040 * Add phony grafts for use with -S; this is primarily to2041 * support git's cvsserver that wants to give a linear history2042 * to its clients.2043 */2044static int read_ancestry(const char *graft_file)2045{2046 FILE *fp = fopen(graft_file, "r");2047 struct strbuf buf = STRBUF_INIT;2048 if (!fp)2049 return -1;2050 while (!strbuf_getwholeline(&buf, fp, '\n')) {2051 /* The format is just "Commit Parent1 Parent2 ...\n" */2052 struct commit_graft *graft = read_graft_line(buf.buf, buf.len);2053 if (graft)2054 register_commit_graft(graft, 0);2055 }2056 fclose(fp);2057 strbuf_release(&buf);2058 return 0;2059}20602061static int update_auto_abbrev(int auto_abbrev, struct blame_origin *suspect)2062{2063 const char *uniq = find_unique_abbrev(suspect->commit->object.oid.hash,2064 auto_abbrev);2065 int len = strlen(uniq);2066 if (auto_abbrev < len)2067 return len;2068 return auto_abbrev;2069}20702071/*2072 * How many columns do we need to show line numbers, authors,2073 * and filenames?2074 */2075static void find_alignment(struct blame_scoreboard *sb, int *option)2076{2077 int longest_src_lines = 0;2078 int longest_dst_lines = 0;2079 unsigned largest_score = 0;2080 struct blame_entry *e;2081 int compute_auto_abbrev = (abbrev < 0);2082 int auto_abbrev = DEFAULT_ABBREV;20832084 for (e = sb->ent; e; e = e->next) {2085 struct blame_origin *suspect = e->suspect;2086 int num;20872088 if (compute_auto_abbrev)2089 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);2090 if (strcmp(suspect->path, sb->path))2091 *option |= OUTPUT_SHOW_NAME;2092 num = strlen(suspect->path);2093 if (longest_file < num)2094 longest_file = num;2095 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {2096 struct commit_info ci;2097 suspect->commit->object.flags |= METAINFO_SHOWN;2098 get_commit_info(suspect->commit, &ci, 1);2099 if (*option & OUTPUT_SHOW_EMAIL)2100 num = utf8_strwidth(ci.author_mail.buf);2101 else2102 num = utf8_strwidth(ci.author.buf);2103 if (longest_author < num)2104 longest_author = num;2105 commit_info_destroy(&ci);2106 }2107 num = e->s_lno + e->num_lines;2108 if (longest_src_lines < num)2109 longest_src_lines = num;2110 num = e->lno + e->num_lines;2111 if (longest_dst_lines < num)2112 longest_dst_lines = num;2113 if (largest_score < blame_entry_score(sb, e))2114 largest_score = blame_entry_score(sb, e);2115 }2116 max_orig_digits = decimal_width(longest_src_lines);2117 max_digits = decimal_width(longest_dst_lines);2118 max_score_digits = decimal_width(largest_score);21192120 if (compute_auto_abbrev)2121 /* one more abbrev length is needed for the boundary commit */2122 abbrev = auto_abbrev + 1;2123}21242125/*2126 * For debugging -- origin is refcounted, and this asserts that2127 * we do not underflow.2128 */2129static void sanity_check_refcnt(struct blame_scoreboard *sb)2130{2131 int baa = 0;2132 struct blame_entry *ent;21332134 for (ent = sb->ent; ent; ent = ent->next) {2135 /* Nobody should have zero or negative refcnt */2136 if (ent->suspect->refcnt <= 0) {2137 fprintf(stderr, "%s in %s has negative refcnt %d\n",2138 ent->suspect->path,2139 oid_to_hex(&ent->suspect->commit->object.oid),2140 ent->suspect->refcnt);2141 baa = 1;2142 }2143 }2144 if (baa) {2145 int opt = 0160;2146 find_alignment(sb, &opt);2147 output(sb, opt);2148 die("Baa %d!", baa);2149 }2150}21512152static unsigned parse_score(const char *arg)2153{2154 char *end;2155 unsigned long score = strtoul(arg, &end, 10);2156 if (*end)2157 return 0;2158 return score;2159}21602161static const char *add_prefix(const char *prefix, const char *path)2162{2163 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);2164}21652166static int git_blame_config(const char *var, const char *value, void *cb)2167{2168 if (!strcmp(var, "blame.showroot")) {2169 show_root = git_config_bool(var, value);2170 return 0;2171 }2172 if (!strcmp(var, "blame.blankboundary")) {2173 blank_boundary = git_config_bool(var, value);2174 return 0;2175 }2176 if (!strcmp(var, "blame.showemail")) {2177 int *output_option = cb;2178 if (git_config_bool(var, value))2179 *output_option |= OUTPUT_SHOW_EMAIL;2180 else2181 *output_option &= ~OUTPUT_SHOW_EMAIL;2182 return 0;2183 }2184 if (!strcmp(var, "blame.date")) {2185 if (!value)2186 return config_error_nonbool(var);2187 parse_date_format(value, &blame_date_mode);2188 return 0;2189 }21902191 if (git_diff_heuristic_config(var, value, cb) < 0)2192 return -1;2193 if (userdiff_config(var, value) < 0)2194 return -1;21952196 return git_default_config(var, value, cb);2197}21982199static void verify_working_tree_path(struct commit *work_tree, const char *path)2200{2201 struct commit_list *parents;2202 int pos;22032204 for (parents = work_tree->parents; parents; parents = parents->next) {2205 const struct object_id *commit_oid = &parents->item->object.oid;2206 struct object_id blob_oid;2207 unsigned mode;22082209 if (!get_tree_entry(commit_oid->hash, path, blob_oid.hash, &mode) &&2210 sha1_object_info(blob_oid.hash, NULL) == OBJ_BLOB)2211 return;2212 }22132214 pos = cache_name_pos(path, strlen(path));2215 if (pos >= 0)2216 ; /* path is in the index */2217 else if (-1 - pos < active_nr &&2218 !strcmp(active_cache[-1 - pos]->name, path))2219 ; /* path is in the index, unmerged */2220 else2221 die("no such path '%s' in HEAD", path);2222}22232224static struct commit_list **append_parent(struct commit_list **tail, const struct object_id *oid)2225{2226 struct commit *parent;22272228 parent = lookup_commit_reference(oid->hash);2229 if (!parent)2230 die("no such commit %s", oid_to_hex(oid));2231 return &commit_list_insert(parent, tail)->next;2232}22332234static void append_merge_parents(struct commit_list **tail)2235{2236 int merge_head;2237 struct strbuf line = STRBUF_INIT;22382239 merge_head = open(git_path_merge_head(), O_RDONLY);2240 if (merge_head < 0) {2241 if (errno == ENOENT)2242 return;2243 die("cannot open '%s' for reading", git_path_merge_head());2244 }22452246 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {2247 struct object_id oid;2248 if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))2249 die("unknown line in '%s': %s", git_path_merge_head(), line.buf);2250 tail = append_parent(tail, &oid);2251 }2252 close(merge_head);2253 strbuf_release(&line);2254}22552256/*2257 * This isn't as simple as passing sb->buf and sb->len, because we2258 * want to transfer ownership of the buffer to the commit (so we2259 * must use detach).2260 */2261static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)2262{2263 size_t len;2264 void *buf = strbuf_detach(sb, &len);2265 set_commit_buffer(c, buf, len);2266}22672268/*2269 * Prepare a dummy commit that represents the work tree (or staged) item.2270 * Note that annotating work tree item never works in the reverse.2271 */2272static struct commit *fake_working_tree_commit(struct diff_options *opt,2273 const char *path,2274 const char *contents_from)2275{2276 struct commit *commit;2277 struct blame_origin *origin;2278 struct commit_list **parent_tail, *parent;2279 struct object_id head_oid;2280 struct strbuf buf = STRBUF_INIT;2281 const char *ident;2282 time_t now;2283 int size, len;2284 struct cache_entry *ce;2285 unsigned mode;2286 struct strbuf msg = STRBUF_INIT;22872288 read_cache();2289 time(&now);2290 commit = alloc_commit_node();2291 commit->object.parsed = 1;2292 commit->date = now;2293 parent_tail = &commit->parents;22942295 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_oid.hash, NULL))2296 die("no such ref: HEAD");22972298 parent_tail = append_parent(parent_tail, &head_oid);2299 append_merge_parents(parent_tail);2300 verify_working_tree_path(commit, path);23012302 origin = make_origin(commit, path);23032304 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);2305 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");2306 for (parent = commit->parents; parent; parent = parent->next)2307 strbuf_addf(&msg, "parent %s\n",2308 oid_to_hex(&parent->item->object.oid));2309 strbuf_addf(&msg,2310 "author %s\n"2311 "committer %s\n\n"2312 "Version of %s from %s\n",2313 ident, ident, path,2314 (!contents_from ? path :2315 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));2316 set_commit_buffer_from_strbuf(commit, &msg);23172318 if (!contents_from || strcmp("-", contents_from)) {2319 struct stat st;2320 const char *read_from;2321 char *buf_ptr;2322 unsigned long buf_len;23232324 if (contents_from) {2325 if (stat(contents_from, &st) < 0)2326 die_errno("Cannot stat '%s'", contents_from);2327 read_from = contents_from;2328 }2329 else {2330 if (lstat(path, &st) < 0)2331 die_errno("Cannot lstat '%s'", path);2332 read_from = path;2333 }2334 mode = canon_mode(st.st_mode);23352336 switch (st.st_mode & S_IFMT) {2337 case S_IFREG:2338 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2339 textconv_object(read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))2340 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);2341 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2342 die_errno("cannot open or read '%s'", read_from);2343 break;2344 case S_IFLNK:2345 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)2346 die_errno("cannot readlink '%s'", read_from);2347 break;2348 default:2349 die("unsupported file type %s", read_from);2350 }2351 }2352 else {2353 /* Reading from stdin */2354 mode = 0;2355 if (strbuf_read(&buf, 0, 0) < 0)2356 die_errno("failed to read from stdin");2357 }2358 convert_to_git(path, buf.buf, buf.len, &buf, 0);2359 origin->file.ptr = buf.buf;2360 origin->file.size = buf.len;2361 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_oid.hash);23622363 /*2364 * Read the current index, replace the path entry with2365 * origin->blob_sha1 without mucking with its mode or type2366 * bits; we are not going to write this index out -- we just2367 * want to run "diff-index --cached".2368 */2369 discard_cache();2370 read_cache();23712372 len = strlen(path);2373 if (!mode) {2374 int pos = cache_name_pos(path, len);2375 if (0 <= pos)2376 mode = active_cache[pos]->ce_mode;2377 else2378 /* Let's not bother reading from HEAD tree */2379 mode = S_IFREG | 0644;2380 }2381 size = cache_entry_size(len);2382 ce = xcalloc(1, size);2383 oidcpy(&ce->oid, &origin->blob_oid);2384 memcpy(ce->name, path, len);2385 ce->ce_flags = create_ce_flags(0);2386 ce->ce_namelen = len;2387 ce->ce_mode = create_ce_mode(mode);2388 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23892390 cache_tree_invalidate_path(&the_index, path);23912392 return commit;2393}23942395static struct commit *find_single_final(struct rev_info *revs,2396 const char **name_p)2397{2398 int i;2399 struct commit *found = NULL;2400 const char *name = NULL;24012402 for (i = 0; i < revs->pending.nr; i++) {2403 struct object *obj = revs->pending.objects[i].item;2404 if (obj->flags & UNINTERESTING)2405 continue;2406 obj = deref_tag(obj, NULL, 0);2407 if (obj->type != OBJ_COMMIT)2408 die("Non commit %s?", revs->pending.objects[i].name);2409 if (found)2410 die("More than one commit to dig from %s and %s?",2411 revs->pending.objects[i].name, name);2412 found = (struct commit *)obj;2413 name = revs->pending.objects[i].name;2414 }2415 if (name_p)2416 *name_p = name;2417 return found;2418}24192420static char *prepare_final(struct blame_scoreboard *sb)2421{2422 const char *name;2423 sb->final = find_single_final(sb->revs, &name);2424 return xstrdup_or_null(name);2425}24262427static const char *dwim_reverse_initial(struct blame_scoreboard *sb)2428{2429 /*2430 * DWIM "git blame --reverse ONE -- PATH" as2431 * "git blame --reverse ONE..HEAD -- PATH" but only do so2432 * when it makes sense.2433 */2434 struct object *obj;2435 struct commit *head_commit;2436 unsigned char head_sha1[20];24372438 if (sb->revs->pending.nr != 1)2439 return NULL;24402441 /* Is that sole rev a committish? */2442 obj = sb->revs->pending.objects[0].item;2443 obj = deref_tag(obj, NULL, 0);2444 if (obj->type != OBJ_COMMIT)2445 return NULL;24462447 /* Do we have HEAD? */2448 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2449 return NULL;2450 head_commit = lookup_commit_reference_gently(head_sha1, 1);2451 if (!head_commit)2452 return NULL;24532454 /* Turn "ONE" into "ONE..HEAD" then */2455 obj->flags |= UNINTERESTING;2456 add_pending_object(sb->revs, &head_commit->object, "HEAD");24572458 sb->final = (struct commit *)obj;2459 return sb->revs->pending.objects[0].name;2460}24612462static char *prepare_initial(struct blame_scoreboard *sb)2463{2464 int i;2465 const char *final_commit_name = NULL;2466 struct rev_info *revs = sb->revs;24672468 /*2469 * There must be one and only one negative commit, and it must be2470 * the boundary.2471 */2472 for (i = 0; i < revs->pending.nr; i++) {2473 struct object *obj = revs->pending.objects[i].item;2474 if (!(obj->flags & UNINTERESTING))2475 continue;2476 obj = deref_tag(obj, NULL, 0);2477 if (obj->type != OBJ_COMMIT)2478 die("Non commit %s?", revs->pending.objects[i].name);2479 if (sb->final)2480 die("More than one commit to dig up from, %s and %s?",2481 revs->pending.objects[i].name,2482 final_commit_name);2483 sb->final = (struct commit *) obj;2484 final_commit_name = revs->pending.objects[i].name;2485 }24862487 if (!final_commit_name)2488 final_commit_name = dwim_reverse_initial(sb);2489 if (!final_commit_name)2490 die("No commit to dig up from?");2491 return xstrdup(final_commit_name);2492}24932494static int blame_copy_callback(const struct option *option, const char *arg, int unset)2495{2496 int *opt = option->value;24972498 /*2499 * -C enables copy from removed files;2500 * -C -C enables copy from existing files, but only2501 * when blaming a new file;2502 * -C -C -C enables copy from existing files for2503 * everybody2504 */2505 if (*opt & PICKAXE_BLAME_COPY_HARDER)2506 *opt |= PICKAXE_BLAME_COPY_HARDEST;2507 if (*opt & PICKAXE_BLAME_COPY)2508 *opt |= PICKAXE_BLAME_COPY_HARDER;2509 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;25102511 if (arg)2512 blame_copy_score = parse_score(arg);2513 return 0;2514}25152516static int blame_move_callback(const struct option *option, const char *arg, int unset)2517{2518 int *opt = option->value;25192520 *opt |= PICKAXE_BLAME_MOVE;25212522 if (arg)2523 blame_move_score = parse_score(arg);2524 return 0;2525}25262527int cmd_blame(int argc, const char **argv, const char *prefix)2528{2529 struct rev_info revs;2530 const char *path;2531 struct blame_scoreboard sb;2532 struct blame_origin *o;2533 struct blame_entry *ent = NULL;2534 long dashdash_pos, lno;2535 char *final_commit_name = NULL;2536 enum object_type type;2537 struct commit *final_commit = NULL;25382539 struct string_list range_list = STRING_LIST_INIT_NODUP;2540 int output_option = 0, opt = 0;2541 int show_stats = 0;2542 const char *revs_file = NULL;2543 const char *contents_from = NULL;2544 const struct option options[] = {2545 OPT_BOOL(0, "incremental", &incremental, N_("Show blame entries as we find them, incrementally")),2546 OPT_BOOL('b', NULL, &blank_boundary, N_("Show blank SHA-1 for boundary commits (Default: off)")),2547 OPT_BOOL(0, "root", &show_root, N_("Do not treat root commits as boundaries (Default: off)")),2548 OPT_BOOL(0, "show-stats", &show_stats, N_("Show work cost statistics")),2549 OPT_BOOL(0, "progress", &show_progress, N_("Force progress reporting")),2550 OPT_BIT(0, "score-debug", &output_option, N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2551 OPT_BIT('f', "show-name", &output_option, N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2552 OPT_BIT('n', "show-number", &output_option, N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2553 OPT_BIT('p', "porcelain", &output_option, N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2554 OPT_BIT(0, "line-porcelain", &output_option, N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2555 OPT_BIT('c', NULL, &output_option, N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2556 OPT_BIT('t', NULL, &output_option, N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2557 OPT_BIT('l', NULL, &output_option, N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2558 OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2559 OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2560 OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),25612562 /*2563 * The following two options are parsed by parse_revision_opt()2564 * and are only included here to get included in the "-h"2565 * output:2566 */2567 { OPTION_LOWLEVEL_CALLBACK, 0, "indent-heuristic", NULL, NULL, N_("Use an experimental heuristic to improve diffs"), PARSE_OPT_NOARG, parse_opt_unknown_cb },25682569 OPT_BIT(0, "minimal", &xdl_opts, N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2570 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("Use revisions from <file> instead of calling git-rev-list")),2571 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("Use <file>'s contents as the final image")),2572 { OPTION_CALLBACK, 'C', NULL, &opt, N_("score"), N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2573 { OPTION_CALLBACK, 'M', NULL, &opt, N_("score"), N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2574 OPT_STRING_LIST('L', NULL, &range_list, N_("n,m"), N_("Process only line range n,m, counting from 1")),2575 OPT__ABBREV(&abbrev),2576 OPT_END()2577 };25782579 struct parse_opt_ctx_t ctx;2580 int cmd_is_annotate = !strcmp(argv[0], "annotate");2581 struct range_set ranges;2582 unsigned int range_i;2583 long anchor;25842585 git_config(git_blame_config, &output_option);2586 init_revisions(&revs, NULL);2587 revs.date_mode = blame_date_mode;2588 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2589 DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25902591 save_commit_buffer = 0;2592 dashdash_pos = 0;2593 show_progress = -1;25942595 parse_options_start(&ctx, argc, argv, prefix, options,2596 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2597 for (;;) {2598 switch (parse_options_step(&ctx, options, blame_opt_usage)) {2599 case PARSE_OPT_HELP:2600 exit(129);2601 case PARSE_OPT_DONE:2602 if (ctx.argv[0])2603 dashdash_pos = ctx.cpidx;2604 goto parse_done;2605 }26062607 if (!strcmp(ctx.argv[0], "--reverse")) {2608 ctx.argv[0] = "--children";2609 reverse = 1;2610 }2611 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2612 }2613parse_done:2614 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2615 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;2616 DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2617 argc = parse_options_end(&ctx);26182619 if (incremental || (output_option & OUTPUT_PORCELAIN)) {2620 if (show_progress > 0)2621 die(_("--progress can't be used with --incremental or porcelain formats"));2622 show_progress = 0;2623 } else if (show_progress < 0)2624 show_progress = isatty(2);26252626 if (0 < abbrev && abbrev < GIT_SHA1_HEXSZ)2627 /* one more abbrev length is needed for the boundary commit */2628 abbrev++;2629 else if (!abbrev)2630 abbrev = GIT_SHA1_HEXSZ;26312632 if (revs_file && read_ancestry(revs_file))2633 die_errno("reading graft file '%s' failed", revs_file);26342635 if (cmd_is_annotate) {2636 output_option |= OUTPUT_ANNOTATE_COMPAT;2637 blame_date_mode.type = DATE_ISO8601;2638 } else {2639 blame_date_mode = revs.date_mode;2640 }26412642 /* The maximum width used to show the dates */2643 switch (blame_date_mode.type) {2644 case DATE_RFC2822:2645 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2646 break;2647 case DATE_ISO8601_STRICT:2648 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");2649 break;2650 case DATE_ISO8601:2651 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");2652 break;2653 case DATE_RAW:2654 blame_date_width = sizeof("1161298804 -0700");2655 break;2656 case DATE_UNIX:2657 blame_date_width = sizeof("1161298804");2658 break;2659 case DATE_SHORT:2660 blame_date_width = sizeof("2006-10-19");2661 break;2662 case DATE_RELATIVE:2663 /* TRANSLATORS: This string is used to tell us the maximum2664 display width for a relative timestamp in "git blame"2665 output. For C locale, "4 years, 11 months ago", which2666 takes 22 places, is the longest among various forms of2667 relative timestamps, but your language may need more or2668 fewer display columns. */2669 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */2670 break;2671 case DATE_NORMAL:2672 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");2673 break;2674 case DATE_STRFTIME:2675 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */2676 break;2677 }2678 blame_date_width -= 1; /* strip the null */26792680 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2681 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2682 PICKAXE_BLAME_COPY_HARDER);26832684 /*2685 * We have collected options unknown to us in argv[1..unk]2686 * which are to be passed to revision machinery if we are2687 * going to do the "bottom" processing.2688 *2689 * The remaining are:2690 *2691 * (1) if dashdash_pos != 0, it is either2692 * "blame [revisions] -- <path>" or2693 * "blame -- <path> <rev>"2694 *2695 * (2) otherwise, it is one of the two:2696 * "blame [revisions] <path>"2697 * "blame <path> <rev>"2698 *2699 * Note that we must strip out <path> from the arguments: we do not2700 * want the path pruning but we may want "bottom" processing.2701 */2702 if (dashdash_pos) {2703 switch (argc - dashdash_pos - 1) {2704 case 2: /* (1b) */2705 if (argc != 4)2706 usage_with_options(blame_opt_usage, options);2707 /* reorder for the new way: <rev> -- <path> */2708 argv[1] = argv[3];2709 argv[3] = argv[2];2710 argv[2] = "--";2711 /* FALLTHROUGH */2712 case 1: /* (1a) */2713 path = add_prefix(prefix, argv[--argc]);2714 argv[argc] = NULL;2715 break;2716 default:2717 usage_with_options(blame_opt_usage, options);2718 }2719 } else {2720 if (argc < 2)2721 usage_with_options(blame_opt_usage, options);2722 path = add_prefix(prefix, argv[argc - 1]);2723 if (argc == 3 && !file_exists(path)) { /* (2b) */2724 path = add_prefix(prefix, argv[1]);2725 argv[1] = argv[2];2726 }2727 argv[argc - 1] = "--";27282729 setup_work_tree();2730 if (!file_exists(path))2731 die_errno("cannot stat path '%s'", path);2732 }27332734 revs.disable_stdin = 1;2735 setup_revisions(argc, argv, &revs, NULL);2736 memset(&sb, 0, sizeof(sb));2737 sb.move_score = BLAME_DEFAULT_MOVE_SCORE;2738 sb.copy_score = BLAME_DEFAULT_COPY_SCORE;27392740 sb.revs = &revs;2741 sb.contents_from = contents_from;2742 if (!reverse) {2743 final_commit_name = prepare_final(&sb);2744 sb.commits.compare = compare_commits_by_commit_date;2745 }2746 else if (contents_from)2747 die(_("--contents and --reverse do not blend well."));2748 else {2749 final_commit_name = prepare_initial(&sb);2750 sb.commits.compare = compare_commits_by_reverse_commit_date;2751 if (revs.first_parent_only)2752 revs.children.name = NULL;2753 }27542755 if (!sb.final) {2756 /*2757 * "--not A B -- path" without anything positive;2758 * do not default to HEAD, but use the working tree2759 * or "--contents".2760 */2761 setup_work_tree();2762 sb.final = fake_working_tree_commit(&sb.revs->diffopt,2763 path, contents_from);2764 add_pending_object(&revs, &(sb.final->object), ":");2765 }2766 else if (contents_from)2767 die(_("cannot use --contents with final commit object name"));27682769 if (reverse && revs.first_parent_only) {2770 final_commit = find_single_final(sb.revs, NULL);2771 if (!final_commit)2772 die(_("--reverse and --first-parent together require specified latest commit"));2773 }27742775 /*2776 * If we have bottom, this will mark the ancestors of the2777 * bottom commits we would reach while traversing as2778 * uninteresting.2779 */2780 if (prepare_revision_walk(&revs))2781 die(_("revision walk setup failed"));27822783 if (reverse && revs.first_parent_only) {2784 struct commit *c = final_commit;27852786 sb.revs->children.name = "children";2787 while (c->parents &&2788 oidcmp(&c->object.oid, &sb.final->object.oid)) {2789 struct commit_list *l = xcalloc(1, sizeof(*l));27902791 l->item = c;2792 if (add_decoration(&sb.revs->children,2793 &c->parents->item->object, l))2794 die("BUG: not unique item in first-parent chain");2795 c = c->parents->item;2796 }27972798 if (oidcmp(&c->object.oid, &sb.final->object.oid))2799 die(_("--reverse --first-parent together require range along first-parent chain"));2800 }28012802 if (is_null_oid(&sb.final->object.oid)) {2803 o = sb.final->util;2804 sb.final_buf = xmemdupz(o->file.ptr, o->file.size);2805 sb.final_buf_size = o->file.size;2806 }2807 else {2808 o = get_origin(sb.final, path);2809 if (fill_blob_sha1_and_mode(o))2810 die(_("no such path %s in %s"), path, final_commit_name);28112812 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2813 textconv_object(path, o->mode, &o->blob_oid, 1, (char **) &sb.final_buf,2814 &sb.final_buf_size))2815 ;2816 else2817 sb.final_buf = read_sha1_file(o->blob_oid.hash, &type,2818 &sb.final_buf_size);28192820 if (!sb.final_buf)2821 die(_("cannot read blob %s for path %s"),2822 oid_to_hex(&o->blob_oid),2823 path);2824 }2825 sb.num_read_blob++;2826 lno = prepare_lines(&sb);28272828 if (lno && !range_list.nr)2829 string_list_append(&range_list, "1");28302831 anchor = 1;2832 range_set_init(&ranges, range_list.nr);2833 for (range_i = 0; range_i < range_list.nr; ++range_i) {2834 long bottom, top;2835 if (parse_range_arg(range_list.items[range_i].string,2836 nth_line_cb, &sb, lno, anchor,2837 &bottom, &top, sb.path))2838 usage(blame_usage);2839 if (lno < top || ((lno || bottom) && lno < bottom))2840 die(Q_("file %s has only %lu line",2841 "file %s has only %lu lines",2842 lno), path, lno);2843 if (bottom < 1)2844 bottom = 1;2845 if (top < 1)2846 top = lno;2847 bottom--;2848 range_set_append_unsafe(&ranges, bottom, top);2849 anchor = top + 1;2850 }2851 sort_and_merge_range_set(&ranges);28522853 for (range_i = ranges.nr; range_i > 0; --range_i) {2854 const struct range *r = &ranges.ranges[range_i - 1];2855 long bottom = r->start;2856 long top = r->end;2857 struct blame_entry *next = ent;2858 ent = xcalloc(1, sizeof(*ent));2859 ent->lno = bottom;2860 ent->num_lines = top - bottom;2861 ent->suspect = o;2862 ent->s_lno = bottom;2863 ent->next = next;2864 blame_origin_incref(o);2865 }28662867 o->suspects = ent;2868 prio_queue_put(&sb.commits, o->commit);28692870 blame_origin_decref(o);28712872 range_set_release(&ranges);2873 string_list_clear(&range_list, 0);28742875 sb.ent = NULL;2876 sb.path = path;28772878 if (blame_move_score)2879 sb.move_score = blame_move_score;2880 if (blame_copy_score)2881 sb.copy_score = blame_copy_score;28822883 read_mailmap(&mailmap, NULL);28842885 assign_blame(&sb, opt);28862887 if (!incremental)2888 setup_pager();28892890 free(final_commit_name);28912892 if (incremental)2893 return 0;28942895 sb.ent = blame_sort(sb.ent, compare_blame_final);28962897 blame_coalesce(&sb);28982899 if (!(output_option & OUTPUT_PORCELAIN))2900 find_alignment(&sb, &output_option);29012902 output(&sb, output_option);2903 free((void *)sb.final_buf);2904 for (ent = sb.ent; ent; ) {2905 struct blame_entry *e = ent->next;2906 free(ent);2907 ent = e;2908 }29092910 if (show_stats) {2911 printf("num read blob: %d\n", sb.num_read_blob);2912 printf("num get patch: %d\n", sb.num_get_patch);2913 printf("num commits: %d\n", sb.num_commits);2914 }2915 return 0;2916}