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,long ctxlen, 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.ctxlen = ctxlen; 146 xecfg.hunk_func = hunk_func; 147 ecb.priv = cb_data; 148returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 149} 150 151/* 152 * Prepare diff_filespec and convert it using diff textconv API 153 * if the textconv driver exists. 154 * Return 1 if the conversion succeeds, 0 otherwise. 155 */ 156inttextconv_object(const char*path, 157unsigned mode, 158const unsigned char*sha1, 159int sha1_valid, 160char**buf, 161unsigned long*buf_size) 162{ 163struct diff_filespec *df; 164struct userdiff_driver *textconv; 165 166 df =alloc_filespec(path); 167fill_filespec(df, sha1, sha1_valid, mode); 168 textconv =get_textconv(df); 169if(!textconv) { 170free_filespec(df); 171return0; 172} 173 174*buf_size =fill_textconv(textconv, df, buf); 175free_filespec(df); 176return1; 177} 178 179/* 180 * Given an origin, prepare mmfile_t structure to be used by the 181 * diff machinery 182 */ 183static voidfill_origin_blob(struct diff_options *opt, 184struct origin *o, mmfile_t *file) 185{ 186if(!o->file.ptr) { 187enum object_type type; 188unsigned long file_size; 189 190 num_read_blob++; 191if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 192textconv_object(o->path, o->mode, o->blob_sha1,1, &file->ptr, &file_size)) 193; 194else 195 file->ptr =read_sha1_file(o->blob_sha1, &type, &file_size); 196 file->size = file_size; 197 198if(!file->ptr) 199die("Cannot read blob%sfor path%s", 200sha1_to_hex(o->blob_sha1), 201 o->path); 202 o->file = *file; 203} 204else 205*file = o->file; 206} 207 208/* 209 * Origin is refcounted and usually we keep the blob contents to be 210 * reused. 211 */ 212staticinlinestruct origin *origin_incref(struct origin *o) 213{ 214if(o) 215 o->refcnt++; 216return o; 217} 218 219static voidorigin_decref(struct origin *o) 220{ 221if(o && --o->refcnt <=0) { 222struct origin *p, *l = NULL; 223if(o->previous) 224origin_decref(o->previous); 225free(o->file.ptr); 226/* Should be present exactly once in commit chain */ 227for(p = o->commit->util; p; l = p, p = p->next) { 228if(p == o) { 229if(l) 230 l->next = p->next; 231else 232 o->commit->util = p->next; 233free(o); 234return; 235} 236} 237die("internal error in blame::origin_decref"); 238} 239} 240 241static voiddrop_origin_blob(struct origin *o) 242{ 243if(o->file.ptr) { 244free(o->file.ptr); 245 o->file.ptr = NULL; 246} 247} 248 249/* 250 * Each group of lines is described by a blame_entry; it can be split 251 * as we pass blame to the parents. They are arranged in linked lists 252 * kept as `suspects' of some unprocessed origin, or entered (when the 253 * blame origin has been finalized) into the scoreboard structure. 254 * While the scoreboard structure is only sorted at the end of 255 * processing (according to final image line number), the lists 256 * attached to an origin are sorted by the target line number. 257 */ 258struct blame_entry { 259struct blame_entry *next; 260 261/* the first line of this group in the final image; 262 * internally all line numbers are 0 based. 263 */ 264int lno; 265 266/* how many lines this group has */ 267int num_lines; 268 269/* the commit that introduced this group into the final image */ 270struct origin *suspect; 271 272/* the line number of the first line of this group in the 273 * suspect's file; internally all line numbers are 0 based. 274 */ 275int s_lno; 276 277/* how significant this entry is -- cached to avoid 278 * scanning the lines over and over. 279 */ 280unsigned score; 281}; 282 283/* 284 * Any merge of blames happens on lists of blames that arrived via 285 * different parents in a single suspect. In this case, we want to 286 * sort according to the suspect line numbers as opposed to the final 287 * image line numbers. The function body is somewhat longish because 288 * it avoids unnecessary writes. 289 */ 290 291static struct blame_entry *blame_merge(struct blame_entry *list1, 292struct blame_entry *list2) 293{ 294struct blame_entry *p1 = list1, *p2 = list2, 295**tail = &list1; 296 297if(!p1) 298return p2; 299if(!p2) 300return p1; 301 302if(p1->s_lno <= p2->s_lno) { 303do{ 304 tail = &p1->next; 305if((p1 = *tail) == NULL) { 306*tail = p2; 307return list1; 308} 309}while(p1->s_lno <= p2->s_lno); 310} 311for(;;) { 312*tail = p2; 313do{ 314 tail = &p2->next; 315if((p2 = *tail) == NULL) { 316*tail = p1; 317return list1; 318} 319}while(p1->s_lno > p2->s_lno); 320*tail = p1; 321do{ 322 tail = &p1->next; 323if((p1 = *tail) == NULL) { 324*tail = p2; 325return list1; 326} 327}while(p1->s_lno <= p2->s_lno); 328} 329} 330 331static void*get_next_blame(const void*p) 332{ 333return((struct blame_entry *)p)->next; 334} 335 336static voidset_next_blame(void*p1,void*p2) 337{ 338((struct blame_entry *)p1)->next = p2; 339} 340 341/* 342 * Final image line numbers are all different, so we don't need a 343 * three-way comparison here. 344 */ 345 346static intcompare_blame_final(const void*p1,const void*p2) 347{ 348return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 349?1: -1; 350} 351 352static intcompare_blame_suspect(const void*p1,const void*p2) 353{ 354const struct blame_entry *s1 = p1, *s2 = p2; 355/* 356 * to allow for collating suspects, we sort according to the 357 * respective pointer value as the primary sorting criterion. 358 * The actual relation is pretty unimportant as long as it 359 * establishes a total order. Comparing as integers gives us 360 * that. 361 */ 362if(s1->suspect != s2->suspect) 363return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 364if(s1->s_lno == s2->s_lno) 365return0; 366return s1->s_lno > s2->s_lno ?1: -1; 367} 368 369static struct blame_entry *blame_sort(struct blame_entry *head, 370int(*compare_fn)(const void*,const void*)) 371{ 372returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 373} 374 375static intcompare_commits_by_reverse_commit_date(const void*a, 376const void*b, 377void*c) 378{ 379return-compare_commits_by_commit_date(a, b, c); 380} 381 382/* 383 * The current state of the blame assignment. 384 */ 385struct scoreboard { 386/* the final commit (i.e. where we started digging from) */ 387struct commit *final; 388/* Priority queue for commits with unassigned blame records */ 389struct prio_queue commits; 390struct rev_info *revs; 391const char*path; 392 393/* 394 * The contents in the final image. 395 * Used by many functions to obtain contents of the nth line, 396 * indexed with scoreboard.lineno[blame_entry.lno]. 397 */ 398const char*final_buf; 399unsigned long final_buf_size; 400 401/* linked list of blames */ 402struct blame_entry *ent; 403 404/* look-up a line in the final buffer */ 405int num_lines; 406int*lineno; 407}; 408 409static voidsanity_check_refcnt(struct scoreboard *); 410 411/* 412 * If two blame entries that are next to each other came from 413 * contiguous lines in the same origin (i.e. <commit, path> pair), 414 * merge them together. 415 */ 416static voidcoalesce(struct scoreboard *sb) 417{ 418struct blame_entry *ent, *next; 419 420for(ent = sb->ent; ent && (next = ent->next); ent = next) { 421if(ent->suspect == next->suspect && 422 ent->s_lno + ent->num_lines == next->s_lno) { 423 ent->num_lines += next->num_lines; 424 ent->next = next->next; 425origin_decref(next->suspect); 426free(next); 427 ent->score =0; 428 next = ent;/* again */ 429} 430} 431 432if(DEBUG)/* sanity */ 433sanity_check_refcnt(sb); 434} 435 436/* 437 * Merge the given sorted list of blames into a preexisting origin. 438 * If there were no previous blames to that commit, it is entered into 439 * the commit priority queue of the score board. 440 */ 441 442static voidqueue_blames(struct scoreboard *sb,struct origin *porigin, 443struct blame_entry *sorted) 444{ 445if(porigin->suspects) 446 porigin->suspects =blame_merge(porigin->suspects, sorted); 447else{ 448struct origin *o; 449for(o = porigin->commit->util; o; o = o->next) { 450if(o->suspects) { 451 porigin->suspects = sorted; 452return; 453} 454} 455 porigin->suspects = sorted; 456prio_queue_put(&sb->commits, porigin->commit); 457} 458} 459 460/* 461 * Given a commit and a path in it, create a new origin structure. 462 * The callers that add blame to the scoreboard should use 463 * get_origin() to obtain shared, refcounted copy instead of calling 464 * this function directly. 465 */ 466static struct origin *make_origin(struct commit *commit,const char*path) 467{ 468struct origin *o; 469size_t pathlen =strlen(path) +1; 470 o =xcalloc(1,sizeof(*o) + pathlen); 471 o->commit = commit; 472 o->refcnt =1; 473 o->next = commit->util; 474 commit->util = o; 475memcpy(o->path, path, pathlen);/* includes NUL */ 476return o; 477} 478 479/* 480 * Locate an existing origin or create a new one. 481 * This moves the origin to front position in the commit util list. 482 */ 483static struct origin *get_origin(struct scoreboard *sb, 484struct commit *commit, 485const char*path) 486{ 487struct origin *o, *l; 488 489for(o = commit->util, l = NULL; o; l = o, o = o->next) { 490if(!strcmp(o->path, path)) { 491/* bump to front */ 492if(l) { 493 l->next = o->next; 494 o->next = commit->util; 495 commit->util = o; 496} 497returnorigin_incref(o); 498} 499} 500returnmake_origin(commit, path); 501} 502 503/* 504 * Fill the blob_sha1 field of an origin if it hasn't, so that later 505 * call to fill_origin_blob() can use it to locate the data. blob_sha1 506 * for an origin is also used to pass the blame for the entire file to 507 * the parent to detect the case where a child's blob is identical to 508 * that of its parent's. 509 * 510 * This also fills origin->mode for corresponding tree path. 511 */ 512static intfill_blob_sha1_and_mode(struct origin *origin) 513{ 514if(!is_null_sha1(origin->blob_sha1)) 515return0; 516if(get_tree_entry(origin->commit->object.oid.hash, 517 origin->path, 518 origin->blob_sha1, &origin->mode)) 519goto error_out; 520if(sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB) 521goto error_out; 522return0; 523 error_out: 524hashclr(origin->blob_sha1); 525 origin->mode = S_IFINVALID; 526return-1; 527} 528 529/* 530 * We have an origin -- check if the same path exists in the 531 * parent and return an origin structure to represent it. 532 */ 533static struct origin *find_origin(struct scoreboard *sb, 534struct commit *parent, 535struct origin *origin) 536{ 537struct origin *porigin; 538struct diff_options diff_opts; 539const char*paths[2]; 540 541/* First check any existing origins */ 542for(porigin = parent->util; porigin; porigin = porigin->next) 543if(!strcmp(porigin->path, origin->path)) { 544/* 545 * The same path between origin and its parent 546 * without renaming -- the most common case. 547 */ 548returnorigin_incref(porigin); 549} 550 551/* See if the origin->path is different between parent 552 * and origin first. Most of the time they are the 553 * same and diff-tree is fairly efficient about this. 554 */ 555diff_setup(&diff_opts); 556DIFF_OPT_SET(&diff_opts, RECURSIVE); 557 diff_opts.detect_rename =0; 558 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 559 paths[0] = origin->path; 560 paths[1] = NULL; 561 562parse_pathspec(&diff_opts.pathspec, 563 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 564 PATHSPEC_LITERAL_PATH,"", paths); 565diff_setup_done(&diff_opts); 566 567if(is_null_oid(&origin->commit->object.oid)) 568do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 569else 570diff_tree_sha1(parent->tree->object.oid.hash, 571 origin->commit->tree->object.oid.hash, 572"", &diff_opts); 573diffcore_std(&diff_opts); 574 575if(!diff_queued_diff.nr) { 576/* The path is the same as parent */ 577 porigin =get_origin(sb, parent, origin->path); 578hashcpy(porigin->blob_sha1, origin->blob_sha1); 579 porigin->mode = origin->mode; 580}else{ 581/* 582 * Since origin->path is a pathspec, if the parent 583 * commit had it as a directory, we will see a whole 584 * bunch of deletion of files in the directory that we 585 * do not care about. 586 */ 587int i; 588struct diff_filepair *p = NULL; 589for(i =0; i < diff_queued_diff.nr; i++) { 590const char*name; 591 p = diff_queued_diff.queue[i]; 592 name = p->one->path ? p->one->path : p->two->path; 593if(!strcmp(name, origin->path)) 594break; 595} 596if(!p) 597die("internal error in blame::find_origin"); 598switch(p->status) { 599default: 600die("internal error in blame::find_origin (%c)", 601 p->status); 602case'M': 603 porigin =get_origin(sb, parent, origin->path); 604hashcpy(porigin->blob_sha1, p->one->sha1); 605 porigin->mode = p->one->mode; 606break; 607case'A': 608case'T': 609/* Did not exist in parent, or type changed */ 610break; 611} 612} 613diff_flush(&diff_opts); 614free_pathspec(&diff_opts.pathspec); 615return porigin; 616} 617 618/* 619 * We have an origin -- find the path that corresponds to it in its 620 * parent and return an origin structure to represent it. 621 */ 622static struct origin *find_rename(struct scoreboard *sb, 623struct commit *parent, 624struct origin *origin) 625{ 626struct origin *porigin = NULL; 627struct diff_options diff_opts; 628int i; 629 630diff_setup(&diff_opts); 631DIFF_OPT_SET(&diff_opts, RECURSIVE); 632 diff_opts.detect_rename = DIFF_DETECT_RENAME; 633 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 634 diff_opts.single_follow = origin->path; 635diff_setup_done(&diff_opts); 636 637if(is_null_oid(&origin->commit->object.oid)) 638do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 639else 640diff_tree_sha1(parent->tree->object.oid.hash, 641 origin->commit->tree->object.oid.hash, 642"", &diff_opts); 643diffcore_std(&diff_opts); 644 645for(i =0; i < diff_queued_diff.nr; i++) { 646struct diff_filepair *p = diff_queued_diff.queue[i]; 647if((p->status =='R'|| p->status =='C') && 648!strcmp(p->two->path, origin->path)) { 649 porigin =get_origin(sb, parent, p->one->path); 650hashcpy(porigin->blob_sha1, p->one->sha1); 651 porigin->mode = p->one->mode; 652break; 653} 654} 655diff_flush(&diff_opts); 656free_pathspec(&diff_opts.pathspec); 657return porigin; 658} 659 660/* 661 * Append a new blame entry to a given output queue. 662 */ 663static voidadd_blame_entry(struct blame_entry ***queue,struct blame_entry *e) 664{ 665origin_incref(e->suspect); 666 667 e->next = **queue; 668**queue = e; 669*queue = &e->next; 670} 671 672/* 673 * src typically is on-stack; we want to copy the information in it to 674 * a malloced blame_entry that gets added to the given queue. The 675 * origin of dst loses a refcnt. 676 */ 677static voiddup_entry(struct blame_entry ***queue, 678struct blame_entry *dst,struct blame_entry *src) 679{ 680origin_incref(src->suspect); 681origin_decref(dst->suspect); 682memcpy(dst, src,sizeof(*src)); 683 dst->next = **queue; 684**queue = dst; 685*queue = &dst->next; 686} 687 688static const char*nth_line(struct scoreboard *sb,long lno) 689{ 690return sb->final_buf + sb->lineno[lno]; 691} 692 693static const char*nth_line_cb(void*data,long lno) 694{ 695returnnth_line((struct scoreboard *)data, lno); 696} 697 698/* 699 * It is known that lines between tlno to same came from parent, and e 700 * has an overlap with that range. it also is known that parent's 701 * line plno corresponds to e's line tlno. 702 * 703 * <---- e -----> 704 * <------> 705 * <------------> 706 * <------------> 707 * <------------------> 708 * 709 * Split e into potentially three parts; before this chunk, the chunk 710 * to be blamed for the parent, and after that portion. 711 */ 712static voidsplit_overlap(struct blame_entry *split, 713struct blame_entry *e, 714int tlno,int plno,int same, 715struct origin *parent) 716{ 717int chunk_end_lno; 718memset(split,0,sizeof(struct blame_entry [3])); 719 720if(e->s_lno < tlno) { 721/* there is a pre-chunk part not blamed on parent */ 722 split[0].suspect =origin_incref(e->suspect); 723 split[0].lno = e->lno; 724 split[0].s_lno = e->s_lno; 725 split[0].num_lines = tlno - e->s_lno; 726 split[1].lno = e->lno + tlno - e->s_lno; 727 split[1].s_lno = plno; 728} 729else{ 730 split[1].lno = e->lno; 731 split[1].s_lno = plno + (e->s_lno - tlno); 732} 733 734if(same < e->s_lno + e->num_lines) { 735/* there is a post-chunk part not blamed on parent */ 736 split[2].suspect =origin_incref(e->suspect); 737 split[2].lno = e->lno + (same - e->s_lno); 738 split[2].s_lno = e->s_lno + (same - e->s_lno); 739 split[2].num_lines = e->s_lno + e->num_lines - same; 740 chunk_end_lno = split[2].lno; 741} 742else 743 chunk_end_lno = e->lno + e->num_lines; 744 split[1].num_lines = chunk_end_lno - split[1].lno; 745 746/* 747 * if it turns out there is nothing to blame the parent for, 748 * forget about the splitting. !split[1].suspect signals this. 749 */ 750if(split[1].num_lines <1) 751return; 752 split[1].suspect =origin_incref(parent); 753} 754 755/* 756 * split_overlap() divided an existing blame e into up to three parts 757 * in split. Any assigned blame is moved to queue to 758 * reflect the split. 759 */ 760static voidsplit_blame(struct blame_entry ***blamed, 761struct blame_entry ***unblamed, 762struct blame_entry *split, 763struct blame_entry *e) 764{ 765struct blame_entry *new_entry; 766 767if(split[0].suspect && split[2].suspect) { 768/* The first part (reuse storage for the existing entry e) */ 769dup_entry(unblamed, e, &split[0]); 770 771/* The last part -- me */ 772 new_entry =xmalloc(sizeof(*new_entry)); 773memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 774add_blame_entry(unblamed, new_entry); 775 776/* ... and the middle part -- parent */ 777 new_entry =xmalloc(sizeof(*new_entry)); 778memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 779add_blame_entry(blamed, new_entry); 780} 781else if(!split[0].suspect && !split[2].suspect) 782/* 783 * The parent covers the entire area; reuse storage for 784 * e and replace it with the parent. 785 */ 786dup_entry(blamed, e, &split[1]); 787else if(split[0].suspect) { 788/* me and then parent */ 789dup_entry(unblamed, e, &split[0]); 790 791 new_entry =xmalloc(sizeof(*new_entry)); 792memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 793add_blame_entry(blamed, new_entry); 794} 795else{ 796/* parent and then me */ 797dup_entry(blamed, e, &split[1]); 798 799 new_entry =xmalloc(sizeof(*new_entry)); 800memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 801add_blame_entry(unblamed, new_entry); 802} 803} 804 805/* 806 * After splitting the blame, the origins used by the 807 * on-stack blame_entry should lose one refcnt each. 808 */ 809static voiddecref_split(struct blame_entry *split) 810{ 811int i; 812 813for(i =0; i <3; i++) 814origin_decref(split[i].suspect); 815} 816 817/* 818 * reverse_blame reverses the list given in head, appending tail. 819 * That allows us to build lists in reverse order, then reverse them 820 * afterwards. This can be faster than building the list in proper 821 * order right away. The reason is that building in proper order 822 * requires writing a link in the _previous_ element, while building 823 * in reverse order just requires placing the list head into the 824 * _current_ element. 825 */ 826 827static struct blame_entry *reverse_blame(struct blame_entry *head, 828struct blame_entry *tail) 829{ 830while(head) { 831struct blame_entry *next = head->next; 832 head->next = tail; 833 tail = head; 834 head = next; 835} 836return tail; 837} 838 839/* 840 * Process one hunk from the patch between the current suspect for 841 * blame_entry e and its parent. This first blames any unfinished 842 * entries before the chunk (which is where target and parent start 843 * differing) on the parent, and then splits blame entries at the 844 * start and at the end of the difference region. Since use of -M and 845 * -C options may lead to overlapping/duplicate source line number 846 * ranges, all we can rely on from sorting/merging is the order of the 847 * first suspect line number. 848 */ 849static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 850int tlno,int offset,int same, 851struct origin *parent) 852{ 853struct blame_entry *e = **srcq; 854struct blame_entry *samep = NULL, *diffp = NULL; 855 856while(e && e->s_lno < tlno) { 857struct blame_entry *next = e->next; 858/* 859 * current record starts before differing portion. If 860 * it reaches into it, we need to split it up and 861 * examine the second part separately. 862 */ 863if(e->s_lno + e->num_lines > tlno) { 864/* Move second half to a new record */ 865int len = tlno - e->s_lno; 866struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 867 n->suspect = e->suspect; 868 n->lno = e->lno + len; 869 n->s_lno = e->s_lno + len; 870 n->num_lines = e->num_lines - len; 871 e->num_lines = len; 872 e->score =0; 873/* Push new record to diffp */ 874 n->next = diffp; 875 diffp = n; 876}else 877origin_decref(e->suspect); 878/* Pass blame for everything before the differing 879 * chunk to the parent */ 880 e->suspect =origin_incref(parent); 881 e->s_lno += offset; 882 e->next = samep; 883 samep = e; 884 e = next; 885} 886/* 887 * As we don't know how much of a common stretch after this 888 * diff will occur, the currently blamed parts are all that we 889 * can assign to the parent for now. 890 */ 891 892if(samep) { 893**dstq =reverse_blame(samep, **dstq); 894*dstq = &samep->next; 895} 896/* 897 * Prepend the split off portions: everything after e starts 898 * after the blameable portion. 899 */ 900 e =reverse_blame(diffp, e); 901 902/* 903 * Now retain records on the target while parts are different 904 * from the parent. 905 */ 906 samep = NULL; 907 diffp = NULL; 908while(e && e->s_lno < same) { 909struct blame_entry *next = e->next; 910 911/* 912 * If current record extends into sameness, need to split. 913 */ 914if(e->s_lno + e->num_lines > same) { 915/* 916 * Move second half to a new record to be 917 * processed by later chunks 918 */ 919int len = same - e->s_lno; 920struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 921 n->suspect =origin_incref(e->suspect); 922 n->lno = e->lno + len; 923 n->s_lno = e->s_lno + len; 924 n->num_lines = e->num_lines - len; 925 e->num_lines = len; 926 e->score =0; 927/* Push new record to samep */ 928 n->next = samep; 929 samep = n; 930} 931 e->next = diffp; 932 diffp = e; 933 e = next; 934} 935**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 936/* Move across elements that are in the unblamable portion */ 937if(diffp) 938*srcq = &diffp->next; 939} 940 941struct blame_chunk_cb_data { 942struct origin *parent; 943long offset; 944struct blame_entry **dstq; 945struct blame_entry **srcq; 946}; 947 948/* diff chunks are from parent to target */ 949static intblame_chunk_cb(long start_a,long count_a, 950long start_b,long count_b,void*data) 951{ 952struct blame_chunk_cb_data *d = data; 953if(start_a - start_b != d->offset) 954die("internal error in blame::blame_chunk_cb"); 955blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 956 start_b + count_b, d->parent); 957 d->offset = start_a + count_a - (start_b + count_b); 958return0; 959} 960 961/* 962 * We are looking at the origin 'target' and aiming to pass blame 963 * for the lines it is suspected to its parent. Run diff to find 964 * which lines came from parent and pass blame for them. 965 */ 966static voidpass_blame_to_parent(struct scoreboard *sb, 967struct origin *target, 968struct origin *parent) 969{ 970 mmfile_t file_p, file_o; 971struct blame_chunk_cb_data d; 972struct blame_entry *newdest = NULL; 973 974if(!target->suspects) 975return;/* nothing remains for this target */ 976 977 d.parent = parent; 978 d.offset =0; 979 d.dstq = &newdest; d.srcq = &target->suspects; 980 981fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 982fill_origin_blob(&sb->revs->diffopt, target, &file_o); 983 num_get_patch++; 984 985if(diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d)) 986die("unable to generate diff (%s->%s)", 987oid_to_hex(&parent->commit->object.oid), 988oid_to_hex(&target->commit->object.oid)); 989/* The rest are the same as the parent */ 990blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 991*d.dstq = NULL; 992queue_blames(sb, parent, newdest); 993 994return; 995} 996 997/* 998 * The lines in blame_entry after splitting blames many times can become 999 * very small and trivial, and at some point it becomes pointless to1000 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any1001 * ordinary C program, and it is not worth to say it was copied from1002 * totally unrelated file in the parent.1003 *1004 * Compute how trivial the lines in the blame_entry are.1005 */1006static unsignedent_score(struct scoreboard *sb,struct blame_entry *e)1007{1008unsigned score;1009const char*cp, *ep;10101011if(e->score)1012return e->score;10131014 score =1;1015 cp =nth_line(sb, e->lno);1016 ep =nth_line(sb, e->lno + e->num_lines);1017while(cp < ep) {1018unsigned ch = *((unsigned char*)cp);1019if(isalnum(ch))1020 score++;1021 cp++;1022}1023 e->score = score;1024return score;1025}10261027/*1028 * best_so_far[] and this[] are both a split of an existing blame_entry1029 * that passes blame to the parent. Maintain best_so_far the best split1030 * so far, by comparing this and best_so_far and copying this into1031 * bst_so_far as needed.1032 */1033static voidcopy_split_if_better(struct scoreboard *sb,1034struct blame_entry *best_so_far,1035struct blame_entry *this)1036{1037int i;10381039if(!this[1].suspect)1040return;1041if(best_so_far[1].suspect) {1042if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1043return;1044}10451046for(i =0; i <3; i++)1047origin_incref(this[i].suspect);1048decref_split(best_so_far);1049memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1050}10511052/*1053 * We are looking at a part of the final image represented by1054 * ent (tlno and same are offset by ent->s_lno).1055 * tlno is where we are looking at in the final image.1056 * up to (but not including) same match preimage.1057 * plno is where we are looking at in the preimage.1058 *1059 * <-------------- final image ---------------------->1060 * <------ent------>1061 * ^tlno ^same1062 * <---------preimage----->1063 * ^plno1064 *1065 * All line numbers are 0-based.1066 */1067static voidhandle_split(struct scoreboard *sb,1068struct blame_entry *ent,1069int tlno,int plno,int same,1070struct origin *parent,1071struct blame_entry *split)1072{1073if(ent->num_lines <= tlno)1074return;1075if(tlno < same) {1076struct blame_entry this[3];1077 tlno += ent->s_lno;1078 same += ent->s_lno;1079split_overlap(this, ent, tlno, plno, same, parent);1080copy_split_if_better(sb, split,this);1081decref_split(this);1082}1083}10841085struct handle_split_cb_data {1086struct scoreboard *sb;1087struct blame_entry *ent;1088struct origin *parent;1089struct blame_entry *split;1090long plno;1091long tlno;1092};10931094static inthandle_split_cb(long start_a,long count_a,1095long start_b,long count_b,void*data)1096{1097struct handle_split_cb_data *d = data;1098handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1099 d->split);1100 d->plno = start_a + count_a;1101 d->tlno = start_b + count_b;1102return0;1103}11041105/*1106 * Find the lines from parent that are the same as ent so that1107 * we can pass blames to it. file_p has the blob contents for1108 * the parent.1109 */1110static voidfind_copy_in_blob(struct scoreboard *sb,1111struct blame_entry *ent,1112struct origin *parent,1113struct blame_entry *split,1114 mmfile_t *file_p)1115{1116const char*cp;1117 mmfile_t file_o;1118struct handle_split_cb_data d;11191120memset(&d,0,sizeof(d));1121 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1122/*1123 * Prepare mmfile that contains only the lines in ent.1124 */1125 cp =nth_line(sb, ent->lno);1126 file_o.ptr = (char*) cp;1127 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11281129/*1130 * file_o is a part of final image we are annotating.1131 * file_p partially may match that image.1132 */1133memset(split,0,sizeof(struct blame_entry [3]));1134if(diff_hunks(file_p, &file_o,1, handle_split_cb, &d))1135die("unable to generate diff (%s)",1136oid_to_hex(&parent->commit->object.oid));1137/* remainder, if any, all match the preimage */1138handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1139}11401141/* Move all blame entries from list *source that have a score smaller1142 * than score_min to the front of list *small.1143 * Returns a pointer to the link pointing to the old head of the small list.1144 */11451146static struct blame_entry **filter_small(struct scoreboard *sb,1147struct blame_entry **small,1148struct blame_entry **source,1149unsigned score_min)1150{1151struct blame_entry *p = *source;1152struct blame_entry *oldsmall = *small;1153while(p) {1154if(ent_score(sb, p) <= score_min) {1155*small = p;1156 small = &p->next;1157 p = *small;1158}else{1159*source = p;1160 source = &p->next;1161 p = *source;1162}1163}1164*small = oldsmall;1165*source = NULL;1166return small;1167}11681169/*1170 * See if lines currently target is suspected for can be attributed to1171 * parent.1172 */1173static voidfind_move_in_parent(struct scoreboard *sb,1174struct blame_entry ***blamed,1175struct blame_entry **toosmall,1176struct origin *target,1177struct origin *parent)1178{1179struct blame_entry *e, split[3];1180struct blame_entry *unblamed = target->suspects;1181struct blame_entry *leftover = NULL;1182 mmfile_t file_p;11831184if(!unblamed)1185return;/* nothing remains for this target */11861187fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1188if(!file_p.ptr)1189return;11901191/* At each iteration, unblamed has a NULL-terminated list of1192 * entries that have not yet been tested for blame. leftover1193 * contains the reversed list of entries that have been tested1194 * without being assignable to the parent.1195 */1196do{1197struct blame_entry **unblamedtail = &unblamed;1198struct blame_entry *next;1199for(e = unblamed; e; e = next) {1200 next = e->next;1201find_copy_in_blob(sb, e, parent, split, &file_p);1202if(split[1].suspect &&1203 blame_move_score <ent_score(sb, &split[1])) {1204split_blame(blamed, &unblamedtail, split, e);1205}else{1206 e->next = leftover;1207 leftover = e;1208}1209decref_split(split);1210}1211*unblamedtail = NULL;1212 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1213}while(unblamed);1214 target->suspects =reverse_blame(leftover, NULL);1215}12161217struct blame_list {1218struct blame_entry *ent;1219struct blame_entry split[3];1220};12211222/*1223 * Count the number of entries the target is suspected for,1224 * and prepare a list of entry and the best split.1225 */1226static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1227int*num_ents_p)1228{1229struct blame_entry *e;1230int num_ents, i;1231struct blame_list *blame_list = NULL;12321233for(e = unblamed, num_ents =0; e; e = e->next)1234 num_ents++;1235if(num_ents) {1236 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1237for(e = unblamed, i =0; e; e = e->next)1238 blame_list[i++].ent = e;1239}1240*num_ents_p = num_ents;1241return blame_list;1242}12431244/*1245 * For lines target is suspected for, see if we can find code movement1246 * across file boundary from the parent commit. porigin is the path1247 * in the parent we already tried.1248 */1249static voidfind_copy_in_parent(struct scoreboard *sb,1250struct blame_entry ***blamed,1251struct blame_entry **toosmall,1252struct origin *target,1253struct commit *parent,1254struct origin *porigin,1255int opt)1256{1257struct diff_options diff_opts;1258int i, j;1259struct blame_list *blame_list;1260int num_ents;1261struct blame_entry *unblamed = target->suspects;1262struct blame_entry *leftover = NULL;12631264if(!unblamed)1265return;/* nothing remains for this target */12661267diff_setup(&diff_opts);1268DIFF_OPT_SET(&diff_opts, RECURSIVE);1269 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12701271diff_setup_done(&diff_opts);12721273/* Try "find copies harder" on new path if requested;1274 * we do not want to use diffcore_rename() actually to1275 * match things up; find_copies_harder is set only to1276 * force diff_tree_sha1() to feed all filepairs to diff_queue,1277 * and this code needs to be after diff_setup_done(), which1278 * usually makes find-copies-harder imply copy detection.1279 */1280if((opt & PICKAXE_BLAME_COPY_HARDEST)1281|| ((opt & PICKAXE_BLAME_COPY_HARDER)1282&& (!porigin ||strcmp(target->path, porigin->path))))1283DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12841285if(is_null_oid(&target->commit->object.oid))1286do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1287else1288diff_tree_sha1(parent->tree->object.oid.hash,1289 target->commit->tree->object.oid.hash,1290"", &diff_opts);12911292if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1293diffcore_std(&diff_opts);12941295do{1296struct blame_entry **unblamedtail = &unblamed;1297 blame_list =setup_blame_list(unblamed, &num_ents);12981299for(i =0; i < diff_queued_diff.nr; i++) {1300struct diff_filepair *p = diff_queued_diff.queue[i];1301struct origin *norigin;1302 mmfile_t file_p;1303struct blame_entry this[3];13041305if(!DIFF_FILE_VALID(p->one))1306continue;/* does not exist in parent */1307if(S_ISGITLINK(p->one->mode))1308continue;/* ignore git links */1309if(porigin && !strcmp(p->one->path, porigin->path))1310/* find_move already dealt with this path */1311continue;13121313 norigin =get_origin(sb, parent, p->one->path);1314hashcpy(norigin->blob_sha1, p->one->sha1);1315 norigin->mode = p->one->mode;1316fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1317if(!file_p.ptr)1318continue;13191320for(j =0; j < num_ents; j++) {1321find_copy_in_blob(sb, blame_list[j].ent,1322 norigin,this, &file_p);1323copy_split_if_better(sb, blame_list[j].split,1324this);1325decref_split(this);1326}1327origin_decref(norigin);1328}13291330for(j =0; j < num_ents; j++) {1331struct blame_entry *split = blame_list[j].split;1332if(split[1].suspect &&1333 blame_copy_score <ent_score(sb, &split[1])) {1334split_blame(blamed, &unblamedtail, split,1335 blame_list[j].ent);1336}else{1337 blame_list[j].ent->next = leftover;1338 leftover = blame_list[j].ent;1339}1340decref_split(split);1341}1342free(blame_list);1343*unblamedtail = NULL;1344 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1345}while(unblamed);1346 target->suspects =reverse_blame(leftover, NULL);1347diff_flush(&diff_opts);1348free_pathspec(&diff_opts.pathspec);1349}13501351/*1352 * The blobs of origin and porigin exactly match, so everything1353 * origin is suspected for can be blamed on the parent.1354 */1355static voidpass_whole_blame(struct scoreboard *sb,1356struct origin *origin,struct origin *porigin)1357{1358struct blame_entry *e, *suspects;13591360if(!porigin->file.ptr && origin->file.ptr) {1361/* Steal its file */1362 porigin->file = origin->file;1363 origin->file.ptr = NULL;1364}1365 suspects = origin->suspects;1366 origin->suspects = NULL;1367for(e = suspects; e; e = e->next) {1368origin_incref(porigin);1369origin_decref(e->suspect);1370 e->suspect = porigin;1371}1372queue_blames(sb, porigin, suspects);1373}13741375/*1376 * We pass blame from the current commit to its parents. We keep saying1377 * "parent" (and "porigin"), but what we mean is to find scapegoat to1378 * exonerate ourselves.1379 */1380static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1381{1382if(!reverse) {1383if(revs->first_parent_only &&1384 commit->parents &&1385 commit->parents->next) {1386free_commit_list(commit->parents->next);1387 commit->parents->next = NULL;1388}1389return commit->parents;1390}1391returnlookup_decoration(&revs->children, &commit->object);1392}13931394static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1395{1396struct commit_list *l =first_scapegoat(revs, commit);1397returncommit_list_count(l);1398}13991400/* Distribute collected unsorted blames to the respected sorted lists1401 * in the various origins.1402 */1403static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1404{1405 blamed =blame_sort(blamed, compare_blame_suspect);1406while(blamed)1407{1408struct origin *porigin = blamed->suspect;1409struct blame_entry *suspects = NULL;1410do{1411struct blame_entry *next = blamed->next;1412 blamed->next = suspects;1413 suspects = blamed;1414 blamed = next;1415}while(blamed && blamed->suspect == porigin);1416 suspects =reverse_blame(suspects, NULL);1417queue_blames(sb, porigin, suspects);1418}1419}14201421#define MAXSG 1614221423static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1424{1425struct rev_info *revs = sb->revs;1426int i, pass, num_sg;1427struct commit *commit = origin->commit;1428struct commit_list *sg;1429struct origin *sg_buf[MAXSG];1430struct origin *porigin, **sg_origin = sg_buf;1431struct blame_entry *toosmall = NULL;1432struct blame_entry *blames, **blametail = &blames;14331434 num_sg =num_scapegoats(revs, commit);1435if(!num_sg)1436goto finish;1437else if(num_sg <ARRAY_SIZE(sg_buf))1438memset(sg_buf,0,sizeof(sg_buf));1439else1440 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14411442/*1443 * The first pass looks for unrenamed path to optimize for1444 * common cases, then we look for renames in the second pass.1445 */1446for(pass =0; pass <2- no_whole_file_rename; pass++) {1447struct origin *(*find)(struct scoreboard *,1448struct commit *,struct origin *);1449 find = pass ? find_rename : find_origin;14501451for(i =0, sg =first_scapegoat(revs, commit);1452 i < num_sg && sg;1453 sg = sg->next, i++) {1454struct commit *p = sg->item;1455int j, same;14561457if(sg_origin[i])1458continue;1459if(parse_commit(p))1460continue;1461 porigin =find(sb, p, origin);1462if(!porigin)1463continue;1464if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1465pass_whole_blame(sb, origin, porigin);1466origin_decref(porigin);1467goto finish;1468}1469for(j = same =0; j < i; j++)1470if(sg_origin[j] &&1471!hashcmp(sg_origin[j]->blob_sha1,1472 porigin->blob_sha1)) {1473 same =1;1474break;1475}1476if(!same)1477 sg_origin[i] = porigin;1478else1479origin_decref(porigin);1480}1481}14821483 num_commits++;1484for(i =0, sg =first_scapegoat(revs, commit);1485 i < num_sg && sg;1486 sg = sg->next, i++) {1487struct origin *porigin = sg_origin[i];1488if(!porigin)1489continue;1490if(!origin->previous) {1491origin_incref(porigin);1492 origin->previous = porigin;1493}1494pass_blame_to_parent(sb, origin, porigin);1495if(!origin->suspects)1496goto finish;1497}14981499/*1500 * Optionally find moves in parents' files.1501 */1502if(opt & PICKAXE_BLAME_MOVE) {1503filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1504if(origin->suspects) {1505for(i =0, sg =first_scapegoat(revs, commit);1506 i < num_sg && sg;1507 sg = sg->next, i++) {1508struct origin *porigin = sg_origin[i];1509if(!porigin)1510continue;1511find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1512if(!origin->suspects)1513break;1514}1515}1516}15171518/*1519 * Optionally find copies from parents' files.1520 */1521if(opt & PICKAXE_BLAME_COPY) {1522if(blame_copy_score > blame_move_score)1523filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1524else if(blame_copy_score < blame_move_score) {1525 origin->suspects =blame_merge(origin->suspects, toosmall);1526 toosmall = NULL;1527filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1528}1529if(!origin->suspects)1530goto finish;15311532for(i =0, sg =first_scapegoat(revs, commit);1533 i < num_sg && sg;1534 sg = sg->next, i++) {1535struct origin *porigin = sg_origin[i];1536find_copy_in_parent(sb, &blametail, &toosmall,1537 origin, sg->item, porigin, opt);1538if(!origin->suspects)1539goto finish;1540}1541}15421543finish:1544*blametail = NULL;1545distribute_blame(sb, blames);1546/*1547 * prepend toosmall to origin->suspects1548 *1549 * There is no point in sorting: this ends up on a big1550 * unsorted list in the caller anyway.1551 */1552if(toosmall) {1553struct blame_entry **tail = &toosmall;1554while(*tail)1555 tail = &(*tail)->next;1556*tail = origin->suspects;1557 origin->suspects = toosmall;1558}1559for(i =0; i < num_sg; i++) {1560if(sg_origin[i]) {1561drop_origin_blob(sg_origin[i]);1562origin_decref(sg_origin[i]);1563}1564}1565drop_origin_blob(origin);1566if(sg_buf != sg_origin)1567free(sg_origin);1568}15691570/*1571 * Information on commits, used for output.1572 */1573struct commit_info {1574struct strbuf author;1575struct strbuf author_mail;1576unsigned long author_time;1577struct strbuf author_tz;15781579/* filled only when asked for details */1580struct strbuf committer;1581struct strbuf committer_mail;1582unsigned long committer_time;1583struct strbuf committer_tz;15841585struct strbuf summary;1586};15871588/*1589 * Parse author/committer line in the commit object buffer1590 */1591static voidget_ac_line(const char*inbuf,const char*what,1592struct strbuf *name,struct strbuf *mail,1593unsigned long*time,struct strbuf *tz)1594{1595struct ident_split ident;1596size_t len, maillen, namelen;1597char*tmp, *endp;1598const char*namebuf, *mailbuf;15991600 tmp =strstr(inbuf, what);1601if(!tmp)1602goto error_out;1603 tmp +=strlen(what);1604 endp =strchr(tmp,'\n');1605if(!endp)1606 len =strlen(tmp);1607else1608 len = endp - tmp;16091610if(split_ident_line(&ident, tmp, len)) {1611 error_out:1612/* Ugh */1613 tmp ="(unknown)";1614strbuf_addstr(name, tmp);1615strbuf_addstr(mail, tmp);1616strbuf_addstr(tz, tmp);1617*time =0;1618return;1619}16201621 namelen = ident.name_end - ident.name_begin;1622 namebuf = ident.name_begin;16231624 maillen = ident.mail_end - ident.mail_begin;1625 mailbuf = ident.mail_begin;16261627if(ident.date_begin && ident.date_end)1628*time =strtoul(ident.date_begin, NULL,10);1629else1630*time =0;16311632if(ident.tz_begin && ident.tz_end)1633strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1634else1635strbuf_addstr(tz,"(unknown)");16361637/*1638 * Now, convert both name and e-mail using mailmap1639 */1640map_user(&mailmap, &mailbuf, &maillen,1641&namebuf, &namelen);16421643strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1644strbuf_add(name, namebuf, namelen);1645}16461647static voidcommit_info_init(struct commit_info *ci)1648{16491650strbuf_init(&ci->author,0);1651strbuf_init(&ci->author_mail,0);1652strbuf_init(&ci->author_tz,0);1653strbuf_init(&ci->committer,0);1654strbuf_init(&ci->committer_mail,0);1655strbuf_init(&ci->committer_tz,0);1656strbuf_init(&ci->summary,0);1657}16581659static voidcommit_info_destroy(struct commit_info *ci)1660{16611662strbuf_release(&ci->author);1663strbuf_release(&ci->author_mail);1664strbuf_release(&ci->author_tz);1665strbuf_release(&ci->committer);1666strbuf_release(&ci->committer_mail);1667strbuf_release(&ci->committer_tz);1668strbuf_release(&ci->summary);1669}16701671static voidget_commit_info(struct commit *commit,1672struct commit_info *ret,1673int detailed)1674{1675int len;1676const char*subject, *encoding;1677const char*message;16781679commit_info_init(ret);16801681 encoding =get_log_output_encoding();1682 message =logmsg_reencode(commit, NULL, encoding);1683get_ac_line(message,"\nauthor ",1684&ret->author, &ret->author_mail,1685&ret->author_time, &ret->author_tz);16861687if(!detailed) {1688unuse_commit_buffer(commit, message);1689return;1690}16911692get_ac_line(message,"\ncommitter ",1693&ret->committer, &ret->committer_mail,1694&ret->committer_time, &ret->committer_tz);16951696 len =find_commit_subject(message, &subject);1697if(len)1698strbuf_add(&ret->summary, subject, len);1699else1700strbuf_addf(&ret->summary,"(%s)",oid_to_hex(&commit->object.oid));17011702unuse_commit_buffer(commit, message);1703}17041705/*1706 * To allow LF and other nonportable characters in pathnames,1707 * they are c-style quoted as needed.1708 */1709static voidwrite_filename_info(const char*path)1710{1711printf("filename ");1712write_name_quoted(path, stdout,'\n');1713}17141715/*1716 * Porcelain/Incremental format wants to show a lot of details per1717 * commit. Instead of repeating this every line, emit it only once,1718 * the first time each commit appears in the output (unless the1719 * user has specifically asked for us to repeat).1720 */1721static intemit_one_suspect_detail(struct origin *suspect,int repeat)1722{1723struct commit_info ci;17241725if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1726return0;17271728 suspect->commit->object.flags |= METAINFO_SHOWN;1729get_commit_info(suspect->commit, &ci,1);1730printf("author%s\n", ci.author.buf);1731printf("author-mail%s\n", ci.author_mail.buf);1732printf("author-time%lu\n", ci.author_time);1733printf("author-tz%s\n", ci.author_tz.buf);1734printf("committer%s\n", ci.committer.buf);1735printf("committer-mail%s\n", ci.committer_mail.buf);1736printf("committer-time%lu\n", ci.committer_time);1737printf("committer-tz%s\n", ci.committer_tz.buf);1738printf("summary%s\n", ci.summary.buf);1739if(suspect->commit->object.flags & UNINTERESTING)1740printf("boundary\n");1741if(suspect->previous) {1742struct origin *prev = suspect->previous;1743printf("previous%s",oid_to_hex(&prev->commit->object.oid));1744write_name_quoted(prev->path, stdout,'\n');1745}17461747commit_info_destroy(&ci);17481749return1;1750}17511752/*1753 * The blame_entry is found to be guilty for the range.1754 * Show it in incremental output.1755 */1756static voidfound_guilty_entry(struct blame_entry *ent,1757struct progress_info *pi)1758{1759if(incremental) {1760struct origin *suspect = ent->suspect;17611762printf("%s %d %d %d\n",1763oid_to_hex(&suspect->commit->object.oid),1764 ent->s_lno +1, ent->lno +1, ent->num_lines);1765emit_one_suspect_detail(suspect,0);1766write_filename_info(suspect->path);1767maybe_flush_or_die(stdout,"stdout");1768}1769 pi->blamed_lines += ent->num_lines;1770display_progress(pi->progress, pi->blamed_lines);1771}17721773/*1774 * The main loop -- while we have blobs with lines whose true origin1775 * is still unknown, pick one blob, and allow its lines to pass blames1776 * to its parents. */1777static voidassign_blame(struct scoreboard *sb,int opt)1778{1779struct rev_info *revs = sb->revs;1780struct commit *commit =prio_queue_get(&sb->commits);1781struct progress_info pi = { NULL,0};17821783if(show_progress)1784 pi.progress =start_progress_delay(_("Blaming lines"),1785 sb->num_lines,50,1);17861787while(commit) {1788struct blame_entry *ent;1789struct origin *suspect = commit->util;17901791/* find one suspect to break down */1792while(suspect && !suspect->suspects)1793 suspect = suspect->next;17941795if(!suspect) {1796 commit =prio_queue_get(&sb->commits);1797continue;1798}17991800assert(commit == suspect->commit);18011802/*1803 * We will use this suspect later in the loop,1804 * so hold onto it in the meantime.1805 */1806origin_incref(suspect);1807parse_commit(commit);1808if(reverse ||1809(!(commit->object.flags & UNINTERESTING) &&1810!(revs->max_age != -1&& commit->date < revs->max_age)))1811pass_blame(sb, suspect, opt);1812else{1813 commit->object.flags |= UNINTERESTING;1814if(commit->object.parsed)1815mark_parents_uninteresting(commit);1816}1817/* treat root commit as boundary */1818if(!commit->parents && !show_root)1819 commit->object.flags |= UNINTERESTING;18201821/* Take responsibility for the remaining entries */1822 ent = suspect->suspects;1823if(ent) {1824 suspect->guilty =1;1825for(;;) {1826struct blame_entry *next = ent->next;1827found_guilty_entry(ent, &pi);1828if(next) {1829 ent = next;1830continue;1831}1832 ent->next = sb->ent;1833 sb->ent = suspect->suspects;1834 suspect->suspects = NULL;1835break;1836}1837}1838origin_decref(suspect);18391840if(DEBUG)/* sanity */1841sanity_check_refcnt(sb);1842}18431844stop_progress(&pi.progress);1845}18461847static const char*format_time(unsigned long time,const char*tz_str,1848int show_raw_time)1849{1850static struct strbuf time_buf = STRBUF_INIT;18511852strbuf_reset(&time_buf);1853if(show_raw_time) {1854strbuf_addf(&time_buf,"%lu%s", time, tz_str);1855}1856else{1857const char*time_str;1858size_t time_width;1859int tz;1860 tz =atoi(tz_str);1861 time_str =show_date(time, tz, &blame_date_mode);1862strbuf_addstr(&time_buf, time_str);1863/*1864 * Add space paddings to time_buf to display a fixed width1865 * string, and use time_width for display width calibration.1866 */1867for(time_width =utf8_strwidth(time_str);1868 time_width < blame_date_width;1869 time_width++)1870strbuf_addch(&time_buf,' ');1871}1872return time_buf.buf;1873}18741875#define OUTPUT_ANNOTATE_COMPAT 0011876#define OUTPUT_LONG_OBJECT_NAME 0021877#define OUTPUT_RAW_TIMESTAMP 0041878#define OUTPUT_PORCELAIN 0101879#define OUTPUT_SHOW_NAME 0201880#define OUTPUT_SHOW_NUMBER 0401881#define OUTPUT_SHOW_SCORE 01001882#define OUTPUT_NO_AUTHOR 02001883#define OUTPUT_SHOW_EMAIL 04001884#define OUTPUT_LINE_PORCELAIN 0100018851886static voidemit_porcelain_details(struct origin *suspect,int repeat)1887{1888if(emit_one_suspect_detail(suspect, repeat) ||1889(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1890write_filename_info(suspect->path);1891}18921893static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1894int opt)1895{1896int repeat = opt & OUTPUT_LINE_PORCELAIN;1897int cnt;1898const char*cp;1899struct origin *suspect = ent->suspect;1900char hex[GIT_SHA1_HEXSZ +1];19011902sha1_to_hex_r(hex, suspect->commit->object.oid.hash);1903printf("%s %d %d %d\n",1904 hex,1905 ent->s_lno +1,1906 ent->lno +1,1907 ent->num_lines);1908emit_porcelain_details(suspect, repeat);19091910 cp =nth_line(sb, ent->lno);1911for(cnt =0; cnt < ent->num_lines; cnt++) {1912char ch;1913if(cnt) {1914printf("%s %d %d\n", hex,1915 ent->s_lno +1+ cnt,1916 ent->lno +1+ cnt);1917if(repeat)1918emit_porcelain_details(suspect,1);1919}1920putchar('\t');1921do{1922 ch = *cp++;1923putchar(ch);1924}while(ch !='\n'&&1925 cp < sb->final_buf + sb->final_buf_size);1926}19271928if(sb->final_buf_size && cp[-1] !='\n')1929putchar('\n');1930}19311932static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1933{1934int cnt;1935const char*cp;1936struct origin *suspect = ent->suspect;1937struct commit_info ci;1938char hex[GIT_SHA1_HEXSZ +1];1939int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19401941get_commit_info(suspect->commit, &ci,1);1942sha1_to_hex_r(hex, suspect->commit->object.oid.hash);19431944 cp =nth_line(sb, ent->lno);1945for(cnt =0; cnt < ent->num_lines; cnt++) {1946char ch;1947int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19481949if(suspect->commit->object.flags & UNINTERESTING) {1950if(blank_boundary)1951memset(hex,' ', length);1952else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1953 length--;1954putchar('^');1955}1956}19571958printf("%.*s", length, hex);1959if(opt & OUTPUT_ANNOTATE_COMPAT) {1960const char*name;1961if(opt & OUTPUT_SHOW_EMAIL)1962 name = ci.author_mail.buf;1963else1964 name = ci.author.buf;1965printf("\t(%10s\t%10s\t%d)", name,1966format_time(ci.author_time, ci.author_tz.buf,1967 show_raw_time),1968 ent->lno +1+ cnt);1969}else{1970if(opt & OUTPUT_SHOW_SCORE)1971printf(" %*d%02d",1972 max_score_digits, ent->score,1973 ent->suspect->refcnt);1974if(opt & OUTPUT_SHOW_NAME)1975printf(" %-*.*s", longest_file, longest_file,1976 suspect->path);1977if(opt & OUTPUT_SHOW_NUMBER)1978printf(" %*d", max_orig_digits,1979 ent->s_lno +1+ cnt);19801981if(!(opt & OUTPUT_NO_AUTHOR)) {1982const char*name;1983int pad;1984if(opt & OUTPUT_SHOW_EMAIL)1985 name = ci.author_mail.buf;1986else1987 name = ci.author.buf;1988 pad = longest_author -utf8_strwidth(name);1989printf(" (%s%*s%10s",1990 name, pad,"",1991format_time(ci.author_time,1992 ci.author_tz.buf,1993 show_raw_time));1994}1995printf(" %*d) ",1996 max_digits, ent->lno +1+ cnt);1997}1998do{1999 ch = *cp++;2000putchar(ch);2001}while(ch !='\n'&&2002 cp < sb->final_buf + sb->final_buf_size);2003}20042005if(sb->final_buf_size && cp[-1] !='\n')2006putchar('\n');20072008commit_info_destroy(&ci);2009}20102011static voidoutput(struct scoreboard *sb,int option)2012{2013struct blame_entry *ent;20142015if(option & OUTPUT_PORCELAIN) {2016for(ent = sb->ent; ent; ent = ent->next) {2017int count =0;2018struct origin *suspect;2019struct commit *commit = ent->suspect->commit;2020if(commit->object.flags & MORE_THAN_ONE_PATH)2021continue;2022for(suspect = commit->util; suspect; suspect = suspect->next) {2023if(suspect->guilty && count++) {2024 commit->object.flags |= MORE_THAN_ONE_PATH;2025break;2026}2027}2028}2029}20302031for(ent = sb->ent; ent; ent = ent->next) {2032if(option & OUTPUT_PORCELAIN)2033emit_porcelain(sb, ent, option);2034else{2035emit_other(sb, ent, option);2036}2037}2038}20392040static const char*get_next_line(const char*start,const char*end)2041{2042const char*nl =memchr(start,'\n', end - start);2043return nl ? nl +1: end;2044}20452046/*2047 * To allow quick access to the contents of nth line in the2048 * final image, prepare an index in the scoreboard.2049 */2050static intprepare_lines(struct scoreboard *sb)2051{2052const char*buf = sb->final_buf;2053unsigned long len = sb->final_buf_size;2054const char*end = buf + len;2055const char*p;2056int*lineno;2057int num =0;20582059for(p = buf; p < end; p =get_next_line(p, end))2060 num++;20612062 sb->lineno = lineno =xmalloc(sizeof(*sb->lineno) * (num +1));20632064for(p = buf; p < end; p =get_next_line(p, end))2065*lineno++ = p - buf;20662067*lineno = len;20682069 sb->num_lines = num;2070return sb->num_lines;2071}20722073/*2074 * Add phony grafts for use with -S; this is primarily to2075 * support git's cvsserver that wants to give a linear history2076 * to its clients.2077 */2078static intread_ancestry(const char*graft_file)2079{2080FILE*fp =fopen(graft_file,"r");2081struct strbuf buf = STRBUF_INIT;2082if(!fp)2083return-1;2084while(!strbuf_getwholeline(&buf, fp,'\n')) {2085/* The format is just "Commit Parent1 Parent2 ...\n" */2086struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2087if(graft)2088register_commit_graft(graft,0);2089}2090fclose(fp);2091strbuf_release(&buf);2092return0;2093}20942095static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2096{2097const char*uniq =find_unique_abbrev(suspect->commit->object.oid.hash,2098 auto_abbrev);2099int len =strlen(uniq);2100if(auto_abbrev < len)2101return len;2102return auto_abbrev;2103}21042105/*2106 * How many columns do we need to show line numbers, authors,2107 * and filenames?2108 */2109static voidfind_alignment(struct scoreboard *sb,int*option)2110{2111int longest_src_lines =0;2112int longest_dst_lines =0;2113unsigned largest_score =0;2114struct blame_entry *e;2115int compute_auto_abbrev = (abbrev <0);2116int auto_abbrev = default_abbrev;21172118for(e = sb->ent; e; e = e->next) {2119struct origin *suspect = e->suspect;2120int num;21212122if(compute_auto_abbrev)2123 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2124if(strcmp(suspect->path, sb->path))2125*option |= OUTPUT_SHOW_NAME;2126 num =strlen(suspect->path);2127if(longest_file < num)2128 longest_file = num;2129if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2130struct commit_info ci;2131 suspect->commit->object.flags |= METAINFO_SHOWN;2132get_commit_info(suspect->commit, &ci,1);2133if(*option & OUTPUT_SHOW_EMAIL)2134 num =utf8_strwidth(ci.author_mail.buf);2135else2136 num =utf8_strwidth(ci.author.buf);2137if(longest_author < num)2138 longest_author = num;2139commit_info_destroy(&ci);2140}2141 num = e->s_lno + e->num_lines;2142if(longest_src_lines < num)2143 longest_src_lines = num;2144 num = e->lno + e->num_lines;2145if(longest_dst_lines < num)2146 longest_dst_lines = num;2147if(largest_score <ent_score(sb, e))2148 largest_score =ent_score(sb, e);2149}2150 max_orig_digits =decimal_width(longest_src_lines);2151 max_digits =decimal_width(longest_dst_lines);2152 max_score_digits =decimal_width(largest_score);21532154if(compute_auto_abbrev)2155/* one more abbrev length is needed for the boundary commit */2156 abbrev = auto_abbrev +1;2157}21582159/*2160 * For debugging -- origin is refcounted, and this asserts that2161 * we do not underflow.2162 */2163static voidsanity_check_refcnt(struct scoreboard *sb)2164{2165int baa =0;2166struct blame_entry *ent;21672168for(ent = sb->ent; ent; ent = ent->next) {2169/* Nobody should have zero or negative refcnt */2170if(ent->suspect->refcnt <=0) {2171fprintf(stderr,"%sin%shas negative refcnt%d\n",2172 ent->suspect->path,2173oid_to_hex(&ent->suspect->commit->object.oid),2174 ent->suspect->refcnt);2175 baa =1;2176}2177}2178if(baa) {2179int opt =0160;2180find_alignment(sb, &opt);2181output(sb, opt);2182die("Baa%d!", baa);2183}2184}21852186static unsignedparse_score(const char*arg)2187{2188char*end;2189unsigned long score =strtoul(arg, &end,10);2190if(*end)2191return0;2192return score;2193}21942195static const char*add_prefix(const char*prefix,const char*path)2196{2197returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2198}21992200static intgit_blame_config(const char*var,const char*value,void*cb)2201{2202if(!strcmp(var,"blame.showroot")) {2203 show_root =git_config_bool(var, value);2204return0;2205}2206if(!strcmp(var,"blame.blankboundary")) {2207 blank_boundary =git_config_bool(var, value);2208return0;2209}2210if(!strcmp(var,"blame.showemail")) {2211int*output_option = cb;2212if(git_config_bool(var, value))2213*output_option |= OUTPUT_SHOW_EMAIL;2214else2215*output_option &= ~OUTPUT_SHOW_EMAIL;2216return0;2217}2218if(!strcmp(var,"blame.date")) {2219if(!value)2220returnconfig_error_nonbool(var);2221parse_date_format(value, &blame_date_mode);2222return0;2223}22242225if(userdiff_config(var, value) <0)2226return-1;22272228returngit_default_config(var, value, cb);2229}22302231static voidverify_working_tree_path(struct commit *work_tree,const char*path)2232{2233struct commit_list *parents;22342235for(parents = work_tree->parents; parents; parents = parents->next) {2236const unsigned char*commit_sha1 = parents->item->object.oid.hash;2237unsigned char blob_sha1[20];2238unsigned mode;22392240if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2241sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2242return;2243}2244die("no such path '%s' in HEAD", path);2245}22462247static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2248{2249struct commit *parent;22502251 parent =lookup_commit_reference(sha1);2252if(!parent)2253die("no such commit%s",sha1_to_hex(sha1));2254return&commit_list_insert(parent, tail)->next;2255}22562257static voidappend_merge_parents(struct commit_list **tail)2258{2259int merge_head;2260struct strbuf line = STRBUF_INIT;22612262 merge_head =open(git_path_merge_head(), O_RDONLY);2263if(merge_head <0) {2264if(errno == ENOENT)2265return;2266die("cannot open '%s' for reading",git_path_merge_head());2267}22682269while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2270unsigned char sha1[20];2271if(line.len <40||get_sha1_hex(line.buf, sha1))2272die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2273 tail =append_parent(tail, sha1);2274}2275close(merge_head);2276strbuf_release(&line);2277}22782279/*2280 * This isn't as simple as passing sb->buf and sb->len, because we2281 * want to transfer ownership of the buffer to the commit (so we2282 * must use detach).2283 */2284static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2285{2286size_t len;2287void*buf =strbuf_detach(sb, &len);2288set_commit_buffer(c, buf, len);2289}22902291/*2292 * Prepare a dummy commit that represents the work tree (or staged) item.2293 * Note that annotating work tree item never works in the reverse.2294 */2295static struct commit *fake_working_tree_commit(struct diff_options *opt,2296const char*path,2297const char*contents_from)2298{2299struct commit *commit;2300struct origin *origin;2301struct commit_list **parent_tail, *parent;2302unsigned char head_sha1[20];2303struct strbuf buf = STRBUF_INIT;2304const char*ident;2305time_t now;2306int size, len;2307struct cache_entry *ce;2308unsigned mode;2309struct strbuf msg = STRBUF_INIT;23102311time(&now);2312 commit =alloc_commit_node();2313 commit->object.parsed =1;2314 commit->date = now;2315 parent_tail = &commit->parents;23162317if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2318die("no such ref: HEAD");23192320 parent_tail =append_parent(parent_tail, head_sha1);2321append_merge_parents(parent_tail);2322verify_working_tree_path(commit, path);23232324 origin =make_origin(commit, path);23252326 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2327strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2328for(parent = commit->parents; parent; parent = parent->next)2329strbuf_addf(&msg,"parent%s\n",2330oid_to_hex(&parent->item->object.oid));2331strbuf_addf(&msg,2332"author%s\n"2333"committer%s\n\n"2334"Version of%sfrom%s\n",2335 ident, ident, path,2336(!contents_from ? path :2337(!strcmp(contents_from,"-") ?"standard input": contents_from)));2338set_commit_buffer_from_strbuf(commit, &msg);23392340if(!contents_from ||strcmp("-", contents_from)) {2341struct stat st;2342const char*read_from;2343char*buf_ptr;2344unsigned long buf_len;23452346if(contents_from) {2347if(stat(contents_from, &st) <0)2348die_errno("Cannot stat '%s'", contents_from);2349 read_from = contents_from;2350}2351else{2352if(lstat(path, &st) <0)2353die_errno("Cannot lstat '%s'", path);2354 read_from = path;2355}2356 mode =canon_mode(st.st_mode);23572358switch(st.st_mode & S_IFMT) {2359case S_IFREG:2360if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2361textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2362strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2363else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2364die_errno("cannot open or read '%s'", read_from);2365break;2366case S_IFLNK:2367if(strbuf_readlink(&buf, read_from, st.st_size) <0)2368die_errno("cannot readlink '%s'", read_from);2369break;2370default:2371die("unsupported file type%s", read_from);2372}2373}2374else{2375/* Reading from stdin */2376 mode =0;2377if(strbuf_read(&buf,0,0) <0)2378die_errno("failed to read from stdin");2379}2380convert_to_git(path, buf.buf, buf.len, &buf,0);2381 origin->file.ptr = buf.buf;2382 origin->file.size = buf.len;2383pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23842385/*2386 * Read the current index, replace the path entry with2387 * origin->blob_sha1 without mucking with its mode or type2388 * bits; we are not going to write this index out -- we just2389 * want to run "diff-index --cached".2390 */2391discard_cache();2392read_cache();23932394 len =strlen(path);2395if(!mode) {2396int pos =cache_name_pos(path, len);2397if(0<= pos)2398 mode = active_cache[pos]->ce_mode;2399else2400/* Let's not bother reading from HEAD tree */2401 mode = S_IFREG |0644;2402}2403 size =cache_entry_size(len);2404 ce =xcalloc(1, size);2405hashcpy(ce->sha1, origin->blob_sha1);2406memcpy(ce->name, path, len);2407 ce->ce_flags =create_ce_flags(0);2408 ce->ce_namelen = len;2409 ce->ce_mode =create_ce_mode(mode);2410add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);24112412/*2413 * We are not going to write this out, so this does not matter2414 * right now, but someday we might optimize diff-index --cached2415 * with cache-tree information.2416 */2417cache_tree_invalidate_path(&the_index, path);24182419return commit;2420}24212422static struct commit *find_single_final(struct rev_info *revs,2423const char**name_p)2424{2425int i;2426struct commit *found = NULL;2427const char*name = NULL;24282429for(i =0; i < revs->pending.nr; i++) {2430struct object *obj = revs->pending.objects[i].item;2431if(obj->flags & UNINTERESTING)2432continue;2433while(obj->type == OBJ_TAG)2434 obj =deref_tag(obj, NULL,0);2435if(obj->type != OBJ_COMMIT)2436die("Non commit%s?", revs->pending.objects[i].name);2437if(found)2438die("More than one commit to dig from%sand%s?",2439 revs->pending.objects[i].name, name);2440 found = (struct commit *)obj;2441 name = revs->pending.objects[i].name;2442}2443if(name_p)2444*name_p = name;2445return found;2446}24472448static char*prepare_final(struct scoreboard *sb)2449{2450const char*name;2451 sb->final =find_single_final(sb->revs, &name);2452returnxstrdup_or_null(name);2453}24542455static char*prepare_initial(struct scoreboard *sb)2456{2457int i;2458const char*final_commit_name = NULL;2459struct rev_info *revs = sb->revs;24602461/*2462 * There must be one and only one negative commit, and it must be2463 * the boundary.2464 */2465for(i =0; i < revs->pending.nr; i++) {2466struct object *obj = revs->pending.objects[i].item;2467if(!(obj->flags & UNINTERESTING))2468continue;2469while(obj->type == OBJ_TAG)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_SHORT:2637 blame_date_width =sizeof("2006-10-19");2638break;2639case DATE_RELATIVE:2640/* TRANSLATORS: This string is used to tell us the maximum2641 display width for a relative timestamp in "git blame"2642 output. For C locale, "4 years, 11 months ago", which2643 takes 22 places, is the longest among various forms of2644 relative timestamps, but your language may need more or2645 fewer display columns. */2646 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2647break;2648case DATE_NORMAL:2649 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2650break;2651case DATE_STRFTIME:2652 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2653break;2654}2655 blame_date_width -=1;/* strip the null */26562657if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2658 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2659 PICKAXE_BLAME_COPY_HARDER);26602661if(!blame_move_score)2662 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2663if(!blame_copy_score)2664 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26652666/*2667 * We have collected options unknown to us in argv[1..unk]2668 * which are to be passed to revision machinery if we are2669 * going to do the "bottom" processing.2670 *2671 * The remaining are:2672 *2673 * (1) if dashdash_pos != 0, it is either2674 * "blame [revisions] -- <path>" or2675 * "blame -- <path> <rev>"2676 *2677 * (2) otherwise, it is one of the two:2678 * "blame [revisions] <path>"2679 * "blame <path> <rev>"2680 *2681 * Note that we must strip out <path> from the arguments: we do not2682 * want the path pruning but we may want "bottom" processing.2683 */2684if(dashdash_pos) {2685switch(argc - dashdash_pos -1) {2686case2:/* (1b) */2687if(argc !=4)2688usage_with_options(blame_opt_usage, options);2689/* reorder for the new way: <rev> -- <path> */2690 argv[1] = argv[3];2691 argv[3] = argv[2];2692 argv[2] ="--";2693/* FALLTHROUGH */2694case1:/* (1a) */2695 path =add_prefix(prefix, argv[--argc]);2696 argv[argc] = NULL;2697break;2698default:2699usage_with_options(blame_opt_usage, options);2700}2701}else{2702if(argc <2)2703usage_with_options(blame_opt_usage, options);2704 path =add_prefix(prefix, argv[argc -1]);2705if(argc ==3&& !file_exists(path)) {/* (2b) */2706 path =add_prefix(prefix, argv[1]);2707 argv[1] = argv[2];2708}2709 argv[argc -1] ="--";27102711setup_work_tree();2712if(!file_exists(path))2713die_errno("cannot stat path '%s'", path);2714}27152716 revs.disable_stdin =1;2717setup_revisions(argc, argv, &revs, NULL);2718memset(&sb,0,sizeof(sb));27192720 sb.revs = &revs;2721if(!reverse) {2722 final_commit_name =prepare_final(&sb);2723 sb.commits.compare = compare_commits_by_commit_date;2724}2725else if(contents_from)2726die("--contents and --reverse do not blend well.");2727else{2728 final_commit_name =prepare_initial(&sb);2729 sb.commits.compare = compare_commits_by_reverse_commit_date;2730if(revs.first_parent_only)2731 revs.children.name = NULL;2732}27332734if(!sb.final) {2735/*2736 * "--not A B -- path" without anything positive;2737 * do not default to HEAD, but use the working tree2738 * or "--contents".2739 */2740setup_work_tree();2741 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2742 path, contents_from);2743add_pending_object(&revs, &(sb.final->object),":");2744}2745else if(contents_from)2746die("Cannot use --contents with final commit object name");27472748if(reverse && revs.first_parent_only) {2749 final_commit =find_single_final(sb.revs, NULL);2750if(!final_commit)2751die("--reverse and --first-parent together require specified latest commit");2752}27532754/*2755 * If we have bottom, this will mark the ancestors of the2756 * bottom commits we would reach while traversing as2757 * uninteresting.2758 */2759if(prepare_revision_walk(&revs))2760die(_("revision walk setup failed"));27612762if(reverse && revs.first_parent_only) {2763struct commit *c = final_commit;27642765 sb.revs->children.name ="children";2766while(c->parents &&2767oidcmp(&c->object.oid, &sb.final->object.oid)) {2768struct commit_list *l =xcalloc(1,sizeof(*l));27692770 l->item = c;2771if(add_decoration(&sb.revs->children,2772&c->parents->item->object, l))2773die("BUG: not unique item in first-parent chain");2774 c = c->parents->item;2775}27762777if(oidcmp(&c->object.oid, &sb.final->object.oid))2778die("--reverse --first-parent together require range along first-parent chain");2779}27802781if(is_null_oid(&sb.final->object.oid)) {2782 o = sb.final->util;2783 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2784 sb.final_buf_size = o->file.size;2785}2786else{2787 o =get_origin(&sb, sb.final, path);2788if(fill_blob_sha1_and_mode(o))2789die("no such path%sin%s", path, final_commit_name);27902791if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2792textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2793&sb.final_buf_size))2794;2795else2796 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2797&sb.final_buf_size);27982799if(!sb.final_buf)2800die("Cannot read blob%sfor path%s",2801sha1_to_hex(o->blob_sha1),2802 path);2803}2804 num_read_blob++;2805 lno =prepare_lines(&sb);28062807if(lno && !range_list.nr)2808string_list_append(&range_list,xstrdup("1"));28092810 anchor =1;2811range_set_init(&ranges, range_list.nr);2812for(range_i =0; range_i < range_list.nr; ++range_i) {2813long bottom, top;2814if(parse_range_arg(range_list.items[range_i].string,2815 nth_line_cb, &sb, lno, anchor,2816&bottom, &top, sb.path))2817usage(blame_usage);2818if(lno < top || ((lno || bottom) && lno < bottom))2819die("file%shas only%lu lines", path, lno);2820if(bottom <1)2821 bottom =1;2822if(top <1)2823 top = lno;2824 bottom--;2825range_set_append_unsafe(&ranges, bottom, top);2826 anchor = top +1;2827}2828sort_and_merge_range_set(&ranges);28292830for(range_i = ranges.nr; range_i >0; --range_i) {2831const struct range *r = &ranges.ranges[range_i -1];2832long bottom = r->start;2833long top = r->end;2834struct blame_entry *next = ent;2835 ent =xcalloc(1,sizeof(*ent));2836 ent->lno = bottom;2837 ent->num_lines = top - bottom;2838 ent->suspect = o;2839 ent->s_lno = bottom;2840 ent->next = next;2841origin_incref(o);2842}28432844 o->suspects = ent;2845prio_queue_put(&sb.commits, o->commit);28462847origin_decref(o);28482849range_set_release(&ranges);2850string_list_clear(&range_list,0);28512852 sb.ent = NULL;2853 sb.path = path;28542855read_mailmap(&mailmap, NULL);28562857assign_blame(&sb, opt);28582859if(!incremental)2860setup_pager();28612862free(final_commit_name);28632864if(incremental)2865return0;28662867 sb.ent =blame_sort(sb.ent, compare_blame_final);28682869coalesce(&sb);28702871if(!(output_option & OUTPUT_PORCELAIN))2872find_alignment(&sb, &output_option);28732874output(&sb, output_option);2875free((void*)sb.final_buf);2876for(ent = sb.ent; ent; ) {2877struct blame_entry *e = ent->next;2878free(ent);2879 ent = e;2880}28812882if(show_stats) {2883printf("num read blob:%d\n", num_read_blob);2884printf("num get patch:%d\n", num_get_patch);2885printf("num commits:%d\n", num_commits);2886}2887return0;2888}