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 * Given an origin, prepare mmfile_t structure to be used by the 151 * diff machinery 152 */ 153static void fill_origin_blob(struct diff_options *opt, 154 struct origin *o, mmfile_t *file) 155{ 156 if (!o->file.ptr) { 157 enum object_type type; 158 unsigned long file_size; 159 160 num_read_blob++; 161 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 162 textconv_object(o->path, o->mode, &o->blob_oid, 1, &file->ptr, &file_size)) 163 ; 164 else 165 file->ptr = read_sha1_file(o->blob_oid.hash, &type, 166 &file_size); 167 file->size = file_size; 168 169 if (!file->ptr) 170 die("Cannot read blob %s for path %s", 171 oid_to_hex(&o->blob_oid), 172 o->path); 173 o->file = *file; 174 } 175 else 176 *file = o->file; 177} 178 179/* 180 * Origin is refcounted and usually we keep the blob contents to be 181 * reused. 182 */ 183static inline struct origin *origin_incref(struct origin *o) 184{ 185 if (o) 186 o->refcnt++; 187 return o; 188} 189 190static void origin_decref(struct origin *o) 191{ 192 if (o && --o->refcnt <= 0) { 193 struct origin *p, *l = NULL; 194 if (o->previous) 195 origin_decref(o->previous); 196 free(o->file.ptr); 197 /* Should be present exactly once in commit chain */ 198 for (p = o->commit->util; p; l = p, p = p->next) { 199 if (p == o) { 200 if (l) 201 l->next = p->next; 202 else 203 o->commit->util = p->next; 204 free(o); 205 return; 206 } 207 } 208 die("internal error in blame::origin_decref"); 209 } 210} 211 212static void drop_origin_blob(struct origin *o) 213{ 214 if (o->file.ptr) { 215 free(o->file.ptr); 216 o->file.ptr = NULL; 217 } 218} 219 220/* 221 * Each group of lines is described by a blame_entry; it can be split 222 * as we pass blame to the parents. They are arranged in linked lists 223 * kept as `suspects' of some unprocessed origin, or entered (when the 224 * blame origin has been finalized) into the scoreboard structure. 225 * While the scoreboard structure is only sorted at the end of 226 * processing (according to final image line number), the lists 227 * attached to an origin are sorted by the target line number. 228 */ 229struct blame_entry { 230 struct blame_entry *next; 231 232 /* the first line of this group in the final image; 233 * internally all line numbers are 0 based. 234 */ 235 int lno; 236 237 /* how many lines this group has */ 238 int num_lines; 239 240 /* the commit that introduced this group into the final image */ 241 struct origin *suspect; 242 243 /* the line number of the first line of this group in the 244 * suspect's file; internally all line numbers are 0 based. 245 */ 246 int s_lno; 247 248 /* how significant this entry is -- cached to avoid 249 * scanning the lines over and over. 250 */ 251 unsigned score; 252}; 253 254/* 255 * Any merge of blames happens on lists of blames that arrived via 256 * different parents in a single suspect. In this case, we want to 257 * sort according to the suspect line numbers as opposed to the final 258 * image line numbers. The function body is somewhat longish because 259 * it avoids unnecessary writes. 260 */ 261 262static struct blame_entry *blame_merge(struct blame_entry *list1, 263 struct blame_entry *list2) 264{ 265 struct blame_entry *p1 = list1, *p2 = list2, 266 **tail = &list1; 267 268 if (!p1) 269 return p2; 270 if (!p2) 271 return p1; 272 273 if (p1->s_lno <= p2->s_lno) { 274 do { 275 tail = &p1->next; 276 if ((p1 = *tail) == NULL) { 277 *tail = p2; 278 return list1; 279 } 280 } while (p1->s_lno <= p2->s_lno); 281 } 282 for (;;) { 283 *tail = p2; 284 do { 285 tail = &p2->next; 286 if ((p2 = *tail) == NULL) { 287 *tail = p1; 288 return list1; 289 } 290 } while (p1->s_lno > p2->s_lno); 291 *tail = p1; 292 do { 293 tail = &p1->next; 294 if ((p1 = *tail) == NULL) { 295 *tail = p2; 296 return list1; 297 } 298 } while (p1->s_lno <= p2->s_lno); 299 } 300} 301 302static void *get_next_blame(const void *p) 303{ 304 return ((struct blame_entry *)p)->next; 305} 306 307static void set_next_blame(void *p1, void *p2) 308{ 309 ((struct blame_entry *)p1)->next = p2; 310} 311 312/* 313 * Final image line numbers are all different, so we don't need a 314 * three-way comparison here. 315 */ 316 317static int compare_blame_final(const void *p1, const void *p2) 318{ 319 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 320 ? 1 : -1; 321} 322 323static int compare_blame_suspect(const void *p1, const void *p2) 324{ 325 const struct blame_entry *s1 = p1, *s2 = p2; 326 /* 327 * to allow for collating suspects, we sort according to the 328 * respective pointer value as the primary sorting criterion. 329 * The actual relation is pretty unimportant as long as it 330 * establishes a total order. Comparing as integers gives us 331 * that. 332 */ 333 if (s1->suspect != s2->suspect) 334 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1; 335 if (s1->s_lno == s2->s_lno) 336 return 0; 337 return s1->s_lno > s2->s_lno ? 1 : -1; 338} 339 340static struct blame_entry *blame_sort(struct blame_entry *head, 341 int (*compare_fn)(const void *, const void *)) 342{ 343 return llist_mergesort (head, get_next_blame, set_next_blame, compare_fn); 344} 345 346static int compare_commits_by_reverse_commit_date(const void *a, 347 const void *b, 348 void *c) 349{ 350 return -compare_commits_by_commit_date(a, b, c); 351} 352 353/* 354 * The current state of the blame assignment. 355 */ 356struct scoreboard { 357 /* the final commit (i.e. where we started digging from) */ 358 struct commit *final; 359 /* Priority queue for commits with unassigned blame records */ 360 struct prio_queue commits; 361 struct rev_info *revs; 362 const char *path; 363 364 /* 365 * The contents in the final image. 366 * Used by many functions to obtain contents of the nth line, 367 * indexed with scoreboard.lineno[blame_entry.lno]. 368 */ 369 const char *final_buf; 370 unsigned long final_buf_size; 371 372 /* linked list of blames */ 373 struct blame_entry *ent; 374 375 /* look-up a line in the final buffer */ 376 int num_lines; 377 int *lineno; 378}; 379 380static void sanity_check_refcnt(struct scoreboard *); 381 382/* 383 * If two blame entries that are next to each other came from 384 * contiguous lines in the same origin (i.e. <commit, path> pair), 385 * merge them together. 386 */ 387static void coalesce(struct scoreboard *sb) 388{ 389 struct blame_entry *ent, *next; 390 391 for (ent = sb->ent; ent && (next = ent->next); ent = next) { 392 if (ent->suspect == next->suspect && 393 ent->s_lno + ent->num_lines == next->s_lno) { 394 ent->num_lines += next->num_lines; 395 ent->next = next->next; 396 origin_decref(next->suspect); 397 free(next); 398 ent->score = 0; 399 next = ent; /* again */ 400 } 401 } 402 403 if (DEBUG) /* sanity */ 404 sanity_check_refcnt(sb); 405} 406 407/* 408 * Merge the given sorted list of blames into a preexisting origin. 409 * If there were no previous blames to that commit, it is entered into 410 * the commit priority queue of the score board. 411 */ 412 413static void queue_blames(struct scoreboard *sb, struct origin *porigin, 414 struct blame_entry *sorted) 415{ 416 if (porigin->suspects) 417 porigin->suspects = blame_merge(porigin->suspects, sorted); 418 else { 419 struct origin *o; 420 for (o = porigin->commit->util; o; o = o->next) { 421 if (o->suspects) { 422 porigin->suspects = sorted; 423 return; 424 } 425 } 426 porigin->suspects = sorted; 427 prio_queue_put(&sb->commits, porigin->commit); 428 } 429} 430 431/* 432 * Given a commit and a path in it, create a new origin structure. 433 * The callers that add blame to the scoreboard should use 434 * get_origin() to obtain shared, refcounted copy instead of calling 435 * this function directly. 436 */ 437static struct origin *make_origin(struct commit *commit, const char *path) 438{ 439 struct origin *o; 440 FLEX_ALLOC_STR(o, path, path); 441 o->commit = commit; 442 o->refcnt = 1; 443 o->next = commit->util; 444 commit->util = o; 445 return o; 446} 447 448/* 449 * Locate an existing origin or create a new one. 450 * This moves the origin to front position in the commit util list. 451 */ 452static struct origin *get_origin(struct scoreboard *sb, 453 struct commit *commit, 454 const char *path) 455{ 456 struct origin *o, *l; 457 458 for (o = commit->util, l = NULL; o; l = o, o = o->next) { 459 if (!strcmp(o->path, path)) { 460 /* bump to front */ 461 if (l) { 462 l->next = o->next; 463 o->next = commit->util; 464 commit->util = o; 465 } 466 return origin_incref(o); 467 } 468 } 469 return make_origin(commit, path); 470} 471 472/* 473 * Fill the blob_sha1 field of an origin if it hasn't, so that later 474 * call to fill_origin_blob() can use it to locate the data. blob_sha1 475 * for an origin is also used to pass the blame for the entire file to 476 * the parent to detect the case where a child's blob is identical to 477 * that of its parent's. 478 * 479 * This also fills origin->mode for corresponding tree path. 480 */ 481static int fill_blob_sha1_and_mode(struct origin *origin) 482{ 483 if (!is_null_oid(&origin->blob_oid)) 484 return 0; 485 if (get_tree_entry(origin->commit->object.oid.hash, 486 origin->path, 487 origin->blob_oid.hash, &origin->mode)) 488 goto error_out; 489 if (sha1_object_info(origin->blob_oid.hash, NULL) != OBJ_BLOB) 490 goto error_out; 491 return 0; 492 error_out: 493 oidclr(&origin->blob_oid); 494 origin->mode = S_IFINVALID; 495 return -1; 496} 497 498/* 499 * We have an origin -- check if the same path exists in the 500 * parent and return an origin structure to represent it. 501 */ 502static struct origin *find_origin(struct scoreboard *sb, 503 struct commit *parent, 504 struct origin *origin) 505{ 506 struct origin *porigin; 507 struct diff_options diff_opts; 508 const char *paths[2]; 509 510 /* First check any existing origins */ 511 for (porigin = parent->util; porigin; porigin = porigin->next) 512 if (!strcmp(porigin->path, origin->path)) { 513 /* 514 * The same path between origin and its parent 515 * without renaming -- the most common case. 516 */ 517 return origin_incref (porigin); 518 } 519 520 /* See if the origin->path is different between parent 521 * and origin first. Most of the time they are the 522 * same and diff-tree is fairly efficient about this. 523 */ 524 diff_setup(&diff_opts); 525 DIFF_OPT_SET(&diff_opts, RECURSIVE); 526 diff_opts.detect_rename = 0; 527 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 528 paths[0] = origin->path; 529 paths[1] = NULL; 530 531 parse_pathspec(&diff_opts.pathspec, 532 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 533 PATHSPEC_LITERAL_PATH, "", paths); 534 diff_setup_done(&diff_opts); 535 536 if (is_null_oid(&origin->commit->object.oid)) 537 do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 538 else 539 diff_tree_sha1(parent->tree->object.oid.hash, 540 origin->commit->tree->object.oid.hash, 541 "", &diff_opts); 542 diffcore_std(&diff_opts); 543 544 if (!diff_queued_diff.nr) { 545 /* The path is the same as parent */ 546 porigin = get_origin(sb, parent, origin->path); 547 oidcpy(&porigin->blob_oid, &origin->blob_oid); 548 porigin->mode = origin->mode; 549 } else { 550 /* 551 * Since origin->path is a pathspec, if the parent 552 * commit had it as a directory, we will see a whole 553 * bunch of deletion of files in the directory that we 554 * do not care about. 555 */ 556 int i; 557 struct diff_filepair *p = NULL; 558 for (i = 0; i < diff_queued_diff.nr; i++) { 559 const char *name; 560 p = diff_queued_diff.queue[i]; 561 name = p->one->path ? p->one->path : p->two->path; 562 if (!strcmp(name, origin->path)) 563 break; 564 } 565 if (!p) 566 die("internal error in blame::find_origin"); 567 switch (p->status) { 568 default: 569 die("internal error in blame::find_origin (%c)", 570 p->status); 571 case 'M': 572 porigin = get_origin(sb, parent, origin->path); 573 oidcpy(&porigin->blob_oid, &p->one->oid); 574 porigin->mode = p->one->mode; 575 break; 576 case 'A': 577 case 'T': 578 /* Did not exist in parent, or type changed */ 579 break; 580 } 581 } 582 diff_flush(&diff_opts); 583 clear_pathspec(&diff_opts.pathspec); 584 return porigin; 585} 586 587/* 588 * We have an origin -- find the path that corresponds to it in its 589 * parent and return an origin structure to represent it. 590 */ 591static struct origin *find_rename(struct scoreboard *sb, 592 struct commit *parent, 593 struct origin *origin) 594{ 595 struct origin *porigin = NULL; 596 struct diff_options diff_opts; 597 int i; 598 599 diff_setup(&diff_opts); 600 DIFF_OPT_SET(&diff_opts, RECURSIVE); 601 diff_opts.detect_rename = DIFF_DETECT_RENAME; 602 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 603 diff_opts.single_follow = origin->path; 604 diff_setup_done(&diff_opts); 605 606 if (is_null_oid(&origin->commit->object.oid)) 607 do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 608 else 609 diff_tree_sha1(parent->tree->object.oid.hash, 610 origin->commit->tree->object.oid.hash, 611 "", &diff_opts); 612 diffcore_std(&diff_opts); 613 614 for (i = 0; i < diff_queued_diff.nr; i++) { 615 struct diff_filepair *p = diff_queued_diff.queue[i]; 616 if ((p->status == 'R' || p->status == 'C') && 617 !strcmp(p->two->path, origin->path)) { 618 porigin = get_origin(sb, parent, p->one->path); 619 oidcpy(&porigin->blob_oid, &p->one->oid); 620 porigin->mode = p->one->mode; 621 break; 622 } 623 } 624 diff_flush(&diff_opts); 625 clear_pathspec(&diff_opts.pathspec); 626 return porigin; 627} 628 629/* 630 * Append a new blame entry to a given output queue. 631 */ 632static void add_blame_entry(struct blame_entry ***queue, 633 const struct blame_entry *src) 634{ 635 struct blame_entry *e = xmalloc(sizeof(*e)); 636 memcpy(e, src, sizeof(*e)); 637 origin_incref(e->suspect); 638 639 e->next = **queue; 640 **queue = e; 641 *queue = &e->next; 642} 643 644/* 645 * src typically is on-stack; we want to copy the information in it to 646 * a malloced blame_entry that gets added to the given queue. The 647 * origin of dst loses a refcnt. 648 */ 649static void dup_entry(struct blame_entry ***queue, 650 struct blame_entry *dst, struct blame_entry *src) 651{ 652 origin_incref(src->suspect); 653 origin_decref(dst->suspect); 654 memcpy(dst, src, sizeof(*src)); 655 dst->next = **queue; 656 **queue = dst; 657 *queue = &dst->next; 658} 659 660static const char *nth_line(struct scoreboard *sb, long lno) 661{ 662 return sb->final_buf + sb->lineno[lno]; 663} 664 665static const char *nth_line_cb(void *data, long lno) 666{ 667 return nth_line((struct scoreboard *)data, lno); 668} 669 670/* 671 * It is known that lines between tlno to same came from parent, and e 672 * has an overlap with that range. it also is known that parent's 673 * line plno corresponds to e's line tlno. 674 * 675 * <---- e -----> 676 * <------> 677 * <------------> 678 * <------------> 679 * <------------------> 680 * 681 * Split e into potentially three parts; before this chunk, the chunk 682 * to be blamed for the parent, and after that portion. 683 */ 684static void split_overlap(struct blame_entry *split, 685 struct blame_entry *e, 686 int tlno, int plno, int same, 687 struct origin *parent) 688{ 689 int chunk_end_lno; 690 memset(split, 0, sizeof(struct blame_entry [3])); 691 692 if (e->s_lno < tlno) { 693 /* there is a pre-chunk part not blamed on parent */ 694 split[0].suspect = origin_incref(e->suspect); 695 split[0].lno = e->lno; 696 split[0].s_lno = e->s_lno; 697 split[0].num_lines = tlno - e->s_lno; 698 split[1].lno = e->lno + tlno - e->s_lno; 699 split[1].s_lno = plno; 700 } 701 else { 702 split[1].lno = e->lno; 703 split[1].s_lno = plno + (e->s_lno - tlno); 704 } 705 706 if (same < e->s_lno + e->num_lines) { 707 /* there is a post-chunk part not blamed on parent */ 708 split[2].suspect = origin_incref(e->suspect); 709 split[2].lno = e->lno + (same - e->s_lno); 710 split[2].s_lno = e->s_lno + (same - e->s_lno); 711 split[2].num_lines = e->s_lno + e->num_lines - same; 712 chunk_end_lno = split[2].lno; 713 } 714 else 715 chunk_end_lno = e->lno + e->num_lines; 716 split[1].num_lines = chunk_end_lno - split[1].lno; 717 718 /* 719 * if it turns out there is nothing to blame the parent for, 720 * forget about the splitting. !split[1].suspect signals this. 721 */ 722 if (split[1].num_lines < 1) 723 return; 724 split[1].suspect = origin_incref(parent); 725} 726 727/* 728 * split_overlap() divided an existing blame e into up to three parts 729 * in split. Any assigned blame is moved to queue to 730 * reflect the split. 731 */ 732static void split_blame(struct blame_entry ***blamed, 733 struct blame_entry ***unblamed, 734 struct blame_entry *split, 735 struct blame_entry *e) 736{ 737 if (split[0].suspect && split[2].suspect) { 738 /* The first part (reuse storage for the existing entry e) */ 739 dup_entry(unblamed, e, &split[0]); 740 741 /* The last part -- me */ 742 add_blame_entry(unblamed, &split[2]); 743 744 /* ... and the middle part -- parent */ 745 add_blame_entry(blamed, &split[1]); 746 } 747 else if (!split[0].suspect && !split[2].suspect) 748 /* 749 * The parent covers the entire area; reuse storage for 750 * e and replace it with the parent. 751 */ 752 dup_entry(blamed, e, &split[1]); 753 else if (split[0].suspect) { 754 /* me and then parent */ 755 dup_entry(unblamed, e, &split[0]); 756 add_blame_entry(blamed, &split[1]); 757 } 758 else { 759 /* parent and then me */ 760 dup_entry(blamed, e, &split[1]); 761 add_blame_entry(unblamed, &split[2]); 762 } 763} 764 765/* 766 * After splitting the blame, the origins used by the 767 * on-stack blame_entry should lose one refcnt each. 768 */ 769static void decref_split(struct blame_entry *split) 770{ 771 int i; 772 773 for (i = 0; i < 3; i++) 774 origin_decref(split[i].suspect); 775} 776 777/* 778 * reverse_blame reverses the list given in head, appending tail. 779 * That allows us to build lists in reverse order, then reverse them 780 * afterwards. This can be faster than building the list in proper 781 * order right away. The reason is that building in proper order 782 * requires writing a link in the _previous_ element, while building 783 * in reverse order just requires placing the list head into the 784 * _current_ element. 785 */ 786 787static struct blame_entry *reverse_blame(struct blame_entry *head, 788 struct blame_entry *tail) 789{ 790 while (head) { 791 struct blame_entry *next = head->next; 792 head->next = tail; 793 tail = head; 794 head = next; 795 } 796 return tail; 797} 798 799/* 800 * Process one hunk from the patch between the current suspect for 801 * blame_entry e and its parent. This first blames any unfinished 802 * entries before the chunk (which is where target and parent start 803 * differing) on the parent, and then splits blame entries at the 804 * start and at the end of the difference region. Since use of -M and 805 * -C options may lead to overlapping/duplicate source line number 806 * ranges, all we can rely on from sorting/merging is the order of the 807 * first suspect line number. 808 */ 809static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq, 810 int tlno, int offset, int same, 811 struct origin *parent) 812{ 813 struct blame_entry *e = **srcq; 814 struct blame_entry *samep = NULL, *diffp = NULL; 815 816 while (e && e->s_lno < tlno) { 817 struct blame_entry *next = e->next; 818 /* 819 * current record starts before differing portion. If 820 * it reaches into it, we need to split it up and 821 * examine the second part separately. 822 */ 823 if (e->s_lno + e->num_lines > tlno) { 824 /* Move second half to a new record */ 825 int len = tlno - e->s_lno; 826 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry)); 827 n->suspect = e->suspect; 828 n->lno = e->lno + len; 829 n->s_lno = e->s_lno + len; 830 n->num_lines = e->num_lines - len; 831 e->num_lines = len; 832 e->score = 0; 833 /* Push new record to diffp */ 834 n->next = diffp; 835 diffp = n; 836 } else 837 origin_decref(e->suspect); 838 /* Pass blame for everything before the differing 839 * chunk to the parent */ 840 e->suspect = origin_incref(parent); 841 e->s_lno += offset; 842 e->next = samep; 843 samep = e; 844 e = next; 845 } 846 /* 847 * As we don't know how much of a common stretch after this 848 * diff will occur, the currently blamed parts are all that we 849 * can assign to the parent for now. 850 */ 851 852 if (samep) { 853 **dstq = reverse_blame(samep, **dstq); 854 *dstq = &samep->next; 855 } 856 /* 857 * Prepend the split off portions: everything after e starts 858 * after the blameable portion. 859 */ 860 e = reverse_blame(diffp, e); 861 862 /* 863 * Now retain records on the target while parts are different 864 * from the parent. 865 */ 866 samep = NULL; 867 diffp = NULL; 868 while (e && e->s_lno < same) { 869 struct blame_entry *next = e->next; 870 871 /* 872 * If current record extends into sameness, need to split. 873 */ 874 if (e->s_lno + e->num_lines > same) { 875 /* 876 * Move second half to a new record to be 877 * processed by later chunks 878 */ 879 int len = same - e->s_lno; 880 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry)); 881 n->suspect = origin_incref(e->suspect); 882 n->lno = e->lno + len; 883 n->s_lno = e->s_lno + len; 884 n->num_lines = e->num_lines - len; 885 e->num_lines = len; 886 e->score = 0; 887 /* Push new record to samep */ 888 n->next = samep; 889 samep = n; 890 } 891 e->next = diffp; 892 diffp = e; 893 e = next; 894 } 895 **srcq = reverse_blame(diffp, reverse_blame(samep, e)); 896 /* Move across elements that are in the unblamable portion */ 897 if (diffp) 898 *srcq = &diffp->next; 899} 900 901struct blame_chunk_cb_data { 902 struct origin *parent; 903 long offset; 904 struct blame_entry **dstq; 905 struct blame_entry **srcq; 906}; 907 908/* diff chunks are from parent to target */ 909static int blame_chunk_cb(long start_a, long count_a, 910 long start_b, long count_b, void *data) 911{ 912 struct blame_chunk_cb_data *d = data; 913 if (start_a - start_b != d->offset) 914 die("internal error in blame::blame_chunk_cb"); 915 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 916 start_b + count_b, d->parent); 917 d->offset = start_a + count_a - (start_b + count_b); 918 return 0; 919} 920 921/* 922 * We are looking at the origin 'target' and aiming to pass blame 923 * for the lines it is suspected to its parent. Run diff to find 924 * which lines came from parent and pass blame for them. 925 */ 926static void pass_blame_to_parent(struct scoreboard *sb, 927 struct origin *target, 928 struct origin *parent) 929{ 930 mmfile_t file_p, file_o; 931 struct blame_chunk_cb_data d; 932 struct blame_entry *newdest = NULL; 933 934 if (!target->suspects) 935 return; /* nothing remains for this target */ 936 937 d.parent = parent; 938 d.offset = 0; 939 d.dstq = &newdest; d.srcq = &target->suspects; 940 941 fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 942 fill_origin_blob(&sb->revs->diffopt, target, &file_o); 943 num_get_patch++; 944 945 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d)) 946 die("unable to generate diff (%s -> %s)", 947 oid_to_hex(&parent->commit->object.oid), 948 oid_to_hex(&target->commit->object.oid)); 949 /* The rest are the same as the parent */ 950 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 951 *d.dstq = NULL; 952 queue_blames(sb, parent, newdest); 953 954 return; 955} 956 957/* 958 * The lines in blame_entry after splitting blames many times can become 959 * very small and trivial, and at some point it becomes pointless to 960 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 961 * ordinary C program, and it is not worth to say it was copied from 962 * totally unrelated file in the parent. 963 * 964 * Compute how trivial the lines in the blame_entry are. 965 */ 966static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e) 967{ 968 unsigned score; 969 const char *cp, *ep; 970 971 if (e->score) 972 return e->score; 973 974 score = 1; 975 cp = nth_line(sb, e->lno); 976 ep = nth_line(sb, e->lno + e->num_lines); 977 while (cp < ep) { 978 unsigned ch = *((unsigned char *)cp); 979 if (isalnum(ch)) 980 score++; 981 cp++; 982 } 983 e->score = score; 984 return score; 985} 986 987/* 988 * best_so_far[] and this[] are both a split of an existing blame_entry 989 * that passes blame to the parent. Maintain best_so_far the best split 990 * so far, by comparing this and best_so_far and copying this into 991 * bst_so_far as needed. 992 */ 993static void copy_split_if_better(struct scoreboard *sb, 994 struct blame_entry *best_so_far, 995 struct blame_entry *this) 996{ 997 int i; 998 999 if (!this[1].suspect)1000 return;1001 if (best_so_far[1].suspect) {1002 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))1003 return;1004 }10051006 for (i = 0; i < 3; i++)1007 origin_incref(this[i].suspect);1008 decref_split(best_so_far);1009 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));1010}10111012/*1013 * We are looking at a part of the final image represented by1014 * ent (tlno and same are offset by ent->s_lno).1015 * tlno is where we are looking at in the final image.1016 * up to (but not including) same match preimage.1017 * plno is where we are looking at in the preimage.1018 *1019 * <-------------- final image ---------------------->1020 * <------ent------>1021 * ^tlno ^same1022 * <---------preimage----->1023 * ^plno1024 *1025 * All line numbers are 0-based.1026 */1027static void handle_split(struct scoreboard *sb,1028 struct blame_entry *ent,1029 int tlno, int plno, int same,1030 struct origin *parent,1031 struct blame_entry *split)1032{1033 if (ent->num_lines <= tlno)1034 return;1035 if (tlno < same) {1036 struct blame_entry this[3];1037 tlno += ent->s_lno;1038 same += ent->s_lno;1039 split_overlap(this, ent, tlno, plno, same, parent);1040 copy_split_if_better(sb, split, this);1041 decref_split(this);1042 }1043}10441045struct handle_split_cb_data {1046 struct scoreboard *sb;1047 struct blame_entry *ent;1048 struct origin *parent;1049 struct blame_entry *split;1050 long plno;1051 long tlno;1052};10531054static int handle_split_cb(long start_a, long count_a,1055 long start_b, long count_b, void *data)1056{1057 struct handle_split_cb_data *d = data;1058 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1059 d->split);1060 d->plno = start_a + count_a;1061 d->tlno = start_b + count_b;1062 return 0;1063}10641065/*1066 * Find the lines from parent that are the same as ent so that1067 * we can pass blames to it. file_p has the blob contents for1068 * the parent.1069 */1070static void find_copy_in_blob(struct scoreboard *sb,1071 struct blame_entry *ent,1072 struct origin *parent,1073 struct blame_entry *split,1074 mmfile_t *file_p)1075{1076 const char *cp;1077 mmfile_t file_o;1078 struct handle_split_cb_data d;10791080 memset(&d, 0, sizeof(d));1081 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1082 /*1083 * Prepare mmfile that contains only the lines in ent.1084 */1085 cp = nth_line(sb, ent->lno);1086 file_o.ptr = (char *) cp;1087 file_o.size = nth_line(sb, ent->lno + ent->num_lines) - cp;10881089 /*1090 * file_o is a part of final image we are annotating.1091 * file_p partially may match that image.1092 */1093 memset(split, 0, sizeof(struct blame_entry [3]));1094 if (diff_hunks(file_p, &file_o, handle_split_cb, &d))1095 die("unable to generate diff (%s)",1096 oid_to_hex(&parent->commit->object.oid));1097 /* remainder, if any, all match the preimage */1098 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1099}11001101/* Move all blame entries from list *source that have a score smaller1102 * than score_min to the front of list *small.1103 * Returns a pointer to the link pointing to the old head of the small list.1104 */11051106static struct blame_entry **filter_small(struct scoreboard *sb,1107 struct blame_entry **small,1108 struct blame_entry **source,1109 unsigned score_min)1110{1111 struct blame_entry *p = *source;1112 struct blame_entry *oldsmall = *small;1113 while (p) {1114 if (ent_score(sb, p) <= score_min) {1115 *small = p;1116 small = &p->next;1117 p = *small;1118 } else {1119 *source = p;1120 source = &p->next;1121 p = *source;1122 }1123 }1124 *small = oldsmall;1125 *source = NULL;1126 return small;1127}11281129/*1130 * See if lines currently target is suspected for can be attributed to1131 * parent.1132 */1133static void find_move_in_parent(struct scoreboard *sb,1134 struct blame_entry ***blamed,1135 struct blame_entry **toosmall,1136 struct origin *target,1137 struct origin *parent)1138{1139 struct blame_entry *e, split[3];1140 struct blame_entry *unblamed = target->suspects;1141 struct blame_entry *leftover = NULL;1142 mmfile_t file_p;11431144 if (!unblamed)1145 return; /* nothing remains for this target */11461147 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1148 if (!file_p.ptr)1149 return;11501151 /* At each iteration, unblamed has a NULL-terminated list of1152 * entries that have not yet been tested for blame. leftover1153 * contains the reversed list of entries that have been tested1154 * without being assignable to the parent.1155 */1156 do {1157 struct blame_entry **unblamedtail = &unblamed;1158 struct blame_entry *next;1159 for (e = unblamed; e; e = next) {1160 next = e->next;1161 find_copy_in_blob(sb, e, parent, split, &file_p);1162 if (split[1].suspect &&1163 blame_move_score < ent_score(sb, &split[1])) {1164 split_blame(blamed, &unblamedtail, split, e);1165 } else {1166 e->next = leftover;1167 leftover = e;1168 }1169 decref_split(split);1170 }1171 *unblamedtail = NULL;1172 toosmall = filter_small(sb, toosmall, &unblamed, blame_move_score);1173 } while (unblamed);1174 target->suspects = reverse_blame(leftover, NULL);1175}11761177struct blame_list {1178 struct blame_entry *ent;1179 struct blame_entry split[3];1180};11811182/*1183 * Count the number of entries the target is suspected for,1184 * and prepare a list of entry and the best split.1185 */1186static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1187 int *num_ents_p)1188{1189 struct blame_entry *e;1190 int num_ents, i;1191 struct blame_list *blame_list = NULL;11921193 for (e = unblamed, num_ents = 0; e; e = e->next)1194 num_ents++;1195 if (num_ents) {1196 blame_list = xcalloc(num_ents, sizeof(struct blame_list));1197 for (e = unblamed, i = 0; e; e = e->next)1198 blame_list[i++].ent = e;1199 }1200 *num_ents_p = num_ents;1201 return blame_list;1202}12031204/*1205 * For lines target is suspected for, see if we can find code movement1206 * across file boundary from the parent commit. porigin is the path1207 * in the parent we already tried.1208 */1209static void find_copy_in_parent(struct scoreboard *sb,1210 struct blame_entry ***blamed,1211 struct blame_entry **toosmall,1212 struct origin *target,1213 struct commit *parent,1214 struct origin *porigin,1215 int opt)1216{1217 struct diff_options diff_opts;1218 int i, j;1219 struct blame_list *blame_list;1220 int num_ents;1221 struct blame_entry *unblamed = target->suspects;1222 struct blame_entry *leftover = NULL;12231224 if (!unblamed)1225 return; /* nothing remains for this target */12261227 diff_setup(&diff_opts);1228 DIFF_OPT_SET(&diff_opts, RECURSIVE);1229 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12301231 diff_setup_done(&diff_opts);12321233 /* Try "find copies harder" on new path if requested;1234 * we do not want to use diffcore_rename() actually to1235 * match things up; find_copies_harder is set only to1236 * force diff_tree_sha1() to feed all filepairs to diff_queue,1237 * and this code needs to be after diff_setup_done(), which1238 * usually makes find-copies-harder imply copy detection.1239 */1240 if ((opt & PICKAXE_BLAME_COPY_HARDEST)1241 || ((opt & PICKAXE_BLAME_COPY_HARDER)1242 && (!porigin || strcmp(target->path, porigin->path))))1243 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12441245 if (is_null_oid(&target->commit->object.oid))1246 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1247 else1248 diff_tree_sha1(parent->tree->object.oid.hash,1249 target->commit->tree->object.oid.hash,1250 "", &diff_opts);12511252 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1253 diffcore_std(&diff_opts);12541255 do {1256 struct blame_entry **unblamedtail = &unblamed;1257 blame_list = setup_blame_list(unblamed, &num_ents);12581259 for (i = 0; i < diff_queued_diff.nr; i++) {1260 struct diff_filepair *p = diff_queued_diff.queue[i];1261 struct origin *norigin;1262 mmfile_t file_p;1263 struct blame_entry this[3];12641265 if (!DIFF_FILE_VALID(p->one))1266 continue; /* does not exist in parent */1267 if (S_ISGITLINK(p->one->mode))1268 continue; /* ignore git links */1269 if (porigin && !strcmp(p->one->path, porigin->path))1270 /* find_move already dealt with this path */1271 continue;12721273 norigin = get_origin(sb, parent, p->one->path);1274 oidcpy(&norigin->blob_oid, &p->one->oid);1275 norigin->mode = p->one->mode;1276 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1277 if (!file_p.ptr)1278 continue;12791280 for (j = 0; j < num_ents; j++) {1281 find_copy_in_blob(sb, blame_list[j].ent,1282 norigin, this, &file_p);1283 copy_split_if_better(sb, blame_list[j].split,1284 this);1285 decref_split(this);1286 }1287 origin_decref(norigin);1288 }12891290 for (j = 0; j < num_ents; j++) {1291 struct blame_entry *split = blame_list[j].split;1292 if (split[1].suspect &&1293 blame_copy_score < ent_score(sb, &split[1])) {1294 split_blame(blamed, &unblamedtail, split,1295 blame_list[j].ent);1296 } else {1297 blame_list[j].ent->next = leftover;1298 leftover = blame_list[j].ent;1299 }1300 decref_split(split);1301 }1302 free(blame_list);1303 *unblamedtail = NULL;1304 toosmall = filter_small(sb, toosmall, &unblamed, blame_copy_score);1305 } while (unblamed);1306 target->suspects = reverse_blame(leftover, NULL);1307 diff_flush(&diff_opts);1308 clear_pathspec(&diff_opts.pathspec);1309}13101311/*1312 * The blobs of origin and porigin exactly match, so everything1313 * origin is suspected for can be blamed on the parent.1314 */1315static void pass_whole_blame(struct scoreboard *sb,1316 struct origin *origin, struct origin *porigin)1317{1318 struct blame_entry *e, *suspects;13191320 if (!porigin->file.ptr && origin->file.ptr) {1321 /* Steal its file */1322 porigin->file = origin->file;1323 origin->file.ptr = NULL;1324 }1325 suspects = origin->suspects;1326 origin->suspects = NULL;1327 for (e = suspects; e; e = e->next) {1328 origin_incref(porigin);1329 origin_decref(e->suspect);1330 e->suspect = porigin;1331 }1332 queue_blames(sb, porigin, suspects);1333}13341335/*1336 * We pass blame from the current commit to its parents. We keep saying1337 * "parent" (and "porigin"), but what we mean is to find scapegoat to1338 * exonerate ourselves.1339 */1340static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)1341{1342 if (!reverse) {1343 if (revs->first_parent_only &&1344 commit->parents &&1345 commit->parents->next) {1346 free_commit_list(commit->parents->next);1347 commit->parents->next = NULL;1348 }1349 return commit->parents;1350 }1351 return lookup_decoration(&revs->children, &commit->object);1352}13531354static int num_scapegoats(struct rev_info *revs, struct commit *commit)1355{1356 struct commit_list *l = first_scapegoat(revs, commit);1357 return commit_list_count(l);1358}13591360/* Distribute collected unsorted blames to the respected sorted lists1361 * in the various origins.1362 */1363static void distribute_blame(struct scoreboard *sb, struct blame_entry *blamed)1364{1365 blamed = blame_sort(blamed, compare_blame_suspect);1366 while (blamed)1367 {1368 struct origin *porigin = blamed->suspect;1369 struct blame_entry *suspects = NULL;1370 do {1371 struct blame_entry *next = blamed->next;1372 blamed->next = suspects;1373 suspects = blamed;1374 blamed = next;1375 } while (blamed && blamed->suspect == porigin);1376 suspects = reverse_blame(suspects, NULL);1377 queue_blames(sb, porigin, suspects);1378 }1379}13801381#define MAXSG 1613821383static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)1384{1385 struct rev_info *revs = sb->revs;1386 int i, pass, num_sg;1387 struct commit *commit = origin->commit;1388 struct commit_list *sg;1389 struct origin *sg_buf[MAXSG];1390 struct origin *porigin, **sg_origin = sg_buf;1391 struct blame_entry *toosmall = NULL;1392 struct blame_entry *blames, **blametail = &blames;13931394 num_sg = num_scapegoats(revs, commit);1395 if (!num_sg)1396 goto finish;1397 else if (num_sg < ARRAY_SIZE(sg_buf))1398 memset(sg_buf, 0, sizeof(sg_buf));1399 else1400 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));14011402 /*1403 * The first pass looks for unrenamed path to optimize for1404 * common cases, then we look for renames in the second pass.1405 */1406 for (pass = 0; pass < 2 - no_whole_file_rename; pass++) {1407 struct origin *(*find)(struct scoreboard *,1408 struct commit *, struct origin *);1409 find = pass ? find_rename : find_origin;14101411 for (i = 0, sg = first_scapegoat(revs, commit);1412 i < num_sg && sg;1413 sg = sg->next, i++) {1414 struct commit *p = sg->item;1415 int j, same;14161417 if (sg_origin[i])1418 continue;1419 if (parse_commit(p))1420 continue;1421 porigin = find(sb, p, origin);1422 if (!porigin)1423 continue;1424 if (!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {1425 pass_whole_blame(sb, origin, porigin);1426 origin_decref(porigin);1427 goto finish;1428 }1429 for (j = same = 0; j < i; j++)1430 if (sg_origin[j] &&1431 !oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {1432 same = 1;1433 break;1434 }1435 if (!same)1436 sg_origin[i] = porigin;1437 else1438 origin_decref(porigin);1439 }1440 }14411442 num_commits++;1443 for (i = 0, sg = first_scapegoat(revs, commit);1444 i < num_sg && sg;1445 sg = sg->next, i++) {1446 struct origin *porigin = sg_origin[i];1447 if (!porigin)1448 continue;1449 if (!origin->previous) {1450 origin_incref(porigin);1451 origin->previous = porigin;1452 }1453 pass_blame_to_parent(sb, origin, porigin);1454 if (!origin->suspects)1455 goto finish;1456 }14571458 /*1459 * Optionally find moves in parents' files.1460 */1461 if (opt & PICKAXE_BLAME_MOVE) {1462 filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1463 if (origin->suspects) {1464 for (i = 0, sg = first_scapegoat(revs, commit);1465 i < num_sg && sg;1466 sg = sg->next, i++) {1467 struct origin *porigin = sg_origin[i];1468 if (!porigin)1469 continue;1470 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1471 if (!origin->suspects)1472 break;1473 }1474 }1475 }14761477 /*1478 * Optionally find copies from parents' files.1479 */1480 if (opt & PICKAXE_BLAME_COPY) {1481 if (blame_copy_score > blame_move_score)1482 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1483 else if (blame_copy_score < blame_move_score) {1484 origin->suspects = blame_merge(origin->suspects, toosmall);1485 toosmall = NULL;1486 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1487 }1488 if (!origin->suspects)1489 goto finish;14901491 for (i = 0, sg = first_scapegoat(revs, commit);1492 i < num_sg && sg;1493 sg = sg->next, i++) {1494 struct origin *porigin = sg_origin[i];1495 find_copy_in_parent(sb, &blametail, &toosmall,1496 origin, sg->item, porigin, opt);1497 if (!origin->suspects)1498 goto finish;1499 }1500 }15011502finish:1503 *blametail = NULL;1504 distribute_blame(sb, blames);1505 /*1506 * prepend toosmall to origin->suspects1507 *1508 * There is no point in sorting: this ends up on a big1509 * unsorted list in the caller anyway.1510 */1511 if (toosmall) {1512 struct blame_entry **tail = &toosmall;1513 while (*tail)1514 tail = &(*tail)->next;1515 *tail = origin->suspects;1516 origin->suspects = toosmall;1517 }1518 for (i = 0; i < num_sg; i++) {1519 if (sg_origin[i]) {1520 drop_origin_blob(sg_origin[i]);1521 origin_decref(sg_origin[i]);1522 }1523 }1524 drop_origin_blob(origin);1525 if (sg_buf != sg_origin)1526 free(sg_origin);1527}15281529/*1530 * Information on commits, used for output.1531 */1532struct commit_info {1533 struct strbuf author;1534 struct strbuf author_mail;1535 timestamp_t author_time;1536 struct strbuf author_tz;15371538 /* filled only when asked for details */1539 struct strbuf committer;1540 struct strbuf committer_mail;1541 timestamp_t committer_time;1542 struct strbuf committer_tz;15431544 struct strbuf summary;1545};15461547/*1548 * Parse author/committer line in the commit object buffer1549 */1550static void get_ac_line(const char *inbuf, const char *what,1551 struct strbuf *name, struct strbuf *mail,1552 timestamp_t *time, struct strbuf *tz)1553{1554 struct ident_split ident;1555 size_t len, maillen, namelen;1556 char *tmp, *endp;1557 const char *namebuf, *mailbuf;15581559 tmp = strstr(inbuf, what);1560 if (!tmp)1561 goto error_out;1562 tmp += strlen(what);1563 endp = strchr(tmp, '\n');1564 if (!endp)1565 len = strlen(tmp);1566 else1567 len = endp - tmp;15681569 if (split_ident_line(&ident, tmp, len)) {1570 error_out:1571 /* Ugh */1572 tmp = "(unknown)";1573 strbuf_addstr(name, tmp);1574 strbuf_addstr(mail, tmp);1575 strbuf_addstr(tz, tmp);1576 *time = 0;1577 return;1578 }15791580 namelen = ident.name_end - ident.name_begin;1581 namebuf = ident.name_begin;15821583 maillen = ident.mail_end - ident.mail_begin;1584 mailbuf = ident.mail_begin;15851586 if (ident.date_begin && ident.date_end)1587 *time = strtoul(ident.date_begin, NULL, 10);1588 else1589 *time = 0;15901591 if (ident.tz_begin && ident.tz_end)1592 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1593 else1594 strbuf_addstr(tz, "(unknown)");15951596 /*1597 * Now, convert both name and e-mail using mailmap1598 */1599 map_user(&mailmap, &mailbuf, &maillen,1600 &namebuf, &namelen);16011602 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);1603 strbuf_add(name, namebuf, namelen);1604}16051606static void commit_info_init(struct commit_info *ci)1607{16081609 strbuf_init(&ci->author, 0);1610 strbuf_init(&ci->author_mail, 0);1611 strbuf_init(&ci->author_tz, 0);1612 strbuf_init(&ci->committer, 0);1613 strbuf_init(&ci->committer_mail, 0);1614 strbuf_init(&ci->committer_tz, 0);1615 strbuf_init(&ci->summary, 0);1616}16171618static void commit_info_destroy(struct commit_info *ci)1619{16201621 strbuf_release(&ci->author);1622 strbuf_release(&ci->author_mail);1623 strbuf_release(&ci->author_tz);1624 strbuf_release(&ci->committer);1625 strbuf_release(&ci->committer_mail);1626 strbuf_release(&ci->committer_tz);1627 strbuf_release(&ci->summary);1628}16291630static void get_commit_info(struct commit *commit,1631 struct commit_info *ret,1632 int detailed)1633{1634 int len;1635 const char *subject, *encoding;1636 const char *message;16371638 commit_info_init(ret);16391640 encoding = get_log_output_encoding();1641 message = logmsg_reencode(commit, NULL, encoding);1642 get_ac_line(message, "\nauthor ",1643 &ret->author, &ret->author_mail,1644 &ret->author_time, &ret->author_tz);16451646 if (!detailed) {1647 unuse_commit_buffer(commit, message);1648 return;1649 }16501651 get_ac_line(message, "\ncommitter ",1652 &ret->committer, &ret->committer_mail,1653 &ret->committer_time, &ret->committer_tz);16541655 len = find_commit_subject(message, &subject);1656 if (len)1657 strbuf_add(&ret->summary, subject, len);1658 else1659 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));16601661 unuse_commit_buffer(commit, message);1662}16631664/*1665 * Write out any suspect information which depends on the path. This must be1666 * handled separately from emit_one_suspect_detail(), because a given commit1667 * may have changes in multiple paths. So this needs to appear each time1668 * we mention a new group.1669 *1670 * To allow LF and other nonportable characters in pathnames,1671 * they are c-style quoted as needed.1672 */1673static void write_filename_info(struct origin *suspect)1674{1675 if (suspect->previous) {1676 struct origin *prev = suspect->previous;1677 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));1678 write_name_quoted(prev->path, stdout, '\n');1679 }1680 printf("filename ");1681 write_name_quoted(suspect->path, stdout, '\n');1682}16831684/*1685 * Porcelain/Incremental format wants to show a lot of details per1686 * commit. Instead of repeating this every line, emit it only once,1687 * the first time each commit appears in the output (unless the1688 * user has specifically asked for us to repeat).1689 */1690static int emit_one_suspect_detail(struct origin *suspect, int repeat)1691{1692 struct commit_info ci;16931694 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1695 return 0;16961697 suspect->commit->object.flags |= METAINFO_SHOWN;1698 get_commit_info(suspect->commit, &ci, 1);1699 printf("author %s\n", ci.author.buf);1700 printf("author-mail %s\n", ci.author_mail.buf);1701 printf("author-time %"PRItime"\n", ci.author_time);1702 printf("author-tz %s\n", ci.author_tz.buf);1703 printf("committer %s\n", ci.committer.buf);1704 printf("committer-mail %s\n", ci.committer_mail.buf);1705 printf("committer-time %"PRItime"\n", ci.committer_time);1706 printf("committer-tz %s\n", ci.committer_tz.buf);1707 printf("summary %s\n", ci.summary.buf);1708 if (suspect->commit->object.flags & UNINTERESTING)1709 printf("boundary\n");17101711 commit_info_destroy(&ci);17121713 return 1;1714}17151716/*1717 * The blame_entry is found to be guilty for the range.1718 * Show it in incremental output.1719 */1720static void found_guilty_entry(struct blame_entry *ent,1721 struct progress_info *pi)1722{1723 if (incremental) {1724 struct origin *suspect = ent->suspect;17251726 printf("%s %d %d %d\n",1727 oid_to_hex(&suspect->commit->object.oid),1728 ent->s_lno + 1, ent->lno + 1, ent->num_lines);1729 emit_one_suspect_detail(suspect, 0);1730 write_filename_info(suspect);1731 maybe_flush_or_die(stdout, "stdout");1732 }1733 pi->blamed_lines += ent->num_lines;1734 display_progress(pi->progress, pi->blamed_lines);1735}17361737/*1738 * The main loop -- while we have blobs with lines whose true origin1739 * is still unknown, pick one blob, and allow its lines to pass blames1740 * to its parents. */1741static void assign_blame(struct scoreboard *sb, int opt)1742{1743 struct rev_info *revs = sb->revs;1744 struct commit *commit = prio_queue_get(&sb->commits);1745 struct progress_info pi = { NULL, 0 };17461747 if (show_progress)1748 pi.progress = start_progress_delay(_("Blaming lines"),1749 sb->num_lines, 50, 1);17501751 while (commit) {1752 struct blame_entry *ent;1753 struct origin *suspect = commit->util;17541755 /* find one suspect to break down */1756 while (suspect && !suspect->suspects)1757 suspect = suspect->next;17581759 if (!suspect) {1760 commit = prio_queue_get(&sb->commits);1761 continue;1762 }17631764 assert(commit == suspect->commit);17651766 /*1767 * We will use this suspect later in the loop,1768 * so hold onto it in the meantime.1769 */1770 origin_incref(suspect);1771 parse_commit(commit);1772 if (reverse ||1773 (!(commit->object.flags & UNINTERESTING) &&1774 !(revs->max_age != -1 && commit->date < revs->max_age)))1775 pass_blame(sb, suspect, opt);1776 else {1777 commit->object.flags |= UNINTERESTING;1778 if (commit->object.parsed)1779 mark_parents_uninteresting(commit);1780 }1781 /* treat root commit as boundary */1782 if (!commit->parents && !show_root)1783 commit->object.flags |= UNINTERESTING;17841785 /* Take responsibility for the remaining entries */1786 ent = suspect->suspects;1787 if (ent) {1788 suspect->guilty = 1;1789 for (;;) {1790 struct blame_entry *next = ent->next;1791 found_guilty_entry(ent, &pi);1792 if (next) {1793 ent = next;1794 continue;1795 }1796 ent->next = sb->ent;1797 sb->ent = suspect->suspects;1798 suspect->suspects = NULL;1799 break;1800 }1801 }1802 origin_decref(suspect);18031804 if (DEBUG) /* sanity */1805 sanity_check_refcnt(sb);1806 }18071808 stop_progress(&pi.progress);1809}18101811static const char *format_time(timestamp_t time, const char *tz_str,1812 int show_raw_time)1813{1814 static struct strbuf time_buf = STRBUF_INIT;18151816 strbuf_reset(&time_buf);1817 if (show_raw_time) {1818 strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);1819 }1820 else {1821 const char *time_str;1822 size_t time_width;1823 int tz;1824 tz = atoi(tz_str);1825 time_str = show_date(time, tz, &blame_date_mode);1826 strbuf_addstr(&time_buf, time_str);1827 /*1828 * Add space paddings to time_buf to display a fixed width1829 * string, and use time_width for display width calibration.1830 */1831 for (time_width = utf8_strwidth(time_str);1832 time_width < blame_date_width;1833 time_width++)1834 strbuf_addch(&time_buf, ' ');1835 }1836 return time_buf.buf;1837}18381839#define OUTPUT_ANNOTATE_COMPAT 0011840#define OUTPUT_LONG_OBJECT_NAME 0021841#define OUTPUT_RAW_TIMESTAMP 0041842#define OUTPUT_PORCELAIN 0101843#define OUTPUT_SHOW_NAME 0201844#define OUTPUT_SHOW_NUMBER 0401845#define OUTPUT_SHOW_SCORE 01001846#define OUTPUT_NO_AUTHOR 02001847#define OUTPUT_SHOW_EMAIL 04001848#define OUTPUT_LINE_PORCELAIN 0100018491850static void emit_porcelain_details(struct origin *suspect, int repeat)1851{1852 if (emit_one_suspect_detail(suspect, repeat) ||1853 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))1854 write_filename_info(suspect);1855}18561857static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent,1858 int opt)1859{1860 int repeat = opt & OUTPUT_LINE_PORCELAIN;1861 int cnt;1862 const char *cp;1863 struct origin *suspect = ent->suspect;1864 char hex[GIT_MAX_HEXSZ + 1];18651866 oid_to_hex_r(hex, &suspect->commit->object.oid);1867 printf("%s %d %d %d\n",1868 hex,1869 ent->s_lno + 1,1870 ent->lno + 1,1871 ent->num_lines);1872 emit_porcelain_details(suspect, repeat);18731874 cp = nth_line(sb, ent->lno);1875 for (cnt = 0; cnt < ent->num_lines; cnt++) {1876 char ch;1877 if (cnt) {1878 printf("%s %d %d\n", hex,1879 ent->s_lno + 1 + cnt,1880 ent->lno + 1 + cnt);1881 if (repeat)1882 emit_porcelain_details(suspect, 1);1883 }1884 putchar('\t');1885 do {1886 ch = *cp++;1887 putchar(ch);1888 } while (ch != '\n' &&1889 cp < sb->final_buf + sb->final_buf_size);1890 }18911892 if (sb->final_buf_size && cp[-1] != '\n')1893 putchar('\n');1894}18951896static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)1897{1898 int cnt;1899 const char *cp;1900 struct origin *suspect = ent->suspect;1901 struct commit_info ci;1902 char hex[GIT_MAX_HEXSZ + 1];1903 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19041905 get_commit_info(suspect->commit, &ci, 1);1906 oid_to_hex_r(hex, &suspect->commit->object.oid);19071908 cp = nth_line(sb, ent->lno);1909 for (cnt = 0; cnt < ent->num_lines; cnt++) {1910 char ch;1911 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? GIT_SHA1_HEXSZ : abbrev;19121913 if (suspect->commit->object.flags & UNINTERESTING) {1914 if (blank_boundary)1915 memset(hex, ' ', length);1916 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {1917 length--;1918 putchar('^');1919 }1920 }19211922 printf("%.*s", length, hex);1923 if (opt & OUTPUT_ANNOTATE_COMPAT) {1924 const char *name;1925 if (opt & OUTPUT_SHOW_EMAIL)1926 name = ci.author_mail.buf;1927 else1928 name = ci.author.buf;1929 printf("\t(%10s\t%10s\t%d)", name,1930 format_time(ci.author_time, ci.author_tz.buf,1931 show_raw_time),1932 ent->lno + 1 + cnt);1933 } else {1934 if (opt & OUTPUT_SHOW_SCORE)1935 printf(" %*d %02d",1936 max_score_digits, ent->score,1937 ent->suspect->refcnt);1938 if (opt & OUTPUT_SHOW_NAME)1939 printf(" %-*.*s", longest_file, longest_file,1940 suspect->path);1941 if (opt & OUTPUT_SHOW_NUMBER)1942 printf(" %*d", max_orig_digits,1943 ent->s_lno + 1 + cnt);19441945 if (!(opt & OUTPUT_NO_AUTHOR)) {1946 const char *name;1947 int pad;1948 if (opt & OUTPUT_SHOW_EMAIL)1949 name = ci.author_mail.buf;1950 else1951 name = ci.author.buf;1952 pad = longest_author - utf8_strwidth(name);1953 printf(" (%s%*s %10s",1954 name, pad, "",1955 format_time(ci.author_time,1956 ci.author_tz.buf,1957 show_raw_time));1958 }1959 printf(" %*d) ",1960 max_digits, ent->lno + 1 + cnt);1961 }1962 do {1963 ch = *cp++;1964 putchar(ch);1965 } while (ch != '\n' &&1966 cp < sb->final_buf + sb->final_buf_size);1967 }19681969 if (sb->final_buf_size && cp[-1] != '\n')1970 putchar('\n');19711972 commit_info_destroy(&ci);1973}19741975static void output(struct scoreboard *sb, int option)1976{1977 struct blame_entry *ent;19781979 if (option & OUTPUT_PORCELAIN) {1980 for (ent = sb->ent; ent; ent = ent->next) {1981 int count = 0;1982 struct origin *suspect;1983 struct commit *commit = ent->suspect->commit;1984 if (commit->object.flags & MORE_THAN_ONE_PATH)1985 continue;1986 for (suspect = commit->util; suspect; suspect = suspect->next) {1987 if (suspect->guilty && count++) {1988 commit->object.flags |= MORE_THAN_ONE_PATH;1989 break;1990 }1991 }1992 }1993 }19941995 for (ent = sb->ent; ent; ent = ent->next) {1996 if (option & OUTPUT_PORCELAIN)1997 emit_porcelain(sb, ent, option);1998 else {1999 emit_other(sb, ent, option);2000 }2001 }2002}20032004static const char *get_next_line(const char *start, const char *end)2005{2006 const char *nl = memchr(start, '\n', end - start);2007 return nl ? nl + 1 : end;2008}20092010/*2011 * To allow quick access to the contents of nth line in the2012 * final image, prepare an index in the scoreboard.2013 */2014static int prepare_lines(struct scoreboard *sb)2015{2016 const char *buf = sb->final_buf;2017 unsigned long len = sb->final_buf_size;2018 const char *end = buf + len;2019 const char *p;2020 int *lineno;2021 int num = 0;20222023 for (p = buf; p < end; p = get_next_line(p, end))2024 num++;20252026 ALLOC_ARRAY(sb->lineno, num + 1);2027 lineno = sb->lineno;20282029 for (p = buf; p < end; p = get_next_line(p, end))2030 *lineno++ = p - buf;20312032 *lineno = len;20332034 sb->num_lines = num;2035 return sb->num_lines;2036}20372038/*2039 * Add phony grafts for use with -S; this is primarily to2040 * support git's cvsserver that wants to give a linear history2041 * to its clients.2042 */2043static int read_ancestry(const char *graft_file)2044{2045 FILE *fp = fopen(graft_file, "r");2046 struct strbuf buf = STRBUF_INIT;2047 if (!fp)2048 return -1;2049 while (!strbuf_getwholeline(&buf, fp, '\n')) {2050 /* The format is just "Commit Parent1 Parent2 ...\n" */2051 struct commit_graft *graft = read_graft_line(buf.buf, buf.len);2052 if (graft)2053 register_commit_graft(graft, 0);2054 }2055 fclose(fp);2056 strbuf_release(&buf);2057 return 0;2058}20592060static int update_auto_abbrev(int auto_abbrev, struct origin *suspect)2061{2062 const char *uniq = find_unique_abbrev(suspect->commit->object.oid.hash,2063 auto_abbrev);2064 int len = strlen(uniq);2065 if (auto_abbrev < len)2066 return len;2067 return auto_abbrev;2068}20692070/*2071 * How many columns do we need to show line numbers, authors,2072 * and filenames?2073 */2074static void find_alignment(struct scoreboard *sb, int *option)2075{2076 int longest_src_lines = 0;2077 int longest_dst_lines = 0;2078 unsigned largest_score = 0;2079 struct blame_entry *e;2080 int compute_auto_abbrev = (abbrev < 0);2081 int auto_abbrev = DEFAULT_ABBREV;20822083 for (e = sb->ent; e; e = e->next) {2084 struct origin *suspect = e->suspect;2085 int num;20862087 if (compute_auto_abbrev)2088 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);2089 if (strcmp(suspect->path, sb->path))2090 *option |= OUTPUT_SHOW_NAME;2091 num = strlen(suspect->path);2092 if (longest_file < num)2093 longest_file = num;2094 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {2095 struct commit_info ci;2096 suspect->commit->object.flags |= METAINFO_SHOWN;2097 get_commit_info(suspect->commit, &ci, 1);2098 if (*option & OUTPUT_SHOW_EMAIL)2099 num = utf8_strwidth(ci.author_mail.buf);2100 else2101 num = utf8_strwidth(ci.author.buf);2102 if (longest_author < num)2103 longest_author = num;2104 commit_info_destroy(&ci);2105 }2106 num = e->s_lno + e->num_lines;2107 if (longest_src_lines < num)2108 longest_src_lines = num;2109 num = e->lno + e->num_lines;2110 if (longest_dst_lines < num)2111 longest_dst_lines = num;2112 if (largest_score < ent_score(sb, e))2113 largest_score = ent_score(sb, e);2114 }2115 max_orig_digits = decimal_width(longest_src_lines);2116 max_digits = decimal_width(longest_dst_lines);2117 max_score_digits = decimal_width(largest_score);21182119 if (compute_auto_abbrev)2120 /* one more abbrev length is needed for the boundary commit */2121 abbrev = auto_abbrev + 1;2122}21232124/*2125 * For debugging -- origin is refcounted, and this asserts that2126 * we do not underflow.2127 */2128static void sanity_check_refcnt(struct scoreboard *sb)2129{2130 int baa = 0;2131 struct blame_entry *ent;21322133 for (ent = sb->ent; ent; ent = ent->next) {2134 /* Nobody should have zero or negative refcnt */2135 if (ent->suspect->refcnt <= 0) {2136 fprintf(stderr, "%s in %s has negative refcnt %d\n",2137 ent->suspect->path,2138 oid_to_hex(&ent->suspect->commit->object.oid),2139 ent->suspect->refcnt);2140 baa = 1;2141 }2142 }2143 if (baa) {2144 int opt = 0160;2145 find_alignment(sb, &opt);2146 output(sb, opt);2147 die("Baa %d!", baa);2148 }2149}21502151static unsigned parse_score(const char *arg)2152{2153 char *end;2154 unsigned long score = strtoul(arg, &end, 10);2155 if (*end)2156 return 0;2157 return score;2158}21592160static const char *add_prefix(const char *prefix, const char *path)2161{2162 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);2163}21642165static int git_blame_config(const char *var, const char *value, void *cb)2166{2167 if (!strcmp(var, "blame.showroot")) {2168 show_root = git_config_bool(var, value);2169 return 0;2170 }2171 if (!strcmp(var, "blame.blankboundary")) {2172 blank_boundary = git_config_bool(var, value);2173 return 0;2174 }2175 if (!strcmp(var, "blame.showemail")) {2176 int *output_option = cb;2177 if (git_config_bool(var, value))2178 *output_option |= OUTPUT_SHOW_EMAIL;2179 else2180 *output_option &= ~OUTPUT_SHOW_EMAIL;2181 return 0;2182 }2183 if (!strcmp(var, "blame.date")) {2184 if (!value)2185 return config_error_nonbool(var);2186 parse_date_format(value, &blame_date_mode);2187 return 0;2188 }21892190 if (git_diff_heuristic_config(var, value, cb) < 0)2191 return -1;2192 if (userdiff_config(var, value) < 0)2193 return -1;21942195 return git_default_config(var, value, cb);2196}21972198static void verify_working_tree_path(struct commit *work_tree, const char *path)2199{2200 struct commit_list *parents;2201 int pos;22022203 for (parents = work_tree->parents; parents; parents = parents->next) {2204 const struct object_id *commit_oid = &parents->item->object.oid;2205 struct object_id blob_oid;2206 unsigned mode;22072208 if (!get_tree_entry(commit_oid->hash, path, blob_oid.hash, &mode) &&2209 sha1_object_info(blob_oid.hash, NULL) == OBJ_BLOB)2210 return;2211 }22122213 pos = cache_name_pos(path, strlen(path));2214 if (pos >= 0)2215 ; /* path is in the index */2216 else if (-1 - pos < active_nr &&2217 !strcmp(active_cache[-1 - pos]->name, path))2218 ; /* path is in the index, unmerged */2219 else2220 die("no such path '%s' in HEAD", path);2221}22222223static struct commit_list **append_parent(struct commit_list **tail, const struct object_id *oid)2224{2225 struct commit *parent;22262227 parent = lookup_commit_reference(oid->hash);2228 if (!parent)2229 die("no such commit %s", oid_to_hex(oid));2230 return &commit_list_insert(parent, tail)->next;2231}22322233static void append_merge_parents(struct commit_list **tail)2234{2235 int merge_head;2236 struct strbuf line = STRBUF_INIT;22372238 merge_head = open(git_path_merge_head(), O_RDONLY);2239 if (merge_head < 0) {2240 if (errno == ENOENT)2241 return;2242 die("cannot open '%s' for reading", git_path_merge_head());2243 }22442245 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {2246 struct object_id oid;2247 if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid))2248 die("unknown line in '%s': %s", git_path_merge_head(), line.buf);2249 tail = append_parent(tail, &oid);2250 }2251 close(merge_head);2252 strbuf_release(&line);2253}22542255/*2256 * This isn't as simple as passing sb->buf and sb->len, because we2257 * want to transfer ownership of the buffer to the commit (so we2258 * must use detach).2259 */2260static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)2261{2262 size_t len;2263 void *buf = strbuf_detach(sb, &len);2264 set_commit_buffer(c, buf, len);2265}22662267/*2268 * Prepare a dummy commit that represents the work tree (or staged) item.2269 * Note that annotating work tree item never works in the reverse.2270 */2271static struct commit *fake_working_tree_commit(struct diff_options *opt,2272 const char *path,2273 const char *contents_from)2274{2275 struct commit *commit;2276 struct origin *origin;2277 struct commit_list **parent_tail, *parent;2278 struct object_id head_oid;2279 struct strbuf buf = STRBUF_INIT;2280 const char *ident;2281 time_t now;2282 int size, len;2283 struct cache_entry *ce;2284 unsigned mode;2285 struct strbuf msg = STRBUF_INIT;22862287 read_cache();2288 time(&now);2289 commit = alloc_commit_node();2290 commit->object.parsed = 1;2291 commit->date = now;2292 parent_tail = &commit->parents;22932294 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_oid.hash, NULL))2295 die("no such ref: HEAD");22962297 parent_tail = append_parent(parent_tail, &head_oid);2298 append_merge_parents(parent_tail);2299 verify_working_tree_path(commit, path);23002301 origin = make_origin(commit, path);23022303 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);2304 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");2305 for (parent = commit->parents; parent; parent = parent->next)2306 strbuf_addf(&msg, "parent %s\n",2307 oid_to_hex(&parent->item->object.oid));2308 strbuf_addf(&msg,2309 "author %s\n"2310 "committer %s\n\n"2311 "Version of %s from %s\n",2312 ident, ident, path,2313 (!contents_from ? path :2314 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));2315 set_commit_buffer_from_strbuf(commit, &msg);23162317 if (!contents_from || strcmp("-", contents_from)) {2318 struct stat st;2319 const char *read_from;2320 char *buf_ptr;2321 unsigned long buf_len;23222323 if (contents_from) {2324 if (stat(contents_from, &st) < 0)2325 die_errno("Cannot stat '%s'", contents_from);2326 read_from = contents_from;2327 }2328 else {2329 if (lstat(path, &st) < 0)2330 die_errno("Cannot lstat '%s'", path);2331 read_from = path;2332 }2333 mode = canon_mode(st.st_mode);23342335 switch (st.st_mode & S_IFMT) {2336 case S_IFREG:2337 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2338 textconv_object(read_from, mode, &null_oid, 0, &buf_ptr, &buf_len))2339 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);2340 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2341 die_errno("cannot open or read '%s'", read_from);2342 break;2343 case S_IFLNK:2344 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)2345 die_errno("cannot readlink '%s'", read_from);2346 break;2347 default:2348 die("unsupported file type %s", read_from);2349 }2350 }2351 else {2352 /* Reading from stdin */2353 mode = 0;2354 if (strbuf_read(&buf, 0, 0) < 0)2355 die_errno("failed to read from stdin");2356 }2357 convert_to_git(path, buf.buf, buf.len, &buf, 0);2358 origin->file.ptr = buf.buf;2359 origin->file.size = buf.len;2360 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_oid.hash);23612362 /*2363 * Read the current index, replace the path entry with2364 * origin->blob_sha1 without mucking with its mode or type2365 * bits; we are not going to write this index out -- we just2366 * want to run "diff-index --cached".2367 */2368 discard_cache();2369 read_cache();23702371 len = strlen(path);2372 if (!mode) {2373 int pos = cache_name_pos(path, len);2374 if (0 <= pos)2375 mode = active_cache[pos]->ce_mode;2376 else2377 /* Let's not bother reading from HEAD tree */2378 mode = S_IFREG | 0644;2379 }2380 size = cache_entry_size(len);2381 ce = xcalloc(1, size);2382 oidcpy(&ce->oid, &origin->blob_oid);2383 memcpy(ce->name, path, len);2384 ce->ce_flags = create_ce_flags(0);2385 ce->ce_namelen = len;2386 ce->ce_mode = create_ce_mode(mode);2387 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23882389 cache_tree_invalidate_path(&the_index, path);23902391 return commit;2392}23932394static struct commit *find_single_final(struct rev_info *revs,2395 const char **name_p)2396{2397 int i;2398 struct commit *found = NULL;2399 const char *name = NULL;24002401 for (i = 0; i < revs->pending.nr; i++) {2402 struct object *obj = revs->pending.objects[i].item;2403 if (obj->flags & UNINTERESTING)2404 continue;2405 obj = deref_tag(obj, NULL, 0);2406 if (obj->type != OBJ_COMMIT)2407 die("Non commit %s?", revs->pending.objects[i].name);2408 if (found)2409 die("More than one commit to dig from %s and %s?",2410 revs->pending.objects[i].name, name);2411 found = (struct commit *)obj;2412 name = revs->pending.objects[i].name;2413 }2414 if (name_p)2415 *name_p = name;2416 return found;2417}24182419static char *prepare_final(struct scoreboard *sb)2420{2421 const char *name;2422 sb->final = find_single_final(sb->revs, &name);2423 return xstrdup_or_null(name);2424}24252426static const char *dwim_reverse_initial(struct scoreboard *sb)2427{2428 /*2429 * DWIM "git blame --reverse ONE -- PATH" as2430 * "git blame --reverse ONE..HEAD -- PATH" but only do so2431 * when it makes sense.2432 */2433 struct object *obj;2434 struct commit *head_commit;2435 unsigned char head_sha1[20];24362437 if (sb->revs->pending.nr != 1)2438 return NULL;24392440 /* Is that sole rev a committish? */2441 obj = sb->revs->pending.objects[0].item;2442 obj = deref_tag(obj, NULL, 0);2443 if (obj->type != OBJ_COMMIT)2444 return NULL;24452446 /* Do we have HEAD? */2447 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2448 return NULL;2449 head_commit = lookup_commit_reference_gently(head_sha1, 1);2450 if (!head_commit)2451 return NULL;24522453 /* Turn "ONE" into "ONE..HEAD" then */2454 obj->flags |= UNINTERESTING;2455 add_pending_object(sb->revs, &head_commit->object, "HEAD");24562457 sb->final = (struct commit *)obj;2458 return sb->revs->pending.objects[0].name;2459}24602461static char *prepare_initial(struct scoreboard *sb)2462{2463 int i;2464 const char *final_commit_name = NULL;2465 struct rev_info *revs = sb->revs;24662467 /*2468 * There must be one and only one negative commit, and it must be2469 * the boundary.2470 */2471 for (i = 0; i < revs->pending.nr; i++) {2472 struct object *obj = revs->pending.objects[i].item;2473 if (!(obj->flags & UNINTERESTING))2474 continue;2475 obj = deref_tag(obj, NULL, 0);2476 if (obj->type != OBJ_COMMIT)2477 die("Non commit %s?", revs->pending.objects[i].name);2478 if (sb->final)2479 die("More than one commit to dig up from, %s and %s?",2480 revs->pending.objects[i].name,2481 final_commit_name);2482 sb->final = (struct commit *) obj;2483 final_commit_name = revs->pending.objects[i].name;2484 }24852486 if (!final_commit_name)2487 final_commit_name = dwim_reverse_initial(sb);2488 if (!final_commit_name)2489 die("No commit to dig up from?");2490 return xstrdup(final_commit_name);2491}24922493static int blame_copy_callback(const struct option *option, const char *arg, int unset)2494{2495 int *opt = option->value;24962497 /*2498 * -C enables copy from removed files;2499 * -C -C enables copy from existing files, but only2500 * when blaming a new file;2501 * -C -C -C enables copy from existing files for2502 * everybody2503 */2504 if (*opt & PICKAXE_BLAME_COPY_HARDER)2505 *opt |= PICKAXE_BLAME_COPY_HARDEST;2506 if (*opt & PICKAXE_BLAME_COPY)2507 *opt |= PICKAXE_BLAME_COPY_HARDER;2508 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;25092510 if (arg)2511 blame_copy_score = parse_score(arg);2512 return 0;2513}25142515static int blame_move_callback(const struct option *option, const char *arg, int unset)2516{2517 int *opt = option->value;25182519 *opt |= PICKAXE_BLAME_MOVE;25202521 if (arg)2522 blame_move_score = parse_score(arg);2523 return 0;2524}25252526int cmd_blame(int argc, const char **argv, const char *prefix)2527{2528 struct rev_info revs;2529 const char *path;2530 struct scoreboard sb;2531 struct origin *o;2532 struct blame_entry *ent = NULL;2533 long dashdash_pos, lno;2534 char *final_commit_name = NULL;2535 enum object_type type;2536 struct commit *final_commit = NULL;25372538 struct string_list range_list = STRING_LIST_INIT_NODUP;2539 int output_option = 0, opt = 0;2540 int show_stats = 0;2541 const char *revs_file = NULL;2542 const char *contents_from = NULL;2543 const struct option options[] = {2544 OPT_BOOL(0, "incremental", &incremental, N_("Show blame entries as we find them, incrementally")),2545 OPT_BOOL('b', NULL, &blank_boundary, N_("Show blank SHA-1 for boundary commits (Default: off)")),2546 OPT_BOOL(0, "root", &show_root, N_("Do not treat root commits as boundaries (Default: off)")),2547 OPT_BOOL(0, "show-stats", &show_stats, N_("Show work cost statistics")),2548 OPT_BOOL(0, "progress", &show_progress, N_("Force progress reporting")),2549 OPT_BIT(0, "score-debug", &output_option, N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2550 OPT_BIT('f', "show-name", &output_option, N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2551 OPT_BIT('n', "show-number", &output_option, N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2552 OPT_BIT('p', "porcelain", &output_option, N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2553 OPT_BIT(0, "line-porcelain", &output_option, N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2554 OPT_BIT('c', NULL, &output_option, N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2555 OPT_BIT('t', NULL, &output_option, N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2556 OPT_BIT('l', NULL, &output_option, N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2557 OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2558 OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2559 OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),25602561 /*2562 * The following two options are parsed by parse_revision_opt()2563 * and are only included here to get included in the "-h"2564 * output:2565 */2566 { OPTION_LOWLEVEL_CALLBACK, 0, "indent-heuristic", NULL, NULL, N_("Use an experimental heuristic to improve diffs"), PARSE_OPT_NOARG, parse_opt_unknown_cb },25672568 OPT_BIT(0, "minimal", &xdl_opts, N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2569 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("Use revisions from <file> instead of calling git-rev-list")),2570 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("Use <file>'s contents as the final image")),2571 { OPTION_CALLBACK, 'C', NULL, &opt, N_("score"), N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2572 { OPTION_CALLBACK, 'M', NULL, &opt, N_("score"), N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2573 OPT_STRING_LIST('L', NULL, &range_list, N_("n,m"), N_("Process only line range n,m, counting from 1")),2574 OPT__ABBREV(&abbrev),2575 OPT_END()2576 };25772578 struct parse_opt_ctx_t ctx;2579 int cmd_is_annotate = !strcmp(argv[0], "annotate");2580 struct range_set ranges;2581 unsigned int range_i;2582 long anchor;25832584 git_config(git_blame_config, &output_option);2585 init_revisions(&revs, NULL);2586 revs.date_mode = blame_date_mode;2587 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2588 DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25892590 save_commit_buffer = 0;2591 dashdash_pos = 0;2592 show_progress = -1;25932594 parse_options_start(&ctx, argc, argv, prefix, options,2595 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2596 for (;;) {2597 switch (parse_options_step(&ctx, options, blame_opt_usage)) {2598 case PARSE_OPT_HELP:2599 exit(129);2600 case PARSE_OPT_DONE:2601 if (ctx.argv[0])2602 dashdash_pos = ctx.cpidx;2603 goto parse_done;2604 }26052606 if (!strcmp(ctx.argv[0], "--reverse")) {2607 ctx.argv[0] = "--children";2608 reverse = 1;2609 }2610 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2611 }2612parse_done:2613 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2614 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;2615 DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2616 argc = parse_options_end(&ctx);26172618 if (incremental || (output_option & OUTPUT_PORCELAIN)) {2619 if (show_progress > 0)2620 die(_("--progress can't be used with --incremental or porcelain formats"));2621 show_progress = 0;2622 } else if (show_progress < 0)2623 show_progress = isatty(2);26242625 if (0 < abbrev && abbrev < GIT_SHA1_HEXSZ)2626 /* one more abbrev length is needed for the boundary commit */2627 abbrev++;2628 else if (!abbrev)2629 abbrev = GIT_SHA1_HEXSZ;26302631 if (revs_file && read_ancestry(revs_file))2632 die_errno("reading graft file '%s' failed", revs_file);26332634 if (cmd_is_annotate) {2635 output_option |= OUTPUT_ANNOTATE_COMPAT;2636 blame_date_mode.type = DATE_ISO8601;2637 } else {2638 blame_date_mode = revs.date_mode;2639 }26402641 /* The maximum width used to show the dates */2642 switch (blame_date_mode.type) {2643 case DATE_RFC2822:2644 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2645 break;2646 case DATE_ISO8601_STRICT:2647 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");2648 break;2649 case DATE_ISO8601:2650 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");2651 break;2652 case DATE_RAW:2653 blame_date_width = sizeof("1161298804 -0700");2654 break;2655 case DATE_UNIX:2656 blame_date_width = sizeof("1161298804");2657 break;2658 case DATE_SHORT:2659 blame_date_width = sizeof("2006-10-19");2660 break;2661 case DATE_RELATIVE:2662 /* TRANSLATORS: This string is used to tell us the maximum2663 display width for a relative timestamp in "git blame"2664 output. For C locale, "4 years, 11 months ago", which2665 takes 22 places, is the longest among various forms of2666 relative timestamps, but your language may need more or2667 fewer display columns. */2668 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */2669 break;2670 case DATE_NORMAL:2671 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");2672 break;2673 case DATE_STRFTIME:2674 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */2675 break;2676 }2677 blame_date_width -= 1; /* strip the null */26782679 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2680 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2681 PICKAXE_BLAME_COPY_HARDER);26822683 if (!blame_move_score)2684 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2685 if (!blame_copy_score)2686 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26872688 /*2689 * We have collected options unknown to us in argv[1..unk]2690 * which are to be passed to revision machinery if we are2691 * going to do the "bottom" processing.2692 *2693 * The remaining are:2694 *2695 * (1) if dashdash_pos != 0, it is either2696 * "blame [revisions] -- <path>" or2697 * "blame -- <path> <rev>"2698 *2699 * (2) otherwise, it is one of the two:2700 * "blame [revisions] <path>"2701 * "blame <path> <rev>"2702 *2703 * Note that we must strip out <path> from the arguments: we do not2704 * want the path pruning but we may want "bottom" processing.2705 */2706 if (dashdash_pos) {2707 switch (argc - dashdash_pos - 1) {2708 case 2: /* (1b) */2709 if (argc != 4)2710 usage_with_options(blame_opt_usage, options);2711 /* reorder for the new way: <rev> -- <path> */2712 argv[1] = argv[3];2713 argv[3] = argv[2];2714 argv[2] = "--";2715 /* FALLTHROUGH */2716 case 1: /* (1a) */2717 path = add_prefix(prefix, argv[--argc]);2718 argv[argc] = NULL;2719 break;2720 default:2721 usage_with_options(blame_opt_usage, options);2722 }2723 } else {2724 if (argc < 2)2725 usage_with_options(blame_opt_usage, options);2726 path = add_prefix(prefix, argv[argc - 1]);2727 if (argc == 3 && !file_exists(path)) { /* (2b) */2728 path = add_prefix(prefix, argv[1]);2729 argv[1] = argv[2];2730 }2731 argv[argc - 1] = "--";27322733 setup_work_tree();2734 if (!file_exists(path))2735 die_errno("cannot stat path '%s'", path);2736 }27372738 revs.disable_stdin = 1;2739 setup_revisions(argc, argv, &revs, NULL);2740 memset(&sb, 0, sizeof(sb));27412742 sb.revs = &revs;2743 if (!reverse) {2744 final_commit_name = prepare_final(&sb);2745 sb.commits.compare = compare_commits_by_commit_date;2746 }2747 else if (contents_from)2748 die(_("--contents and --reverse do not blend well."));2749 else {2750 final_commit_name = prepare_initial(&sb);2751 sb.commits.compare = compare_commits_by_reverse_commit_date;2752 if (revs.first_parent_only)2753 revs.children.name = NULL;2754 }27552756 if (!sb.final) {2757 /*2758 * "--not A B -- path" without anything positive;2759 * do not default to HEAD, but use the working tree2760 * or "--contents".2761 */2762 setup_work_tree();2763 sb.final = fake_working_tree_commit(&sb.revs->diffopt,2764 path, contents_from);2765 add_pending_object(&revs, &(sb.final->object), ":");2766 }2767 else if (contents_from)2768 die(_("cannot use --contents with final commit object name"));27692770 if (reverse && revs.first_parent_only) {2771 final_commit = find_single_final(sb.revs, NULL);2772 if (!final_commit)2773 die(_("--reverse and --first-parent together require specified latest commit"));2774 }27752776 /*2777 * If we have bottom, this will mark the ancestors of the2778 * bottom commits we would reach while traversing as2779 * uninteresting.2780 */2781 if (prepare_revision_walk(&revs))2782 die(_("revision walk setup failed"));27832784 if (reverse && revs.first_parent_only) {2785 struct commit *c = final_commit;27862787 sb.revs->children.name = "children";2788 while (c->parents &&2789 oidcmp(&c->object.oid, &sb.final->object.oid)) {2790 struct commit_list *l = xcalloc(1, sizeof(*l));27912792 l->item = c;2793 if (add_decoration(&sb.revs->children,2794 &c->parents->item->object, l))2795 die("BUG: not unique item in first-parent chain");2796 c = c->parents->item;2797 }27982799 if (oidcmp(&c->object.oid, &sb.final->object.oid))2800 die(_("--reverse --first-parent together require range along first-parent chain"));2801 }28022803 if (is_null_oid(&sb.final->object.oid)) {2804 o = sb.final->util;2805 sb.final_buf = xmemdupz(o->file.ptr, o->file.size);2806 sb.final_buf_size = o->file.size;2807 }2808 else {2809 o = get_origin(&sb, sb.final, path);2810 if (fill_blob_sha1_and_mode(o))2811 die(_("no such path %s in %s"), path, final_commit_name);28122813 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2814 textconv_object(path, o->mode, &o->blob_oid, 1, (char **) &sb.final_buf,2815 &sb.final_buf_size))2816 ;2817 else2818 sb.final_buf = read_sha1_file(o->blob_oid.hash, &type,2819 &sb.final_buf_size);28202821 if (!sb.final_buf)2822 die(_("cannot read blob %s for path %s"),2823 oid_to_hex(&o->blob_oid),2824 path);2825 }2826 num_read_blob++;2827 lno = prepare_lines(&sb);28282829 if (lno && !range_list.nr)2830 string_list_append(&range_list, "1");28312832 anchor = 1;2833 range_set_init(&ranges, range_list.nr);2834 for (range_i = 0; range_i < range_list.nr; ++range_i) {2835 long bottom, top;2836 if (parse_range_arg(range_list.items[range_i].string,2837 nth_line_cb, &sb, lno, anchor,2838 &bottom, &top, sb.path))2839 usage(blame_usage);2840 if (lno < top || ((lno || bottom) && lno < bottom))2841 die(Q_("file %s has only %lu line",2842 "file %s has only %lu lines",2843 lno), path, lno);2844 if (bottom < 1)2845 bottom = 1;2846 if (top < 1)2847 top = lno;2848 bottom--;2849 range_set_append_unsafe(&ranges, bottom, top);2850 anchor = top + 1;2851 }2852 sort_and_merge_range_set(&ranges);28532854 for (range_i = ranges.nr; range_i > 0; --range_i) {2855 const struct range *r = &ranges.ranges[range_i - 1];2856 long bottom = r->start;2857 long top = r->end;2858 struct blame_entry *next = ent;2859 ent = xcalloc(1, sizeof(*ent));2860 ent->lno = bottom;2861 ent->num_lines = top - bottom;2862 ent->suspect = o;2863 ent->s_lno = bottom;2864 ent->next = next;2865 origin_incref(o);2866 }28672868 o->suspects = ent;2869 prio_queue_put(&sb.commits, o->commit);28702871 origin_decref(o);28722873 range_set_release(&ranges);2874 string_list_clear(&range_list, 0);28752876 sb.ent = NULL;2877 sb.path = path;28782879 read_mailmap(&mailmap, NULL);28802881 assign_blame(&sb, opt);28822883 if (!incremental)2884 setup_pager();28852886 free(final_commit_name);28872888 if (incremental)2889 return 0;28902891 sb.ent = blame_sort(sb.ent, compare_blame_final);28922893 coalesce(&sb);28942895 if (!(output_option & OUTPUT_PORCELAIN))2896 find_alignment(&sb, &output_option);28972898 output(&sb, output_option);2899 free((void *)sb.final_buf);2900 for (ent = sb.ent; ent; ) {2901 struct blame_entry *e = ent->next;2902 free(ent);2903 ent = e;2904 }29052906 if (show_stats) {2907 printf("num read blob: %d\n", num_read_blob);2908 printf("num get patch: %d\n", num_get_patch);2909 printf("num commits: %d\n", num_commits);2910 }2911 return 0;2912}