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"", 37N_("<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 blame_origin { 91int refcnt; 92/* Record preceding blame record for this blob */ 93struct blame_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 */ 111struct blame_origin *next; 112struct 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 */ 120struct blame_entry *suspects; 121 mmfile_t file; 122struct object_id blob_oid; 123unsigned mode; 124/* guilty gets set when shipping any suspects to the final 125 * blame list instead of other commits 126 */ 127char guilty; 128char path[FLEX_ARRAY]; 129}; 130 131struct progress_info { 132struct progress *progress; 133int blamed_lines; 134}; 135 136static intdiff_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; 146returnxdi_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 voidfill_origin_blob(struct diff_options *opt, 154struct blame_origin *o, mmfile_t *file) 155{ 156if(!o->file.ptr) { 157enum object_type type; 158unsigned long file_size; 159 160 num_read_blob++; 161if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 162textconv_object(o->path, o->mode, &o->blob_oid,1, &file->ptr, &file_size)) 163; 164else 165 file->ptr =read_sha1_file(o->blob_oid.hash, &type, 166&file_size); 167 file->size = file_size; 168 169if(!file->ptr) 170die("Cannot read blob%sfor path%s", 171oid_to_hex(&o->blob_oid), 172 o->path); 173 o->file = *file; 174} 175else 176*file = o->file; 177} 178 179/* 180 * Origin is refcounted and usually we keep the blob contents to be 181 * reused. 182 */ 183staticinlinestruct blame_origin *blame_origin_incref(struct blame_origin *o) 184{ 185if(o) 186 o->refcnt++; 187return o; 188} 189 190static voidblame_origin_decref(struct blame_origin *o) 191{ 192if(o && --o->refcnt <=0) { 193struct blame_origin *p, *l = NULL; 194if(o->previous) 195blame_origin_decref(o->previous); 196free(o->file.ptr); 197/* Should be present exactly once in commit chain */ 198for(p = o->commit->util; p; l = p, p = p->next) { 199if(p == o) { 200if(l) 201 l->next = p->next; 202else 203 o->commit->util = p->next; 204free(o); 205return; 206} 207} 208die("internal error in blame_origin_decref"); 209} 210} 211 212static voiddrop_origin_blob(struct blame_origin *o) 213{ 214if(o->file.ptr) { 215free(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 { 230struct blame_entry *next; 231 232/* the first line of this group in the final image; 233 * internally all line numbers are 0 based. 234 */ 235int lno; 236 237/* how many lines this group has */ 238int num_lines; 239 240/* the commit that introduced this group into the final image */ 241struct blame_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 */ 246int s_lno; 247 248/* how significant this entry is -- cached to avoid 249 * scanning the lines over and over. 250 */ 251unsigned 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, 263struct blame_entry *list2) 264{ 265struct blame_entry *p1 = list1, *p2 = list2, 266**tail = &list1; 267 268if(!p1) 269return p2; 270if(!p2) 271return p1; 272 273if(p1->s_lno <= p2->s_lno) { 274do{ 275 tail = &p1->next; 276if((p1 = *tail) == NULL) { 277*tail = p2; 278return list1; 279} 280}while(p1->s_lno <= p2->s_lno); 281} 282for(;;) { 283*tail = p2; 284do{ 285 tail = &p2->next; 286if((p2 = *tail) == NULL) { 287*tail = p1; 288return list1; 289} 290}while(p1->s_lno > p2->s_lno); 291*tail = p1; 292do{ 293 tail = &p1->next; 294if((p1 = *tail) == NULL) { 295*tail = p2; 296return list1; 297} 298}while(p1->s_lno <= p2->s_lno); 299} 300} 301 302static void*get_next_blame(const void*p) 303{ 304return((struct blame_entry *)p)->next; 305} 306 307static voidset_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 intcompare_blame_final(const void*p1,const void*p2) 318{ 319return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 320?1: -1; 321} 322 323static intcompare_blame_suspect(const void*p1,const void*p2) 324{ 325const 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 */ 333if(s1->suspect != s2->suspect) 334return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 335if(s1->s_lno == s2->s_lno) 336return0; 337return s1->s_lno > s2->s_lno ?1: -1; 338} 339 340static struct blame_entry *blame_sort(struct blame_entry *head, 341int(*compare_fn)(const void*,const void*)) 342{ 343returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 344} 345 346static intcompare_commits_by_reverse_commit_date(const void*a, 347const void*b, 348void*c) 349{ 350return-compare_commits_by_commit_date(a, b, c); 351} 352 353/* 354 * The current state of the blame assignment. 355 */ 356struct blame_scoreboard { 357/* the final commit (i.e. where we started digging from) */ 358struct commit *final; 359/* Priority queue for commits with unassigned blame records */ 360struct prio_queue commits; 361struct rev_info *revs; 362const 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 */ 369const char*final_buf; 370unsigned long final_buf_size; 371 372/* linked list of blames */ 373struct blame_entry *ent; 374 375/* look-up a line in the final buffer */ 376int num_lines; 377int*lineno; 378}; 379 380static voidsanity_check_refcnt(struct blame_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 voidblame_coalesce(struct blame_scoreboard *sb) 388{ 389struct blame_entry *ent, *next; 390 391for(ent = sb->ent; ent && (next = ent->next); ent = next) { 392if(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; 396blame_origin_decref(next->suspect); 397free(next); 398 ent->score =0; 399 next = ent;/* again */ 400} 401} 402 403if(DEBUG)/* sanity */ 404sanity_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 voidqueue_blames(struct blame_scoreboard *sb,struct blame_origin *porigin, 414struct blame_entry *sorted) 415{ 416if(porigin->suspects) 417 porigin->suspects =blame_merge(porigin->suspects, sorted); 418else{ 419struct blame_origin *o; 420for(o = porigin->commit->util; o; o = o->next) { 421if(o->suspects) { 422 porigin->suspects = sorted; 423return; 424} 425} 426 porigin->suspects = sorted; 427prio_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 blame_origin *make_origin(struct commit *commit,const char*path) 438{ 439struct blame_origin *o; 440FLEX_ALLOC_STR(o, path, path); 441 o->commit = commit; 442 o->refcnt =1; 443 o->next = commit->util; 444 commit->util = o; 445return 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 blame_origin *get_origin(struct commit *commit,const char*path) 453{ 454struct blame_origin *o, *l; 455 456for(o = commit->util, l = NULL; o; l = o, o = o->next) { 457if(!strcmp(o->path, path)) { 458/* bump to front */ 459if(l) { 460 l->next = o->next; 461 o->next = commit->util; 462 commit->util = o; 463} 464returnblame_origin_incref(o); 465} 466} 467returnmake_origin(commit, path); 468} 469 470/* 471 * Fill the blob_sha1 field of an origin if it hasn't, so that later 472 * call to fill_origin_blob() can use it to locate the data. blob_sha1 473 * for an origin is also used to pass the blame for the entire file to 474 * the parent to detect the case where a child's blob is identical to 475 * that of its parent's. 476 * 477 * This also fills origin->mode for corresponding tree path. 478 */ 479static intfill_blob_sha1_and_mode(struct blame_origin *origin) 480{ 481if(!is_null_oid(&origin->blob_oid)) 482return0; 483if(get_tree_entry(origin->commit->object.oid.hash, 484 origin->path, 485 origin->blob_oid.hash, &origin->mode)) 486goto error_out; 487if(sha1_object_info(origin->blob_oid.hash, NULL) != OBJ_BLOB) 488goto error_out; 489return0; 490 error_out: 491oidclr(&origin->blob_oid); 492 origin->mode = S_IFINVALID; 493return-1; 494} 495 496/* 497 * We have an origin -- check if the same path exists in the 498 * parent and return an origin structure to represent it. 499 */ 500static struct blame_origin *find_origin(struct commit *parent, 501struct blame_origin *origin) 502{ 503struct blame_origin *porigin; 504struct diff_options diff_opts; 505const char*paths[2]; 506 507/* First check any existing origins */ 508for(porigin = parent->util; porigin; porigin = porigin->next) 509if(!strcmp(porigin->path, origin->path)) { 510/* 511 * The same path between origin and its parent 512 * without renaming -- the most common case. 513 */ 514returnblame_origin_incref(porigin); 515} 516 517/* See if the origin->path is different between parent 518 * and origin first. Most of the time they are the 519 * same and diff-tree is fairly efficient about this. 520 */ 521diff_setup(&diff_opts); 522DIFF_OPT_SET(&diff_opts, RECURSIVE); 523 diff_opts.detect_rename =0; 524 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 525 paths[0] = origin->path; 526 paths[1] = NULL; 527 528parse_pathspec(&diff_opts.pathspec, 529 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 530 PATHSPEC_LITERAL_PATH,"", paths); 531diff_setup_done(&diff_opts); 532 533if(is_null_oid(&origin->commit->object.oid)) 534do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 535else 536diff_tree_sha1(parent->tree->object.oid.hash, 537 origin->commit->tree->object.oid.hash, 538"", &diff_opts); 539diffcore_std(&diff_opts); 540 541if(!diff_queued_diff.nr) { 542/* The path is the same as parent */ 543 porigin =get_origin(parent, origin->path); 544oidcpy(&porigin->blob_oid, &origin->blob_oid); 545 porigin->mode = origin->mode; 546}else{ 547/* 548 * Since origin->path is a pathspec, if the parent 549 * commit had it as a directory, we will see a whole 550 * bunch of deletion of files in the directory that we 551 * do not care about. 552 */ 553int i; 554struct diff_filepair *p = NULL; 555for(i =0; i < diff_queued_diff.nr; i++) { 556const char*name; 557 p = diff_queued_diff.queue[i]; 558 name = p->one->path ? p->one->path : p->two->path; 559if(!strcmp(name, origin->path)) 560break; 561} 562if(!p) 563die("internal error in blame::find_origin"); 564switch(p->status) { 565default: 566die("internal error in blame::find_origin (%c)", 567 p->status); 568case'M': 569 porigin =get_origin(parent, origin->path); 570oidcpy(&porigin->blob_oid, &p->one->oid); 571 porigin->mode = p->one->mode; 572break; 573case'A': 574case'T': 575/* Did not exist in parent, or type changed */ 576break; 577} 578} 579diff_flush(&diff_opts); 580clear_pathspec(&diff_opts.pathspec); 581return porigin; 582} 583 584/* 585 * We have an origin -- find the path that corresponds to it in its 586 * parent and return an origin structure to represent it. 587 */ 588static struct blame_origin *find_rename(struct commit *parent, 589struct blame_origin *origin) 590{ 591struct blame_origin *porigin = NULL; 592struct diff_options diff_opts; 593int i; 594 595diff_setup(&diff_opts); 596DIFF_OPT_SET(&diff_opts, RECURSIVE); 597 diff_opts.detect_rename = DIFF_DETECT_RENAME; 598 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 599 diff_opts.single_follow = origin->path; 600diff_setup_done(&diff_opts); 601 602if(is_null_oid(&origin->commit->object.oid)) 603do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 604else 605diff_tree_sha1(parent->tree->object.oid.hash, 606 origin->commit->tree->object.oid.hash, 607"", &diff_opts); 608diffcore_std(&diff_opts); 609 610for(i =0; i < diff_queued_diff.nr; i++) { 611struct diff_filepair *p = diff_queued_diff.queue[i]; 612if((p->status =='R'|| p->status =='C') && 613!strcmp(p->two->path, origin->path)) { 614 porigin =get_origin(parent, p->one->path); 615oidcpy(&porigin->blob_oid, &p->one->oid); 616 porigin->mode = p->one->mode; 617break; 618} 619} 620diff_flush(&diff_opts); 621clear_pathspec(&diff_opts.pathspec); 622return porigin; 623} 624 625/* 626 * Append a new blame entry to a given output queue. 627 */ 628static voidadd_blame_entry(struct blame_entry ***queue, 629const struct blame_entry *src) 630{ 631struct blame_entry *e =xmalloc(sizeof(*e)); 632memcpy(e, src,sizeof(*e)); 633blame_origin_incref(e->suspect); 634 635 e->next = **queue; 636**queue = e; 637*queue = &e->next; 638} 639 640/* 641 * src typically is on-stack; we want to copy the information in it to 642 * a malloced blame_entry that gets added to the given queue. The 643 * origin of dst loses a refcnt. 644 */ 645static voiddup_entry(struct blame_entry ***queue, 646struct blame_entry *dst,struct blame_entry *src) 647{ 648blame_origin_incref(src->suspect); 649blame_origin_decref(dst->suspect); 650memcpy(dst, src,sizeof(*src)); 651 dst->next = **queue; 652**queue = dst; 653*queue = &dst->next; 654} 655 656static const char*nth_line(struct blame_scoreboard *sb,long lno) 657{ 658return sb->final_buf + sb->lineno[lno]; 659} 660 661static const char*nth_line_cb(void*data,long lno) 662{ 663returnnth_line((struct blame_scoreboard *)data, lno); 664} 665 666/* 667 * It is known that lines between tlno to same came from parent, and e 668 * has an overlap with that range. it also is known that parent's 669 * line plno corresponds to e's line tlno. 670 * 671 * <---- e -----> 672 * <------> 673 * <------------> 674 * <------------> 675 * <------------------> 676 * 677 * Split e into potentially three parts; before this chunk, the chunk 678 * to be blamed for the parent, and after that portion. 679 */ 680static voidsplit_overlap(struct blame_entry *split, 681struct blame_entry *e, 682int tlno,int plno,int same, 683struct blame_origin *parent) 684{ 685int chunk_end_lno; 686memset(split,0,sizeof(struct blame_entry [3])); 687 688if(e->s_lno < tlno) { 689/* there is a pre-chunk part not blamed on parent */ 690 split[0].suspect =blame_origin_incref(e->suspect); 691 split[0].lno = e->lno; 692 split[0].s_lno = e->s_lno; 693 split[0].num_lines = tlno - e->s_lno; 694 split[1].lno = e->lno + tlno - e->s_lno; 695 split[1].s_lno = plno; 696} 697else{ 698 split[1].lno = e->lno; 699 split[1].s_lno = plno + (e->s_lno - tlno); 700} 701 702if(same < e->s_lno + e->num_lines) { 703/* there is a post-chunk part not blamed on parent */ 704 split[2].suspect =blame_origin_incref(e->suspect); 705 split[2].lno = e->lno + (same - e->s_lno); 706 split[2].s_lno = e->s_lno + (same - e->s_lno); 707 split[2].num_lines = e->s_lno + e->num_lines - same; 708 chunk_end_lno = split[2].lno; 709} 710else 711 chunk_end_lno = e->lno + e->num_lines; 712 split[1].num_lines = chunk_end_lno - split[1].lno; 713 714/* 715 * if it turns out there is nothing to blame the parent for, 716 * forget about the splitting. !split[1].suspect signals this. 717 */ 718if(split[1].num_lines <1) 719return; 720 split[1].suspect =blame_origin_incref(parent); 721} 722 723/* 724 * split_overlap() divided an existing blame e into up to three parts 725 * in split. Any assigned blame is moved to queue to 726 * reflect the split. 727 */ 728static voidsplit_blame(struct blame_entry ***blamed, 729struct blame_entry ***unblamed, 730struct blame_entry *split, 731struct blame_entry *e) 732{ 733if(split[0].suspect && split[2].suspect) { 734/* The first part (reuse storage for the existing entry e) */ 735dup_entry(unblamed, e, &split[0]); 736 737/* The last part -- me */ 738add_blame_entry(unblamed, &split[2]); 739 740/* ... and the middle part -- parent */ 741add_blame_entry(blamed, &split[1]); 742} 743else if(!split[0].suspect && !split[2].suspect) 744/* 745 * The parent covers the entire area; reuse storage for 746 * e and replace it with the parent. 747 */ 748dup_entry(blamed, e, &split[1]); 749else if(split[0].suspect) { 750/* me and then parent */ 751dup_entry(unblamed, e, &split[0]); 752add_blame_entry(blamed, &split[1]); 753} 754else{ 755/* parent and then me */ 756dup_entry(blamed, e, &split[1]); 757add_blame_entry(unblamed, &split[2]); 758} 759} 760 761/* 762 * After splitting the blame, the origins used by the 763 * on-stack blame_entry should lose one refcnt each. 764 */ 765static voiddecref_split(struct blame_entry *split) 766{ 767int i; 768 769for(i =0; i <3; i++) 770blame_origin_decref(split[i].suspect); 771} 772 773/* 774 * reverse_blame reverses the list given in head, appending tail. 775 * That allows us to build lists in reverse order, then reverse them 776 * afterwards. This can be faster than building the list in proper 777 * order right away. The reason is that building in proper order 778 * requires writing a link in the _previous_ element, while building 779 * in reverse order just requires placing the list head into the 780 * _current_ element. 781 */ 782 783static struct blame_entry *reverse_blame(struct blame_entry *head, 784struct blame_entry *tail) 785{ 786while(head) { 787struct blame_entry *next = head->next; 788 head->next = tail; 789 tail = head; 790 head = next; 791} 792return tail; 793} 794 795/* 796 * Process one hunk from the patch between the current suspect for 797 * blame_entry e and its parent. This first blames any unfinished 798 * entries before the chunk (which is where target and parent start 799 * differing) on the parent, and then splits blame entries at the 800 * start and at the end of the difference region. Since use of -M and 801 * -C options may lead to overlapping/duplicate source line number 802 * ranges, all we can rely on from sorting/merging is the order of the 803 * first suspect line number. 804 */ 805static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 806int tlno,int offset,int same, 807struct blame_origin *parent) 808{ 809struct blame_entry *e = **srcq; 810struct blame_entry *samep = NULL, *diffp = NULL; 811 812while(e && e->s_lno < tlno) { 813struct blame_entry *next = e->next; 814/* 815 * current record starts before differing portion. If 816 * it reaches into it, we need to split it up and 817 * examine the second part separately. 818 */ 819if(e->s_lno + e->num_lines > tlno) { 820/* Move second half to a new record */ 821int len = tlno - e->s_lno; 822struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 823 n->suspect = e->suspect; 824 n->lno = e->lno + len; 825 n->s_lno = e->s_lno + len; 826 n->num_lines = e->num_lines - len; 827 e->num_lines = len; 828 e->score =0; 829/* Push new record to diffp */ 830 n->next = diffp; 831 diffp = n; 832}else 833blame_origin_decref(e->suspect); 834/* Pass blame for everything before the differing 835 * chunk to the parent */ 836 e->suspect =blame_origin_incref(parent); 837 e->s_lno += offset; 838 e->next = samep; 839 samep = e; 840 e = next; 841} 842/* 843 * As we don't know how much of a common stretch after this 844 * diff will occur, the currently blamed parts are all that we 845 * can assign to the parent for now. 846 */ 847 848if(samep) { 849**dstq =reverse_blame(samep, **dstq); 850*dstq = &samep->next; 851} 852/* 853 * Prepend the split off portions: everything after e starts 854 * after the blameable portion. 855 */ 856 e =reverse_blame(diffp, e); 857 858/* 859 * Now retain records on the target while parts are different 860 * from the parent. 861 */ 862 samep = NULL; 863 diffp = NULL; 864while(e && e->s_lno < same) { 865struct blame_entry *next = e->next; 866 867/* 868 * If current record extends into sameness, need to split. 869 */ 870if(e->s_lno + e->num_lines > same) { 871/* 872 * Move second half to a new record to be 873 * processed by later chunks 874 */ 875int len = same - e->s_lno; 876struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 877 n->suspect =blame_origin_incref(e->suspect); 878 n->lno = e->lno + len; 879 n->s_lno = e->s_lno + len; 880 n->num_lines = e->num_lines - len; 881 e->num_lines = len; 882 e->score =0; 883/* Push new record to samep */ 884 n->next = samep; 885 samep = n; 886} 887 e->next = diffp; 888 diffp = e; 889 e = next; 890} 891**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 892/* Move across elements that are in the unblamable portion */ 893if(diffp) 894*srcq = &diffp->next; 895} 896 897struct blame_chunk_cb_data { 898struct blame_origin *parent; 899long offset; 900struct blame_entry **dstq; 901struct blame_entry **srcq; 902}; 903 904/* diff chunks are from parent to target */ 905static intblame_chunk_cb(long start_a,long count_a, 906long start_b,long count_b,void*data) 907{ 908struct blame_chunk_cb_data *d = data; 909if(start_a - start_b != d->offset) 910die("internal error in blame::blame_chunk_cb"); 911blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 912 start_b + count_b, d->parent); 913 d->offset = start_a + count_a - (start_b + count_b); 914return0; 915} 916 917/* 918 * We are looking at the origin 'target' and aiming to pass blame 919 * for the lines it is suspected to its parent. Run diff to find 920 * which lines came from parent and pass blame for them. 921 */ 922static voidpass_blame_to_parent(struct blame_scoreboard *sb, 923struct blame_origin *target, 924struct blame_origin *parent) 925{ 926 mmfile_t file_p, file_o; 927struct blame_chunk_cb_data d; 928struct blame_entry *newdest = NULL; 929 930if(!target->suspects) 931return;/* nothing remains for this target */ 932 933 d.parent = parent; 934 d.offset =0; 935 d.dstq = &newdest; d.srcq = &target->suspects; 936 937fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 938fill_origin_blob(&sb->revs->diffopt, target, &file_o); 939 num_get_patch++; 940 941if(diff_hunks(&file_p, &file_o, blame_chunk_cb, &d)) 942die("unable to generate diff (%s->%s)", 943oid_to_hex(&parent->commit->object.oid), 944oid_to_hex(&target->commit->object.oid)); 945/* The rest are the same as the parent */ 946blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 947*d.dstq = NULL; 948queue_blames(sb, parent, newdest); 949 950return; 951} 952 953/* 954 * The lines in blame_entry after splitting blames many times can become 955 * very small and trivial, and at some point it becomes pointless to 956 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 957 * ordinary C program, and it is not worth to say it was copied from 958 * totally unrelated file in the parent. 959 * 960 * Compute how trivial the lines in the blame_entry are. 961 */ 962static unsignedblame_entry_score(struct blame_scoreboard *sb,struct blame_entry *e) 963{ 964unsigned score; 965const char*cp, *ep; 966 967if(e->score) 968return e->score; 969 970 score =1; 971 cp =nth_line(sb, e->lno); 972 ep =nth_line(sb, e->lno + e->num_lines); 973while(cp < ep) { 974unsigned ch = *((unsigned char*)cp); 975if(isalnum(ch)) 976 score++; 977 cp++; 978} 979 e->score = score; 980return score; 981} 982 983/* 984 * best_so_far[] and this[] are both a split of an existing blame_entry 985 * that passes blame to the parent. Maintain best_so_far the best split 986 * so far, by comparing this and best_so_far and copying this into 987 * bst_so_far as needed. 988 */ 989static voidcopy_split_if_better(struct blame_scoreboard *sb, 990struct blame_entry *best_so_far, 991struct blame_entry *this) 992{ 993int i; 994 995if(!this[1].suspect) 996return; 997if(best_so_far[1].suspect) { 998if(blame_entry_score(sb, &this[1]) <blame_entry_score(sb, &best_so_far[1])) 999return;1000}10011002for(i =0; i <3; i++)1003blame_origin_incref(this[i].suspect);1004decref_split(best_so_far);1005memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1006}10071008/*1009 * We are looking at a part of the final image represented by1010 * ent (tlno and same are offset by ent->s_lno).1011 * tlno is where we are looking at in the final image.1012 * up to (but not including) same match preimage.1013 * plno is where we are looking at in the preimage.1014 *1015 * <-------------- final image ---------------------->1016 * <------ent------>1017 * ^tlno ^same1018 * <---------preimage----->1019 * ^plno1020 *1021 * All line numbers are 0-based.1022 */1023static voidhandle_split(struct blame_scoreboard *sb,1024struct blame_entry *ent,1025int tlno,int plno,int same,1026struct blame_origin *parent,1027struct blame_entry *split)1028{1029if(ent->num_lines <= tlno)1030return;1031if(tlno < same) {1032struct blame_entry this[3];1033 tlno += ent->s_lno;1034 same += ent->s_lno;1035split_overlap(this, ent, tlno, plno, same, parent);1036copy_split_if_better(sb, split,this);1037decref_split(this);1038}1039}10401041struct handle_split_cb_data {1042struct blame_scoreboard *sb;1043struct blame_entry *ent;1044struct blame_origin *parent;1045struct blame_entry *split;1046long plno;1047long tlno;1048};10491050static inthandle_split_cb(long start_a,long count_a,1051long start_b,long count_b,void*data)1052{1053struct handle_split_cb_data *d = data;1054handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1055 d->split);1056 d->plno = start_a + count_a;1057 d->tlno = start_b + count_b;1058return0;1059}10601061/*1062 * Find the lines from parent that are the same as ent so that1063 * we can pass blames to it. file_p has the blob contents for1064 * the parent.1065 */1066static voidfind_copy_in_blob(struct blame_scoreboard *sb,1067struct blame_entry *ent,1068struct blame_origin *parent,1069struct blame_entry *split,1070 mmfile_t *file_p)1071{1072const char*cp;1073 mmfile_t file_o;1074struct handle_split_cb_data d;10751076memset(&d,0,sizeof(d));1077 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1078/*1079 * Prepare mmfile that contains only the lines in ent.1080 */1081 cp =nth_line(sb, ent->lno);1082 file_o.ptr = (char*) cp;1083 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;10841085/*1086 * file_o is a part of final image we are annotating.1087 * file_p partially may match that image.1088 */1089memset(split,0,sizeof(struct blame_entry [3]));1090if(diff_hunks(file_p, &file_o, handle_split_cb, &d))1091die("unable to generate diff (%s)",1092oid_to_hex(&parent->commit->object.oid));1093/* remainder, if any, all match the preimage */1094handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1095}10961097/* Move all blame entries from list *source that have a score smaller1098 * than score_min to the front of list *small.1099 * Returns a pointer to the link pointing to the old head of the small list.1100 */11011102static struct blame_entry **filter_small(struct blame_scoreboard *sb,1103struct blame_entry **small,1104struct blame_entry **source,1105unsigned score_min)1106{1107struct blame_entry *p = *source;1108struct blame_entry *oldsmall = *small;1109while(p) {1110if(blame_entry_score(sb, p) <= score_min) {1111*small = p;1112 small = &p->next;1113 p = *small;1114}else{1115*source = p;1116 source = &p->next;1117 p = *source;1118}1119}1120*small = oldsmall;1121*source = NULL;1122return small;1123}11241125/*1126 * See if lines currently target is suspected for can be attributed to1127 * parent.1128 */1129static voidfind_move_in_parent(struct blame_scoreboard *sb,1130struct blame_entry ***blamed,1131struct blame_entry **toosmall,1132struct blame_origin *target,1133struct blame_origin *parent)1134{1135struct blame_entry *e, split[3];1136struct blame_entry *unblamed = target->suspects;1137struct blame_entry *leftover = NULL;1138 mmfile_t file_p;11391140if(!unblamed)1141return;/* nothing remains for this target */11421143fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1144if(!file_p.ptr)1145return;11461147/* At each iteration, unblamed has a NULL-terminated list of1148 * entries that have not yet been tested for blame. leftover1149 * contains the reversed list of entries that have been tested1150 * without being assignable to the parent.1151 */1152do{1153struct blame_entry **unblamedtail = &unblamed;1154struct blame_entry *next;1155for(e = unblamed; e; e = next) {1156 next = e->next;1157find_copy_in_blob(sb, e, parent, split, &file_p);1158if(split[1].suspect &&1159 blame_move_score <blame_entry_score(sb, &split[1])) {1160split_blame(blamed, &unblamedtail, split, e);1161}else{1162 e->next = leftover;1163 leftover = e;1164}1165decref_split(split);1166}1167*unblamedtail = NULL;1168 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1169}while(unblamed);1170 target->suspects =reverse_blame(leftover, NULL);1171}11721173struct blame_list {1174struct blame_entry *ent;1175struct blame_entry split[3];1176};11771178/*1179 * Count the number of entries the target is suspected for,1180 * and prepare a list of entry and the best split.1181 */1182static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1183int*num_ents_p)1184{1185struct blame_entry *e;1186int num_ents, i;1187struct blame_list *blame_list = NULL;11881189for(e = unblamed, num_ents =0; e; e = e->next)1190 num_ents++;1191if(num_ents) {1192 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1193for(e = unblamed, i =0; e; e = e->next)1194 blame_list[i++].ent = e;1195}1196*num_ents_p = num_ents;1197return blame_list;1198}11991200/*1201 * For lines target is suspected for, see if we can find code movement1202 * across file boundary from the parent commit. porigin is the path1203 * in the parent we already tried.1204 */1205static voidfind_copy_in_parent(struct blame_scoreboard *sb,1206struct blame_entry ***blamed,1207struct blame_entry **toosmall,1208struct blame_origin *target,1209struct commit *parent,1210struct blame_origin *porigin,1211int opt)1212{1213struct diff_options diff_opts;1214int i, j;1215struct blame_list *blame_list;1216int num_ents;1217struct blame_entry *unblamed = target->suspects;1218struct blame_entry *leftover = NULL;12191220if(!unblamed)1221return;/* nothing remains for this target */12221223diff_setup(&diff_opts);1224DIFF_OPT_SET(&diff_opts, RECURSIVE);1225 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12261227diff_setup_done(&diff_opts);12281229/* Try "find copies harder" on new path if requested;1230 * we do not want to use diffcore_rename() actually to1231 * match things up; find_copies_harder is set only to1232 * force diff_tree_sha1() to feed all filepairs to diff_queue,1233 * and this code needs to be after diff_setup_done(), which1234 * usually makes find-copies-harder imply copy detection.1235 */1236if((opt & PICKAXE_BLAME_COPY_HARDEST)1237|| ((opt & PICKAXE_BLAME_COPY_HARDER)1238&& (!porigin ||strcmp(target->path, porigin->path))))1239DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12401241if(is_null_oid(&target->commit->object.oid))1242do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1243else1244diff_tree_sha1(parent->tree->object.oid.hash,1245 target->commit->tree->object.oid.hash,1246"", &diff_opts);12471248if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1249diffcore_std(&diff_opts);12501251do{1252struct blame_entry **unblamedtail = &unblamed;1253 blame_list =setup_blame_list(unblamed, &num_ents);12541255for(i =0; i < diff_queued_diff.nr; i++) {1256struct diff_filepair *p = diff_queued_diff.queue[i];1257struct blame_origin *norigin;1258 mmfile_t file_p;1259struct blame_entry this[3];12601261if(!DIFF_FILE_VALID(p->one))1262continue;/* does not exist in parent */1263if(S_ISGITLINK(p->one->mode))1264continue;/* ignore git links */1265if(porigin && !strcmp(p->one->path, porigin->path))1266/* find_move already dealt with this path */1267continue;12681269 norigin =get_origin(parent, p->one->path);1270oidcpy(&norigin->blob_oid, &p->one->oid);1271 norigin->mode = p->one->mode;1272fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1273if(!file_p.ptr)1274continue;12751276for(j =0; j < num_ents; j++) {1277find_copy_in_blob(sb, blame_list[j].ent,1278 norigin,this, &file_p);1279copy_split_if_better(sb, blame_list[j].split,1280this);1281decref_split(this);1282}1283blame_origin_decref(norigin);1284}12851286for(j =0; j < num_ents; j++) {1287struct blame_entry *split = blame_list[j].split;1288if(split[1].suspect &&1289 blame_copy_score <blame_entry_score(sb, &split[1])) {1290split_blame(blamed, &unblamedtail, split,1291 blame_list[j].ent);1292}else{1293 blame_list[j].ent->next = leftover;1294 leftover = blame_list[j].ent;1295}1296decref_split(split);1297}1298free(blame_list);1299*unblamedtail = NULL;1300 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1301}while(unblamed);1302 target->suspects =reverse_blame(leftover, NULL);1303diff_flush(&diff_opts);1304clear_pathspec(&diff_opts.pathspec);1305}13061307/*1308 * The blobs of origin and porigin exactly match, so everything1309 * origin is suspected for can be blamed on the parent.1310 */1311static voidpass_whole_blame(struct blame_scoreboard *sb,1312struct blame_origin *origin,struct blame_origin *porigin)1313{1314struct blame_entry *e, *suspects;13151316if(!porigin->file.ptr && origin->file.ptr) {1317/* Steal its file */1318 porigin->file = origin->file;1319 origin->file.ptr = NULL;1320}1321 suspects = origin->suspects;1322 origin->suspects = NULL;1323for(e = suspects; e; e = e->next) {1324blame_origin_incref(porigin);1325blame_origin_decref(e->suspect);1326 e->suspect = porigin;1327}1328queue_blames(sb, porigin, suspects);1329}13301331/*1332 * We pass blame from the current commit to its parents. We keep saying1333 * "parent" (and "porigin"), but what we mean is to find scapegoat to1334 * exonerate ourselves.1335 */1336static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1337{1338if(!reverse) {1339if(revs->first_parent_only &&1340 commit->parents &&1341 commit->parents->next) {1342free_commit_list(commit->parents->next);1343 commit->parents->next = NULL;1344}1345return commit->parents;1346}1347returnlookup_decoration(&revs->children, &commit->object);1348}13491350static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1351{1352struct commit_list *l =first_scapegoat(revs, commit);1353returncommit_list_count(l);1354}13551356/* Distribute collected unsorted blames to the respected sorted lists1357 * in the various origins.1358 */1359static voiddistribute_blame(struct blame_scoreboard *sb,struct blame_entry *blamed)1360{1361 blamed =blame_sort(blamed, compare_blame_suspect);1362while(blamed)1363{1364struct blame_origin *porigin = blamed->suspect;1365struct blame_entry *suspects = NULL;1366do{1367struct blame_entry *next = blamed->next;1368 blamed->next = suspects;1369 suspects = blamed;1370 blamed = next;1371}while(blamed && blamed->suspect == porigin);1372 suspects =reverse_blame(suspects, NULL);1373queue_blames(sb, porigin, suspects);1374}1375}13761377#define MAXSG 1613781379static voidpass_blame(struct blame_scoreboard *sb,struct blame_origin *origin,int opt)1380{1381struct rev_info *revs = sb->revs;1382int i, pass, num_sg;1383struct commit *commit = origin->commit;1384struct commit_list *sg;1385struct blame_origin *sg_buf[MAXSG];1386struct blame_origin *porigin, **sg_origin = sg_buf;1387struct blame_entry *toosmall = NULL;1388struct blame_entry *blames, **blametail = &blames;13891390 num_sg =num_scapegoats(revs, commit);1391if(!num_sg)1392goto finish;1393else if(num_sg <ARRAY_SIZE(sg_buf))1394memset(sg_buf,0,sizeof(sg_buf));1395else1396 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));13971398/*1399 * The first pass looks for unrenamed path to optimize for1400 * common cases, then we look for renames in the second pass.1401 */1402for(pass =0; pass <2- no_whole_file_rename; pass++) {1403struct blame_origin *(*find)(struct commit *,struct blame_origin *);1404 find = pass ? find_rename : find_origin;14051406for(i =0, sg =first_scapegoat(revs, commit);1407 i < num_sg && sg;1408 sg = sg->next, i++) {1409struct commit *p = sg->item;1410int j, same;14111412if(sg_origin[i])1413continue;1414if(parse_commit(p))1415continue;1416 porigin =find(p, origin);1417if(!porigin)1418continue;1419if(!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {1420pass_whole_blame(sb, origin, porigin);1421blame_origin_decref(porigin);1422goto finish;1423}1424for(j = same =0; j < i; j++)1425if(sg_origin[j] &&1426!oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {1427 same =1;1428break;1429}1430if(!same)1431 sg_origin[i] = porigin;1432else1433blame_origin_decref(porigin);1434}1435}14361437 num_commits++;1438for(i =0, sg =first_scapegoat(revs, commit);1439 i < num_sg && sg;1440 sg = sg->next, i++) {1441struct blame_origin *porigin = sg_origin[i];1442if(!porigin)1443continue;1444if(!origin->previous) {1445blame_origin_incref(porigin);1446 origin->previous = porigin;1447}1448pass_blame_to_parent(sb, origin, porigin);1449if(!origin->suspects)1450goto finish;1451}14521453/*1454 * Optionally find moves in parents' files.1455 */1456if(opt & PICKAXE_BLAME_MOVE) {1457filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1458if(origin->suspects) {1459for(i =0, sg =first_scapegoat(revs, commit);1460 i < num_sg && sg;1461 sg = sg->next, i++) {1462struct blame_origin *porigin = sg_origin[i];1463if(!porigin)1464continue;1465find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1466if(!origin->suspects)1467break;1468}1469}1470}14711472/*1473 * Optionally find copies from parents' files.1474 */1475if(opt & PICKAXE_BLAME_COPY) {1476if(blame_copy_score > blame_move_score)1477filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1478else if(blame_copy_score < blame_move_score) {1479 origin->suspects =blame_merge(origin->suspects, toosmall);1480 toosmall = NULL;1481filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1482}1483if(!origin->suspects)1484goto finish;14851486for(i =0, sg =first_scapegoat(revs, commit);1487 i < num_sg && sg;1488 sg = sg->next, i++) {1489struct blame_origin *porigin = sg_origin[i];1490find_copy_in_parent(sb, &blametail, &toosmall,1491 origin, sg->item, porigin, opt);1492if(!origin->suspects)1493goto finish;1494}1495}14961497finish:1498*blametail = NULL;1499distribute_blame(sb, blames);1500/*1501 * prepend toosmall to origin->suspects1502 *1503 * There is no point in sorting: this ends up on a big1504 * unsorted list in the caller anyway.1505 */1506if(toosmall) {1507struct blame_entry **tail = &toosmall;1508while(*tail)1509 tail = &(*tail)->next;1510*tail = origin->suspects;1511 origin->suspects = toosmall;1512}1513for(i =0; i < num_sg; i++) {1514if(sg_origin[i]) {1515drop_origin_blob(sg_origin[i]);1516blame_origin_decref(sg_origin[i]);1517}1518}1519drop_origin_blob(origin);1520if(sg_buf != sg_origin)1521free(sg_origin);1522}15231524/*1525 * Information on commits, used for output.1526 */1527struct commit_info {1528struct strbuf author;1529struct strbuf author_mail;1530 timestamp_t author_time;1531struct strbuf author_tz;15321533/* filled only when asked for details */1534struct strbuf committer;1535struct strbuf committer_mail;1536 timestamp_t committer_time;1537struct strbuf committer_tz;15381539struct strbuf summary;1540};15411542/*1543 * Parse author/committer line in the commit object buffer1544 */1545static voidget_ac_line(const char*inbuf,const char*what,1546struct strbuf *name,struct strbuf *mail,1547 timestamp_t *time,struct strbuf *tz)1548{1549struct ident_split ident;1550size_t len, maillen, namelen;1551char*tmp, *endp;1552const char*namebuf, *mailbuf;15531554 tmp =strstr(inbuf, what);1555if(!tmp)1556goto error_out;1557 tmp +=strlen(what);1558 endp =strchr(tmp,'\n');1559if(!endp)1560 len =strlen(tmp);1561else1562 len = endp - tmp;15631564if(split_ident_line(&ident, tmp, len)) {1565 error_out:1566/* Ugh */1567 tmp ="(unknown)";1568strbuf_addstr(name, tmp);1569strbuf_addstr(mail, tmp);1570strbuf_addstr(tz, tmp);1571*time =0;1572return;1573}15741575 namelen = ident.name_end - ident.name_begin;1576 namebuf = ident.name_begin;15771578 maillen = ident.mail_end - ident.mail_begin;1579 mailbuf = ident.mail_begin;15801581if(ident.date_begin && ident.date_end)1582*time =strtoul(ident.date_begin, NULL,10);1583else1584*time =0;15851586if(ident.tz_begin && ident.tz_end)1587strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1588else1589strbuf_addstr(tz,"(unknown)");15901591/*1592 * Now, convert both name and e-mail using mailmap1593 */1594map_user(&mailmap, &mailbuf, &maillen,1595&namebuf, &namelen);15961597strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1598strbuf_add(name, namebuf, namelen);1599}16001601static voidcommit_info_init(struct commit_info *ci)1602{16031604strbuf_init(&ci->author,0);1605strbuf_init(&ci->author_mail,0);1606strbuf_init(&ci->author_tz,0);1607strbuf_init(&ci->committer,0);1608strbuf_init(&ci->committer_mail,0);1609strbuf_init(&ci->committer_tz,0);1610strbuf_init(&ci->summary,0);1611}16121613static voidcommit_info_destroy(struct commit_info *ci)1614{16151616strbuf_release(&ci->author);1617strbuf_release(&ci->author_mail);1618strbuf_release(&ci->author_tz);1619strbuf_release(&ci->committer);1620strbuf_release(&ci->committer_mail);1621strbuf_release(&ci->committer_tz);1622strbuf_release(&ci->summary);1623}16241625static voidget_commit_info(struct commit *commit,1626struct commit_info *ret,1627int detailed)1628{1629int len;1630const char*subject, *encoding;1631const char*message;16321633commit_info_init(ret);16341635 encoding =get_log_output_encoding();1636 message =logmsg_reencode(commit, NULL, encoding);1637get_ac_line(message,"\nauthor ",1638&ret->author, &ret->author_mail,1639&ret->author_time, &ret->author_tz);16401641if(!detailed) {1642unuse_commit_buffer(commit, message);1643return;1644}16451646get_ac_line(message,"\ncommitter ",1647&ret->committer, &ret->committer_mail,1648&ret->committer_time, &ret->committer_tz);16491650 len =find_commit_subject(message, &subject);1651if(len)1652strbuf_add(&ret->summary, subject, len);1653else1654strbuf_addf(&ret->summary,"(%s)",oid_to_hex(&commit->object.oid));16551656unuse_commit_buffer(commit, message);1657}16581659/*1660 * Write out any suspect information which depends on the path. This must be1661 * handled separately from emit_one_suspect_detail(), because a given commit1662 * may have changes in multiple paths. So this needs to appear each time1663 * we mention a new group.1664 *1665 * To allow LF and other nonportable characters in pathnames,1666 * they are c-style quoted as needed.1667 */1668static voidwrite_filename_info(struct blame_origin *suspect)1669{1670if(suspect->previous) {1671struct blame_origin *prev = suspect->previous;1672printf("previous%s",oid_to_hex(&prev->commit->object.oid));1673write_name_quoted(prev->path, stdout,'\n');1674}1675printf("filename ");1676write_name_quoted(suspect->path, stdout,'\n');1677}16781679/*1680 * Porcelain/Incremental format wants to show a lot of details per1681 * commit. Instead of repeating this every line, emit it only once,1682 * the first time each commit appears in the output (unless the1683 * user has specifically asked for us to repeat).1684 */1685static intemit_one_suspect_detail(struct blame_origin *suspect,int repeat)1686{1687struct commit_info ci;16881689if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1690return0;16911692 suspect->commit->object.flags |= METAINFO_SHOWN;1693get_commit_info(suspect->commit, &ci,1);1694printf("author%s\n", ci.author.buf);1695printf("author-mail%s\n", ci.author_mail.buf);1696printf("author-time %"PRItime"\n", ci.author_time);1697printf("author-tz%s\n", ci.author_tz.buf);1698printf("committer%s\n", ci.committer.buf);1699printf("committer-mail%s\n", ci.committer_mail.buf);1700printf("committer-time %"PRItime"\n", ci.committer_time);1701printf("committer-tz%s\n", ci.committer_tz.buf);1702printf("summary%s\n", ci.summary.buf);1703if(suspect->commit->object.flags & UNINTERESTING)1704printf("boundary\n");17051706commit_info_destroy(&ci);17071708return1;1709}17101711/*1712 * The blame_entry is found to be guilty for the range.1713 * Show it in incremental output.1714 */1715static voidfound_guilty_entry(struct blame_entry *ent,1716struct progress_info *pi)1717{1718if(incremental) {1719struct blame_origin *suspect = ent->suspect;17201721printf("%s %d %d %d\n",1722oid_to_hex(&suspect->commit->object.oid),1723 ent->s_lno +1, ent->lno +1, ent->num_lines);1724emit_one_suspect_detail(suspect,0);1725write_filename_info(suspect);1726maybe_flush_or_die(stdout,"stdout");1727}1728 pi->blamed_lines += ent->num_lines;1729display_progress(pi->progress, pi->blamed_lines);1730}17311732/*1733 * The main loop -- while we have blobs with lines whose true origin1734 * is still unknown, pick one blob, and allow its lines to pass blames1735 * to its parents. */1736static voidassign_blame(struct blame_scoreboard *sb,int opt)1737{1738struct rev_info *revs = sb->revs;1739struct commit *commit =prio_queue_get(&sb->commits);1740struct progress_info pi = { NULL,0};17411742if(show_progress)1743 pi.progress =start_progress_delay(_("Blaming lines"),1744 sb->num_lines,50,1);17451746while(commit) {1747struct blame_entry *ent;1748struct blame_origin *suspect = commit->util;17491750/* find one suspect to break down */1751while(suspect && !suspect->suspects)1752 suspect = suspect->next;17531754if(!suspect) {1755 commit =prio_queue_get(&sb->commits);1756continue;1757}17581759assert(commit == suspect->commit);17601761/*1762 * We will use this suspect later in the loop,1763 * so hold onto it in the meantime.1764 */1765blame_origin_incref(suspect);1766parse_commit(commit);1767if(reverse ||1768(!(commit->object.flags & UNINTERESTING) &&1769!(revs->max_age != -1&& commit->date < revs->max_age)))1770pass_blame(sb, suspect, opt);1771else{1772 commit->object.flags |= UNINTERESTING;1773if(commit->object.parsed)1774mark_parents_uninteresting(commit);1775}1776/* treat root commit as boundary */1777if(!commit->parents && !show_root)1778 commit->object.flags |= UNINTERESTING;17791780/* Take responsibility for the remaining entries */1781 ent = suspect->suspects;1782if(ent) {1783 suspect->guilty =1;1784for(;;) {1785struct blame_entry *next = ent->next;1786found_guilty_entry(ent, &pi);1787if(next) {1788 ent = next;1789continue;1790}1791 ent->next = sb->ent;1792 sb->ent = suspect->suspects;1793 suspect->suspects = NULL;1794break;1795}1796}1797blame_origin_decref(suspect);17981799if(DEBUG)/* sanity */1800sanity_check_refcnt(sb);1801}18021803stop_progress(&pi.progress);1804}18051806static const char*format_time(timestamp_t time,const char*tz_str,1807int show_raw_time)1808{1809static struct strbuf time_buf = STRBUF_INIT;18101811strbuf_reset(&time_buf);1812if(show_raw_time) {1813strbuf_addf(&time_buf,"%"PRItime"%s", time, tz_str);1814}1815else{1816const char*time_str;1817size_t time_width;1818int tz;1819 tz =atoi(tz_str);1820 time_str =show_date(time, tz, &blame_date_mode);1821strbuf_addstr(&time_buf, time_str);1822/*1823 * Add space paddings to time_buf to display a fixed width1824 * string, and use time_width for display width calibration.1825 */1826for(time_width =utf8_strwidth(time_str);1827 time_width < blame_date_width;1828 time_width++)1829strbuf_addch(&time_buf,' ');1830}1831return time_buf.buf;1832}18331834#define OUTPUT_ANNOTATE_COMPAT 0011835#define OUTPUT_LONG_OBJECT_NAME 0021836#define OUTPUT_RAW_TIMESTAMP 0041837#define OUTPUT_PORCELAIN 0101838#define OUTPUT_SHOW_NAME 0201839#define OUTPUT_SHOW_NUMBER 0401840#define OUTPUT_SHOW_SCORE 01001841#define OUTPUT_NO_AUTHOR 02001842#define OUTPUT_SHOW_EMAIL 04001843#define OUTPUT_LINE_PORCELAIN 0100018441845static voidemit_porcelain_details(struct blame_origin *suspect,int repeat)1846{1847if(emit_one_suspect_detail(suspect, repeat) ||1848(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1849write_filename_info(suspect);1850}18511852static voidemit_porcelain(struct blame_scoreboard *sb,struct blame_entry *ent,1853int opt)1854{1855int repeat = opt & OUTPUT_LINE_PORCELAIN;1856int cnt;1857const char*cp;1858struct blame_origin *suspect = ent->suspect;1859char hex[GIT_MAX_HEXSZ +1];18601861oid_to_hex_r(hex, &suspect->commit->object.oid);1862printf("%s %d %d %d\n",1863 hex,1864 ent->s_lno +1,1865 ent->lno +1,1866 ent->num_lines);1867emit_porcelain_details(suspect, repeat);18681869 cp =nth_line(sb, ent->lno);1870for(cnt =0; cnt < ent->num_lines; cnt++) {1871char ch;1872if(cnt) {1873printf("%s %d %d\n", hex,1874 ent->s_lno +1+ cnt,1875 ent->lno +1+ cnt);1876if(repeat)1877emit_porcelain_details(suspect,1);1878}1879putchar('\t');1880do{1881 ch = *cp++;1882putchar(ch);1883}while(ch !='\n'&&1884 cp < sb->final_buf + sb->final_buf_size);1885}18861887if(sb->final_buf_size && cp[-1] !='\n')1888putchar('\n');1889}18901891static voidemit_other(struct blame_scoreboard *sb,struct blame_entry *ent,int opt)1892{1893int cnt;1894const char*cp;1895struct blame_origin *suspect = ent->suspect;1896struct commit_info ci;1897char hex[GIT_MAX_HEXSZ +1];1898int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);18991900get_commit_info(suspect->commit, &ci,1);1901oid_to_hex_r(hex, &suspect->commit->object.oid);19021903 cp =nth_line(sb, ent->lno);1904for(cnt =0; cnt < ent->num_lines; cnt++) {1905char ch;1906int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? GIT_SHA1_HEXSZ : abbrev;19071908if(suspect->commit->object.flags & UNINTERESTING) {1909if(blank_boundary)1910memset(hex,' ', length);1911else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1912 length--;1913putchar('^');1914}1915}19161917printf("%.*s", length, hex);1918if(opt & OUTPUT_ANNOTATE_COMPAT) {1919const char*name;1920if(opt & OUTPUT_SHOW_EMAIL)1921 name = ci.author_mail.buf;1922else1923 name = ci.author.buf;1924printf("\t(%10s\t%10s\t%d)", name,1925format_time(ci.author_time, ci.author_tz.buf,1926 show_raw_time),1927 ent->lno +1+ cnt);1928}else{1929if(opt & OUTPUT_SHOW_SCORE)1930printf(" %*d%02d",1931 max_score_digits, ent->score,1932 ent->suspect->refcnt);1933if(opt & OUTPUT_SHOW_NAME)1934printf(" %-*.*s", longest_file, longest_file,1935 suspect->path);1936if(opt & OUTPUT_SHOW_NUMBER)1937printf(" %*d", max_orig_digits,1938 ent->s_lno +1+ cnt);19391940if(!(opt & OUTPUT_NO_AUTHOR)) {1941const char*name;1942int pad;1943if(opt & OUTPUT_SHOW_EMAIL)1944 name = ci.author_mail.buf;1945else1946 name = ci.author.buf;1947 pad = longest_author -utf8_strwidth(name);1948printf(" (%s%*s%10s",1949 name, pad,"",1950format_time(ci.author_time,1951 ci.author_tz.buf,1952 show_raw_time));1953}1954printf(" %*d) ",1955 max_digits, ent->lno +1+ cnt);1956}1957do{1958 ch = *cp++;1959putchar(ch);1960}while(ch !='\n'&&1961 cp < sb->final_buf + sb->final_buf_size);1962}19631964if(sb->final_buf_size && cp[-1] !='\n')1965putchar('\n');19661967commit_info_destroy(&ci);1968}19691970static voidoutput(struct blame_scoreboard *sb,int option)1971{1972struct blame_entry *ent;19731974if(option & OUTPUT_PORCELAIN) {1975for(ent = sb->ent; ent; ent = ent->next) {1976int count =0;1977struct blame_origin *suspect;1978struct commit *commit = ent->suspect->commit;1979if(commit->object.flags & MORE_THAN_ONE_PATH)1980continue;1981for(suspect = commit->util; suspect; suspect = suspect->next) {1982if(suspect->guilty && count++) {1983 commit->object.flags |= MORE_THAN_ONE_PATH;1984break;1985}1986}1987}1988}19891990for(ent = sb->ent; ent; ent = ent->next) {1991if(option & OUTPUT_PORCELAIN)1992emit_porcelain(sb, ent, option);1993else{1994emit_other(sb, ent, option);1995}1996}1997}19981999static const char*get_next_line(const char*start,const char*end)2000{2001const char*nl =memchr(start,'\n', end - start);2002return nl ? nl +1: end;2003}20042005/*2006 * To allow quick access to the contents of nth line in the2007 * final image, prepare an index in the scoreboard.2008 */2009static intprepare_lines(struct blame_scoreboard *sb)2010{2011const char*buf = sb->final_buf;2012unsigned long len = sb->final_buf_size;2013const char*end = buf + len;2014const char*p;2015int*lineno;2016int num =0;20172018for(p = buf; p < end; p =get_next_line(p, end))2019 num++;20202021ALLOC_ARRAY(sb->lineno, num +1);2022 lineno = sb->lineno;20232024for(p = buf; p < end; p =get_next_line(p, end))2025*lineno++ = p - buf;20262027*lineno = len;20282029 sb->num_lines = num;2030return sb->num_lines;2031}20322033/*2034 * Add phony grafts for use with -S; this is primarily to2035 * support git's cvsserver that wants to give a linear history2036 * to its clients.2037 */2038static intread_ancestry(const char*graft_file)2039{2040FILE*fp =fopen(graft_file,"r");2041struct strbuf buf = STRBUF_INIT;2042if(!fp)2043return-1;2044while(!strbuf_getwholeline(&buf, fp,'\n')) {2045/* The format is just "Commit Parent1 Parent2 ...\n" */2046struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2047if(graft)2048register_commit_graft(graft,0);2049}2050fclose(fp);2051strbuf_release(&buf);2052return0;2053}20542055static intupdate_auto_abbrev(int auto_abbrev,struct blame_origin *suspect)2056{2057const char*uniq =find_unique_abbrev(suspect->commit->object.oid.hash,2058 auto_abbrev);2059int len =strlen(uniq);2060if(auto_abbrev < len)2061return len;2062return auto_abbrev;2063}20642065/*2066 * How many columns do we need to show line numbers, authors,2067 * and filenames?2068 */2069static voidfind_alignment(struct blame_scoreboard *sb,int*option)2070{2071int longest_src_lines =0;2072int longest_dst_lines =0;2073unsigned largest_score =0;2074struct blame_entry *e;2075int compute_auto_abbrev = (abbrev <0);2076int auto_abbrev = DEFAULT_ABBREV;20772078for(e = sb->ent; e; e = e->next) {2079struct blame_origin *suspect = e->suspect;2080int num;20812082if(compute_auto_abbrev)2083 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2084if(strcmp(suspect->path, sb->path))2085*option |= OUTPUT_SHOW_NAME;2086 num =strlen(suspect->path);2087if(longest_file < num)2088 longest_file = num;2089if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2090struct commit_info ci;2091 suspect->commit->object.flags |= METAINFO_SHOWN;2092get_commit_info(suspect->commit, &ci,1);2093if(*option & OUTPUT_SHOW_EMAIL)2094 num =utf8_strwidth(ci.author_mail.buf);2095else2096 num =utf8_strwidth(ci.author.buf);2097if(longest_author < num)2098 longest_author = num;2099commit_info_destroy(&ci);2100}2101 num = e->s_lno + e->num_lines;2102if(longest_src_lines < num)2103 longest_src_lines = num;2104 num = e->lno + e->num_lines;2105if(longest_dst_lines < num)2106 longest_dst_lines = num;2107if(largest_score <blame_entry_score(sb, e))2108 largest_score =blame_entry_score(sb, e);2109}2110 max_orig_digits =decimal_width(longest_src_lines);2111 max_digits =decimal_width(longest_dst_lines);2112 max_score_digits =decimal_width(largest_score);21132114if(compute_auto_abbrev)2115/* one more abbrev length is needed for the boundary commit */2116 abbrev = auto_abbrev +1;2117}21182119/*2120 * For debugging -- origin is refcounted, and this asserts that2121 * we do not underflow.2122 */2123static voidsanity_check_refcnt(struct blame_scoreboard *sb)2124{2125int baa =0;2126struct blame_entry *ent;21272128for(ent = sb->ent; ent; ent = ent->next) {2129/* Nobody should have zero or negative refcnt */2130if(ent->suspect->refcnt <=0) {2131fprintf(stderr,"%sin%shas negative refcnt%d\n",2132 ent->suspect->path,2133oid_to_hex(&ent->suspect->commit->object.oid),2134 ent->suspect->refcnt);2135 baa =1;2136}2137}2138if(baa) {2139int opt =0160;2140find_alignment(sb, &opt);2141output(sb, opt);2142die("Baa%d!", baa);2143}2144}21452146static unsignedparse_score(const char*arg)2147{2148char*end;2149unsigned long score =strtoul(arg, &end,10);2150if(*end)2151return0;2152return score;2153}21542155static const char*add_prefix(const char*prefix,const char*path)2156{2157returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2158}21592160static intgit_blame_config(const char*var,const char*value,void*cb)2161{2162if(!strcmp(var,"blame.showroot")) {2163 show_root =git_config_bool(var, value);2164return0;2165}2166if(!strcmp(var,"blame.blankboundary")) {2167 blank_boundary =git_config_bool(var, value);2168return0;2169}2170if(!strcmp(var,"blame.showemail")) {2171int*output_option = cb;2172if(git_config_bool(var, value))2173*output_option |= OUTPUT_SHOW_EMAIL;2174else2175*output_option &= ~OUTPUT_SHOW_EMAIL;2176return0;2177}2178if(!strcmp(var,"blame.date")) {2179if(!value)2180returnconfig_error_nonbool(var);2181parse_date_format(value, &blame_date_mode);2182return0;2183}21842185if(git_diff_heuristic_config(var, value, cb) <0)2186return-1;2187if(userdiff_config(var, value) <0)2188return-1;21892190returngit_default_config(var, value, cb);2191}21922193static voidverify_working_tree_path(struct commit *work_tree,const char*path)2194{2195struct commit_list *parents;2196int pos;21972198for(parents = work_tree->parents; parents; parents = parents->next) {2199const struct object_id *commit_oid = &parents->item->object.oid;2200struct object_id blob_oid;2201unsigned mode;22022203if(!get_tree_entry(commit_oid->hash, path, blob_oid.hash, &mode) &&2204sha1_object_info(blob_oid.hash, NULL) == OBJ_BLOB)2205return;2206}22072208 pos =cache_name_pos(path,strlen(path));2209if(pos >=0)2210;/* path is in the index */2211else if(-1- pos < active_nr &&2212!strcmp(active_cache[-1- pos]->name, path))2213;/* path is in the index, unmerged */2214else2215die("no such path '%s' in HEAD", path);2216}22172218static struct commit_list **append_parent(struct commit_list **tail,const struct object_id *oid)2219{2220struct commit *parent;22212222 parent =lookup_commit_reference(oid->hash);2223if(!parent)2224die("no such commit%s",oid_to_hex(oid));2225return&commit_list_insert(parent, tail)->next;2226}22272228static voidappend_merge_parents(struct commit_list **tail)2229{2230int merge_head;2231struct strbuf line = STRBUF_INIT;22322233 merge_head =open(git_path_merge_head(), O_RDONLY);2234if(merge_head <0) {2235if(errno == ENOENT)2236return;2237die("cannot open '%s' for reading",git_path_merge_head());2238}22392240while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2241struct object_id oid;2242if(line.len < GIT_SHA1_HEXSZ ||get_oid_hex(line.buf, &oid))2243die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2244 tail =append_parent(tail, &oid);2245}2246close(merge_head);2247strbuf_release(&line);2248}22492250/*2251 * This isn't as simple as passing sb->buf and sb->len, because we2252 * want to transfer ownership of the buffer to the commit (so we2253 * must use detach).2254 */2255static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2256{2257size_t len;2258void*buf =strbuf_detach(sb, &len);2259set_commit_buffer(c, buf, len);2260}22612262/*2263 * Prepare a dummy commit that represents the work tree (or staged) item.2264 * Note that annotating work tree item never works in the reverse.2265 */2266static struct commit *fake_working_tree_commit(struct diff_options *opt,2267const char*path,2268const char*contents_from)2269{2270struct commit *commit;2271struct blame_origin *origin;2272struct commit_list **parent_tail, *parent;2273struct object_id head_oid;2274struct strbuf buf = STRBUF_INIT;2275const char*ident;2276time_t now;2277int size, len;2278struct cache_entry *ce;2279unsigned mode;2280struct strbuf msg = STRBUF_INIT;22812282read_cache();2283time(&now);2284 commit =alloc_commit_node();2285 commit->object.parsed =1;2286 commit->date = now;2287 parent_tail = &commit->parents;22882289if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_oid.hash, NULL))2290die("no such ref: HEAD");22912292 parent_tail =append_parent(parent_tail, &head_oid);2293append_merge_parents(parent_tail);2294verify_working_tree_path(commit, path);22952296 origin =make_origin(commit, path);22972298 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2299strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2300for(parent = commit->parents; parent; parent = parent->next)2301strbuf_addf(&msg,"parent%s\n",2302oid_to_hex(&parent->item->object.oid));2303strbuf_addf(&msg,2304"author%s\n"2305"committer%s\n\n"2306"Version of%sfrom%s\n",2307 ident, ident, path,2308(!contents_from ? path :2309(!strcmp(contents_from,"-") ?"standard input": contents_from)));2310set_commit_buffer_from_strbuf(commit, &msg);23112312if(!contents_from ||strcmp("-", contents_from)) {2313struct stat st;2314const char*read_from;2315char*buf_ptr;2316unsigned long buf_len;23172318if(contents_from) {2319if(stat(contents_from, &st) <0)2320die_errno("Cannot stat '%s'", contents_from);2321 read_from = contents_from;2322}2323else{2324if(lstat(path, &st) <0)2325die_errno("Cannot lstat '%s'", path);2326 read_from = path;2327}2328 mode =canon_mode(st.st_mode);23292330switch(st.st_mode & S_IFMT) {2331case S_IFREG:2332if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2333textconv_object(read_from, mode, &null_oid,0, &buf_ptr, &buf_len))2334strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2335else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2336die_errno("cannot open or read '%s'", read_from);2337break;2338case S_IFLNK:2339if(strbuf_readlink(&buf, read_from, st.st_size) <0)2340die_errno("cannot readlink '%s'", read_from);2341break;2342default:2343die("unsupported file type%s", read_from);2344}2345}2346else{2347/* Reading from stdin */2348 mode =0;2349if(strbuf_read(&buf,0,0) <0)2350die_errno("failed to read from stdin");2351}2352convert_to_git(path, buf.buf, buf.len, &buf,0);2353 origin->file.ptr = buf.buf;2354 origin->file.size = buf.len;2355pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_oid.hash);23562357/*2358 * Read the current index, replace the path entry with2359 * origin->blob_sha1 without mucking with its mode or type2360 * bits; we are not going to write this index out -- we just2361 * want to run "diff-index --cached".2362 */2363discard_cache();2364read_cache();23652366 len =strlen(path);2367if(!mode) {2368int pos =cache_name_pos(path, len);2369if(0<= pos)2370 mode = active_cache[pos]->ce_mode;2371else2372/* Let's not bother reading from HEAD tree */2373 mode = S_IFREG |0644;2374}2375 size =cache_entry_size(len);2376 ce =xcalloc(1, size);2377oidcpy(&ce->oid, &origin->blob_oid);2378memcpy(ce->name, path, len);2379 ce->ce_flags =create_ce_flags(0);2380 ce->ce_namelen = len;2381 ce->ce_mode =create_ce_mode(mode);2382add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23832384cache_tree_invalidate_path(&the_index, path);23852386return commit;2387}23882389static struct commit *find_single_final(struct rev_info *revs,2390const char**name_p)2391{2392int i;2393struct commit *found = NULL;2394const char*name = NULL;23952396for(i =0; i < revs->pending.nr; i++) {2397struct object *obj = revs->pending.objects[i].item;2398if(obj->flags & UNINTERESTING)2399continue;2400 obj =deref_tag(obj, NULL,0);2401if(obj->type != OBJ_COMMIT)2402die("Non commit%s?", revs->pending.objects[i].name);2403if(found)2404die("More than one commit to dig from%sand%s?",2405 revs->pending.objects[i].name, name);2406 found = (struct commit *)obj;2407 name = revs->pending.objects[i].name;2408}2409if(name_p)2410*name_p = name;2411return found;2412}24132414static char*prepare_final(struct blame_scoreboard *sb)2415{2416const char*name;2417 sb->final =find_single_final(sb->revs, &name);2418returnxstrdup_or_null(name);2419}24202421static const char*dwim_reverse_initial(struct blame_scoreboard *sb)2422{2423/*2424 * DWIM "git blame --reverse ONE -- PATH" as2425 * "git blame --reverse ONE..HEAD -- PATH" but only do so2426 * when it makes sense.2427 */2428struct object *obj;2429struct commit *head_commit;2430unsigned char head_sha1[20];24312432if(sb->revs->pending.nr !=1)2433return NULL;24342435/* Is that sole rev a committish? */2436 obj = sb->revs->pending.objects[0].item;2437 obj =deref_tag(obj, NULL,0);2438if(obj->type != OBJ_COMMIT)2439return NULL;24402441/* Do we have HEAD? */2442if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2443return NULL;2444 head_commit =lookup_commit_reference_gently(head_sha1,1);2445if(!head_commit)2446return NULL;24472448/* Turn "ONE" into "ONE..HEAD" then */2449 obj->flags |= UNINTERESTING;2450add_pending_object(sb->revs, &head_commit->object,"HEAD");24512452 sb->final = (struct commit *)obj;2453return sb->revs->pending.objects[0].name;2454}24552456static char*prepare_initial(struct blame_scoreboard *sb)2457{2458int i;2459const char*final_commit_name = NULL;2460struct rev_info *revs = sb->revs;24612462/*2463 * There must be one and only one negative commit, and it must be2464 * the boundary.2465 */2466for(i =0; i < revs->pending.nr; i++) {2467struct object *obj = revs->pending.objects[i].item;2468if(!(obj->flags & UNINTERESTING))2469continue;2470 obj =deref_tag(obj, NULL,0);2471if(obj->type != OBJ_COMMIT)2472die("Non commit%s?", revs->pending.objects[i].name);2473if(sb->final)2474die("More than one commit to dig up from,%sand%s?",2475 revs->pending.objects[i].name,2476 final_commit_name);2477 sb->final = (struct commit *) obj;2478 final_commit_name = revs->pending.objects[i].name;2479}24802481if(!final_commit_name)2482 final_commit_name =dwim_reverse_initial(sb);2483if(!final_commit_name)2484die("No commit to dig up from?");2485returnxstrdup(final_commit_name);2486}24872488static intblame_copy_callback(const struct option *option,const char*arg,int unset)2489{2490int*opt = option->value;24912492/*2493 * -C enables copy from removed files;2494 * -C -C enables copy from existing files, but only2495 * when blaming a new file;2496 * -C -C -C enables copy from existing files for2497 * everybody2498 */2499if(*opt & PICKAXE_BLAME_COPY_HARDER)2500*opt |= PICKAXE_BLAME_COPY_HARDEST;2501if(*opt & PICKAXE_BLAME_COPY)2502*opt |= PICKAXE_BLAME_COPY_HARDER;2503*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;25042505if(arg)2506 blame_copy_score =parse_score(arg);2507return0;2508}25092510static intblame_move_callback(const struct option *option,const char*arg,int unset)2511{2512int*opt = option->value;25132514*opt |= PICKAXE_BLAME_MOVE;25152516if(arg)2517 blame_move_score =parse_score(arg);2518return0;2519}25202521intcmd_blame(int argc,const char**argv,const char*prefix)2522{2523struct rev_info revs;2524const char*path;2525struct blame_scoreboard sb;2526struct blame_origin *o;2527struct blame_entry *ent = NULL;2528long dashdash_pos, lno;2529char*final_commit_name = NULL;2530enum object_type type;2531struct commit *final_commit = NULL;25322533struct string_list range_list = STRING_LIST_INIT_NODUP;2534int output_option =0, opt =0;2535int show_stats =0;2536const char*revs_file = NULL;2537const char*contents_from = NULL;2538const struct option options[] = {2539OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2540OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2541OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2542OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2543OPT_BOOL(0,"progress", &show_progress,N_("Force progress reporting")),2544OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2545OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2546OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2547OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2548OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2549OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2550OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2551OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2552OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2553OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2554OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),25552556/*2557 * The following two options are parsed by parse_revision_opt()2558 * and are only included here to get included in the "-h"2559 * output:2560 */2561{ OPTION_LOWLEVEL_CALLBACK,0,"indent-heuristic", NULL, NULL,N_("Use an experimental heuristic to improve diffs"), PARSE_OPT_NOARG, parse_opt_unknown_cb },25622563OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2564OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2565OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2566{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2567{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2568OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2569OPT__ABBREV(&abbrev),2570OPT_END()2571};25722573struct parse_opt_ctx_t ctx;2574int cmd_is_annotate = !strcmp(argv[0],"annotate");2575struct range_set ranges;2576unsigned int range_i;2577long anchor;25782579git_config(git_blame_config, &output_option);2580init_revisions(&revs, NULL);2581 revs.date_mode = blame_date_mode;2582DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2583DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25842585 save_commit_buffer =0;2586 dashdash_pos =0;2587 show_progress = -1;25882589parse_options_start(&ctx, argc, argv, prefix, options,2590 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2591for(;;) {2592switch(parse_options_step(&ctx, options, blame_opt_usage)) {2593case PARSE_OPT_HELP:2594exit(129);2595case PARSE_OPT_DONE:2596if(ctx.argv[0])2597 dashdash_pos = ctx.cpidx;2598goto parse_done;2599}26002601if(!strcmp(ctx.argv[0],"--reverse")) {2602 ctx.argv[0] ="--children";2603 reverse =1;2604}2605parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2606}2607parse_done:2608 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2609 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;2610DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2611 argc =parse_options_end(&ctx);26122613if(incremental || (output_option & OUTPUT_PORCELAIN)) {2614if(show_progress >0)2615die(_("--progress can't be used with --incremental or porcelain formats"));2616 show_progress =0;2617}else if(show_progress <0)2618 show_progress =isatty(2);26192620if(0< abbrev && abbrev < GIT_SHA1_HEXSZ)2621/* one more abbrev length is needed for the boundary commit */2622 abbrev++;2623else if(!abbrev)2624 abbrev = GIT_SHA1_HEXSZ;26252626if(revs_file &&read_ancestry(revs_file))2627die_errno("reading graft file '%s' failed", revs_file);26282629if(cmd_is_annotate) {2630 output_option |= OUTPUT_ANNOTATE_COMPAT;2631 blame_date_mode.type = DATE_ISO8601;2632}else{2633 blame_date_mode = revs.date_mode;2634}26352636/* The maximum width used to show the dates */2637switch(blame_date_mode.type) {2638case DATE_RFC2822:2639 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2640break;2641case DATE_ISO8601_STRICT:2642 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2643break;2644case DATE_ISO8601:2645 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2646break;2647case DATE_RAW:2648 blame_date_width =sizeof("1161298804 -0700");2649break;2650case DATE_UNIX:2651 blame_date_width =sizeof("1161298804");2652break;2653case DATE_SHORT:2654 blame_date_width =sizeof("2006-10-19");2655break;2656case DATE_RELATIVE:2657/* TRANSLATORS: This string is used to tell us the maximum2658 display width for a relative timestamp in "git blame"2659 output. For C locale, "4 years, 11 months ago", which2660 takes 22 places, is the longest among various forms of2661 relative timestamps, but your language may need more or2662 fewer display columns. */2663 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2664break;2665case DATE_NORMAL:2666 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2667break;2668case DATE_STRFTIME:2669 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2670break;2671}2672 blame_date_width -=1;/* strip the null */26732674if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2675 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2676 PICKAXE_BLAME_COPY_HARDER);26772678if(!blame_move_score)2679 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2680if(!blame_copy_score)2681 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26822683/*2684 * We have collected options unknown to us in argv[1..unk]2685 * which are to be passed to revision machinery if we are2686 * going to do the "bottom" processing.2687 *2688 * The remaining are:2689 *2690 * (1) if dashdash_pos != 0, it is either2691 * "blame [revisions] -- <path>" or2692 * "blame -- <path> <rev>"2693 *2694 * (2) otherwise, it is one of the two:2695 * "blame [revisions] <path>"2696 * "blame <path> <rev>"2697 *2698 * Note that we must strip out <path> from the arguments: we do not2699 * want the path pruning but we may want "bottom" processing.2700 */2701if(dashdash_pos) {2702switch(argc - dashdash_pos -1) {2703case2:/* (1b) */2704if(argc !=4)2705usage_with_options(blame_opt_usage, options);2706/* reorder for the new way: <rev> -- <path> */2707 argv[1] = argv[3];2708 argv[3] = argv[2];2709 argv[2] ="--";2710/* FALLTHROUGH */2711case1:/* (1a) */2712 path =add_prefix(prefix, argv[--argc]);2713 argv[argc] = NULL;2714break;2715default:2716usage_with_options(blame_opt_usage, options);2717}2718}else{2719if(argc <2)2720usage_with_options(blame_opt_usage, options);2721 path =add_prefix(prefix, argv[argc -1]);2722if(argc ==3&& !file_exists(path)) {/* (2b) */2723 path =add_prefix(prefix, argv[1]);2724 argv[1] = argv[2];2725}2726 argv[argc -1] ="--";27272728setup_work_tree();2729if(!file_exists(path))2730die_errno("cannot stat path '%s'", path);2731}27322733 revs.disable_stdin =1;2734setup_revisions(argc, argv, &revs, NULL);2735memset(&sb,0,sizeof(sb));27362737 sb.revs = &revs;2738if(!reverse) {2739 final_commit_name =prepare_final(&sb);2740 sb.commits.compare = compare_commits_by_commit_date;2741}2742else if(contents_from)2743die(_("--contents and --reverse do not blend well."));2744else{2745 final_commit_name =prepare_initial(&sb);2746 sb.commits.compare = compare_commits_by_reverse_commit_date;2747if(revs.first_parent_only)2748 revs.children.name = NULL;2749}27502751if(!sb.final) {2752/*2753 * "--not A B -- path" without anything positive;2754 * do not default to HEAD, but use the working tree2755 * or "--contents".2756 */2757setup_work_tree();2758 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2759 path, contents_from);2760add_pending_object(&revs, &(sb.final->object),":");2761}2762else if(contents_from)2763die(_("cannot use --contents with final commit object name"));27642765if(reverse && revs.first_parent_only) {2766 final_commit =find_single_final(sb.revs, NULL);2767if(!final_commit)2768die(_("--reverse and --first-parent together require specified latest commit"));2769}27702771/*2772 * If we have bottom, this will mark the ancestors of the2773 * bottom commits we would reach while traversing as2774 * uninteresting.2775 */2776if(prepare_revision_walk(&revs))2777die(_("revision walk setup failed"));27782779if(reverse && revs.first_parent_only) {2780struct commit *c = final_commit;27812782 sb.revs->children.name ="children";2783while(c->parents &&2784oidcmp(&c->object.oid, &sb.final->object.oid)) {2785struct commit_list *l =xcalloc(1,sizeof(*l));27862787 l->item = c;2788if(add_decoration(&sb.revs->children,2789&c->parents->item->object, l))2790die("BUG: not unique item in first-parent chain");2791 c = c->parents->item;2792}27932794if(oidcmp(&c->object.oid, &sb.final->object.oid))2795die(_("--reverse --first-parent together require range along first-parent chain"));2796}27972798if(is_null_oid(&sb.final->object.oid)) {2799 o = sb.final->util;2800 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2801 sb.final_buf_size = o->file.size;2802}2803else{2804 o =get_origin(sb.final, path);2805if(fill_blob_sha1_and_mode(o))2806die(_("no such path%sin%s"), path, final_commit_name);28072808if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2809textconv_object(path, o->mode, &o->blob_oid,1, (char**) &sb.final_buf,2810&sb.final_buf_size))2811;2812else2813 sb.final_buf =read_sha1_file(o->blob_oid.hash, &type,2814&sb.final_buf_size);28152816if(!sb.final_buf)2817die(_("cannot read blob%sfor path%s"),2818oid_to_hex(&o->blob_oid),2819 path);2820}2821 num_read_blob++;2822 lno =prepare_lines(&sb);28232824if(lno && !range_list.nr)2825string_list_append(&range_list,"1");28262827 anchor =1;2828range_set_init(&ranges, range_list.nr);2829for(range_i =0; range_i < range_list.nr; ++range_i) {2830long bottom, top;2831if(parse_range_arg(range_list.items[range_i].string,2832 nth_line_cb, &sb, lno, anchor,2833&bottom, &top, sb.path))2834usage(blame_usage);2835if(lno < top || ((lno || bottom) && lno < bottom))2836die(Q_("file%shas only%lu line",2837"file%shas only%lu lines",2838 lno), path, lno);2839if(bottom <1)2840 bottom =1;2841if(top <1)2842 top = lno;2843 bottom--;2844range_set_append_unsafe(&ranges, bottom, top);2845 anchor = top +1;2846}2847sort_and_merge_range_set(&ranges);28482849for(range_i = ranges.nr; range_i >0; --range_i) {2850const struct range *r = &ranges.ranges[range_i -1];2851long bottom = r->start;2852long top = r->end;2853struct blame_entry *next = ent;2854 ent =xcalloc(1,sizeof(*ent));2855 ent->lno = bottom;2856 ent->num_lines = top - bottom;2857 ent->suspect = o;2858 ent->s_lno = bottom;2859 ent->next = next;2860blame_origin_incref(o);2861}28622863 o->suspects = ent;2864prio_queue_put(&sb.commits, o->commit);28652866blame_origin_decref(o);28672868range_set_release(&ranges);2869string_list_clear(&range_list,0);28702871 sb.ent = NULL;2872 sb.path = path;28732874read_mailmap(&mailmap, NULL);28752876assign_blame(&sb, opt);28772878if(!incremental)2879setup_pager();28802881free(final_commit_name);28822883if(incremental)2884return0;28852886 sb.ent =blame_sort(sb.ent, compare_blame_final);28872888blame_coalesce(&sb);28892890if(!(output_option & OUTPUT_PORCELAIN))2891find_alignment(&sb, &output_option);28922893output(&sb, output_option);2894free((void*)sb.final_buf);2895for(ent = sb.ent; ent; ) {2896struct blame_entry *e = ent->next;2897free(ent);2898 ent = e;2899}29002901if(show_stats) {2902printf("num read blob:%d\n", num_read_blob);2903printf("num get patch:%d\n", num_get_patch);2904printf("num commits:%d\n", num_commits);2905}2906return0;2907}