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/* stats */ 65static int num_read_blob; 66static int num_get_patch; 67static int num_commits; 68 69#define PICKAXE_BLAME_MOVE 01 70#define PICKAXE_BLAME_COPY 02 71#define PICKAXE_BLAME_COPY_HARDER 04 72#define PICKAXE_BLAME_COPY_HARDEST 010 73 74/* 75 * blame for a blame_entry with score lower than these thresholds 76 * is not passed to the parent using move/copy logic. 77 */ 78static unsigned blame_move_score; 79static unsigned blame_copy_score; 80#define BLAME_DEFAULT_MOVE_SCORE 20 81#define BLAME_DEFAULT_COPY_SCORE 40 82 83/* Remember to update object flag allocation in object.h */ 84#define METAINFO_SHOWN (1u<<12) 85#define MORE_THAN_ONE_PATH (1u<<13) 86 87/* 88 * One blob in a commit that is being suspected 89 */ 90struct origin { 91 int refcnt; 92 /* Record preceding blame record for this blob */ 93 struct origin *previous; 94 /* origins are put in a list linked via `next' hanging off the 95 * corresponding commit's util field in order to make finding 96 * them fast. The presence in this chain does not count 97 * towards the origin's reference count. It is tempting to 98 * let it count as long as the commit is pending examination, 99 * but even under circumstances where the commit will be 100 * present multiple times in the priority queue of unexamined 101 * commits, processing the first instance will not leave any 102 * work requiring the origin data for the second instance. An 103 * interspersed commit changing that would have to be 104 * preexisting with a different ancestry and with the same 105 * commit date in order to wedge itself between two instances 106 * of the same commit in the priority queue _and_ produce 107 * blame entries relevant for it. While we don't want to let 108 * us get tripped up by this case, it certainly does not seem 109 * worth optimizing for. 110 */ 111 struct origin *next; 112 struct commit *commit; 113 /* `suspects' contains blame entries that may be attributed to 114 * this origin's commit or to parent commits. When a commit 115 * is being processed, all suspects will be moved, either by 116 * assigning them to an origin in a different commit, or by 117 * shipping them to the scoreboard's ent list because they 118 * cannot be attributed to a different commit. 119 */ 120 struct blame_entry *suspects; 121 mmfile_t file; 122 struct object_id blob_oid; 123 unsigned mode; 124 /* guilty gets set when shipping any suspects to the final 125 * blame list instead of other commits 126 */ 127 char guilty; 128 char path[FLEX_ARRAY]; 129}; 130 131struct progress_info { 132 struct progress *progress; 133 int blamed_lines; 134}; 135 136static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b, 137 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data) 138{ 139 xpparam_t xpp = {0}; 140 xdemitconf_t xecfg = {0}; 141 xdemitcb_t ecb = {NULL}; 142 143 xpp.flags = xdl_opts; 144 xecfg.hunk_func = hunk_func; 145 ecb.priv = cb_data; 146 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 147} 148 149/* 150 * Prepare diff_filespec and convert it using diff textconv API 151 * if the textconv driver exists. 152 * Return 1 if the conversion succeeds, 0 otherwise. 153 */ 154int textconv_object(const char *path, 155 unsigned mode, 156 const struct object_id *oid, 157 int oid_valid, 158 char **buf, 159 unsigned long *buf_size) 160{ 161 struct diff_filespec *df; 162 struct userdiff_driver *textconv; 163 164 df = alloc_filespec(path); 165 fill_filespec(df, oid->hash, oid_valid, mode); 166 textconv = get_textconv(df); 167 if (!textconv) { 168 free_filespec(df); 169 return 0; 170 } 171 172 *buf_size = fill_textconv(textconv, df, buf); 173 free_filespec(df); 174 return 1; 175} 176 177/* 178 * Given an origin, prepare mmfile_t structure to be used by the 179 * diff machinery 180 */ 181static void fill_origin_blob(struct diff_options *opt, 182 struct origin *o, mmfile_t *file) 183{ 184 if (!o->file.ptr) { 185 enum object_type type; 186 unsigned long file_size; 187 188 num_read_blob++; 189 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 190 textconv_object(o->path, o->mode, &o->blob_oid, 1, &file->ptr, &file_size)) 191 ; 192 else 193 file->ptr = read_sha1_file(o->blob_oid.hash, &type, 194 &file_size); 195 file->size = file_size; 196 197 if (!file->ptr) 198 die("Cannot read blob %s for path %s", 199 oid_to_hex(&o->blob_oid), 200 o->path); 201 o->file = *file; 202 } 203 else 204 *file = o->file; 205} 206 207/* 208 * Origin is refcounted and usually we keep the blob contents to be 209 * reused. 210 */ 211static inline struct origin *origin_incref(struct origin *o) 212{ 213 if (o) 214 o->refcnt++; 215 return o; 216} 217 218static void origin_decref(struct origin *o) 219{ 220 if (o && --o->refcnt <= 0) { 221 struct origin *p, *l = NULL; 222 if (o->previous) 223 origin_decref(o->previous); 224 free(o->file.ptr); 225 /* Should be present exactly once in commit chain */ 226 for (p = o->commit->util; p; l = p, p = p->next) { 227 if (p == o) { 228 if (l) 229 l->next = p->next; 230 else 231 o->commit->util = p->next; 232 free(o); 233 return; 234 } 235 } 236 die("internal error in blame::origin_decref"); 237 } 238} 239 240static void drop_origin_blob(struct origin *o) 241{ 242 if (o->file.ptr) { 243 free(o->file.ptr); 244 o->file.ptr = NULL; 245 } 246} 247 248/* 249 * Each group of lines is described by a blame_entry; it can be split 250 * as we pass blame to the parents. They are arranged in linked lists 251 * kept as `suspects' of some unprocessed origin, or entered (when the 252 * blame origin has been finalized) into the scoreboard structure. 253 * While the scoreboard structure is only sorted at the end of 254 * processing (according to final image line number), the lists 255 * attached to an origin are sorted by the target line number. 256 */ 257struct blame_entry { 258 struct blame_entry *next; 259 260 /* the first line of this group in the final image; 261 * internally all line numbers are 0 based. 262 */ 263 int lno; 264 265 /* how many lines this group has */ 266 int num_lines; 267 268 /* the commit that introduced this group into the final image */ 269 struct origin *suspect; 270 271 /* the line number of the first line of this group in the 272 * suspect's file; internally all line numbers are 0 based. 273 */ 274 int s_lno; 275 276 /* how significant this entry is -- cached to avoid 277 * scanning the lines over and over. 278 */ 279 unsigned score; 280}; 281 282/* 283 * Any merge of blames happens on lists of blames that arrived via 284 * different parents in a single suspect. In this case, we want to 285 * sort according to the suspect line numbers as opposed to the final 286 * image line numbers. The function body is somewhat longish because 287 * it avoids unnecessary writes. 288 */ 289 290static struct blame_entry *blame_merge(struct blame_entry *list1, 291 struct blame_entry *list2) 292{ 293 struct blame_entry *p1 = list1, *p2 = list2, 294 **tail = &list1; 295 296 if (!p1) 297 return p2; 298 if (!p2) 299 return p1; 300 301 if (p1->s_lno <= p2->s_lno) { 302 do { 303 tail = &p1->next; 304 if ((p1 = *tail) == NULL) { 305 *tail = p2; 306 return list1; 307 } 308 } while (p1->s_lno <= p2->s_lno); 309 } 310 for (;;) { 311 *tail = p2; 312 do { 313 tail = &p2->next; 314 if ((p2 = *tail) == NULL) { 315 *tail = p1; 316 return list1; 317 } 318 } while (p1->s_lno > p2->s_lno); 319 *tail = p1; 320 do { 321 tail = &p1->next; 322 if ((p1 = *tail) == NULL) { 323 *tail = p2; 324 return list1; 325 } 326 } while (p1->s_lno <= p2->s_lno); 327 } 328} 329 330static void *get_next_blame(const void *p) 331{ 332 return ((struct blame_entry *)p)->next; 333} 334 335static void set_next_blame(void *p1, void *p2) 336{ 337 ((struct blame_entry *)p1)->next = p2; 338} 339 340/* 341 * Final image line numbers are all different, so we don't need a 342 * three-way comparison here. 343 */ 344 345static int compare_blame_final(const void *p1, const void *p2) 346{ 347 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 348 ? 1 : -1; 349} 350 351static int compare_blame_suspect(const void *p1, const void *p2) 352{ 353 const struct blame_entry *s1 = p1, *s2 = p2; 354 /* 355 * to allow for collating suspects, we sort according to the 356 * respective pointer value as the primary sorting criterion. 357 * The actual relation is pretty unimportant as long as it 358 * establishes a total order. Comparing as integers gives us 359 * that. 360 */ 361 if (s1->suspect != s2->suspect) 362 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1; 363 if (s1->s_lno == s2->s_lno) 364 return 0; 365 return s1->s_lno > s2->s_lno ? 1 : -1; 366} 367 368static struct blame_entry *blame_sort(struct blame_entry *head, 369 int (*compare_fn)(const void *, const void *)) 370{ 371 return llist_mergesort (head, get_next_blame, set_next_blame, compare_fn); 372} 373 374static int compare_commits_by_reverse_commit_date(const void *a, 375 const void *b, 376 void *c) 377{ 378 return -compare_commits_by_commit_date(a, b, c); 379} 380 381/* 382 * The current state of the blame assignment. 383 */ 384struct scoreboard { 385 /* the final commit (i.e. where we started digging from) */ 386 struct commit *final; 387 /* Priority queue for commits with unassigned blame records */ 388 struct prio_queue commits; 389 struct rev_info *revs; 390 const char *path; 391 392 /* 393 * The contents in the final image. 394 * Used by many functions to obtain contents of the nth line, 395 * indexed with scoreboard.lineno[blame_entry.lno]. 396 */ 397 const char *final_buf; 398 unsigned long final_buf_size; 399 400 /* linked list of blames */ 401 struct blame_entry *ent; 402 403 /* look-up a line in the final buffer */ 404 int num_lines; 405 int *lineno; 406}; 407 408static void sanity_check_refcnt(struct scoreboard *); 409 410/* 411 * If two blame entries that are next to each other came from 412 * contiguous lines in the same origin (i.e. <commit, path> pair), 413 * merge them together. 414 */ 415static void coalesce(struct scoreboard *sb) 416{ 417 struct blame_entry *ent, *next; 418 419 for (ent = sb->ent; ent && (next = ent->next); ent = next) { 420 if (ent->suspect == next->suspect && 421 ent->s_lno + ent->num_lines == next->s_lno) { 422 ent->num_lines += next->num_lines; 423 ent->next = next->next; 424 origin_decref(next->suspect); 425 free(next); 426 ent->score = 0; 427 next = ent; /* again */ 428 } 429 } 430 431 if (DEBUG) /* sanity */ 432 sanity_check_refcnt(sb); 433} 434 435/* 436 * Merge the given sorted list of blames into a preexisting origin. 437 * If there were no previous blames to that commit, it is entered into 438 * the commit priority queue of the score board. 439 */ 440 441static void queue_blames(struct scoreboard *sb, struct origin *porigin, 442 struct blame_entry *sorted) 443{ 444 if (porigin->suspects) 445 porigin->suspects = blame_merge(porigin->suspects, sorted); 446 else { 447 struct origin *o; 448 for (o = porigin->commit->util; o; o = o->next) { 449 if (o->suspects) { 450 porigin->suspects = sorted; 451 return; 452 } 453 } 454 porigin->suspects = sorted; 455 prio_queue_put(&sb->commits, porigin->commit); 456 } 457} 458 459/* 460 * Given a commit and a path in it, create a new origin structure. 461 * The callers that add blame to the scoreboard should use 462 * get_origin() to obtain shared, refcounted copy instead of calling 463 * this function directly. 464 */ 465static struct origin *make_origin(struct commit *commit, const char *path) 466{ 467 struct origin *o; 468 FLEX_ALLOC_STR(o, path, path); 469 o->commit = commit; 470 o->refcnt = 1; 471 o->next = commit->util; 472 commit->util = o; 473 return o; 474} 475 476/* 477 * Locate an existing origin or create a new one. 478 * This moves the origin to front position in the commit util list. 479 */ 480static struct origin *get_origin(struct scoreboard *sb, 481 struct commit *commit, 482 const char *path) 483{ 484 struct origin *o, *l; 485 486 for (o = commit->util, l = NULL; o; l = o, o = o->next) { 487 if (!strcmp(o->path, path)) { 488 /* bump to front */ 489 if (l) { 490 l->next = o->next; 491 o->next = commit->util; 492 commit->util = o; 493 } 494 return origin_incref(o); 495 } 496 } 497 return make_origin(commit, path); 498} 499 500/* 501 * Fill the blob_sha1 field of an origin if it hasn't, so that later 502 * call to fill_origin_blob() can use it to locate the data. blob_sha1 503 * for an origin is also used to pass the blame for the entire file to 504 * the parent to detect the case where a child's blob is identical to 505 * that of its parent's. 506 * 507 * This also fills origin->mode for corresponding tree path. 508 */ 509static int fill_blob_sha1_and_mode(struct origin *origin) 510{ 511 if (!is_null_oid(&origin->blob_oid)) 512 return 0; 513 if (get_tree_entry(origin->commit->object.oid.hash, 514 origin->path, 515 origin->blob_oid.hash, &origin->mode)) 516 goto error_out; 517 if (sha1_object_info(origin->blob_oid.hash, NULL) != OBJ_BLOB) 518 goto error_out; 519 return 0; 520 error_out: 521 oidclr(&origin->blob_oid); 522 origin->mode = S_IFINVALID; 523 return -1; 524} 525 526/* 527 * We have an origin -- check if the same path exists in the 528 * parent and return an origin structure to represent it. 529 */ 530static struct origin *find_origin(struct scoreboard *sb, 531 struct commit *parent, 532 struct origin *origin) 533{ 534 struct origin *porigin; 535 struct diff_options diff_opts; 536 const char *paths[2]; 537 538 /* First check any existing origins */ 539 for (porigin = parent->util; porigin; porigin = porigin->next) 540 if (!strcmp(porigin->path, origin->path)) { 541 /* 542 * The same path between origin and its parent 543 * without renaming -- the most common case. 544 */ 545 return origin_incref (porigin); 546 } 547 548 /* See if the origin->path is different between parent 549 * and origin first. Most of the time they are the 550 * same and diff-tree is fairly efficient about this. 551 */ 552 diff_setup(&diff_opts); 553 DIFF_OPT_SET(&diff_opts, RECURSIVE); 554 diff_opts.detect_rename = 0; 555 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 556 paths[0] = origin->path; 557 paths[1] = NULL; 558 559 parse_pathspec(&diff_opts.pathspec, 560 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 561 PATHSPEC_LITERAL_PATH, "", paths); 562 diff_setup_done(&diff_opts); 563 564 if (is_null_oid(&origin->commit->object.oid)) 565 do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 566 else 567 diff_tree_sha1(parent->tree->object.oid.hash, 568 origin->commit->tree->object.oid.hash, 569 "", &diff_opts); 570 diffcore_std(&diff_opts); 571 572 if (!diff_queued_diff.nr) { 573 /* The path is the same as parent */ 574 porigin = get_origin(sb, parent, origin->path); 575 oidcpy(&porigin->blob_oid, &origin->blob_oid); 576 porigin->mode = origin->mode; 577 } else { 578 /* 579 * Since origin->path is a pathspec, if the parent 580 * commit had it as a directory, we will see a whole 581 * bunch of deletion of files in the directory that we 582 * do not care about. 583 */ 584 int i; 585 struct diff_filepair *p = NULL; 586 for (i = 0; i < diff_queued_diff.nr; i++) { 587 const char *name; 588 p = diff_queued_diff.queue[i]; 589 name = p->one->path ? p->one->path : p->two->path; 590 if (!strcmp(name, origin->path)) 591 break; 592 } 593 if (!p) 594 die("internal error in blame::find_origin"); 595 switch (p->status) { 596 default: 597 die("internal error in blame::find_origin (%c)", 598 p->status); 599 case 'M': 600 porigin = get_origin(sb, parent, origin->path); 601 oidcpy(&porigin->blob_oid, &p->one->oid); 602 porigin->mode = p->one->mode; 603 break; 604 case 'A': 605 case 'T': 606 /* Did not exist in parent, or type changed */ 607 break; 608 } 609 } 610 diff_flush(&diff_opts); 611 clear_pathspec(&diff_opts.pathspec); 612 return porigin; 613} 614 615/* 616 * We have an origin -- find the path that corresponds to it in its 617 * parent and return an origin structure to represent it. 618 */ 619static struct origin *find_rename(struct scoreboard *sb, 620 struct commit *parent, 621 struct origin *origin) 622{ 623 struct origin *porigin = NULL; 624 struct diff_options diff_opts; 625 int i; 626 627 diff_setup(&diff_opts); 628 DIFF_OPT_SET(&diff_opts, RECURSIVE); 629 diff_opts.detect_rename = DIFF_DETECT_RENAME; 630 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 631 diff_opts.single_follow = origin->path; 632 diff_setup_done(&diff_opts); 633 634 if (is_null_oid(&origin->commit->object.oid)) 635 do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 636 else 637 diff_tree_sha1(parent->tree->object.oid.hash, 638 origin->commit->tree->object.oid.hash, 639 "", &diff_opts); 640 diffcore_std(&diff_opts); 641 642 for (i = 0; i < diff_queued_diff.nr; i++) { 643 struct diff_filepair *p = diff_queued_diff.queue[i]; 644 if ((p->status == 'R' || p->status == 'C') && 645 !strcmp(p->two->path, origin->path)) { 646 porigin = get_origin(sb, parent, p->one->path); 647 oidcpy(&porigin->blob_oid, &p->one->oid); 648 porigin->mode = p->one->mode; 649 break; 650 } 651 } 652 diff_flush(&diff_opts); 653 clear_pathspec(&diff_opts.pathspec); 654 return porigin; 655} 656 657/* 658 * Append a new blame entry to a given output queue. 659 */ 660static void add_blame_entry(struct blame_entry ***queue, 661 const struct blame_entry *src) 662{ 663 struct blame_entry *e = xmalloc(sizeof(*e)); 664 memcpy(e, src, sizeof(*e)); 665 origin_incref(e->suspect); 666 667 e->next = **queue; 668 **queue = e; 669 *queue = &e->next; 670} 671 672/* 673 * src typically is on-stack; we want to copy the information in it to 674 * a malloced blame_entry that gets added to the given queue. The 675 * origin of dst loses a refcnt. 676 */ 677static void dup_entry(struct blame_entry ***queue, 678 struct blame_entry *dst, struct blame_entry *src) 679{ 680 origin_incref(src->suspect); 681 origin_decref(dst->suspect); 682 memcpy(dst, src, sizeof(*src)); 683 dst->next = **queue; 684 **queue = dst; 685 *queue = &dst->next; 686} 687 688static const char *nth_line(struct scoreboard *sb, long lno) 689{ 690 return sb->final_buf + sb->lineno[lno]; 691} 692 693static const char *nth_line_cb(void *data, long lno) 694{ 695 return nth_line((struct scoreboard *)data, lno); 696} 697 698/* 699 * It is known that lines between tlno to same came from parent, and e 700 * has an overlap with that range. it also is known that parent's 701 * line plno corresponds to e's line tlno. 702 * 703 * <---- e -----> 704 * <------> 705 * <------------> 706 * <------------> 707 * <------------------> 708 * 709 * Split e into potentially three parts; before this chunk, the chunk 710 * to be blamed for the parent, and after that portion. 711 */ 712static void split_overlap(struct blame_entry *split, 713 struct blame_entry *e, 714 int tlno, int plno, int same, 715 struct origin *parent) 716{ 717 int chunk_end_lno; 718 memset(split, 0, sizeof(struct blame_entry [3])); 719 720 if (e->s_lno < tlno) { 721 /* there is a pre-chunk part not blamed on parent */ 722 split[0].suspect = origin_incref(e->suspect); 723 split[0].lno = e->lno; 724 split[0].s_lno = e->s_lno; 725 split[0].num_lines = tlno - e->s_lno; 726 split[1].lno = e->lno + tlno - e->s_lno; 727 split[1].s_lno = plno; 728 } 729 else { 730 split[1].lno = e->lno; 731 split[1].s_lno = plno + (e->s_lno - tlno); 732 } 733 734 if (same < e->s_lno + e->num_lines) { 735 /* there is a post-chunk part not blamed on parent */ 736 split[2].suspect = origin_incref(e->suspect); 737 split[2].lno = e->lno + (same - e->s_lno); 738 split[2].s_lno = e->s_lno + (same - e->s_lno); 739 split[2].num_lines = e->s_lno + e->num_lines - same; 740 chunk_end_lno = split[2].lno; 741 } 742 else 743 chunk_end_lno = e->lno + e->num_lines; 744 split[1].num_lines = chunk_end_lno - split[1].lno; 745 746 /* 747 * if it turns out there is nothing to blame the parent for, 748 * forget about the splitting. !split[1].suspect signals this. 749 */ 750 if (split[1].num_lines < 1) 751 return; 752 split[1].suspect = origin_incref(parent); 753} 754 755/* 756 * split_overlap() divided an existing blame e into up to three parts 757 * in split. Any assigned blame is moved to queue to 758 * reflect the split. 759 */ 760static void split_blame(struct blame_entry ***blamed, 761 struct blame_entry ***unblamed, 762 struct blame_entry *split, 763 struct blame_entry *e) 764{ 765 if (split[0].suspect && split[2].suspect) { 766 /* The first part (reuse storage for the existing entry e) */ 767 dup_entry(unblamed, e, &split[0]); 768 769 /* The last part -- me */ 770 add_blame_entry(unblamed, &split[2]); 771 772 /* ... and the middle part -- parent */ 773 add_blame_entry(blamed, &split[1]); 774 } 775 else if (!split[0].suspect && !split[2].suspect) 776 /* 777 * The parent covers the entire area; reuse storage for 778 * e and replace it with the parent. 779 */ 780 dup_entry(blamed, e, &split[1]); 781 else if (split[0].suspect) { 782 /* me and then parent */ 783 dup_entry(unblamed, e, &split[0]); 784 add_blame_entry(blamed, &split[1]); 785 } 786 else { 787 /* parent and then me */ 788 dup_entry(blamed, e, &split[1]); 789 add_blame_entry(unblamed, &split[2]); 790 } 791} 792 793/* 794 * After splitting the blame, the origins used by the 795 * on-stack blame_entry should lose one refcnt each. 796 */ 797static void decref_split(struct blame_entry *split) 798{ 799 int i; 800 801 for (i = 0; i < 3; i++) 802 origin_decref(split[i].suspect); 803} 804 805/* 806 * reverse_blame reverses the list given in head, appending tail. 807 * That allows us to build lists in reverse order, then reverse them 808 * afterwards. This can be faster than building the list in proper 809 * order right away. The reason is that building in proper order 810 * requires writing a link in the _previous_ element, while building 811 * in reverse order just requires placing the list head into the 812 * _current_ element. 813 */ 814 815static struct blame_entry *reverse_blame(struct blame_entry *head, 816 struct blame_entry *tail) 817{ 818 while (head) { 819 struct blame_entry *next = head->next; 820 head->next = tail; 821 tail = head; 822 head = next; 823 } 824 return tail; 825} 826 827/* 828 * Process one hunk from the patch between the current suspect for 829 * blame_entry e and its parent. This first blames any unfinished 830 * entries before the chunk (which is where target and parent start 831 * differing) on the parent, and then splits blame entries at the 832 * start and at the end of the difference region. Since use of -M and 833 * -C options may lead to overlapping/duplicate source line number 834 * ranges, all we can rely on from sorting/merging is the order of the 835 * first suspect line number. 836 */ 837static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq, 838 int tlno, int offset, int same, 839 struct origin *parent) 840{ 841 struct blame_entry *e = **srcq; 842 struct blame_entry *samep = NULL, *diffp = NULL; 843 844 while (e && e->s_lno < tlno) { 845 struct blame_entry *next = e->next; 846 /* 847 * current record starts before differing portion. If 848 * it reaches into it, we need to split it up and 849 * examine the second part separately. 850 */ 851 if (e->s_lno + e->num_lines > tlno) { 852 /* Move second half to a new record */ 853 int len = tlno - e->s_lno; 854 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry)); 855 n->suspect = e->suspect; 856 n->lno = e->lno + len; 857 n->s_lno = e->s_lno + len; 858 n->num_lines = e->num_lines - len; 859 e->num_lines = len; 860 e->score = 0; 861 /* Push new record to diffp */ 862 n->next = diffp; 863 diffp = n; 864 } else 865 origin_decref(e->suspect); 866 /* Pass blame for everything before the differing 867 * chunk to the parent */ 868 e->suspect = origin_incref(parent); 869 e->s_lno += offset; 870 e->next = samep; 871 samep = e; 872 e = next; 873 } 874 /* 875 * As we don't know how much of a common stretch after this 876 * diff will occur, the currently blamed parts are all that we 877 * can assign to the parent for now. 878 */ 879 880 if (samep) { 881 **dstq = reverse_blame(samep, **dstq); 882 *dstq = &samep->next; 883 } 884 /* 885 * Prepend the split off portions: everything after e starts 886 * after the blameable portion. 887 */ 888 e = reverse_blame(diffp, e); 889 890 /* 891 * Now retain records on the target while parts are different 892 * from the parent. 893 */ 894 samep = NULL; 895 diffp = NULL; 896 while (e && e->s_lno < same) { 897 struct blame_entry *next = e->next; 898 899 /* 900 * If current record extends into sameness, need to split. 901 */ 902 if (e->s_lno + e->num_lines > same) { 903 /* 904 * Move second half to a new record to be 905 * processed by later chunks 906 */ 907 int len = same - e->s_lno; 908 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry)); 909 n->suspect = origin_incref(e->suspect); 910 n->lno = e->lno + len; 911 n->s_lno = e->s_lno + len; 912 n->num_lines = e->num_lines - len; 913 e->num_lines = len; 914 e->score = 0; 915 /* Push new record to samep */ 916 n->next = samep; 917 samep = n; 918 } 919 e->next = diffp; 920 diffp = e; 921 e = next; 922 } 923 **srcq = reverse_blame(diffp, reverse_blame(samep, e)); 924 /* Move across elements that are in the unblamable portion */ 925 if (diffp) 926 *srcq = &diffp->next; 927} 928 929struct blame_chunk_cb_data { 930 struct origin *parent; 931 long offset; 932 struct blame_entry **dstq; 933 struct blame_entry **srcq; 934}; 935 936/* diff chunks are from parent to target */ 937static int blame_chunk_cb(long start_a, long count_a, 938 long start_b, long count_b, void *data) 939{ 940 struct blame_chunk_cb_data *d = data; 941 if (start_a - start_b != d->offset) 942 die("internal error in blame::blame_chunk_cb"); 943 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 944 start_b + count_b, d->parent); 945 d->offset = start_a + count_a - (start_b + count_b); 946 return 0; 947} 948 949/* 950 * We are looking at the origin 'target' and aiming to pass blame 951 * for the lines it is suspected to its parent. Run diff to find 952 * which lines came from parent and pass blame for them. 953 */ 954static void pass_blame_to_parent(struct scoreboard *sb, 955 struct origin *target, 956 struct origin *parent) 957{ 958 mmfile_t file_p, file_o; 959 struct blame_chunk_cb_data d; 960 struct blame_entry *newdest = NULL; 961 962 if (!target->suspects) 963 return; /* nothing remains for this target */ 964 965 d.parent = parent; 966 d.offset = 0; 967 d.dstq = &newdest; d.srcq = &target->suspects; 968 969 fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 970 fill_origin_blob(&sb->revs->diffopt, target, &file_o); 971 num_get_patch++; 972 973 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d)) 974 die("unable to generate diff (%s -> %s)", 975 oid_to_hex(&parent->commit->object.oid), 976 oid_to_hex(&target->commit->object.oid)); 977 /* The rest are the same as the parent */ 978 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 979 *d.dstq = NULL; 980 queue_blames(sb, parent, newdest); 981 982 return; 983} 984 985/* 986 * The lines in blame_entry after splitting blames many times can become 987 * very small and trivial, and at some point it becomes pointless to 988 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 989 * ordinary C program, and it is not worth to say it was copied from 990 * totally unrelated file in the parent. 991 * 992 * Compute how trivial the lines in the blame_entry are. 993 */ 994static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e) 995{ 996 unsigned score; 997 const char *cp, *ep; 998 999 if (e->score)1000 return e->score;10011002 score = 1;1003 cp = nth_line(sb, e->lno);1004 ep = nth_line(sb, e->lno + e->num_lines);1005 while (cp < ep) {1006 unsigned ch = *((unsigned char *)cp);1007 if (isalnum(ch))1008 score++;1009 cp++;1010 }1011 e->score = score;1012 return score;1013}10141015/*1016 * best_so_far[] and this[] are both a split of an existing blame_entry1017 * that passes blame to the parent. Maintain best_so_far the best split1018 * so far, by comparing this and best_so_far and copying this into1019 * bst_so_far as needed.1020 */1021static void copy_split_if_better(struct scoreboard *sb,1022 struct blame_entry *best_so_far,1023 struct blame_entry *this)1024{1025 int i;10261027 if (!this[1].suspect)1028 return;1029 if (best_so_far[1].suspect) {1030 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))1031 return;1032 }10331034 for (i = 0; i < 3; i++)1035 origin_incref(this[i].suspect);1036 decref_split(best_so_far);1037 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));1038}10391040/*1041 * We are looking at a part of the final image represented by1042 * ent (tlno and same are offset by ent->s_lno).1043 * tlno is where we are looking at in the final image.1044 * up to (but not including) same match preimage.1045 * plno is where we are looking at in the preimage.1046 *1047 * <-------------- final image ---------------------->1048 * <------ent------>1049 * ^tlno ^same1050 * <---------preimage----->1051 * ^plno1052 *1053 * All line numbers are 0-based.1054 */1055static void handle_split(struct scoreboard *sb,1056 struct blame_entry *ent,1057 int tlno, int plno, int same,1058 struct origin *parent,1059 struct blame_entry *split)1060{1061 if (ent->num_lines <= tlno)1062 return;1063 if (tlno < same) {1064 struct blame_entry this[3];1065 tlno += ent->s_lno;1066 same += ent->s_lno;1067 split_overlap(this, ent, tlno, plno, same, parent);1068 copy_split_if_better(sb, split, this);1069 decref_split(this);1070 }1071}10721073struct handle_split_cb_data {1074 struct scoreboard *sb;1075 struct blame_entry *ent;1076 struct origin *parent;1077 struct blame_entry *split;1078 long plno;1079 long tlno;1080};10811082static int handle_split_cb(long start_a, long count_a,1083 long start_b, long count_b, void *data)1084{1085 struct handle_split_cb_data *d = data;1086 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1087 d->split);1088 d->plno = start_a + count_a;1089 d->tlno = start_b + count_b;1090 return 0;1091}10921093/*1094 * Find the lines from parent that are the same as ent so that1095 * we can pass blames to it. file_p has the blob contents for1096 * the parent.1097 */1098static void find_copy_in_blob(struct scoreboard *sb,1099 struct blame_entry *ent,1100 struct origin *parent,1101 struct blame_entry *split,1102 mmfile_t *file_p)1103{1104 const char *cp;1105 mmfile_t file_o;1106 struct handle_split_cb_data d;11071108 memset(&d, 0, sizeof(d));1109 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1110 /*1111 * Prepare mmfile that contains only the lines in ent.1112 */1113 cp = nth_line(sb, ent->lno);1114 file_o.ptr = (char *) cp;1115 file_o.size = nth_line(sb, ent->lno + ent->num_lines) - cp;11161117 /*1118 * file_o is a part of final image we are annotating.1119 * file_p partially may match that image.1120 */1121 memset(split, 0, sizeof(struct blame_entry [3]));1122 if (diff_hunks(file_p, &file_o, handle_split_cb, &d))1123 die("unable to generate diff (%s)",1124 oid_to_hex(&parent->commit->object.oid));1125 /* remainder, if any, all match the preimage */1126 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1127}11281129/* Move all blame entries from list *source that have a score smaller1130 * than score_min to the front of list *small.1131 * Returns a pointer to the link pointing to the old head of the small list.1132 */11331134static struct blame_entry **filter_small(struct scoreboard *sb,1135 struct blame_entry **small,1136 struct blame_entry **source,1137 unsigned score_min)1138{1139 struct blame_entry *p = *source;1140 struct blame_entry *oldsmall = *small;1141 while (p) {1142 if (ent_score(sb, p) <= score_min) {1143 *small = p;1144 small = &p->next;1145 p = *small;1146 } else {1147 *source = p;1148 source = &p->next;1149 p = *source;1150 }1151 }1152 *small = oldsmall;1153 *source = NULL;1154 return small;1155}11561157/*1158 * See if lines currently target is suspected for can be attributed to1159 * parent.1160 */1161static void find_move_in_parent(struct scoreboard *sb,1162 struct blame_entry ***blamed,1163 struct blame_entry **toosmall,1164 struct origin *target,1165 struct origin *parent)1166{1167 struct blame_entry *e, split[3];1168 struct blame_entry *unblamed = target->suspects;1169 struct blame_entry *leftover = NULL;1170 mmfile_t file_p;11711172 if (!unblamed)1173 return; /* nothing remains for this target */11741175 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1176 if (!file_p.ptr)1177 return;11781179 /* At each iteration, unblamed has a NULL-terminated list of1180 * entries that have not yet been tested for blame. leftover1181 * contains the reversed list of entries that have been tested1182 * without being assignable to the parent.1183 */1184 do {1185 struct blame_entry **unblamedtail = &unblamed;1186 struct blame_entry *next;1187 for (e = unblamed; e; e = next) {1188 next = e->next;1189 find_copy_in_blob(sb, e, parent, split, &file_p);1190 if (split[1].suspect &&1191 blame_move_score < ent_score(sb, &split[1])) {1192 split_blame(blamed, &unblamedtail, split, e);1193 } else {1194 e->next = leftover;1195 leftover = e;1196 }1197 decref_split(split);1198 }1199 *unblamedtail = NULL;1200 toosmall = filter_small(sb, toosmall, &unblamed, blame_move_score);1201 } while (unblamed);1202 target->suspects = reverse_blame(leftover, NULL);1203}12041205struct blame_list {1206 struct blame_entry *ent;1207 struct blame_entry split[3];1208};12091210/*1211 * Count the number of entries the target is suspected for,1212 * and prepare a list of entry and the best split.1213 */1214static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1215 int *num_ents_p)1216{1217 struct blame_entry *e;1218 int num_ents, i;1219 struct blame_list *blame_list = NULL;12201221 for (e = unblamed, num_ents = 0; e; e = e->next)1222 num_ents++;1223 if (num_ents) {1224 blame_list = xcalloc(num_ents, sizeof(struct blame_list));1225 for (e = unblamed, i = 0; e; e = e->next)1226 blame_list[i++].ent = e;1227 }1228 *num_ents_p = num_ents;1229 return blame_list;1230}12311232/*1233 * For lines target is suspected for, see if we can find code movement1234 * across file boundary from the parent commit. porigin is the path1235 * in the parent we already tried.1236 */1237static void find_copy_in_parent(struct scoreboard *sb,1238 struct blame_entry ***blamed,1239 struct blame_entry **toosmall,1240 struct origin *target,1241 struct commit *parent,1242 struct origin *porigin,1243 int opt)1244{1245 struct diff_options diff_opts;1246 int i, j;1247 struct blame_list *blame_list;1248 int num_ents;1249 struct blame_entry *unblamed = target->suspects;1250 struct blame_entry *leftover = NULL;12511252 if (!unblamed)1253 return; /* nothing remains for this target */12541255 diff_setup(&diff_opts);1256 DIFF_OPT_SET(&diff_opts, RECURSIVE);1257 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12581259 diff_setup_done(&diff_opts);12601261 /* Try "find copies harder" on new path if requested;1262 * we do not want to use diffcore_rename() actually to1263 * match things up; find_copies_harder is set only to1264 * force diff_tree_sha1() to feed all filepairs to diff_queue,1265 * and this code needs to be after diff_setup_done(), which1266 * usually makes find-copies-harder imply copy detection.1267 */1268 if ((opt & PICKAXE_BLAME_COPY_HARDEST)1269 || ((opt & PICKAXE_BLAME_COPY_HARDER)1270 && (!porigin || strcmp(target->path, porigin->path))))1271 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12721273 if (is_null_oid(&target->commit->object.oid))1274 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1275 else1276 diff_tree_sha1(parent->tree->object.oid.hash,1277 target->commit->tree->object.oid.hash,1278 "", &diff_opts);12791280 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1281 diffcore_std(&diff_opts);12821283 do {1284 struct blame_entry **unblamedtail = &unblamed;1285 blame_list = setup_blame_list(unblamed, &num_ents);12861287 for (i = 0; i < diff_queued_diff.nr; i++) {1288 struct diff_filepair *p = diff_queued_diff.queue[i];1289 struct origin *norigin;1290 mmfile_t file_p;1291 struct blame_entry this[3];12921293 if (!DIFF_FILE_VALID(p->one))1294 continue; /* does not exist in parent */1295 if (S_ISGITLINK(p->one->mode))1296 continue; /* ignore git links */1297 if (porigin && !strcmp(p->one->path, porigin->path))1298 /* find_move already dealt with this path */1299 continue;13001301 norigin = get_origin(sb, parent, p->one->path);1302 oidcpy(&norigin->blob_oid, &p->one->oid);1303 norigin->mode = p->one->mode;1304 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1305 if (!file_p.ptr)1306 continue;13071308 for (j = 0; j < num_ents; j++) {1309 find_copy_in_blob(sb, blame_list[j].ent,1310 norigin, this, &file_p);1311 copy_split_if_better(sb, blame_list[j].split,1312 this);1313 decref_split(this);1314 }1315 origin_decref(norigin);1316 }13171318 for (j = 0; j < num_ents; j++) {1319 struct blame_entry *split = blame_list[j].split;1320 if (split[1].suspect &&1321 blame_copy_score < ent_score(sb, &split[1])) {1322 split_blame(blamed, &unblamedtail, split,1323 blame_list[j].ent);1324 } else {1325 blame_list[j].ent->next = leftover;1326 leftover = blame_list[j].ent;1327 }1328 decref_split(split);1329 }1330 free(blame_list);1331 *unblamedtail = NULL;1332 toosmall = filter_small(sb, toosmall, &unblamed, blame_copy_score);1333 } while (unblamed);1334 target->suspects = reverse_blame(leftover, NULL);1335 diff_flush(&diff_opts);1336 clear_pathspec(&diff_opts.pathspec);1337}13381339/*1340 * The blobs of origin and porigin exactly match, so everything1341 * origin is suspected for can be blamed on the parent.1342 */1343static void pass_whole_blame(struct scoreboard *sb,1344 struct origin *origin, struct origin *porigin)1345{1346 struct blame_entry *e, *suspects;13471348 if (!porigin->file.ptr && origin->file.ptr) {1349 /* Steal its file */1350 porigin->file = origin->file;1351 origin->file.ptr = NULL;1352 }1353 suspects = origin->suspects;1354 origin->suspects = NULL;1355 for (e = suspects; e; e = e->next) {1356 origin_incref(porigin);1357 origin_decref(e->suspect);1358 e->suspect = porigin;1359 }1360 queue_blames(sb, porigin, suspects);1361}13621363/*1364 * We pass blame from the current commit to its parents. We keep saying1365 * "parent" (and "porigin"), but what we mean is to find scapegoat to1366 * exonerate ourselves.1367 */1368static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)1369{1370 if (!reverse) {1371 if (revs->first_parent_only &&1372 commit->parents &&1373 commit->parents->next) {1374 free_commit_list(commit->parents->next);1375 commit->parents->next = NULL;1376 }1377 return commit->parents;1378 }1379 return lookup_decoration(&revs->children, &commit->object);1380}13811382static int num_scapegoats(struct rev_info *revs, struct commit *commit)1383{1384 struct commit_list *l = first_scapegoat(revs, commit);1385 return commit_list_count(l);1386}13871388/* Distribute collected unsorted blames to the respected sorted lists1389 * in the various origins.1390 */1391static void distribute_blame(struct scoreboard *sb, struct blame_entry *blamed)1392{1393 blamed = blame_sort(blamed, compare_blame_suspect);1394 while (blamed)1395 {1396 struct origin *porigin = blamed->suspect;1397 struct blame_entry *suspects = NULL;1398 do {1399 struct blame_entry *next = blamed->next;1400 blamed->next = suspects;1401 suspects = blamed;1402 blamed = next;1403 } while (blamed && blamed->suspect == porigin);1404 suspects = reverse_blame(suspects, NULL);1405 queue_blames(sb, porigin, suspects);1406 }1407}14081409#define MAXSG 1614101411static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)1412{1413 struct rev_info *revs = sb->revs;1414 int i, pass, num_sg;1415 struct commit *commit = origin->commit;1416 struct commit_list *sg;1417 struct origin *sg_buf[MAXSG];1418 struct origin *porigin, **sg_origin = sg_buf;1419 struct blame_entry *toosmall = NULL;1420 struct blame_entry *blames, **blametail = &blames;14211422 num_sg = num_scapegoats(revs, commit);1423 if (!num_sg)1424 goto finish;1425 else if (num_sg < ARRAY_SIZE(sg_buf))1426 memset(sg_buf, 0, sizeof(sg_buf));1427 else1428 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));14291430 /*1431 * The first pass looks for unrenamed path to optimize for1432 * common cases, then we look for renames in the second pass.1433 */1434 for (pass = 0; pass < 2 - no_whole_file_rename; pass++) {1435 struct origin *(*find)(struct scoreboard *,1436 struct commit *, struct origin *);1437 find = pass ? find_rename : find_origin;14381439 for (i = 0, sg = first_scapegoat(revs, commit);1440 i < num_sg && sg;1441 sg = sg->next, i++) {1442 struct commit *p = sg->item;1443 int j, same;14441445 if (sg_origin[i])1446 continue;1447 if (parse_commit(p))1448 continue;1449 porigin = find(sb, p, origin);1450 if (!porigin)1451 continue;1452 if (!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {1453 pass_whole_blame(sb, origin, porigin);1454 origin_decref(porigin);1455 goto finish;1456 }1457 for (j = same = 0; j < i; j++)1458 if (sg_origin[j] &&1459 !oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {1460 same = 1;1461 break;1462 }1463 if (!same)1464 sg_origin[i] = porigin;1465 else1466 origin_decref(porigin);1467 }1468 }14691470 num_commits++;1471 for (i = 0, sg = first_scapegoat(revs, commit);1472 i < num_sg && sg;1473 sg = sg->next, i++) {1474 struct origin *porigin = sg_origin[i];1475 if (!porigin)1476 continue;1477 if (!origin->previous) {1478 origin_incref(porigin);1479 origin->previous = porigin;1480 }1481 pass_blame_to_parent(sb, origin, porigin);1482 if (!origin->suspects)1483 goto finish;1484 }14851486 /*1487 * Optionally find moves in parents' files.1488 */1489 if (opt & PICKAXE_BLAME_MOVE) {1490 filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1491 if (origin->suspects) {1492 for (i = 0, sg = first_scapegoat(revs, commit);1493 i < num_sg && sg;1494 sg = sg->next, i++) {1495 struct origin *porigin = sg_origin[i];1496 if (!porigin)1497 continue;1498 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1499 if (!origin->suspects)1500 break;1501 }1502 }1503 }15041505 /*1506 * Optionally find copies from parents' files.1507 */1508 if (opt & PICKAXE_BLAME_COPY) {1509 if (blame_copy_score > blame_move_score)1510 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1511 else if (blame_copy_score < blame_move_score) {1512 origin->suspects = blame_merge(origin->suspects, toosmall);1513 toosmall = NULL;1514 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1515 }1516 if (!origin->suspects)1517 goto finish;15181519 for (i = 0, sg = first_scapegoat(revs, commit);1520 i < num_sg && sg;1521 sg = sg->next, i++) {1522 struct origin *porigin = sg_origin[i];1523 find_copy_in_parent(sb, &blametail, &toosmall,1524 origin, sg->item, porigin, opt);1525 if (!origin->suspects)1526 goto finish;1527 }1528 }15291530finish:1531 *blametail = NULL;1532 distribute_blame(sb, blames);1533 /*1534 * prepend toosmall to origin->suspects1535 *1536 * There is no point in sorting: this ends up on a big1537 * unsorted list in the caller anyway.1538 */1539 if (toosmall) {1540 struct blame_entry **tail = &toosmall;1541 while (*tail)1542 tail = &(*tail)->next;1543 *tail = origin->suspects;1544 origin->suspects = toosmall;1545 }1546 for (i = 0; i < num_sg; i++) {1547 if (sg_origin[i]) {1548 drop_origin_blob(sg_origin[i]);1549 origin_decref(sg_origin[i]);1550 }1551 }1552 drop_origin_blob(origin);1553 if (sg_buf != sg_origin)1554 free(sg_origin);1555}15561557/*1558 * Information on commits, used for output.1559 */1560struct commit_info {1561 struct strbuf author;1562 struct strbuf author_mail;1563 timestamp_t author_time;1564 struct strbuf author_tz;15651566 /* filled only when asked for details */1567 struct strbuf committer;1568 struct strbuf committer_mail;1569 timestamp_t committer_time;1570 struct strbuf committer_tz;15711572 struct strbuf summary;1573};15741575/*1576 * Parse author/committer line in the commit object buffer1577 */1578static void get_ac_line(const char *inbuf, const char *what,1579 struct strbuf *name, struct strbuf *mail,1580 timestamp_t *time, struct strbuf *tz)1581{1582 struct ident_split ident;1583 size_t len, maillen, namelen;1584 char *tmp, *endp;1585 const char *namebuf, *mailbuf;15861587 tmp = strstr(inbuf, what);1588 if (!tmp)1589 goto error_out;1590 tmp += strlen(what);1591 endp = strchr(tmp, '\n');1592 if (!endp)1593 len = strlen(tmp);1594 else1595 len = endp - tmp;15961597 if (split_ident_line(&ident, tmp, len)) {1598 error_out:1599 /* Ugh */1600 tmp = "(unknown)";1601 strbuf_addstr(name, tmp);1602 strbuf_addstr(mail, tmp);1603 strbuf_addstr(tz, tmp);1604 *time = 0;1605 return;1606 }16071608 namelen = ident.name_end - ident.name_begin;1609 namebuf = ident.name_begin;16101611 maillen = ident.mail_end - ident.mail_begin;1612 mailbuf = ident.mail_begin;16131614 if (ident.date_begin && ident.date_end)1615 *time = strtoul(ident.date_begin, NULL, 10);1616 else1617 *time = 0;16181619 if (ident.tz_begin && ident.tz_end)1620 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1621 else1622 strbuf_addstr(tz, "(unknown)");16231624 /*1625 * Now, convert both name and e-mail using mailmap1626 */1627 map_user(&mailmap, &mailbuf, &maillen,1628 &namebuf, &namelen);16291630 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);1631 strbuf_add(name, namebuf, namelen);1632}16331634static void commit_info_init(struct commit_info *ci)1635{16361637 strbuf_init(&ci->author, 0);1638 strbuf_init(&ci->author_mail, 0);1639 strbuf_init(&ci->author_tz, 0);1640 strbuf_init(&ci->committer, 0);1641 strbuf_init(&ci->committer_mail, 0);1642 strbuf_init(&ci->committer_tz, 0);1643 strbuf_init(&ci->summary, 0);1644}16451646static void commit_info_destroy(struct commit_info *ci)1647{16481649 strbuf_release(&ci->author);1650 strbuf_release(&ci->author_mail);1651 strbuf_release(&ci->author_tz);1652 strbuf_release(&ci->committer);1653 strbuf_release(&ci->committer_mail);1654 strbuf_release(&ci->committer_tz);1655 strbuf_release(&ci->summary);1656}16571658static void get_commit_info(struct commit *commit,1659 struct commit_info *ret,1660 int detailed)1661{1662 int len;1663 const char *subject, *encoding;1664 const char *message;16651666 commit_info_init(ret);16671668 encoding = get_log_output_encoding();1669 message = logmsg_reencode(commit, NULL, encoding);1670 get_ac_line(message, "\nauthor ",1671 &ret->author, &ret->author_mail,1672 &ret->author_time, &ret->author_tz);16731674 if (!detailed) {1675 unuse_commit_buffer(commit, message);1676 return;1677 }16781679 get_ac_line(message, "\ncommitter ",1680 &ret->committer, &ret->committer_mail,1681 &ret->committer_time, &ret->committer_tz);16821683 len = find_commit_subject(message, &subject);1684 if (len)1685 strbuf_add(&ret->summary, subject, len);1686 else1687 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));16881689 unuse_commit_buffer(commit, message);1690}16911692/*1693 * Write out any suspect information which depends on the path. This must be1694 * handled separately from emit_one_suspect_detail(), because a given commit1695 * may have changes in multiple paths. So this needs to appear each time1696 * we mention a new group.1697 *1698 * To allow LF and other nonportable characters in pathnames,1699 * they are c-style quoted as needed.1700 */1701static void write_filename_info(struct origin *suspect)1702{1703 if (suspect->previous) {1704 struct origin *prev = suspect->previous;1705 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));1706 write_name_quoted(prev->path, stdout, '\n');1707 }1708 printf("filename ");1709 write_name_quoted(suspect->path, stdout, '\n');1710}17111712/*1713 * Porcelain/Incremental format wants to show a lot of details per1714 * commit. Instead of repeating this every line, emit it only once,1715 * the first time each commit appears in the output (unless the1716 * user has specifically asked for us to repeat).1717 */1718static int emit_one_suspect_detail(struct origin *suspect, int repeat)1719{1720 struct commit_info ci;17211722 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1723 return 0;17241725 suspect->commit->object.flags |= METAINFO_SHOWN;1726 get_commit_info(suspect->commit, &ci, 1);1727 printf("author %s\n", ci.author.buf);1728 printf("author-mail %s\n", ci.author_mail.buf);1729 printf("author-time %"PRItime"\n", ci.author_time);1730 printf("author-tz %s\n", ci.author_tz.buf);1731 printf("committer %s\n", ci.committer.buf);1732 printf("committer-mail %s\n", ci.committer_mail.buf);1733 printf("committer-time %"PRItime"\n", ci.committer_time);1734 printf("committer-tz %s\n", ci.committer_tz.buf);1735 printf("summary %s\n", ci.summary.buf);1736 if (suspect->commit->object.flags & UNINTERESTING)1737 printf("boundary\n");17381739 commit_info_destroy(&ci);17401741 return 1;1742}17431744/*1745 * The blame_entry is found to be guilty for the range.1746 * Show it in incremental output.1747 */1748static void found_guilty_entry(struct blame_entry *ent,1749 struct progress_info *pi)1750{1751 if (incremental) {1752 struct origin *suspect = ent->suspect;17531754 printf("%s %d %d %d\n",1755 oid_to_hex(&suspect->commit->object.oid),1756 ent->s_lno + 1, ent->lno + 1, ent->num_lines);1757 emit_one_suspect_detail(suspect, 0);1758 write_filename_info(suspect);1759 maybe_flush_or_die(stdout, "stdout");1760 }1761 pi->blamed_lines += ent->num_lines;1762 display_progress(pi->progress, pi->blamed_lines);1763}17641765/*1766 * The main loop -- while we have blobs with lines whose true origin1767 * is still unknown, pick one blob, and allow its lines to pass blames1768 * to its parents. */1769static void assign_blame(struct scoreboard *sb, int opt)1770{1771 struct rev_info *revs = sb->revs;1772 struct commit *commit = prio_queue_get(&sb->commits);1773 struct progress_info pi = { NULL, 0 };17741775 if (show_progress)1776 pi.progress = start_progress_delay(_("Blaming lines"),1777 sb->num_lines, 50, 1);17781779 while (commit) {1780 struct blame_entry *ent;1781 struct origin *suspect = commit->util;17821783 /* find one suspect to break down */1784 while (suspect && !suspect->suspects)1785 suspect = suspect->next;17861787 if (!suspect) {1788 commit = prio_queue_get(&sb->commits);1789 continue;1790 }17911792 assert(commit == suspect->commit);17931794 /*1795 * We will use this suspect later in the loop,1796 * so hold onto it in the meantime.1797 */1798 origin_incref(suspect);1799 parse_commit(commit);1800 if (reverse ||1801 (!(commit->object.flags & UNINTERESTING) &&1802 !(revs->max_age != -1 && commit->date < revs->max_age)))1803 pass_blame(sb, suspect, opt);1804 else {1805 commit->object.flags |= UNINTERESTING;1806 if (commit->object.parsed)1807 mark_parents_uninteresting(commit);1808 }1809 /* treat root commit as boundary */1810 if (!commit->parents && !show_root)1811 commit->object.flags |= UNINTERESTING;18121813 /* Take responsibility for the remaining entries */1814 ent = suspect->suspects;1815 if (ent) {1816 suspect->guilty = 1;1817 for (;;) {1818 struct blame_entry *next = ent->next;1819 found_guilty_entry(ent, &pi);1820 if (next) {1821 ent = next;1822 continue;1823 }1824 ent->next = sb->ent;1825 sb->ent = suspect->suspects;1826 suspect->suspects = NULL;1827 break;1828 }1829 }1830 origin_decref(suspect);18311832 if (DEBUG) /* sanity */1833 sanity_check_refcnt(sb);1834 }18351836 stop_progress(&pi.progress);1837}18381839static const char *format_time(timestamp_t time, const char *tz_str,1840 int show_raw_time)1841{1842 static struct strbuf time_buf = STRBUF_INIT;18431844 strbuf_reset(&time_buf);1845 if (show_raw_time) {1846 strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);1847 }1848 else {1849 const char *time_str;1850 size_t time_width;1851 int tz;1852 tz = atoi(tz_str);1853 time_str = show_date(time, tz, &blame_date_mode);1854 strbuf_addstr(&time_buf, time_str);1855 /*1856 * Add space paddings to time_buf to display a fixed width1857 * string, and use time_width for display width calibration.1858 */1859 for (time_width = utf8_strwidth(time_str);1860 time_width < blame_date_width;1861 time_width++)1862 strbuf_addch(&time_buf, ' ');1863 }1864 return time_buf.buf;1865}18661867#define OUTPUT_ANNOTATE_COMPAT 0011868#define OUTPUT_LONG_OBJECT_NAME 0021869#define OUTPUT_RAW_TIMESTAMP 0041870#define OUTPUT_PORCELAIN 0101871#define OUTPUT_SHOW_NAME 0201872#define OUTPUT_SHOW_NUMBER 0401873#define OUTPUT_SHOW_SCORE 01001874#define OUTPUT_NO_AUTHOR 02001875#define OUTPUT_SHOW_EMAIL 04001876#define OUTPUT_LINE_PORCELAIN 0100018771878static void emit_porcelain_details(struct origin *suspect, int repeat)1879{1880 if (emit_one_suspect_detail(suspect, repeat) ||1881 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))1882 write_filename_info(suspect);1883}18841885static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent,1886 int opt)1887{1888 int repeat = opt & OUTPUT_LINE_PORCELAIN;1889 int cnt;1890 const char *cp;1891 struct origin *suspect = ent->suspect;1892 char hex[GIT_MAX_HEXSZ + 1];18931894 oid_to_hex_r(hex, &suspect->commit->object.oid);1895 printf("%s %d %d %d\n",1896 hex,1897 ent->s_lno + 1,1898 ent->lno + 1,1899 ent->num_lines);1900 emit_porcelain_details(suspect, repeat);19011902 cp = nth_line(sb, ent->lno);1903 for (cnt = 0; cnt < ent->num_lines; cnt++) {1904 char ch;1905 if (cnt) {1906 printf("%s %d %d\n", hex,1907 ent->s_lno + 1 + cnt,1908 ent->lno + 1 + cnt);1909 if (repeat)1910 emit_porcelain_details(suspect, 1);1911 }1912 putchar('\t');1913 do {1914 ch = *cp++;1915 putchar(ch);1916 } while (ch != '\n' &&1917 cp < sb->final_buf + sb->final_buf_size);1918 }19191920 if (sb->final_buf_size && cp[-1] != '\n')1921 putchar('\n');1922}19231924static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)1925{1926 int cnt;1927 const char *cp;1928 struct origin *suspect = ent->suspect;1929 struct commit_info ci;1930 char hex[GIT_MAX_HEXSZ + 1];1931 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19321933 get_commit_info(suspect->commit, &ci, 1);1934 oid_to_hex_r(hex, &suspect->commit->object.oid);19351936 cp = nth_line(sb, ent->lno);1937 for (cnt = 0; cnt < ent->num_lines; cnt++) {1938 char ch;1939 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? GIT_SHA1_HEXSZ : abbrev;19401941 if (suspect->commit->object.flags & UNINTERESTING) {1942 if (blank_boundary)1943 memset(hex, ' ', length);1944 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {1945 length--;1946 putchar('^');1947 }1948 }19491950 printf("%.*s", length, hex);1951 if (opt & OUTPUT_ANNOTATE_COMPAT) {1952 const char *name;1953 if (opt & OUTPUT_SHOW_EMAIL)1954 name = ci.author_mail.buf;1955 else1956 name = ci.author.buf;1957 printf("\t(%10s\t%10s\t%d)", name,1958 format_time(ci.author_time, ci.author_tz.buf,1959 show_raw_time),1960 ent->lno + 1 + cnt);1961 } else {1962 if (opt & OUTPUT_SHOW_SCORE)1963 printf(" %*d %02d",1964 max_score_digits, ent->score,1965 ent->suspect->refcnt);1966 if (opt & OUTPUT_SHOW_NAME)1967 printf(" %-*.*s", longest_file, longest_file,1968 suspect->path);1969 if (opt & OUTPUT_SHOW_NUMBER)1970 printf(" %*d", max_orig_digits,1971 ent->s_lno + 1 + cnt);19721973 if (!(opt & OUTPUT_NO_AUTHOR)) {1974 const char *name;1975 int pad;1976 if (opt & OUTPUT_SHOW_EMAIL)1977 name = ci.author_mail.buf;1978 else1979 name = ci.author.buf;1980 pad = longest_author - utf8_strwidth(name);1981 printf(" (%s%*s %10s",1982 name, pad, "",1983 format_time(ci.author_time,1984 ci.author_tz.buf,1985 show_raw_time));1986 }1987 printf(" %*d) ",1988 max_digits, ent->lno + 1 + cnt);1989 }1990 do {1991 ch = *cp++;1992 putchar(ch);1993 } while (ch != '\n' &&1994 cp < sb->final_buf + sb->final_buf_size);1995 }19961997 if (sb->final_buf_size && cp[-1] != '\n')1998 putchar('\n');19992000 commit_info_destroy(&ci);2001}20022003static void output(struct scoreboard *sb, int option)2004{2005 struct blame_entry *ent;20062007 if (option & OUTPUT_PORCELAIN) {2008 for (ent = sb->ent; ent; ent = ent->next) {2009 int count = 0;2010 struct origin *suspect;2011 struct commit *commit = ent->suspect->commit;2012 if (commit->object.flags & MORE_THAN_ONE_PATH)2013 continue;2014 for (suspect = commit->util; suspect; suspect = suspect->next) {2015 if (suspect->guilty && count++) {2016 commit->object.flags |= MORE_THAN_ONE_PATH;2017 break;2018 }2019 }2020 }2021 }20222023 for (ent = sb->ent; ent; ent = ent->next) {2024 if (option & OUTPUT_PORCELAIN)2025 emit_porcelain(sb, ent, option);2026 else {2027 emit_other(sb, ent, option);2028 }2029 }2030}20312032static const char *get_next_line(const char *start, const char *end)2033{2034 const char *nl = memchr(start, '\n', end - start);2035 return nl ? nl + 1 : end;2036}20372038/*2039 * To allow quick access to the contents of nth line in the2040 * final image, prepare an index in the scoreboard.2041 */2042static int prepare_lines(struct scoreboard *sb)2043{2044 const char *buf = sb->final_buf;2045 unsigned long len = sb->final_buf_size;2046 const char *end = buf + len;2047 const char *p;2048 int *lineno;2049 int num = 0;20502051 for (p = buf; p < end; p = get_next_line(p, end))2052 num++;20532054 ALLOC_ARRAY(sb->lineno, num + 1);2055 lineno = sb->lineno;20562057 for (p = buf; p < end; p = get_next_line(p, end))2058 *lineno++ = p - buf;20592060 *lineno = len;20612062 sb->num_lines = num;2063 return sb->num_lines;2064}20652066/*2067 * Add phony grafts for use with -S; this is primarily to2068 * support git's cvsserver that wants to give a linear history2069 * to its clients.2070 */2071static int read_ancestry(const char *graft_file)2072{2073 FILE *fp = fopen(graft_file, "r");2074 struct strbuf buf = STRBUF_INIT;2075 if (!fp)2076 return -1;2077 while (!strbuf_getwholeline(&buf, fp, '\n')) {2078 /* The format is just "Commit Parent1 Parent2 ...\n" */2079 struct commit_graft *graft = read_graft_line(buf.buf, buf.len);2080 if (graft)2081 register_commit_graft(graft, 0);2082 }2083 fclose(fp);2084 strbuf_release(&buf);2085 return 0;2086}20872088static int update_auto_abbrev(int auto_abbrev, struct origin *suspect)2089{2090 const char *uniq = find_unique_abbrev(suspect->commit->object.oid.hash,2091 auto_abbrev);2092 int len = strlen(uniq);2093 if (auto_abbrev < len)2094 return len;2095 return auto_abbrev;2096}20972098/*2099 * How many columns do we need to show line numbers, authors,2100 * and filenames?2101 */2102static void find_alignment(struct scoreboard *sb, int *option)2103{2104 int longest_src_lines = 0;2105 int longest_dst_lines = 0;2106 unsigned largest_score = 0;2107 struct blame_entry *e;2108 int compute_auto_abbrev = (abbrev < 0);2109 int auto_abbrev = DEFAULT_ABBREV;21102111 for (e = sb->ent; e; e = e->next) {2112 struct origin *suspect = e->suspect;2113 int num;21142115 if (compute_auto_abbrev)2116 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);2117 if (strcmp(suspect->path, sb->path))2118 *option |= OUTPUT_SHOW_NAME;2119 num = strlen(suspect->path);2120 if (longest_file < num)2121 longest_file = num;2122 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {2123 struct commit_info ci;2124 suspect->commit->object.flags |= METAINFO_SHOWN;2125 get_commit_info(suspect->commit, &ci, 1);2126 if (*option & OUTPUT_SHOW_EMAIL)2127 num = utf8_strwidth(ci.author_mail.buf);2128 else2129 num = utf8_strwidth(ci.author.buf);2130 if (longest_author < num)2131 longest_author = num;2132 commit_info_destroy(&ci);2133 }2134 num = e->s_lno + e->num_lines;2135 if (longest_src_lines < num)2136 longest_src_lines = num;2137 num = e->lno + e->num_lines;2138 if (longest_dst_lines < num)2139 longest_dst_lines = num;2140 if (largest_score < ent_score(sb, e))2141 largest_score = ent_score(sb, e);2142 }2143 max_orig_digits = decimal_width(longest_src_lines);2144 max_digits = decimal_width(longest_dst_lines);2145 max_score_digits = decimal_width(largest_score);21462147 if (compute_auto_abbrev)2148 /* one more abbrev length is needed for the boundary commit */2149 abbrev = auto_abbrev + 1;2150}21512152/*2153 * For debugging -- origin is refcounted, and this asserts that2154 * we do not underflow.2155 */2156static void sanity_check_refcnt(struct scoreboard *sb)2157{2158 int baa = 0;2159 struct blame_entry *ent;21602161 for (ent = sb->ent; ent; ent = ent->next) {2162 /* Nobody should have zero or negative refcnt */2163 if (ent->suspect->refcnt <= 0) {2164 fprintf(stderr, "%s in %s has negative refcnt %d\n",2165 ent->suspect->path,2166 oid_to_hex(&ent->suspect->commit->object.oid),2167 ent->suspect->refcnt);2168 baa = 1;2169 }2170 }2171 if (baa) {2172 int opt = 0160;2173 find_alignment(sb, &opt);2174 output(sb, opt);2175 die("Baa %d!", baa);2176 }2177}21782179static unsigned parse_score(const char *arg)2180{2181 char *end;2182 unsigned long score = strtoul(arg, &end, 10);2183 if (*end)2184 return 0;2185 return score;2186}21872188static const char *add_prefix(const char *prefix, const char *path)2189{2190 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);2191}21922193static int git_blame_config(const char *var, const char *value, void *cb)2194{2195 if (!strcmp(var, "blame.showroot")) {2196 show_root = git_config_bool(var, value);2197 return 0;2198 }2199 if (!strcmp(var, "blame.blankboundary")) {2200 blank_boundary = git_config_bool(var, value);2201 return 0;2202 }2203 if (!strcmp(var, "blame.showemail")) {2204 int *output_option = cb;2205 if (git_config_bool(var, value))2206 *output_option |= OUTPUT_SHOW_EMAIL;2207 else2208 *output_option &= ~OUTPUT_SHOW_EMAIL;2209 return 0;2210 }2211 if (!strcmp(var, "blame.date")) {2212 if (!value)2213 return config_error_nonbool(var);2214 parse_date_format(value, &blame_date_mode);2215 return 0;2216 }22172218 if (git_diff_heuristic_config(var, value, cb) < 0)2219 return -1;2220 if (userdiff_config(var, value) < 0)2221 return -1;22222223 return git_default_config(var, value, cb);2224}22252226static void verify_working_tree_path(struct commit *work_tree, const char *path)2227{2228 struct commit_list *parents;2229 int pos;22302231 for (parents = work_tree->parents; parents; parents = parents->next) {2232 const struct object_id *commit_oid = &parents->item->object.oid;2233 struct object_id blob_oid;2234 unsigned mode;22352236 if (!get_tree_entry(commit_oid->hash, path, blob_oid.hash, &mode) &&2237 sha1_object_info(blob_oid.hash, NULL) == OBJ_BLOB)2238 return;2239 }22402241 pos = cache_name_pos(path, strlen(path));2242 if (pos >= 0)2243 ; /* path is in the index */2244 else if (-1 - pos < active_nr &&2245 !strcmp(active_cache[-1 - pos]->name, path))2246 ; /* path is in the index, unmerged */2247 else2248 die("no such path '%s' in HEAD", path);2249}22502251static struct commit_list **append_parent(struct commit_list **tail, const struct object_id *oid)2252{2253 struct commit *parent;22542255 parent = lookup_commit_reference(oid->hash);2256 if (!parent)2257 die("no such commit %s", oid_to_hex(oid));2258 return &commit_list_insert(parent, tail)->next;2259}22602261static void append_merge_parents(struct commit_list **tail)2262{2263 int merge_head;2264 struct strbuf line = STRBUF_INIT;22652266 merge_head = open(git_path_merge_head(), O_RDONLY);2267 if (merge_head < 0) {2268 if (errno == ENOENT)2269 return;2270 die("cannot open '%s' for reading", git_path_merge_head());2271 }22722273 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {2274 struct object_id oid;2275 if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))2276 die("unknown line in '%s': %s", git_path_merge_head(), line.buf);2277 tail = append_parent(tail, &oid);2278 }2279 close(merge_head);2280 strbuf_release(&line);2281}22822283/*2284 * This isn't as simple as passing sb->buf and sb->len, because we2285 * want to transfer ownership of the buffer to the commit (so we2286 * must use detach).2287 */2288static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)2289{2290 size_t len;2291 void *buf = strbuf_detach(sb, &len);2292 set_commit_buffer(c, buf, len);2293}22942295/*2296 * Prepare a dummy commit that represents the work tree (or staged) item.2297 * Note that annotating work tree item never works in the reverse.2298 */2299static struct commit *fake_working_tree_commit(struct diff_options *opt,2300 const char *path,2301 const char *contents_from)2302{2303 struct commit *commit;2304 struct origin *origin;2305 struct commit_list **parent_tail, *parent;2306 struct object_id head_oid;2307 struct strbuf buf = STRBUF_INIT;2308 const char *ident;2309 time_t now;2310 int size, len;2311 struct cache_entry *ce;2312 unsigned mode;2313 struct strbuf msg = STRBUF_INIT;23142315 read_cache();2316 time(&now);2317 commit = alloc_commit_node();2318 commit->object.parsed = 1;2319 commit->date = now;2320 parent_tail = &commit->parents;23212322 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_oid.hash, NULL))2323 die("no such ref: HEAD");23242325 parent_tail = append_parent(parent_tail, &head_oid);2326 append_merge_parents(parent_tail);2327 verify_working_tree_path(commit, path);23282329 origin = make_origin(commit, path);23302331 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);2332 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");2333 for (parent = commit->parents; parent; parent = parent->next)2334 strbuf_addf(&msg, "parent %s\n",2335 oid_to_hex(&parent->item->object.oid));2336 strbuf_addf(&msg,2337 "author %s\n"2338 "committer %s\n\n"2339 "Version of %s from %s\n",2340 ident, ident, path,2341 (!contents_from ? path :2342 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));2343 set_commit_buffer_from_strbuf(commit, &msg);23442345 if (!contents_from || strcmp("-", contents_from)) {2346 struct stat st;2347 const char *read_from;2348 char *buf_ptr;2349 unsigned long buf_len;23502351 if (contents_from) {2352 if (stat(contents_from, &st) < 0)2353 die_errno("Cannot stat '%s'", contents_from);2354 read_from = contents_from;2355 }2356 else {2357 if (lstat(path, &st) < 0)2358 die_errno("Cannot lstat '%s'", path);2359 read_from = path;2360 }2361 mode = canon_mode(st.st_mode);23622363 switch (st.st_mode & S_IFMT) {2364 case S_IFREG:2365 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2366 textconv_object(read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))2367 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);2368 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2369 die_errno("cannot open or read '%s'", read_from);2370 break;2371 case S_IFLNK:2372 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)2373 die_errno("cannot readlink '%s'", read_from);2374 break;2375 default:2376 die("unsupported file type %s", read_from);2377 }2378 }2379 else {2380 /* Reading from stdin */2381 mode = 0;2382 if (strbuf_read(&buf, 0, 0) < 0)2383 die_errno("failed to read from stdin");2384 }2385 convert_to_git(path, buf.buf, buf.len, &buf, 0);2386 origin->file.ptr = buf.buf;2387 origin->file.size = buf.len;2388 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_oid.hash);23892390 /*2391 * Read the current index, replace the path entry with2392 * origin->blob_sha1 without mucking with its mode or type2393 * bits; we are not going to write this index out -- we just2394 * want to run "diff-index --cached".2395 */2396 discard_cache();2397 read_cache();23982399 len = strlen(path);2400 if (!mode) {2401 int pos = cache_name_pos(path, len);2402 if (0 <= pos)2403 mode = active_cache[pos]->ce_mode;2404 else2405 /* Let's not bother reading from HEAD tree */2406 mode = S_IFREG | 0644;2407 }2408 size = cache_entry_size(len);2409 ce = xcalloc(1, size);2410 oidcpy(&ce->oid, &origin->blob_oid);2411 memcpy(ce->name, path, len);2412 ce->ce_flags = create_ce_flags(0);2413 ce->ce_namelen = len;2414 ce->ce_mode = create_ce_mode(mode);2415 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);24162417 cache_tree_invalidate_path(&the_index, path);24182419 return commit;2420}24212422static struct commit *find_single_final(struct rev_info *revs,2423 const char **name_p)2424{2425 int i;2426 struct commit *found = NULL;2427 const char *name = NULL;24282429 for (i = 0; i < revs->pending.nr; i++) {2430 struct object *obj = revs->pending.objects[i].item;2431 if (obj->flags & UNINTERESTING)2432 continue;2433 obj = deref_tag(obj, NULL, 0);2434 if (obj->type != OBJ_COMMIT)2435 die("Non commit %s?", revs->pending.objects[i].name);2436 if (found)2437 die("More than one commit to dig from %s and %s?",2438 revs->pending.objects[i].name, name);2439 found = (struct commit *)obj;2440 name = revs->pending.objects[i].name;2441 }2442 if (name_p)2443 *name_p = name;2444 return found;2445}24462447static char *prepare_final(struct scoreboard *sb)2448{2449 const char *name;2450 sb->final = find_single_final(sb->revs, &name);2451 return xstrdup_or_null(name);2452}24532454static const char *dwim_reverse_initial(struct scoreboard *sb)2455{2456 /*2457 * DWIM "git blame --reverse ONE -- PATH" as2458 * "git blame --reverse ONE..HEAD -- PATH" but only do so2459 * when it makes sense.2460 */2461 struct object *obj;2462 struct commit *head_commit;2463 unsigned char head_sha1[20];24642465 if (sb->revs->pending.nr != 1)2466 return NULL;24672468 /* Is that sole rev a committish? */2469 obj = sb->revs->pending.objects[0].item;2470 obj = deref_tag(obj, NULL, 0);2471 if (obj->type != OBJ_COMMIT)2472 return NULL;24732474 /* Do we have HEAD? */2475 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2476 return NULL;2477 head_commit = lookup_commit_reference_gently(head_sha1, 1);2478 if (!head_commit)2479 return NULL;24802481 /* Turn "ONE" into "ONE..HEAD" then */2482 obj->flags |= UNINTERESTING;2483 add_pending_object(sb->revs, &head_commit->object, "HEAD");24842485 sb->final = (struct commit *)obj;2486 return sb->revs->pending.objects[0].name;2487}24882489static char *prepare_initial(struct scoreboard *sb)2490{2491 int i;2492 const char *final_commit_name = NULL;2493 struct rev_info *revs = sb->revs;24942495 /*2496 * There must be one and only one negative commit, and it must be2497 * the boundary.2498 */2499 for (i = 0; i < revs->pending.nr; i++) {2500 struct object *obj = revs->pending.objects[i].item;2501 if (!(obj->flags & UNINTERESTING))2502 continue;2503 obj = deref_tag(obj, NULL, 0);2504 if (obj->type != OBJ_COMMIT)2505 die("Non commit %s?", revs->pending.objects[i].name);2506 if (sb->final)2507 die("More than one commit to dig up from, %s and %s?",2508 revs->pending.objects[i].name,2509 final_commit_name);2510 sb->final = (struct commit *) obj;2511 final_commit_name = revs->pending.objects[i].name;2512 }25132514 if (!final_commit_name)2515 final_commit_name = dwim_reverse_initial(sb);2516 if (!final_commit_name)2517 die("No commit to dig up from?");2518 return xstrdup(final_commit_name);2519}25202521static int blame_copy_callback(const struct option *option, const char *arg, int unset)2522{2523 int *opt = option->value;25242525 /*2526 * -C enables copy from removed files;2527 * -C -C enables copy from existing files, but only2528 * when blaming a new file;2529 * -C -C -C enables copy from existing files for2530 * everybody2531 */2532 if (*opt & PICKAXE_BLAME_COPY_HARDER)2533 *opt |= PICKAXE_BLAME_COPY_HARDEST;2534 if (*opt & PICKAXE_BLAME_COPY)2535 *opt |= PICKAXE_BLAME_COPY_HARDER;2536 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;25372538 if (arg)2539 blame_copy_score = parse_score(arg);2540 return 0;2541}25422543static int blame_move_callback(const struct option *option, const char *arg, int unset)2544{2545 int *opt = option->value;25462547 *opt |= PICKAXE_BLAME_MOVE;25482549 if (arg)2550 blame_move_score = parse_score(arg);2551 return 0;2552}25532554int cmd_blame(int argc, const char **argv, const char *prefix)2555{2556 struct rev_info revs;2557 const char *path;2558 struct scoreboard sb;2559 struct origin *o;2560 struct blame_entry *ent = NULL;2561 long dashdash_pos, lno;2562 char *final_commit_name = NULL;2563 enum object_type type;2564 struct commit *final_commit = NULL;25652566 struct string_list range_list = STRING_LIST_INIT_NODUP;2567 int output_option = 0, opt = 0;2568 int show_stats = 0;2569 const char *revs_file = NULL;2570 const char *contents_from = NULL;2571 const struct option options[] = {2572 OPT_BOOL(0, "incremental", &incremental, N_("Show blame entries as we find them, incrementally")),2573 OPT_BOOL('b', NULL, &blank_boundary, N_("Show blank SHA-1 for boundary commits (Default: off)")),2574 OPT_BOOL(0, "root", &show_root, N_("Do not treat root commits as boundaries (Default: off)")),2575 OPT_BOOL(0, "show-stats", &show_stats, N_("Show work cost statistics")),2576 OPT_BOOL(0, "progress", &show_progress, N_("Force progress reporting")),2577 OPT_BIT(0, "score-debug", &output_option, N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2578 OPT_BIT('f', "show-name", &output_option, N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2579 OPT_BIT('n', "show-number", &output_option, N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2580 OPT_BIT('p', "porcelain", &output_option, N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2581 OPT_BIT(0, "line-porcelain", &output_option, N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2582 OPT_BIT('c', NULL, &output_option, N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2583 OPT_BIT('t', NULL, &output_option, N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2584 OPT_BIT('l', NULL, &output_option, N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2585 OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2586 OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2587 OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),25882589 /*2590 * The following two options are parsed by parse_revision_opt()2591 * and are only included here to get included in the "-h"2592 * output:2593 */2594 { OPTION_LOWLEVEL_CALLBACK, 0, "indent-heuristic", NULL, NULL, N_("Use an experimental heuristic to improve diffs"), PARSE_OPT_NOARG, parse_opt_unknown_cb },25952596 OPT_BIT(0, "minimal", &xdl_opts, N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2597 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("Use revisions from <file> instead of calling git-rev-list")),2598 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("Use <file>'s contents as the final image")),2599 { OPTION_CALLBACK, 'C', NULL, &opt, N_("score"), N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2600 { OPTION_CALLBACK, 'M', NULL, &opt, N_("score"), N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2601 OPT_STRING_LIST('L', NULL, &range_list, N_("n,m"), N_("Process only line range n,m, counting from 1")),2602 OPT__ABBREV(&abbrev),2603 OPT_END()2604 };26052606 struct parse_opt_ctx_t ctx;2607 int cmd_is_annotate = !strcmp(argv[0], "annotate");2608 struct range_set ranges;2609 unsigned int range_i;2610 long anchor;26112612 git_config(git_blame_config, &output_option);2613 init_revisions(&revs, NULL);2614 revs.date_mode = blame_date_mode;2615 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2616 DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);26172618 save_commit_buffer = 0;2619 dashdash_pos = 0;2620 show_progress = -1;26212622 parse_options_start(&ctx, argc, argv, prefix, options,2623 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2624 for (;;) {2625 switch (parse_options_step(&ctx, options, blame_opt_usage)) {2626 case PARSE_OPT_HELP:2627 exit(129);2628 case PARSE_OPT_DONE:2629 if (ctx.argv[0])2630 dashdash_pos = ctx.cpidx;2631 goto parse_done;2632 }26332634 if (!strcmp(ctx.argv[0], "--reverse")) {2635 ctx.argv[0] = "--children";2636 reverse = 1;2637 }2638 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2639 }2640parse_done:2641 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2642 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;2643 DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2644 argc = parse_options_end(&ctx);26452646 if (incremental || (output_option & OUTPUT_PORCELAIN)) {2647 if (show_progress > 0)2648 die(_("--progress can't be used with --incremental or porcelain formats"));2649 show_progress = 0;2650 } else if (show_progress < 0)2651 show_progress = isatty(2);26522653 if (0 < abbrev && abbrev < GIT_SHA1_HEXSZ)2654 /* one more abbrev length is needed for the boundary commit */2655 abbrev++;2656 else if (!abbrev)2657 abbrev = GIT_SHA1_HEXSZ;26582659 if (revs_file && read_ancestry(revs_file))2660 die_errno("reading graft file '%s' failed", revs_file);26612662 if (cmd_is_annotate) {2663 output_option |= OUTPUT_ANNOTATE_COMPAT;2664 blame_date_mode.type = DATE_ISO8601;2665 } else {2666 blame_date_mode = revs.date_mode;2667 }26682669 /* The maximum width used to show the dates */2670 switch (blame_date_mode.type) {2671 case DATE_RFC2822:2672 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2673 break;2674 case DATE_ISO8601_STRICT:2675 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");2676 break;2677 case DATE_ISO8601:2678 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");2679 break;2680 case DATE_RAW:2681 blame_date_width = sizeof("1161298804 -0700");2682 break;2683 case DATE_UNIX:2684 blame_date_width = sizeof("1161298804");2685 break;2686 case DATE_SHORT:2687 blame_date_width = sizeof("2006-10-19");2688 break;2689 case DATE_RELATIVE:2690 /* TRANSLATORS: This string is used to tell us the maximum2691 display width for a relative timestamp in "git blame"2692 output. For C locale, "4 years, 11 months ago", which2693 takes 22 places, is the longest among various forms of2694 relative timestamps, but your language may need more or2695 fewer display columns. */2696 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */2697 break;2698 case DATE_NORMAL:2699 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");2700 break;2701 case DATE_STRFTIME:2702 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */2703 break;2704 }2705 blame_date_width -= 1; /* strip the null */27062707 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2708 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2709 PICKAXE_BLAME_COPY_HARDER);27102711 if (!blame_move_score)2712 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2713 if (!blame_copy_score)2714 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;27152716 /*2717 * We have collected options unknown to us in argv[1..unk]2718 * which are to be passed to revision machinery if we are2719 * going to do the "bottom" processing.2720 *2721 * The remaining are:2722 *2723 * (1) if dashdash_pos != 0, it is either2724 * "blame [revisions] -- <path>" or2725 * "blame -- <path> <rev>"2726 *2727 * (2) otherwise, it is one of the two:2728 * "blame [revisions] <path>"2729 * "blame <path> <rev>"2730 *2731 * Note that we must strip out <path> from the arguments: we do not2732 * want the path pruning but we may want "bottom" processing.2733 */2734 if (dashdash_pos) {2735 switch (argc - dashdash_pos - 1) {2736 case 2: /* (1b) */2737 if (argc != 4)2738 usage_with_options(blame_opt_usage, options);2739 /* reorder for the new way: <rev> -- <path> */2740 argv[1] = argv[3];2741 argv[3] = argv[2];2742 argv[2] = "--";2743 /* FALLTHROUGH */2744 case 1: /* (1a) */2745 path = add_prefix(prefix, argv[--argc]);2746 argv[argc] = NULL;2747 break;2748 default:2749 usage_with_options(blame_opt_usage, options);2750 }2751 } else {2752 if (argc < 2)2753 usage_with_options(blame_opt_usage, options);2754 path = add_prefix(prefix, argv[argc - 1]);2755 if (argc == 3 && !file_exists(path)) { /* (2b) */2756 path = add_prefix(prefix, argv[1]);2757 argv[1] = argv[2];2758 }2759 argv[argc - 1] = "--";27602761 setup_work_tree();2762 if (!file_exists(path))2763 die_errno("cannot stat path '%s'", path);2764 }27652766 revs.disable_stdin = 1;2767 setup_revisions(argc, argv, &revs, NULL);2768 memset(&sb, 0, sizeof(sb));27692770 sb.revs = &revs;2771 if (!reverse) {2772 final_commit_name = prepare_final(&sb);2773 sb.commits.compare = compare_commits_by_commit_date;2774 }2775 else if (contents_from)2776 die(_("--contents and --reverse do not blend well."));2777 else {2778 final_commit_name = prepare_initial(&sb);2779 sb.commits.compare = compare_commits_by_reverse_commit_date;2780 if (revs.first_parent_only)2781 revs.children.name = NULL;2782 }27832784 if (!sb.final) {2785 /*2786 * "--not A B -- path" without anything positive;2787 * do not default to HEAD, but use the working tree2788 * or "--contents".2789 */2790 setup_work_tree();2791 sb.final = fake_working_tree_commit(&sb.revs->diffopt,2792 path, contents_from);2793 add_pending_object(&revs, &(sb.final->object), ":");2794 }2795 else if (contents_from)2796 die(_("cannot use --contents with final commit object name"));27972798 if (reverse && revs.first_parent_only) {2799 final_commit = find_single_final(sb.revs, NULL);2800 if (!final_commit)2801 die(_("--reverse and --first-parent together require specified latest commit"));2802 }28032804 /*2805 * If we have bottom, this will mark the ancestors of the2806 * bottom commits we would reach while traversing as2807 * uninteresting.2808 */2809 if (prepare_revision_walk(&revs))2810 die(_("revision walk setup failed"));28112812 if (reverse && revs.first_parent_only) {2813 struct commit *c = final_commit;28142815 sb.revs->children.name = "children";2816 while (c->parents &&2817 oidcmp(&c->object.oid, &sb.final->object.oid)) {2818 struct commit_list *l = xcalloc(1, sizeof(*l));28192820 l->item = c;2821 if (add_decoration(&sb.revs->children,2822 &c->parents->item->object, l))2823 die("BUG: not unique item in first-parent chain");2824 c = c->parents->item;2825 }28262827 if (oidcmp(&c->object.oid, &sb.final->object.oid))2828 die(_("--reverse --first-parent together require range along first-parent chain"));2829 }28302831 if (is_null_oid(&sb.final->object.oid)) {2832 o = sb.final->util;2833 sb.final_buf = xmemdupz(o->file.ptr, o->file.size);2834 sb.final_buf_size = o->file.size;2835 }2836 else {2837 o = get_origin(&sb, sb.final, path);2838 if (fill_blob_sha1_and_mode(o))2839 die(_("no such path %s in %s"), path, final_commit_name);28402841 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2842 textconv_object(path, o->mode, &o->blob_oid, 1, (char **) &sb.final_buf,2843 &sb.final_buf_size))2844 ;2845 else2846 sb.final_buf = read_sha1_file(o->blob_oid.hash, &type,2847 &sb.final_buf_size);28482849 if (!sb.final_buf)2850 die(_("cannot read blob %s for path %s"),2851 oid_to_hex(&o->blob_oid),2852 path);2853 }2854 num_read_blob++;2855 lno = prepare_lines(&sb);28562857 if (lno && !range_list.nr)2858 string_list_append(&range_list, "1");28592860 anchor = 1;2861 range_set_init(&ranges, range_list.nr);2862 for (range_i = 0; range_i < range_list.nr; ++range_i) {2863 long bottom, top;2864 if (parse_range_arg(range_list.items[range_i].string,2865 nth_line_cb, &sb, lno, anchor,2866 &bottom, &top, sb.path))2867 usage(blame_usage);2868 if (lno < top || ((lno || bottom) && lno < bottom))2869 die(Q_("file %s has only %lu line",2870 "file %s has only %lu lines",2871 lno), path, lno);2872 if (bottom < 1)2873 bottom = 1;2874 if (top < 1)2875 top = lno;2876 bottom--;2877 range_set_append_unsafe(&ranges, bottom, top);2878 anchor = top + 1;2879 }2880 sort_and_merge_range_set(&ranges);28812882 for (range_i = ranges.nr; range_i > 0; --range_i) {2883 const struct range *r = &ranges.ranges[range_i - 1];2884 long bottom = r->start;2885 long top = r->end;2886 struct blame_entry *next = ent;2887 ent = xcalloc(1, sizeof(*ent));2888 ent->lno = bottom;2889 ent->num_lines = top - bottom;2890 ent->suspect = o;2891 ent->s_lno = bottom;2892 ent->next = next;2893 origin_incref(o);2894 }28952896 o->suspects = ent;2897 prio_queue_put(&sb.commits, o->commit);28982899 origin_decref(o);29002901 range_set_release(&ranges);2902 string_list_clear(&range_list, 0);29032904 sb.ent = NULL;2905 sb.path = path;29062907 read_mailmap(&mailmap, NULL);29082909 assign_blame(&sb, opt);29102911 if (!incremental)2912 setup_pager();29132914 free(final_commit_name);29152916 if (incremental)2917 return 0;29182919 sb.ent = blame_sort(sb.ent, compare_blame_final);29202921 coalesce(&sb);29222923 if (!(output_option & OUTPUT_PORCELAIN))2924 find_alignment(&sb, &output_option);29252926 output(&sb, output_option);2927 free((void *)sb.final_buf);2928 for (ent = sb.ent; ent; ) {2929 struct blame_entry *e = ent->next;2930 free(ent);2931 ent = e;2932 }29332934 if (show_stats) {2935 printf("num read blob: %d\n", num_read_blob);2936 printf("num get patch: %d\n", num_get_patch);2937 printf("num commits: %d\n", num_commits);2938 }2939 return 0;2940}