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"blob.h" 12#include"commit.h" 13#include"tag.h" 14#include"tree-walk.h" 15#include"diff.h" 16#include"diffcore.h" 17#include"revision.h" 18#include"quote.h" 19#include"xdiff-interface.h" 20#include"cache-tree.h" 21#include"string-list.h" 22#include"mailmap.h" 23#include"mergesort.h" 24#include"parse-options.h" 25#include"prio-queue.h" 26#include"utf8.h" 27#include"userdiff.h" 28#include"line-range.h" 29#include"line-log.h" 30#include"dir.h" 31#include"progress.h" 32 33static char blame_usage[] =N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>"); 34 35static const char*blame_opt_usage[] = { 36 blame_usage, 37"", 38N_("<rev-opts> are documented in git-rev-list(1)"), 39 NULL 40}; 41 42static int longest_file; 43static int longest_author; 44static int max_orig_digits; 45static int max_digits; 46static int max_score_digits; 47static int show_root; 48static int reverse; 49static int blank_boundary; 50static int incremental; 51static int xdl_opts; 52static int abbrev = -1; 53static int no_whole_file_rename; 54static int show_progress; 55 56static struct date_mode blame_date_mode = { DATE_ISO8601 }; 57static size_t blame_date_width; 58 59static struct string_list mailmap; 60 61#ifndef DEBUG 62#define DEBUG 0 63#endif 64 65/* stats */ 66static int num_read_blob; 67static int num_get_patch; 68static int num_commits; 69 70#define PICKAXE_BLAME_MOVE 01 71#define PICKAXE_BLAME_COPY 02 72#define PICKAXE_BLAME_COPY_HARDER 04 73#define PICKAXE_BLAME_COPY_HARDEST 010 74 75/* 76 * blame for a blame_entry with score lower than these thresholds 77 * is not passed to the parent using move/copy logic. 78 */ 79static unsigned blame_move_score; 80static unsigned blame_copy_score; 81#define BLAME_DEFAULT_MOVE_SCORE 20 82#define BLAME_DEFAULT_COPY_SCORE 40 83 84/* Remember to update object flag allocation in object.h */ 85#define METAINFO_SHOWN (1u<<12) 86#define MORE_THAN_ONE_PATH (1u<<13) 87 88/* 89 * One blob in a commit that is being suspected 90 */ 91struct origin { 92int refcnt; 93/* Record preceding blame record for this blob */ 94struct origin *previous; 95/* origins are put in a list linked via `next' hanging off the 96 * corresponding commit's util field in order to make finding 97 * them fast. The presence in this chain does not count 98 * towards the origin's reference count. It is tempting to 99 * let it count as long as the commit is pending examination, 100 * but even under circumstances where the commit will be 101 * present multiple times in the priority queue of unexamined 102 * commits, processing the first instance will not leave any 103 * work requiring the origin data for the second instance. An 104 * interspersed commit changing that would have to be 105 * preexisting with a different ancestry and with the same 106 * commit date in order to wedge itself between two instances 107 * of the same commit in the priority queue _and_ produce 108 * blame entries relevant for it. While we don't want to let 109 * us get tripped up by this case, it certainly does not seem 110 * worth optimizing for. 111 */ 112struct origin *next; 113struct commit *commit; 114/* `suspects' contains blame entries that may be attributed to 115 * this origin's commit or to parent commits. When a commit 116 * is being processed, all suspects will be moved, either by 117 * assigning them to an origin in a different commit, or by 118 * shipping them to the scoreboard's ent list because they 119 * cannot be attributed to a different commit. 120 */ 121struct blame_entry *suspects; 122 mmfile_t file; 123unsigned char blob_sha1[20]; 124unsigned mode; 125/* guilty gets set when shipping any suspects to the final 126 * blame list instead of other commits 127 */ 128char guilty; 129char path[FLEX_ARRAY]; 130}; 131 132struct progress_info { 133struct progress *progress; 134int blamed_lines; 135}; 136 137static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b, 138 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data) 139{ 140 xpparam_t xpp = {0}; 141 xdemitconf_t xecfg = {0}; 142 xdemitcb_t ecb = {NULL}; 143 144 xpp.flags = xdl_opts; 145 xecfg.hunk_func = hunk_func; 146 ecb.priv = cb_data; 147returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 148} 149 150/* 151 * Prepare diff_filespec and convert it using diff textconv API 152 * if the textconv driver exists. 153 * Return 1 if the conversion succeeds, 0 otherwise. 154 */ 155inttextconv_object(const char*path, 156unsigned mode, 157const unsigned char*sha1, 158int sha1_valid, 159char**buf, 160unsigned long*buf_size) 161{ 162struct diff_filespec *df; 163struct userdiff_driver *textconv; 164 165 df =alloc_filespec(path); 166fill_filespec(df, sha1, sha1_valid, mode); 167 textconv =get_textconv(df); 168if(!textconv) { 169free_filespec(df); 170return0; 171} 172 173*buf_size =fill_textconv(textconv, df, buf); 174free_filespec(df); 175return1; 176} 177 178/* 179 * Given an origin, prepare mmfile_t structure to be used by the 180 * diff machinery 181 */ 182static voidfill_origin_blob(struct diff_options *opt, 183struct origin *o, mmfile_t *file) 184{ 185if(!o->file.ptr) { 186enum object_type type; 187unsigned long file_size; 188 189 num_read_blob++; 190if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 191textconv_object(o->path, o->mode, o->blob_sha1,1, &file->ptr, &file_size)) 192; 193else 194 file->ptr =read_sha1_file(o->blob_sha1, &type, &file_size); 195 file->size = file_size; 196 197if(!file->ptr) 198die("Cannot read blob%sfor path%s", 199sha1_to_hex(o->blob_sha1), 200 o->path); 201 o->file = *file; 202} 203else 204*file = o->file; 205} 206 207/* 208 * Origin is refcounted and usually we keep the blob contents to be 209 * reused. 210 */ 211staticinlinestruct origin *origin_incref(struct origin *o) 212{ 213if(o) 214 o->refcnt++; 215return o; 216} 217 218static voidorigin_decref(struct origin *o) 219{ 220if(o && --o->refcnt <=0) { 221struct origin *p, *l = NULL; 222if(o->previous) 223origin_decref(o->previous); 224free(o->file.ptr); 225/* Should be present exactly once in commit chain */ 226for(p = o->commit->util; p; l = p, p = p->next) { 227if(p == o) { 228if(l) 229 l->next = p->next; 230else 231 o->commit->util = p->next; 232free(o); 233return; 234} 235} 236die("internal error in blame::origin_decref"); 237} 238} 239 240static voiddrop_origin_blob(struct origin *o) 241{ 242if(o->file.ptr) { 243free(o->file.ptr); 244 o->file.ptr = NULL; 245} 246} 247 248/* 249 * Each group of lines is described by a blame_entry; it can be split 250 * as we pass blame to the parents. They are arranged in linked lists 251 * kept as `suspects' of some unprocessed origin, or entered (when the 252 * blame origin has been finalized) into the scoreboard structure. 253 * While the scoreboard structure is only sorted at the end of 254 * processing (according to final image line number), the lists 255 * attached to an origin are sorted by the target line number. 256 */ 257struct blame_entry { 258struct blame_entry *next; 259 260/* the first line of this group in the final image; 261 * internally all line numbers are 0 based. 262 */ 263int lno; 264 265/* how many lines this group has */ 266int num_lines; 267 268/* the commit that introduced this group into the final image */ 269struct origin *suspect; 270 271/* the line number of the first line of this group in the 272 * suspect's file; internally all line numbers are 0 based. 273 */ 274int s_lno; 275 276/* how significant this entry is -- cached to avoid 277 * scanning the lines over and over. 278 */ 279unsigned score; 280}; 281 282/* 283 * Any merge of blames happens on lists of blames that arrived via 284 * different parents in a single suspect. In this case, we want to 285 * sort according to the suspect line numbers as opposed to the final 286 * image line numbers. The function body is somewhat longish because 287 * it avoids unnecessary writes. 288 */ 289 290static struct blame_entry *blame_merge(struct blame_entry *list1, 291struct blame_entry *list2) 292{ 293struct blame_entry *p1 = list1, *p2 = list2, 294**tail = &list1; 295 296if(!p1) 297return p2; 298if(!p2) 299return p1; 300 301if(p1->s_lno <= p2->s_lno) { 302do{ 303 tail = &p1->next; 304if((p1 = *tail) == NULL) { 305*tail = p2; 306return list1; 307} 308}while(p1->s_lno <= p2->s_lno); 309} 310for(;;) { 311*tail = p2; 312do{ 313 tail = &p2->next; 314if((p2 = *tail) == NULL) { 315*tail = p1; 316return list1; 317} 318}while(p1->s_lno > p2->s_lno); 319*tail = p1; 320do{ 321 tail = &p1->next; 322if((p1 = *tail) == NULL) { 323*tail = p2; 324return list1; 325} 326}while(p1->s_lno <= p2->s_lno); 327} 328} 329 330static void*get_next_blame(const void*p) 331{ 332return((struct blame_entry *)p)->next; 333} 334 335static voidset_next_blame(void*p1,void*p2) 336{ 337((struct blame_entry *)p1)->next = p2; 338} 339 340/* 341 * Final image line numbers are all different, so we don't need a 342 * three-way comparison here. 343 */ 344 345static intcompare_blame_final(const void*p1,const void*p2) 346{ 347return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 348?1: -1; 349} 350 351static intcompare_blame_suspect(const void*p1,const void*p2) 352{ 353const struct blame_entry *s1 = p1, *s2 = p2; 354/* 355 * to allow for collating suspects, we sort according to the 356 * respective pointer value as the primary sorting criterion. 357 * The actual relation is pretty unimportant as long as it 358 * establishes a total order. Comparing as integers gives us 359 * that. 360 */ 361if(s1->suspect != s2->suspect) 362return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 363if(s1->s_lno == s2->s_lno) 364return0; 365return s1->s_lno > s2->s_lno ?1: -1; 366} 367 368static struct blame_entry *blame_sort(struct blame_entry *head, 369int(*compare_fn)(const void*,const void*)) 370{ 371returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 372} 373 374static intcompare_commits_by_reverse_commit_date(const void*a, 375const void*b, 376void*c) 377{ 378return-compare_commits_by_commit_date(a, b, c); 379} 380 381/* 382 * The current state of the blame assignment. 383 */ 384struct scoreboard { 385/* the final commit (i.e. where we started digging from) */ 386struct commit *final; 387/* Priority queue for commits with unassigned blame records */ 388struct prio_queue commits; 389struct rev_info *revs; 390const char*path; 391 392/* 393 * The contents in the final image. 394 * Used by many functions to obtain contents of the nth line, 395 * indexed with scoreboard.lineno[blame_entry.lno]. 396 */ 397const char*final_buf; 398unsigned long final_buf_size; 399 400/* linked list of blames */ 401struct blame_entry *ent; 402 403/* look-up a line in the final buffer */ 404int num_lines; 405int*lineno; 406}; 407 408static voidsanity_check_refcnt(struct scoreboard *); 409 410/* 411 * If two blame entries that are next to each other came from 412 * contiguous lines in the same origin (i.e. <commit, path> pair), 413 * merge them together. 414 */ 415static voidcoalesce(struct scoreboard *sb) 416{ 417struct blame_entry *ent, *next; 418 419for(ent = sb->ent; ent && (next = ent->next); ent = next) { 420if(ent->suspect == next->suspect && 421 ent->s_lno + ent->num_lines == next->s_lno) { 422 ent->num_lines += next->num_lines; 423 ent->next = next->next; 424origin_decref(next->suspect); 425free(next); 426 ent->score =0; 427 next = ent;/* again */ 428} 429} 430 431if(DEBUG)/* sanity */ 432sanity_check_refcnt(sb); 433} 434 435/* 436 * Merge the given sorted list of blames into a preexisting origin. 437 * If there were no previous blames to that commit, it is entered into 438 * the commit priority queue of the score board. 439 */ 440 441static voidqueue_blames(struct scoreboard *sb,struct origin *porigin, 442struct blame_entry *sorted) 443{ 444if(porigin->suspects) 445 porigin->suspects =blame_merge(porigin->suspects, sorted); 446else{ 447struct origin *o; 448for(o = porigin->commit->util; o; o = o->next) { 449if(o->suspects) { 450 porigin->suspects = sorted; 451return; 452} 453} 454 porigin->suspects = sorted; 455prio_queue_put(&sb->commits, porigin->commit); 456} 457} 458 459/* 460 * Given a commit and a path in it, create a new origin structure. 461 * The callers that add blame to the scoreboard should use 462 * get_origin() to obtain shared, refcounted copy instead of calling 463 * this function directly. 464 */ 465static struct origin *make_origin(struct commit *commit,const char*path) 466{ 467struct origin *o; 468FLEX_ALLOC_STR(o, path, path); 469 o->commit = commit; 470 o->refcnt =1; 471 o->next = commit->util; 472 commit->util = o; 473return o; 474} 475 476/* 477 * Locate an existing origin or create a new one. 478 * This moves the origin to front position in the commit util list. 479 */ 480static struct origin *get_origin(struct scoreboard *sb, 481struct commit *commit, 482const char*path) 483{ 484struct origin *o, *l; 485 486for(o = commit->util, l = NULL; o; l = o, o = o->next) { 487if(!strcmp(o->path, path)) { 488/* bump to front */ 489if(l) { 490 l->next = o->next; 491 o->next = commit->util; 492 commit->util = o; 493} 494returnorigin_incref(o); 495} 496} 497returnmake_origin(commit, path); 498} 499 500/* 501 * Fill the blob_sha1 field of an origin if it hasn't, so that later 502 * call to fill_origin_blob() can use it to locate the data. blob_sha1 503 * for an origin is also used to pass the blame for the entire file to 504 * the parent to detect the case where a child's blob is identical to 505 * that of its parent's. 506 * 507 * This also fills origin->mode for corresponding tree path. 508 */ 509static intfill_blob_sha1_and_mode(struct origin *origin) 510{ 511if(!is_null_sha1(origin->blob_sha1)) 512return0; 513if(get_tree_entry(origin->commit->object.oid.hash, 514 origin->path, 515 origin->blob_sha1, &origin->mode)) 516goto error_out; 517if(sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB) 518goto error_out; 519return0; 520 error_out: 521hashclr(origin->blob_sha1); 522 origin->mode = S_IFINVALID; 523return-1; 524} 525 526/* 527 * We have an origin -- check if the same path exists in the 528 * parent and return an origin structure to represent it. 529 */ 530static struct origin *find_origin(struct scoreboard *sb, 531struct commit *parent, 532struct origin *origin) 533{ 534struct origin *porigin; 535struct diff_options diff_opts; 536const char*paths[2]; 537 538/* First check any existing origins */ 539for(porigin = parent->util; porigin; porigin = porigin->next) 540if(!strcmp(porigin->path, origin->path)) { 541/* 542 * The same path between origin and its parent 543 * without renaming -- the most common case. 544 */ 545returnorigin_incref(porigin); 546} 547 548/* See if the origin->path is different between parent 549 * and origin first. Most of the time they are the 550 * same and diff-tree is fairly efficient about this. 551 */ 552diff_setup(&diff_opts); 553DIFF_OPT_SET(&diff_opts, RECURSIVE); 554 diff_opts.detect_rename =0; 555 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 556 paths[0] = origin->path; 557 paths[1] = NULL; 558 559parse_pathspec(&diff_opts.pathspec, 560 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 561 PATHSPEC_LITERAL_PATH,"", paths); 562diff_setup_done(&diff_opts); 563 564if(is_null_oid(&origin->commit->object.oid)) 565do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 566else 567diff_tree_sha1(parent->tree->object.oid.hash, 568 origin->commit->tree->object.oid.hash, 569"", &diff_opts); 570diffcore_std(&diff_opts); 571 572if(!diff_queued_diff.nr) { 573/* The path is the same as parent */ 574 porigin =get_origin(sb, parent, origin->path); 575hashcpy(porigin->blob_sha1, origin->blob_sha1); 576 porigin->mode = origin->mode; 577}else{ 578/* 579 * Since origin->path is a pathspec, if the parent 580 * commit had it as a directory, we will see a whole 581 * bunch of deletion of files in the directory that we 582 * do not care about. 583 */ 584int i; 585struct diff_filepair *p = NULL; 586for(i =0; i < diff_queued_diff.nr; i++) { 587const char*name; 588 p = diff_queued_diff.queue[i]; 589 name = p->one->path ? p->one->path : p->two->path; 590if(!strcmp(name, origin->path)) 591break; 592} 593if(!p) 594die("internal error in blame::find_origin"); 595switch(p->status) { 596default: 597die("internal error in blame::find_origin (%c)", 598 p->status); 599case'M': 600 porigin =get_origin(sb, parent, origin->path); 601hashcpy(porigin->blob_sha1, p->one->sha1); 602 porigin->mode = p->one->mode; 603break; 604case'A': 605case'T': 606/* Did not exist in parent, or type changed */ 607break; 608} 609} 610diff_flush(&diff_opts); 611free_pathspec(&diff_opts.pathspec); 612return porigin; 613} 614 615/* 616 * We have an origin -- find the path that corresponds to it in its 617 * parent and return an origin structure to represent it. 618 */ 619static struct origin *find_rename(struct scoreboard *sb, 620struct commit *parent, 621struct origin *origin) 622{ 623struct origin *porigin = NULL; 624struct diff_options diff_opts; 625int i; 626 627diff_setup(&diff_opts); 628DIFF_OPT_SET(&diff_opts, RECURSIVE); 629 diff_opts.detect_rename = DIFF_DETECT_RENAME; 630 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 631 diff_opts.single_follow = origin->path; 632diff_setup_done(&diff_opts); 633 634if(is_null_oid(&origin->commit->object.oid)) 635do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 636else 637diff_tree_sha1(parent->tree->object.oid.hash, 638 origin->commit->tree->object.oid.hash, 639"", &diff_opts); 640diffcore_std(&diff_opts); 641 642for(i =0; i < diff_queued_diff.nr; i++) { 643struct diff_filepair *p = diff_queued_diff.queue[i]; 644if((p->status =='R'|| p->status =='C') && 645!strcmp(p->two->path, origin->path)) { 646 porigin =get_origin(sb, parent, p->one->path); 647hashcpy(porigin->blob_sha1, p->one->sha1); 648 porigin->mode = p->one->mode; 649break; 650} 651} 652diff_flush(&diff_opts); 653free_pathspec(&diff_opts.pathspec); 654return porigin; 655} 656 657/* 658 * Append a new blame entry to a given output queue. 659 */ 660static voidadd_blame_entry(struct blame_entry ***queue,struct blame_entry *e) 661{ 662origin_incref(e->suspect); 663 664 e->next = **queue; 665**queue = e; 666*queue = &e->next; 667} 668 669/* 670 * src typically is on-stack; we want to copy the information in it to 671 * a malloced blame_entry that gets added to the given queue. The 672 * origin of dst loses a refcnt. 673 */ 674static voiddup_entry(struct blame_entry ***queue, 675struct blame_entry *dst,struct blame_entry *src) 676{ 677origin_incref(src->suspect); 678origin_decref(dst->suspect); 679memcpy(dst, src,sizeof(*src)); 680 dst->next = **queue; 681**queue = dst; 682*queue = &dst->next; 683} 684 685static const char*nth_line(struct scoreboard *sb,long lno) 686{ 687return sb->final_buf + sb->lineno[lno]; 688} 689 690static const char*nth_line_cb(void*data,long lno) 691{ 692returnnth_line((struct scoreboard *)data, lno); 693} 694 695/* 696 * It is known that lines between tlno to same came from parent, and e 697 * has an overlap with that range. it also is known that parent's 698 * line plno corresponds to e's line tlno. 699 * 700 * <---- e -----> 701 * <------> 702 * <------------> 703 * <------------> 704 * <------------------> 705 * 706 * Split e into potentially three parts; before this chunk, the chunk 707 * to be blamed for the parent, and after that portion. 708 */ 709static voidsplit_overlap(struct blame_entry *split, 710struct blame_entry *e, 711int tlno,int plno,int same, 712struct origin *parent) 713{ 714int chunk_end_lno; 715memset(split,0,sizeof(struct blame_entry [3])); 716 717if(e->s_lno < tlno) { 718/* there is a pre-chunk part not blamed on parent */ 719 split[0].suspect =origin_incref(e->suspect); 720 split[0].lno = e->lno; 721 split[0].s_lno = e->s_lno; 722 split[0].num_lines = tlno - e->s_lno; 723 split[1].lno = e->lno + tlno - e->s_lno; 724 split[1].s_lno = plno; 725} 726else{ 727 split[1].lno = e->lno; 728 split[1].s_lno = plno + (e->s_lno - tlno); 729} 730 731if(same < e->s_lno + e->num_lines) { 732/* there is a post-chunk part not blamed on parent */ 733 split[2].suspect =origin_incref(e->suspect); 734 split[2].lno = e->lno + (same - e->s_lno); 735 split[2].s_lno = e->s_lno + (same - e->s_lno); 736 split[2].num_lines = e->s_lno + e->num_lines - same; 737 chunk_end_lno = split[2].lno; 738} 739else 740 chunk_end_lno = e->lno + e->num_lines; 741 split[1].num_lines = chunk_end_lno - split[1].lno; 742 743/* 744 * if it turns out there is nothing to blame the parent for, 745 * forget about the splitting. !split[1].suspect signals this. 746 */ 747if(split[1].num_lines <1) 748return; 749 split[1].suspect =origin_incref(parent); 750} 751 752/* 753 * split_overlap() divided an existing blame e into up to three parts 754 * in split. Any assigned blame is moved to queue to 755 * reflect the split. 756 */ 757static voidsplit_blame(struct blame_entry ***blamed, 758struct blame_entry ***unblamed, 759struct blame_entry *split, 760struct blame_entry *e) 761{ 762struct blame_entry *new_entry; 763 764if(split[0].suspect && split[2].suspect) { 765/* The first part (reuse storage for the existing entry e) */ 766dup_entry(unblamed, e, &split[0]); 767 768/* The last part -- me */ 769 new_entry =xmalloc(sizeof(*new_entry)); 770memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 771add_blame_entry(unblamed, new_entry); 772 773/* ... and the middle part -- parent */ 774 new_entry =xmalloc(sizeof(*new_entry)); 775memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 776add_blame_entry(blamed, new_entry); 777} 778else if(!split[0].suspect && !split[2].suspect) 779/* 780 * The parent covers the entire area; reuse storage for 781 * e and replace it with the parent. 782 */ 783dup_entry(blamed, e, &split[1]); 784else if(split[0].suspect) { 785/* me and then parent */ 786dup_entry(unblamed, e, &split[0]); 787 788 new_entry =xmalloc(sizeof(*new_entry)); 789memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 790add_blame_entry(blamed, new_entry); 791} 792else{ 793/* parent and then me */ 794dup_entry(blamed, e, &split[1]); 795 796 new_entry =xmalloc(sizeof(*new_entry)); 797memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 798add_blame_entry(unblamed, new_entry); 799} 800} 801 802/* 803 * After splitting the blame, the origins used by the 804 * on-stack blame_entry should lose one refcnt each. 805 */ 806static voiddecref_split(struct blame_entry *split) 807{ 808int i; 809 810for(i =0; i <3; i++) 811origin_decref(split[i].suspect); 812} 813 814/* 815 * reverse_blame reverses the list given in head, appending tail. 816 * That allows us to build lists in reverse order, then reverse them 817 * afterwards. This can be faster than building the list in proper 818 * order right away. The reason is that building in proper order 819 * requires writing a link in the _previous_ element, while building 820 * in reverse order just requires placing the list head into the 821 * _current_ element. 822 */ 823 824static struct blame_entry *reverse_blame(struct blame_entry *head, 825struct blame_entry *tail) 826{ 827while(head) { 828struct blame_entry *next = head->next; 829 head->next = tail; 830 tail = head; 831 head = next; 832} 833return tail; 834} 835 836/* 837 * Process one hunk from the patch between the current suspect for 838 * blame_entry e and its parent. This first blames any unfinished 839 * entries before the chunk (which is where target and parent start 840 * differing) on the parent, and then splits blame entries at the 841 * start and at the end of the difference region. Since use of -M and 842 * -C options may lead to overlapping/duplicate source line number 843 * ranges, all we can rely on from sorting/merging is the order of the 844 * first suspect line number. 845 */ 846static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 847int tlno,int offset,int same, 848struct origin *parent) 849{ 850struct blame_entry *e = **srcq; 851struct blame_entry *samep = NULL, *diffp = NULL; 852 853while(e && e->s_lno < tlno) { 854struct blame_entry *next = e->next; 855/* 856 * current record starts before differing portion. If 857 * it reaches into it, we need to split it up and 858 * examine the second part separately. 859 */ 860if(e->s_lno + e->num_lines > tlno) { 861/* Move second half to a new record */ 862int len = tlno - e->s_lno; 863struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 864 n->suspect = e->suspect; 865 n->lno = e->lno + len; 866 n->s_lno = e->s_lno + len; 867 n->num_lines = e->num_lines - len; 868 e->num_lines = len; 869 e->score =0; 870/* Push new record to diffp */ 871 n->next = diffp; 872 diffp = n; 873}else 874origin_decref(e->suspect); 875/* Pass blame for everything before the differing 876 * chunk to the parent */ 877 e->suspect =origin_incref(parent); 878 e->s_lno += offset; 879 e->next = samep; 880 samep = e; 881 e = next; 882} 883/* 884 * As we don't know how much of a common stretch after this 885 * diff will occur, the currently blamed parts are all that we 886 * can assign to the parent for now. 887 */ 888 889if(samep) { 890**dstq =reverse_blame(samep, **dstq); 891*dstq = &samep->next; 892} 893/* 894 * Prepend the split off portions: everything after e starts 895 * after the blameable portion. 896 */ 897 e =reverse_blame(diffp, e); 898 899/* 900 * Now retain records on the target while parts are different 901 * from the parent. 902 */ 903 samep = NULL; 904 diffp = NULL; 905while(e && e->s_lno < same) { 906struct blame_entry *next = e->next; 907 908/* 909 * If current record extends into sameness, need to split. 910 */ 911if(e->s_lno + e->num_lines > same) { 912/* 913 * Move second half to a new record to be 914 * processed by later chunks 915 */ 916int len = same - e->s_lno; 917struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 918 n->suspect =origin_incref(e->suspect); 919 n->lno = e->lno + len; 920 n->s_lno = e->s_lno + len; 921 n->num_lines = e->num_lines - len; 922 e->num_lines = len; 923 e->score =0; 924/* Push new record to samep */ 925 n->next = samep; 926 samep = n; 927} 928 e->next = diffp; 929 diffp = e; 930 e = next; 931} 932**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 933/* Move across elements that are in the unblamable portion */ 934if(diffp) 935*srcq = &diffp->next; 936} 937 938struct blame_chunk_cb_data { 939struct origin *parent; 940long offset; 941struct blame_entry **dstq; 942struct blame_entry **srcq; 943}; 944 945/* diff chunks are from parent to target */ 946static intblame_chunk_cb(long start_a,long count_a, 947long start_b,long count_b,void*data) 948{ 949struct blame_chunk_cb_data *d = data; 950if(start_a - start_b != d->offset) 951die("internal error in blame::blame_chunk_cb"); 952blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 953 start_b + count_b, d->parent); 954 d->offset = start_a + count_a - (start_b + count_b); 955return0; 956} 957 958/* 959 * We are looking at the origin 'target' and aiming to pass blame 960 * for the lines it is suspected to its parent. Run diff to find 961 * which lines came from parent and pass blame for them. 962 */ 963static voidpass_blame_to_parent(struct scoreboard *sb, 964struct origin *target, 965struct origin *parent) 966{ 967 mmfile_t file_p, file_o; 968struct blame_chunk_cb_data d; 969struct blame_entry *newdest = NULL; 970 971if(!target->suspects) 972return;/* nothing remains for this target */ 973 974 d.parent = parent; 975 d.offset =0; 976 d.dstq = &newdest; d.srcq = &target->suspects; 977 978fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 979fill_origin_blob(&sb->revs->diffopt, target, &file_o); 980 num_get_patch++; 981 982if(diff_hunks(&file_p, &file_o, blame_chunk_cb, &d)) 983die("unable to generate diff (%s->%s)", 984oid_to_hex(&parent->commit->object.oid), 985oid_to_hex(&target->commit->object.oid)); 986/* The rest are the same as the parent */ 987blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 988*d.dstq = NULL; 989queue_blames(sb, parent, newdest); 990 991return; 992} 993 994/* 995 * The lines in blame_entry after splitting blames many times can become 996 * very small and trivial, and at some point it becomes pointless to 997 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 998 * ordinary C program, and it is not worth to say it was copied from 999 * totally unrelated file in the parent.1000 *1001 * Compute how trivial the lines in the blame_entry are.1002 */1003static unsignedent_score(struct scoreboard *sb,struct blame_entry *e)1004{1005unsigned score;1006const char*cp, *ep;10071008if(e->score)1009return e->score;10101011 score =1;1012 cp =nth_line(sb, e->lno);1013 ep =nth_line(sb, e->lno + e->num_lines);1014while(cp < ep) {1015unsigned ch = *((unsigned char*)cp);1016if(isalnum(ch))1017 score++;1018 cp++;1019}1020 e->score = score;1021return score;1022}10231024/*1025 * best_so_far[] and this[] are both a split of an existing blame_entry1026 * that passes blame to the parent. Maintain best_so_far the best split1027 * so far, by comparing this and best_so_far and copying this into1028 * bst_so_far as needed.1029 */1030static voidcopy_split_if_better(struct scoreboard *sb,1031struct blame_entry *best_so_far,1032struct blame_entry *this)1033{1034int i;10351036if(!this[1].suspect)1037return;1038if(best_so_far[1].suspect) {1039if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1040return;1041}10421043for(i =0; i <3; i++)1044origin_incref(this[i].suspect);1045decref_split(best_so_far);1046memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1047}10481049/*1050 * We are looking at a part of the final image represented by1051 * ent (tlno and same are offset by ent->s_lno).1052 * tlno is where we are looking at in the final image.1053 * up to (but not including) same match preimage.1054 * plno is where we are looking at in the preimage.1055 *1056 * <-------------- final image ---------------------->1057 * <------ent------>1058 * ^tlno ^same1059 * <---------preimage----->1060 * ^plno1061 *1062 * All line numbers are 0-based.1063 */1064static voidhandle_split(struct scoreboard *sb,1065struct blame_entry *ent,1066int tlno,int plno,int same,1067struct origin *parent,1068struct blame_entry *split)1069{1070if(ent->num_lines <= tlno)1071return;1072if(tlno < same) {1073struct blame_entry this[3];1074 tlno += ent->s_lno;1075 same += ent->s_lno;1076split_overlap(this, ent, tlno, plno, same, parent);1077copy_split_if_better(sb, split,this);1078decref_split(this);1079}1080}10811082struct handle_split_cb_data {1083struct scoreboard *sb;1084struct blame_entry *ent;1085struct origin *parent;1086struct blame_entry *split;1087long plno;1088long tlno;1089};10901091static inthandle_split_cb(long start_a,long count_a,1092long start_b,long count_b,void*data)1093{1094struct handle_split_cb_data *d = data;1095handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1096 d->split);1097 d->plno = start_a + count_a;1098 d->tlno = start_b + count_b;1099return0;1100}11011102/*1103 * Find the lines from parent that are the same as ent so that1104 * we can pass blames to it. file_p has the blob contents for1105 * the parent.1106 */1107static voidfind_copy_in_blob(struct scoreboard *sb,1108struct blame_entry *ent,1109struct origin *parent,1110struct blame_entry *split,1111 mmfile_t *file_p)1112{1113const char*cp;1114 mmfile_t file_o;1115struct handle_split_cb_data d;11161117memset(&d,0,sizeof(d));1118 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1119/*1120 * Prepare mmfile that contains only the lines in ent.1121 */1122 cp =nth_line(sb, ent->lno);1123 file_o.ptr = (char*) cp;1124 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11251126/*1127 * file_o is a part of final image we are annotating.1128 * file_p partially may match that image.1129 */1130memset(split,0,sizeof(struct blame_entry [3]));1131if(diff_hunks(file_p, &file_o, handle_split_cb, &d))1132die("unable to generate diff (%s)",1133oid_to_hex(&parent->commit->object.oid));1134/* remainder, if any, all match the preimage */1135handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1136}11371138/* Move all blame entries from list *source that have a score smaller1139 * than score_min to the front of list *small.1140 * Returns a pointer to the link pointing to the old head of the small list.1141 */11421143static struct blame_entry **filter_small(struct scoreboard *sb,1144struct blame_entry **small,1145struct blame_entry **source,1146unsigned score_min)1147{1148struct blame_entry *p = *source;1149struct blame_entry *oldsmall = *small;1150while(p) {1151if(ent_score(sb, p) <= score_min) {1152*small = p;1153 small = &p->next;1154 p = *small;1155}else{1156*source = p;1157 source = &p->next;1158 p = *source;1159}1160}1161*small = oldsmall;1162*source = NULL;1163return small;1164}11651166/*1167 * See if lines currently target is suspected for can be attributed to1168 * parent.1169 */1170static voidfind_move_in_parent(struct scoreboard *sb,1171struct blame_entry ***blamed,1172struct blame_entry **toosmall,1173struct origin *target,1174struct origin *parent)1175{1176struct blame_entry *e, split[3];1177struct blame_entry *unblamed = target->suspects;1178struct blame_entry *leftover = NULL;1179 mmfile_t file_p;11801181if(!unblamed)1182return;/* nothing remains for this target */11831184fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1185if(!file_p.ptr)1186return;11871188/* At each iteration, unblamed has a NULL-terminated list of1189 * entries that have not yet been tested for blame. leftover1190 * contains the reversed list of entries that have been tested1191 * without being assignable to the parent.1192 */1193do{1194struct blame_entry **unblamedtail = &unblamed;1195struct blame_entry *next;1196for(e = unblamed; e; e = next) {1197 next = e->next;1198find_copy_in_blob(sb, e, parent, split, &file_p);1199if(split[1].suspect &&1200 blame_move_score <ent_score(sb, &split[1])) {1201split_blame(blamed, &unblamedtail, split, e);1202}else{1203 e->next = leftover;1204 leftover = e;1205}1206decref_split(split);1207}1208*unblamedtail = NULL;1209 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1210}while(unblamed);1211 target->suspects =reverse_blame(leftover, NULL);1212}12131214struct blame_list {1215struct blame_entry *ent;1216struct blame_entry split[3];1217};12181219/*1220 * Count the number of entries the target is suspected for,1221 * and prepare a list of entry and the best split.1222 */1223static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1224int*num_ents_p)1225{1226struct blame_entry *e;1227int num_ents, i;1228struct blame_list *blame_list = NULL;12291230for(e = unblamed, num_ents =0; e; e = e->next)1231 num_ents++;1232if(num_ents) {1233 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1234for(e = unblamed, i =0; e; e = e->next)1235 blame_list[i++].ent = e;1236}1237*num_ents_p = num_ents;1238return blame_list;1239}12401241/*1242 * For lines target is suspected for, see if we can find code movement1243 * across file boundary from the parent commit. porigin is the path1244 * in the parent we already tried.1245 */1246static voidfind_copy_in_parent(struct scoreboard *sb,1247struct blame_entry ***blamed,1248struct blame_entry **toosmall,1249struct origin *target,1250struct commit *parent,1251struct origin *porigin,1252int opt)1253{1254struct diff_options diff_opts;1255int i, j;1256struct blame_list *blame_list;1257int num_ents;1258struct blame_entry *unblamed = target->suspects;1259struct blame_entry *leftover = NULL;12601261if(!unblamed)1262return;/* nothing remains for this target */12631264diff_setup(&diff_opts);1265DIFF_OPT_SET(&diff_opts, RECURSIVE);1266 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12671268diff_setup_done(&diff_opts);12691270/* Try "find copies harder" on new path if requested;1271 * we do not want to use diffcore_rename() actually to1272 * match things up; find_copies_harder is set only to1273 * force diff_tree_sha1() to feed all filepairs to diff_queue,1274 * and this code needs to be after diff_setup_done(), which1275 * usually makes find-copies-harder imply copy detection.1276 */1277if((opt & PICKAXE_BLAME_COPY_HARDEST)1278|| ((opt & PICKAXE_BLAME_COPY_HARDER)1279&& (!porigin ||strcmp(target->path, porigin->path))))1280DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12811282if(is_null_oid(&target->commit->object.oid))1283do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1284else1285diff_tree_sha1(parent->tree->object.oid.hash,1286 target->commit->tree->object.oid.hash,1287"", &diff_opts);12881289if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1290diffcore_std(&diff_opts);12911292do{1293struct blame_entry **unblamedtail = &unblamed;1294 blame_list =setup_blame_list(unblamed, &num_ents);12951296for(i =0; i < diff_queued_diff.nr; i++) {1297struct diff_filepair *p = diff_queued_diff.queue[i];1298struct origin *norigin;1299 mmfile_t file_p;1300struct blame_entry this[3];13011302if(!DIFF_FILE_VALID(p->one))1303continue;/* does not exist in parent */1304if(S_ISGITLINK(p->one->mode))1305continue;/* ignore git links */1306if(porigin && !strcmp(p->one->path, porigin->path))1307/* find_move already dealt with this path */1308continue;13091310 norigin =get_origin(sb, parent, p->one->path);1311hashcpy(norigin->blob_sha1, p->one->sha1);1312 norigin->mode = p->one->mode;1313fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1314if(!file_p.ptr)1315continue;13161317for(j =0; j < num_ents; j++) {1318find_copy_in_blob(sb, blame_list[j].ent,1319 norigin,this, &file_p);1320copy_split_if_better(sb, blame_list[j].split,1321this);1322decref_split(this);1323}1324origin_decref(norigin);1325}13261327for(j =0; j < num_ents; j++) {1328struct blame_entry *split = blame_list[j].split;1329if(split[1].suspect &&1330 blame_copy_score <ent_score(sb, &split[1])) {1331split_blame(blamed, &unblamedtail, split,1332 blame_list[j].ent);1333}else{1334 blame_list[j].ent->next = leftover;1335 leftover = blame_list[j].ent;1336}1337decref_split(split);1338}1339free(blame_list);1340*unblamedtail = NULL;1341 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1342}while(unblamed);1343 target->suspects =reverse_blame(leftover, NULL);1344diff_flush(&diff_opts);1345free_pathspec(&diff_opts.pathspec);1346}13471348/*1349 * The blobs of origin and porigin exactly match, so everything1350 * origin is suspected for can be blamed on the parent.1351 */1352static voidpass_whole_blame(struct scoreboard *sb,1353struct origin *origin,struct origin *porigin)1354{1355struct blame_entry *e, *suspects;13561357if(!porigin->file.ptr && origin->file.ptr) {1358/* Steal its file */1359 porigin->file = origin->file;1360 origin->file.ptr = NULL;1361}1362 suspects = origin->suspects;1363 origin->suspects = NULL;1364for(e = suspects; e; e = e->next) {1365origin_incref(porigin);1366origin_decref(e->suspect);1367 e->suspect = porigin;1368}1369queue_blames(sb, porigin, suspects);1370}13711372/*1373 * We pass blame from the current commit to its parents. We keep saying1374 * "parent" (and "porigin"), but what we mean is to find scapegoat to1375 * exonerate ourselves.1376 */1377static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1378{1379if(!reverse) {1380if(revs->first_parent_only &&1381 commit->parents &&1382 commit->parents->next) {1383free_commit_list(commit->parents->next);1384 commit->parents->next = NULL;1385}1386return commit->parents;1387}1388returnlookup_decoration(&revs->children, &commit->object);1389}13901391static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1392{1393struct commit_list *l =first_scapegoat(revs, commit);1394returncommit_list_count(l);1395}13961397/* Distribute collected unsorted blames to the respected sorted lists1398 * in the various origins.1399 */1400static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1401{1402 blamed =blame_sort(blamed, compare_blame_suspect);1403while(blamed)1404{1405struct origin *porigin = blamed->suspect;1406struct blame_entry *suspects = NULL;1407do{1408struct blame_entry *next = blamed->next;1409 blamed->next = suspects;1410 suspects = blamed;1411 blamed = next;1412}while(blamed && blamed->suspect == porigin);1413 suspects =reverse_blame(suspects, NULL);1414queue_blames(sb, porigin, suspects);1415}1416}14171418#define MAXSG 1614191420static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1421{1422struct rev_info *revs = sb->revs;1423int i, pass, num_sg;1424struct commit *commit = origin->commit;1425struct commit_list *sg;1426struct origin *sg_buf[MAXSG];1427struct origin *porigin, **sg_origin = sg_buf;1428struct blame_entry *toosmall = NULL;1429struct blame_entry *blames, **blametail = &blames;14301431 num_sg =num_scapegoats(revs, commit);1432if(!num_sg)1433goto finish;1434else if(num_sg <ARRAY_SIZE(sg_buf))1435memset(sg_buf,0,sizeof(sg_buf));1436else1437 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14381439/*1440 * The first pass looks for unrenamed path to optimize for1441 * common cases, then we look for renames in the second pass.1442 */1443for(pass =0; pass <2- no_whole_file_rename; pass++) {1444struct origin *(*find)(struct scoreboard *,1445struct commit *,struct origin *);1446 find = pass ? find_rename : find_origin;14471448for(i =0, sg =first_scapegoat(revs, commit);1449 i < num_sg && sg;1450 sg = sg->next, i++) {1451struct commit *p = sg->item;1452int j, same;14531454if(sg_origin[i])1455continue;1456if(parse_commit(p))1457continue;1458 porigin =find(sb, p, origin);1459if(!porigin)1460continue;1461if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1462pass_whole_blame(sb, origin, porigin);1463origin_decref(porigin);1464goto finish;1465}1466for(j = same =0; j < i; j++)1467if(sg_origin[j] &&1468!hashcmp(sg_origin[j]->blob_sha1,1469 porigin->blob_sha1)) {1470 same =1;1471break;1472}1473if(!same)1474 sg_origin[i] = porigin;1475else1476origin_decref(porigin);1477}1478}14791480 num_commits++;1481for(i =0, sg =first_scapegoat(revs, commit);1482 i < num_sg && sg;1483 sg = sg->next, i++) {1484struct origin *porigin = sg_origin[i];1485if(!porigin)1486continue;1487if(!origin->previous) {1488origin_incref(porigin);1489 origin->previous = porigin;1490}1491pass_blame_to_parent(sb, origin, porigin);1492if(!origin->suspects)1493goto finish;1494}14951496/*1497 * Optionally find moves in parents' files.1498 */1499if(opt & PICKAXE_BLAME_MOVE) {1500filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1501if(origin->suspects) {1502for(i =0, sg =first_scapegoat(revs, commit);1503 i < num_sg && sg;1504 sg = sg->next, i++) {1505struct origin *porigin = sg_origin[i];1506if(!porigin)1507continue;1508find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1509if(!origin->suspects)1510break;1511}1512}1513}15141515/*1516 * Optionally find copies from parents' files.1517 */1518if(opt & PICKAXE_BLAME_COPY) {1519if(blame_copy_score > blame_move_score)1520filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1521else if(blame_copy_score < blame_move_score) {1522 origin->suspects =blame_merge(origin->suspects, toosmall);1523 toosmall = NULL;1524filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1525}1526if(!origin->suspects)1527goto finish;15281529for(i =0, sg =first_scapegoat(revs, commit);1530 i < num_sg && sg;1531 sg = sg->next, i++) {1532struct origin *porigin = sg_origin[i];1533find_copy_in_parent(sb, &blametail, &toosmall,1534 origin, sg->item, porigin, opt);1535if(!origin->suspects)1536goto finish;1537}1538}15391540finish:1541*blametail = NULL;1542distribute_blame(sb, blames);1543/*1544 * prepend toosmall to origin->suspects1545 *1546 * There is no point in sorting: this ends up on a big1547 * unsorted list in the caller anyway.1548 */1549if(toosmall) {1550struct blame_entry **tail = &toosmall;1551while(*tail)1552 tail = &(*tail)->next;1553*tail = origin->suspects;1554 origin->suspects = toosmall;1555}1556for(i =0; i < num_sg; i++) {1557if(sg_origin[i]) {1558drop_origin_blob(sg_origin[i]);1559origin_decref(sg_origin[i]);1560}1561}1562drop_origin_blob(origin);1563if(sg_buf != sg_origin)1564free(sg_origin);1565}15661567/*1568 * Information on commits, used for output.1569 */1570struct commit_info {1571struct strbuf author;1572struct strbuf author_mail;1573unsigned long author_time;1574struct strbuf author_tz;15751576/* filled only when asked for details */1577struct strbuf committer;1578struct strbuf committer_mail;1579unsigned long committer_time;1580struct strbuf committer_tz;15811582struct strbuf summary;1583};15841585/*1586 * Parse author/committer line in the commit object buffer1587 */1588static voidget_ac_line(const char*inbuf,const char*what,1589struct strbuf *name,struct strbuf *mail,1590unsigned long*time,struct strbuf *tz)1591{1592struct ident_split ident;1593size_t len, maillen, namelen;1594char*tmp, *endp;1595const char*namebuf, *mailbuf;15961597 tmp =strstr(inbuf, what);1598if(!tmp)1599goto error_out;1600 tmp +=strlen(what);1601 endp =strchr(tmp,'\n');1602if(!endp)1603 len =strlen(tmp);1604else1605 len = endp - tmp;16061607if(split_ident_line(&ident, tmp, len)) {1608 error_out:1609/* Ugh */1610 tmp ="(unknown)";1611strbuf_addstr(name, tmp);1612strbuf_addstr(mail, tmp);1613strbuf_addstr(tz, tmp);1614*time =0;1615return;1616}16171618 namelen = ident.name_end - ident.name_begin;1619 namebuf = ident.name_begin;16201621 maillen = ident.mail_end - ident.mail_begin;1622 mailbuf = ident.mail_begin;16231624if(ident.date_begin && ident.date_end)1625*time =strtoul(ident.date_begin, NULL,10);1626else1627*time =0;16281629if(ident.tz_begin && ident.tz_end)1630strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1631else1632strbuf_addstr(tz,"(unknown)");16331634/*1635 * Now, convert both name and e-mail using mailmap1636 */1637map_user(&mailmap, &mailbuf, &maillen,1638&namebuf, &namelen);16391640strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1641strbuf_add(name, namebuf, namelen);1642}16431644static voidcommit_info_init(struct commit_info *ci)1645{16461647strbuf_init(&ci->author,0);1648strbuf_init(&ci->author_mail,0);1649strbuf_init(&ci->author_tz,0);1650strbuf_init(&ci->committer,0);1651strbuf_init(&ci->committer_mail,0);1652strbuf_init(&ci->committer_tz,0);1653strbuf_init(&ci->summary,0);1654}16551656static voidcommit_info_destroy(struct commit_info *ci)1657{16581659strbuf_release(&ci->author);1660strbuf_release(&ci->author_mail);1661strbuf_release(&ci->author_tz);1662strbuf_release(&ci->committer);1663strbuf_release(&ci->committer_mail);1664strbuf_release(&ci->committer_tz);1665strbuf_release(&ci->summary);1666}16671668static voidget_commit_info(struct commit *commit,1669struct commit_info *ret,1670int detailed)1671{1672int len;1673const char*subject, *encoding;1674const char*message;16751676commit_info_init(ret);16771678 encoding =get_log_output_encoding();1679 message =logmsg_reencode(commit, NULL, encoding);1680get_ac_line(message,"\nauthor ",1681&ret->author, &ret->author_mail,1682&ret->author_time, &ret->author_tz);16831684if(!detailed) {1685unuse_commit_buffer(commit, message);1686return;1687}16881689get_ac_line(message,"\ncommitter ",1690&ret->committer, &ret->committer_mail,1691&ret->committer_time, &ret->committer_tz);16921693 len =find_commit_subject(message, &subject);1694if(len)1695strbuf_add(&ret->summary, subject, len);1696else1697strbuf_addf(&ret->summary,"(%s)",oid_to_hex(&commit->object.oid));16981699unuse_commit_buffer(commit, message);1700}17011702/*1703 * To allow LF and other nonportable characters in pathnames,1704 * they are c-style quoted as needed.1705 */1706static voidwrite_filename_info(const char*path)1707{1708printf("filename ");1709write_name_quoted(path, stdout,'\n');1710}17111712/*1713 * Porcelain/Incremental format wants to show a lot of details per1714 * commit. Instead of repeating this every line, emit it only once,1715 * the first time each commit appears in the output (unless the1716 * user has specifically asked for us to repeat).1717 */1718static intemit_one_suspect_detail(struct origin *suspect,int repeat)1719{1720struct commit_info ci;17211722if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1723return0;17241725 suspect->commit->object.flags |= METAINFO_SHOWN;1726get_commit_info(suspect->commit, &ci,1);1727printf("author%s\n", ci.author.buf);1728printf("author-mail%s\n", ci.author_mail.buf);1729printf("author-time%lu\n", ci.author_time);1730printf("author-tz%s\n", ci.author_tz.buf);1731printf("committer%s\n", ci.committer.buf);1732printf("committer-mail%s\n", ci.committer_mail.buf);1733printf("committer-time%lu\n", ci.committer_time);1734printf("committer-tz%s\n", ci.committer_tz.buf);1735printf("summary%s\n", ci.summary.buf);1736if(suspect->commit->object.flags & UNINTERESTING)1737printf("boundary\n");1738if(suspect->previous) {1739struct origin *prev = suspect->previous;1740printf("previous%s",oid_to_hex(&prev->commit->object.oid));1741write_name_quoted(prev->path, stdout,'\n');1742}17431744commit_info_destroy(&ci);17451746return1;1747}17481749/*1750 * The blame_entry is found to be guilty for the range.1751 * Show it in incremental output.1752 */1753static voidfound_guilty_entry(struct blame_entry *ent,1754struct progress_info *pi)1755{1756if(incremental) {1757struct origin *suspect = ent->suspect;17581759printf("%s %d %d %d\n",1760oid_to_hex(&suspect->commit->object.oid),1761 ent->s_lno +1, ent->lno +1, ent->num_lines);1762emit_one_suspect_detail(suspect,0);1763write_filename_info(suspect->path);1764maybe_flush_or_die(stdout,"stdout");1765}1766 pi->blamed_lines += ent->num_lines;1767display_progress(pi->progress, pi->blamed_lines);1768}17691770/*1771 * The main loop -- while we have blobs with lines whose true origin1772 * is still unknown, pick one blob, and allow its lines to pass blames1773 * to its parents. */1774static voidassign_blame(struct scoreboard *sb,int opt)1775{1776struct rev_info *revs = sb->revs;1777struct commit *commit =prio_queue_get(&sb->commits);1778struct progress_info pi = { NULL,0};17791780if(show_progress)1781 pi.progress =start_progress_delay(_("Blaming lines"),1782 sb->num_lines,50,1);17831784while(commit) {1785struct blame_entry *ent;1786struct origin *suspect = commit->util;17871788/* find one suspect to break down */1789while(suspect && !suspect->suspects)1790 suspect = suspect->next;17911792if(!suspect) {1793 commit =prio_queue_get(&sb->commits);1794continue;1795}17961797assert(commit == suspect->commit);17981799/*1800 * We will use this suspect later in the loop,1801 * so hold onto it in the meantime.1802 */1803origin_incref(suspect);1804parse_commit(commit);1805if(reverse ||1806(!(commit->object.flags & UNINTERESTING) &&1807!(revs->max_age != -1&& commit->date < revs->max_age)))1808pass_blame(sb, suspect, opt);1809else{1810 commit->object.flags |= UNINTERESTING;1811if(commit->object.parsed)1812mark_parents_uninteresting(commit);1813}1814/* treat root commit as boundary */1815if(!commit->parents && !show_root)1816 commit->object.flags |= UNINTERESTING;18171818/* Take responsibility for the remaining entries */1819 ent = suspect->suspects;1820if(ent) {1821 suspect->guilty =1;1822for(;;) {1823struct blame_entry *next = ent->next;1824found_guilty_entry(ent, &pi);1825if(next) {1826 ent = next;1827continue;1828}1829 ent->next = sb->ent;1830 sb->ent = suspect->suspects;1831 suspect->suspects = NULL;1832break;1833}1834}1835origin_decref(suspect);18361837if(DEBUG)/* sanity */1838sanity_check_refcnt(sb);1839}18401841stop_progress(&pi.progress);1842}18431844static const char*format_time(unsigned long time,const char*tz_str,1845int show_raw_time)1846{1847static struct strbuf time_buf = STRBUF_INIT;18481849strbuf_reset(&time_buf);1850if(show_raw_time) {1851strbuf_addf(&time_buf,"%lu%s", time, tz_str);1852}1853else{1854const char*time_str;1855size_t time_width;1856int tz;1857 tz =atoi(tz_str);1858 time_str =show_date(time, tz, &blame_date_mode);1859strbuf_addstr(&time_buf, time_str);1860/*1861 * Add space paddings to time_buf to display a fixed width1862 * string, and use time_width for display width calibration.1863 */1864for(time_width =utf8_strwidth(time_str);1865 time_width < blame_date_width;1866 time_width++)1867strbuf_addch(&time_buf,' ');1868}1869return time_buf.buf;1870}18711872#define OUTPUT_ANNOTATE_COMPAT 0011873#define OUTPUT_LONG_OBJECT_NAME 0021874#define OUTPUT_RAW_TIMESTAMP 0041875#define OUTPUT_PORCELAIN 0101876#define OUTPUT_SHOW_NAME 0201877#define OUTPUT_SHOW_NUMBER 0401878#define OUTPUT_SHOW_SCORE 01001879#define OUTPUT_NO_AUTHOR 02001880#define OUTPUT_SHOW_EMAIL 04001881#define OUTPUT_LINE_PORCELAIN 0100018821883static voidemit_porcelain_details(struct origin *suspect,int repeat)1884{1885if(emit_one_suspect_detail(suspect, repeat) ||1886(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1887write_filename_info(suspect->path);1888}18891890static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1891int opt)1892{1893int repeat = opt & OUTPUT_LINE_PORCELAIN;1894int cnt;1895const char*cp;1896struct origin *suspect = ent->suspect;1897char hex[GIT_SHA1_HEXSZ +1];18981899sha1_to_hex_r(hex, suspect->commit->object.oid.hash);1900printf("%s %d %d %d\n",1901 hex,1902 ent->s_lno +1,1903 ent->lno +1,1904 ent->num_lines);1905emit_porcelain_details(suspect, repeat);19061907 cp =nth_line(sb, ent->lno);1908for(cnt =0; cnt < ent->num_lines; cnt++) {1909char ch;1910if(cnt) {1911printf("%s %d %d\n", hex,1912 ent->s_lno +1+ cnt,1913 ent->lno +1+ cnt);1914if(repeat)1915emit_porcelain_details(suspect,1);1916}1917putchar('\t');1918do{1919 ch = *cp++;1920putchar(ch);1921}while(ch !='\n'&&1922 cp < sb->final_buf + sb->final_buf_size);1923}19241925if(sb->final_buf_size && cp[-1] !='\n')1926putchar('\n');1927}19281929static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1930{1931int cnt;1932const char*cp;1933struct origin *suspect = ent->suspect;1934struct commit_info ci;1935char hex[GIT_SHA1_HEXSZ +1];1936int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19371938get_commit_info(suspect->commit, &ci,1);1939sha1_to_hex_r(hex, suspect->commit->object.oid.hash);19401941 cp =nth_line(sb, ent->lno);1942for(cnt =0; cnt < ent->num_lines; cnt++) {1943char ch;1944int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19451946if(suspect->commit->object.flags & UNINTERESTING) {1947if(blank_boundary)1948memset(hex,' ', length);1949else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1950 length--;1951putchar('^');1952}1953}19541955printf("%.*s", length, hex);1956if(opt & OUTPUT_ANNOTATE_COMPAT) {1957const char*name;1958if(opt & OUTPUT_SHOW_EMAIL)1959 name = ci.author_mail.buf;1960else1961 name = ci.author.buf;1962printf("\t(%10s\t%10s\t%d)", name,1963format_time(ci.author_time, ci.author_tz.buf,1964 show_raw_time),1965 ent->lno +1+ cnt);1966}else{1967if(opt & OUTPUT_SHOW_SCORE)1968printf(" %*d%02d",1969 max_score_digits, ent->score,1970 ent->suspect->refcnt);1971if(opt & OUTPUT_SHOW_NAME)1972printf(" %-*.*s", longest_file, longest_file,1973 suspect->path);1974if(opt & OUTPUT_SHOW_NUMBER)1975printf(" %*d", max_orig_digits,1976 ent->s_lno +1+ cnt);19771978if(!(opt & OUTPUT_NO_AUTHOR)) {1979const char*name;1980int pad;1981if(opt & OUTPUT_SHOW_EMAIL)1982 name = ci.author_mail.buf;1983else1984 name = ci.author.buf;1985 pad = longest_author -utf8_strwidth(name);1986printf(" (%s%*s%10s",1987 name, pad,"",1988format_time(ci.author_time,1989 ci.author_tz.buf,1990 show_raw_time));1991}1992printf(" %*d) ",1993 max_digits, ent->lno +1+ cnt);1994}1995do{1996 ch = *cp++;1997putchar(ch);1998}while(ch !='\n'&&1999 cp < sb->final_buf + sb->final_buf_size);2000}20012002if(sb->final_buf_size && cp[-1] !='\n')2003putchar('\n');20042005commit_info_destroy(&ci);2006}20072008static voidoutput(struct scoreboard *sb,int option)2009{2010struct blame_entry *ent;20112012if(option & OUTPUT_PORCELAIN) {2013for(ent = sb->ent; ent; ent = ent->next) {2014int count =0;2015struct origin *suspect;2016struct commit *commit = ent->suspect->commit;2017if(commit->object.flags & MORE_THAN_ONE_PATH)2018continue;2019for(suspect = commit->util; suspect; suspect = suspect->next) {2020if(suspect->guilty && count++) {2021 commit->object.flags |= MORE_THAN_ONE_PATH;2022break;2023}2024}2025}2026}20272028for(ent = sb->ent; ent; ent = ent->next) {2029if(option & OUTPUT_PORCELAIN)2030emit_porcelain(sb, ent, option);2031else{2032emit_other(sb, ent, option);2033}2034}2035}20362037static const char*get_next_line(const char*start,const char*end)2038{2039const char*nl =memchr(start,'\n', end - start);2040return nl ? nl +1: end;2041}20422043/*2044 * To allow quick access to the contents of nth line in the2045 * final image, prepare an index in the scoreboard.2046 */2047static intprepare_lines(struct scoreboard *sb)2048{2049const char*buf = sb->final_buf;2050unsigned long len = sb->final_buf_size;2051const char*end = buf + len;2052const char*p;2053int*lineno;2054int num =0;20552056for(p = buf; p < end; p =get_next_line(p, end))2057 num++;20582059ALLOC_ARRAY(sb->lineno, num +1);2060 lineno = sb->lineno;20612062for(p = buf; p < end; p =get_next_line(p, end))2063*lineno++ = p - buf;20642065*lineno = len;20662067 sb->num_lines = num;2068return sb->num_lines;2069}20702071/*2072 * Add phony grafts for use with -S; this is primarily to2073 * support git's cvsserver that wants to give a linear history2074 * to its clients.2075 */2076static intread_ancestry(const char*graft_file)2077{2078FILE*fp =fopen(graft_file,"r");2079struct strbuf buf = STRBUF_INIT;2080if(!fp)2081return-1;2082while(!strbuf_getwholeline(&buf, fp,'\n')) {2083/* The format is just "Commit Parent1 Parent2 ...\n" */2084struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2085if(graft)2086register_commit_graft(graft,0);2087}2088fclose(fp);2089strbuf_release(&buf);2090return0;2091}20922093static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2094{2095const char*uniq =find_unique_abbrev(suspect->commit->object.oid.hash,2096 auto_abbrev);2097int len =strlen(uniq);2098if(auto_abbrev < len)2099return len;2100return auto_abbrev;2101}21022103/*2104 * How many columns do we need to show line numbers, authors,2105 * and filenames?2106 */2107static voidfind_alignment(struct scoreboard *sb,int*option)2108{2109int longest_src_lines =0;2110int longest_dst_lines =0;2111unsigned largest_score =0;2112struct blame_entry *e;2113int compute_auto_abbrev = (abbrev <0);2114int auto_abbrev = default_abbrev;21152116for(e = sb->ent; e; e = e->next) {2117struct origin *suspect = e->suspect;2118int num;21192120if(compute_auto_abbrev)2121 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2122if(strcmp(suspect->path, sb->path))2123*option |= OUTPUT_SHOW_NAME;2124 num =strlen(suspect->path);2125if(longest_file < num)2126 longest_file = num;2127if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2128struct commit_info ci;2129 suspect->commit->object.flags |= METAINFO_SHOWN;2130get_commit_info(suspect->commit, &ci,1);2131if(*option & OUTPUT_SHOW_EMAIL)2132 num =utf8_strwidth(ci.author_mail.buf);2133else2134 num =utf8_strwidth(ci.author.buf);2135if(longest_author < num)2136 longest_author = num;2137commit_info_destroy(&ci);2138}2139 num = e->s_lno + e->num_lines;2140if(longest_src_lines < num)2141 longest_src_lines = num;2142 num = e->lno + e->num_lines;2143if(longest_dst_lines < num)2144 longest_dst_lines = num;2145if(largest_score <ent_score(sb, e))2146 largest_score =ent_score(sb, e);2147}2148 max_orig_digits =decimal_width(longest_src_lines);2149 max_digits =decimal_width(longest_dst_lines);2150 max_score_digits =decimal_width(largest_score);21512152if(compute_auto_abbrev)2153/* one more abbrev length is needed for the boundary commit */2154 abbrev = auto_abbrev +1;2155}21562157/*2158 * For debugging -- origin is refcounted, and this asserts that2159 * we do not underflow.2160 */2161static voidsanity_check_refcnt(struct scoreboard *sb)2162{2163int baa =0;2164struct blame_entry *ent;21652166for(ent = sb->ent; ent; ent = ent->next) {2167/* Nobody should have zero or negative refcnt */2168if(ent->suspect->refcnt <=0) {2169fprintf(stderr,"%sin%shas negative refcnt%d\n",2170 ent->suspect->path,2171oid_to_hex(&ent->suspect->commit->object.oid),2172 ent->suspect->refcnt);2173 baa =1;2174}2175}2176if(baa) {2177int opt =0160;2178find_alignment(sb, &opt);2179output(sb, opt);2180die("Baa%d!", baa);2181}2182}21832184static unsignedparse_score(const char*arg)2185{2186char*end;2187unsigned long score =strtoul(arg, &end,10);2188if(*end)2189return0;2190return score;2191}21922193static const char*add_prefix(const char*prefix,const char*path)2194{2195returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2196}21972198static intgit_blame_config(const char*var,const char*value,void*cb)2199{2200if(!strcmp(var,"blame.showroot")) {2201 show_root =git_config_bool(var, value);2202return0;2203}2204if(!strcmp(var,"blame.blankboundary")) {2205 blank_boundary =git_config_bool(var, value);2206return0;2207}2208if(!strcmp(var,"blame.showemail")) {2209int*output_option = cb;2210if(git_config_bool(var, value))2211*output_option |= OUTPUT_SHOW_EMAIL;2212else2213*output_option &= ~OUTPUT_SHOW_EMAIL;2214return0;2215}2216if(!strcmp(var,"blame.date")) {2217if(!value)2218returnconfig_error_nonbool(var);2219parse_date_format(value, &blame_date_mode);2220return0;2221}22222223if(userdiff_config(var, value) <0)2224return-1;22252226returngit_default_config(var, value, cb);2227}22282229static voidverify_working_tree_path(struct commit *work_tree,const char*path)2230{2231struct commit_list *parents;2232int pos;22332234for(parents = work_tree->parents; parents; parents = parents->next) {2235const unsigned char*commit_sha1 = parents->item->object.oid.hash;2236unsigned char blob_sha1[20];2237unsigned mode;22382239if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2240sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2241return;2242}22432244 pos =cache_name_pos(path,strlen(path));2245if(pos >=0)2246;/* path is in the index */2247else if(!strcmp(active_cache[-1- pos]->name, path))2248;/* path is in the index, unmerged */2249else2250die("no such path '%s' in HEAD", path);2251}22522253static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2254{2255struct commit *parent;22562257 parent =lookup_commit_reference(sha1);2258if(!parent)2259die("no such commit%s",sha1_to_hex(sha1));2260return&commit_list_insert(parent, tail)->next;2261}22622263static voidappend_merge_parents(struct commit_list **tail)2264{2265int merge_head;2266struct strbuf line = STRBUF_INIT;22672268 merge_head =open(git_path_merge_head(), O_RDONLY);2269if(merge_head <0) {2270if(errno == ENOENT)2271return;2272die("cannot open '%s' for reading",git_path_merge_head());2273}22742275while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2276unsigned char sha1[20];2277if(line.len <40||get_sha1_hex(line.buf, sha1))2278die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2279 tail =append_parent(tail, sha1);2280}2281close(merge_head);2282strbuf_release(&line);2283}22842285/*2286 * This isn't as simple as passing sb->buf and sb->len, because we2287 * want to transfer ownership of the buffer to the commit (so we2288 * must use detach).2289 */2290static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2291{2292size_t len;2293void*buf =strbuf_detach(sb, &len);2294set_commit_buffer(c, buf, len);2295}22962297/*2298 * Prepare a dummy commit that represents the work tree (or staged) item.2299 * Note that annotating work tree item never works in the reverse.2300 */2301static struct commit *fake_working_tree_commit(struct diff_options *opt,2302const char*path,2303const char*contents_from)2304{2305struct commit *commit;2306struct origin *origin;2307struct commit_list **parent_tail, *parent;2308unsigned char head_sha1[20];2309struct strbuf buf = STRBUF_INIT;2310const char*ident;2311time_t now;2312int size, len;2313struct cache_entry *ce;2314unsigned mode;2315struct strbuf msg = STRBUF_INIT;23162317read_cache();2318time(&now);2319 commit =alloc_commit_node();2320 commit->object.parsed =1;2321 commit->date = now;2322 parent_tail = &commit->parents;23232324if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2325die("no such ref: HEAD");23262327 parent_tail =append_parent(parent_tail, head_sha1);2328append_merge_parents(parent_tail);2329verify_working_tree_path(commit, path);23302331 origin =make_origin(commit, path);23322333 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2334strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2335for(parent = commit->parents; parent; parent = parent->next)2336strbuf_addf(&msg,"parent%s\n",2337oid_to_hex(&parent->item->object.oid));2338strbuf_addf(&msg,2339"author%s\n"2340"committer%s\n\n"2341"Version of%sfrom%s\n",2342 ident, ident, path,2343(!contents_from ? path :2344(!strcmp(contents_from,"-") ?"standard input": contents_from)));2345set_commit_buffer_from_strbuf(commit, &msg);23462347if(!contents_from ||strcmp("-", contents_from)) {2348struct stat st;2349const char*read_from;2350char*buf_ptr;2351unsigned long buf_len;23522353if(contents_from) {2354if(stat(contents_from, &st) <0)2355die_errno("Cannot stat '%s'", contents_from);2356 read_from = contents_from;2357}2358else{2359if(lstat(path, &st) <0)2360die_errno("Cannot lstat '%s'", path);2361 read_from = path;2362}2363 mode =canon_mode(st.st_mode);23642365switch(st.st_mode & S_IFMT) {2366case S_IFREG:2367if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2368textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2369strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2370else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2371die_errno("cannot open or read '%s'", read_from);2372break;2373case S_IFLNK:2374if(strbuf_readlink(&buf, read_from, st.st_size) <0)2375die_errno("cannot readlink '%s'", read_from);2376break;2377default:2378die("unsupported file type%s", read_from);2379}2380}2381else{2382/* Reading from stdin */2383 mode =0;2384if(strbuf_read(&buf,0,0) <0)2385die_errno("failed to read from stdin");2386}2387convert_to_git(path, buf.buf, buf.len, &buf,0);2388 origin->file.ptr = buf.buf;2389 origin->file.size = buf.len;2390pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23912392/*2393 * Read the current index, replace the path entry with2394 * origin->blob_sha1 without mucking with its mode or type2395 * bits; we are not going to write this index out -- we just2396 * want to run "diff-index --cached".2397 */2398discard_cache();2399read_cache();24002401 len =strlen(path);2402if(!mode) {2403int pos =cache_name_pos(path, len);2404if(0<= pos)2405 mode = active_cache[pos]->ce_mode;2406else2407/* Let's not bother reading from HEAD tree */2408 mode = S_IFREG |0644;2409}2410 size =cache_entry_size(len);2411 ce =xcalloc(1, size);2412hashcpy(ce->sha1, origin->blob_sha1);2413memcpy(ce->name, path, len);2414 ce->ce_flags =create_ce_flags(0);2415 ce->ce_namelen = len;2416 ce->ce_mode =create_ce_mode(mode);2417add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);24182419cache_tree_invalidate_path(&the_index, path);24202421return commit;2422}24232424static struct commit *find_single_final(struct rev_info *revs,2425const char**name_p)2426{2427int i;2428struct commit *found = NULL;2429const char*name = NULL;24302431for(i =0; i < revs->pending.nr; i++) {2432struct object *obj = revs->pending.objects[i].item;2433if(obj->flags & UNINTERESTING)2434continue;2435 obj =deref_tag(obj, NULL,0);2436if(obj->type != OBJ_COMMIT)2437die("Non commit%s?", revs->pending.objects[i].name);2438if(found)2439die("More than one commit to dig from%sand%s?",2440 revs->pending.objects[i].name, name);2441 found = (struct commit *)obj;2442 name = revs->pending.objects[i].name;2443}2444if(name_p)2445*name_p = name;2446return found;2447}24482449static char*prepare_final(struct scoreboard *sb)2450{2451const char*name;2452 sb->final =find_single_final(sb->revs, &name);2453returnxstrdup_or_null(name);2454}24552456static char*prepare_initial(struct 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 down to%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}2480if(!final_commit_name)2481die("No commit to dig down to?");2482returnxstrdup(final_commit_name);2483}24842485static intblame_copy_callback(const struct option *option,const char*arg,int unset)2486{2487int*opt = option->value;24882489/*2490 * -C enables copy from removed files;2491 * -C -C enables copy from existing files, but only2492 * when blaming a new file;2493 * -C -C -C enables copy from existing files for2494 * everybody2495 */2496if(*opt & PICKAXE_BLAME_COPY_HARDER)2497*opt |= PICKAXE_BLAME_COPY_HARDEST;2498if(*opt & PICKAXE_BLAME_COPY)2499*opt |= PICKAXE_BLAME_COPY_HARDER;2500*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;25012502if(arg)2503 blame_copy_score =parse_score(arg);2504return0;2505}25062507static intblame_move_callback(const struct option *option,const char*arg,int unset)2508{2509int*opt = option->value;25102511*opt |= PICKAXE_BLAME_MOVE;25122513if(arg)2514 blame_move_score =parse_score(arg);2515return0;2516}25172518intcmd_blame(int argc,const char**argv,const char*prefix)2519{2520struct rev_info revs;2521const char*path;2522struct scoreboard sb;2523struct origin *o;2524struct blame_entry *ent = NULL;2525long dashdash_pos, lno;2526char*final_commit_name = NULL;2527enum object_type type;2528struct commit *final_commit = NULL;25292530static struct string_list range_list;2531static int output_option =0, opt =0;2532static int show_stats =0;2533static const char*revs_file = NULL;2534static const char*contents_from = NULL;2535static const struct option options[] = {2536OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2537OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2538OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2539OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2540OPT_BOOL(0,"progress", &show_progress,N_("Force progress reporting")),2541OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2542OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2543OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2544OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2545OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2546OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2547OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2548OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2549OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2550OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2551OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2552OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2553OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2554OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2555{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2556{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2557OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2558OPT__ABBREV(&abbrev),2559OPT_END()2560};25612562struct parse_opt_ctx_t ctx;2563int cmd_is_annotate = !strcmp(argv[0],"annotate");2564struct range_set ranges;2565unsigned int range_i;2566long anchor;25672568git_config(git_blame_config, &output_option);2569init_revisions(&revs, NULL);2570 revs.date_mode = blame_date_mode;2571DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2572DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25732574 save_commit_buffer =0;2575 dashdash_pos =0;2576 show_progress = -1;25772578parse_options_start(&ctx, argc, argv, prefix, options,2579 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2580for(;;) {2581switch(parse_options_step(&ctx, options, blame_opt_usage)) {2582case PARSE_OPT_HELP:2583exit(129);2584case PARSE_OPT_DONE:2585if(ctx.argv[0])2586 dashdash_pos = ctx.cpidx;2587goto parse_done;2588}25892590if(!strcmp(ctx.argv[0],"--reverse")) {2591 ctx.argv[0] ="--children";2592 reverse =1;2593}2594parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2595}2596parse_done:2597 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2598DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2599 argc =parse_options_end(&ctx);26002601if(incremental || (output_option & OUTPUT_PORCELAIN)) {2602if(show_progress >0)2603die("--progress can't be used with --incremental or porcelain formats");2604 show_progress =0;2605}else if(show_progress <0)2606 show_progress =isatty(2);26072608if(0< abbrev)2609/* one more abbrev length is needed for the boundary commit */2610 abbrev++;26112612if(revs_file &&read_ancestry(revs_file))2613die_errno("reading graft file '%s' failed", revs_file);26142615if(cmd_is_annotate) {2616 output_option |= OUTPUT_ANNOTATE_COMPAT;2617 blame_date_mode.type = DATE_ISO8601;2618}else{2619 blame_date_mode = revs.date_mode;2620}26212622/* The maximum width used to show the dates */2623switch(blame_date_mode.type) {2624case DATE_RFC2822:2625 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2626break;2627case DATE_ISO8601_STRICT:2628 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2629break;2630case DATE_ISO8601:2631 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2632break;2633case DATE_RAW:2634 blame_date_width =sizeof("1161298804 -0700");2635break;2636case DATE_UNIX:2637 blame_date_width =sizeof("1161298804");2638break;2639case DATE_SHORT:2640 blame_date_width =sizeof("2006-10-19");2641break;2642case DATE_RELATIVE:2643/* TRANSLATORS: This string is used to tell us the maximum2644 display width for a relative timestamp in "git blame"2645 output. For C locale, "4 years, 11 months ago", which2646 takes 22 places, is the longest among various forms of2647 relative timestamps, but your language may need more or2648 fewer display columns. */2649 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2650break;2651case DATE_NORMAL:2652 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2653break;2654case DATE_STRFTIME:2655 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2656break;2657}2658 blame_date_width -=1;/* strip the null */26592660if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2661 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2662 PICKAXE_BLAME_COPY_HARDER);26632664if(!blame_move_score)2665 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2666if(!blame_copy_score)2667 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26682669/*2670 * We have collected options unknown to us in argv[1..unk]2671 * which are to be passed to revision machinery if we are2672 * going to do the "bottom" processing.2673 *2674 * The remaining are:2675 *2676 * (1) if dashdash_pos != 0, it is either2677 * "blame [revisions] -- <path>" or2678 * "blame -- <path> <rev>"2679 *2680 * (2) otherwise, it is one of the two:2681 * "blame [revisions] <path>"2682 * "blame <path> <rev>"2683 *2684 * Note that we must strip out <path> from the arguments: we do not2685 * want the path pruning but we may want "bottom" processing.2686 */2687if(dashdash_pos) {2688switch(argc - dashdash_pos -1) {2689case2:/* (1b) */2690if(argc !=4)2691usage_with_options(blame_opt_usage, options);2692/* reorder for the new way: <rev> -- <path> */2693 argv[1] = argv[3];2694 argv[3] = argv[2];2695 argv[2] ="--";2696/* FALLTHROUGH */2697case1:/* (1a) */2698 path =add_prefix(prefix, argv[--argc]);2699 argv[argc] = NULL;2700break;2701default:2702usage_with_options(blame_opt_usage, options);2703}2704}else{2705if(argc <2)2706usage_with_options(blame_opt_usage, options);2707 path =add_prefix(prefix, argv[argc -1]);2708if(argc ==3&& !file_exists(path)) {/* (2b) */2709 path =add_prefix(prefix, argv[1]);2710 argv[1] = argv[2];2711}2712 argv[argc -1] ="--";27132714setup_work_tree();2715if(!file_exists(path))2716die_errno("cannot stat path '%s'", path);2717}27182719 revs.disable_stdin =1;2720setup_revisions(argc, argv, &revs, NULL);2721memset(&sb,0,sizeof(sb));27222723 sb.revs = &revs;2724if(!reverse) {2725 final_commit_name =prepare_final(&sb);2726 sb.commits.compare = compare_commits_by_commit_date;2727}2728else if(contents_from)2729die("--contents and --reverse do not blend well.");2730else{2731 final_commit_name =prepare_initial(&sb);2732 sb.commits.compare = compare_commits_by_reverse_commit_date;2733if(revs.first_parent_only)2734 revs.children.name = NULL;2735}27362737if(!sb.final) {2738/*2739 * "--not A B -- path" without anything positive;2740 * do not default to HEAD, but use the working tree2741 * or "--contents".2742 */2743setup_work_tree();2744 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2745 path, contents_from);2746add_pending_object(&revs, &(sb.final->object),":");2747}2748else if(contents_from)2749die("Cannot use --contents with final commit object name");27502751if(reverse && revs.first_parent_only) {2752 final_commit =find_single_final(sb.revs, NULL);2753if(!final_commit)2754die("--reverse and --first-parent together require specified latest commit");2755}27562757/*2758 * If we have bottom, this will mark the ancestors of the2759 * bottom commits we would reach while traversing as2760 * uninteresting.2761 */2762if(prepare_revision_walk(&revs))2763die(_("revision walk setup failed"));27642765if(reverse && revs.first_parent_only) {2766struct commit *c = final_commit;27672768 sb.revs->children.name ="children";2769while(c->parents &&2770oidcmp(&c->object.oid, &sb.final->object.oid)) {2771struct commit_list *l =xcalloc(1,sizeof(*l));27722773 l->item = c;2774if(add_decoration(&sb.revs->children,2775&c->parents->item->object, l))2776die("BUG: not unique item in first-parent chain");2777 c = c->parents->item;2778}27792780if(oidcmp(&c->object.oid, &sb.final->object.oid))2781die("--reverse --first-parent together require range along first-parent chain");2782}27832784if(is_null_oid(&sb.final->object.oid)) {2785 o = sb.final->util;2786 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2787 sb.final_buf_size = o->file.size;2788}2789else{2790 o =get_origin(&sb, sb.final, path);2791if(fill_blob_sha1_and_mode(o))2792die("no such path%sin%s", path, final_commit_name);27932794if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2795textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2796&sb.final_buf_size))2797;2798else2799 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2800&sb.final_buf_size);28012802if(!sb.final_buf)2803die("Cannot read blob%sfor path%s",2804sha1_to_hex(o->blob_sha1),2805 path);2806}2807 num_read_blob++;2808 lno =prepare_lines(&sb);28092810if(lno && !range_list.nr)2811string_list_append(&range_list,xstrdup("1"));28122813 anchor =1;2814range_set_init(&ranges, range_list.nr);2815for(range_i =0; range_i < range_list.nr; ++range_i) {2816long bottom, top;2817if(parse_range_arg(range_list.items[range_i].string,2818 nth_line_cb, &sb, lno, anchor,2819&bottom, &top, sb.path))2820usage(blame_usage);2821if(lno < top || ((lno || bottom) && lno < bottom))2822die("file%shas only%lu lines", path, lno);2823if(bottom <1)2824 bottom =1;2825if(top <1)2826 top = lno;2827 bottom--;2828range_set_append_unsafe(&ranges, bottom, top);2829 anchor = top +1;2830}2831sort_and_merge_range_set(&ranges);28322833for(range_i = ranges.nr; range_i >0; --range_i) {2834const struct range *r = &ranges.ranges[range_i -1];2835long bottom = r->start;2836long top = r->end;2837struct blame_entry *next = ent;2838 ent =xcalloc(1,sizeof(*ent));2839 ent->lno = bottom;2840 ent->num_lines = top - bottom;2841 ent->suspect = o;2842 ent->s_lno = bottom;2843 ent->next = next;2844origin_incref(o);2845}28462847 o->suspects = ent;2848prio_queue_put(&sb.commits, o->commit);28492850origin_decref(o);28512852range_set_release(&ranges);2853string_list_clear(&range_list,0);28542855 sb.ent = NULL;2856 sb.path = path;28572858read_mailmap(&mailmap, NULL);28592860assign_blame(&sb, opt);28612862if(!incremental)2863setup_pager();28642865free(final_commit_name);28662867if(incremental)2868return0;28692870 sb.ent =blame_sort(sb.ent, compare_blame_final);28712872coalesce(&sb);28732874if(!(output_option & OUTPUT_PORCELAIN))2875find_alignment(&sb, &output_option);28762877output(&sb, output_option);2878free((void*)sb.final_buf);2879for(ent = sb.ent; ent; ) {2880struct blame_entry *e = ent->next;2881free(ent);2882 ent = e;2883}28842885if(show_stats) {2886printf("num read blob:%d\n", num_read_blob);2887printf("num get patch:%d\n", num_get_patch);2888printf("num commits:%d\n", num_commits);2889}2890return0;2891}