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"builtin.h" 10#include"blob.h" 11#include"commit.h" 12#include"tag.h" 13#include"tree-walk.h" 14#include"diff.h" 15#include"diffcore.h" 16#include"revision.h" 17#include"quote.h" 18#include"xdiff-interface.h" 19#include"cache-tree.h" 20#include"string-list.h" 21#include"mailmap.h" 22#include"mergesort.h" 23#include"parse-options.h" 24#include"prio-queue.h" 25#include"utf8.h" 26#include"userdiff.h" 27#include"line-range.h" 28#include"line-log.h" 29 30static char blame_usage[] =N_("git blame [options] [rev-opts] [rev] [--] file"); 31 32static const char*blame_opt_usage[] = { 33 blame_usage, 34"", 35N_("[rev-opts] are documented in git-rev-list(1)"), 36 NULL 37}; 38 39static int longest_file; 40static int longest_author; 41static int max_orig_digits; 42static int max_digits; 43static int max_score_digits; 44static int show_root; 45static int reverse; 46static int blank_boundary; 47static int incremental; 48static int xdl_opts; 49static int abbrev = -1; 50static int no_whole_file_rename; 51 52static enum date_mode blame_date_mode = DATE_ISO8601; 53static size_t blame_date_width; 54 55static struct string_list mailmap; 56 57#ifndef DEBUG 58#define DEBUG 0 59#endif 60 61/* stats */ 62static int num_read_blob; 63static int num_get_patch; 64static int num_commits; 65 66#define PICKAXE_BLAME_MOVE 01 67#define PICKAXE_BLAME_COPY 02 68#define PICKAXE_BLAME_COPY_HARDER 04 69#define PICKAXE_BLAME_COPY_HARDEST 010 70 71/* 72 * blame for a blame_entry with score lower than these thresholds 73 * is not passed to the parent using move/copy logic. 74 */ 75static unsigned blame_move_score; 76static unsigned blame_copy_score; 77#define BLAME_DEFAULT_MOVE_SCORE 20 78#define BLAME_DEFAULT_COPY_SCORE 40 79 80/* Remember to update object flag allocation in object.h */ 81#define METAINFO_SHOWN (1u<<12) 82#define MORE_THAN_ONE_PATH (1u<<13) 83 84/* 85 * One blob in a commit that is being suspected 86 */ 87struct origin { 88int refcnt; 89/* Record preceding blame record for this blob */ 90struct origin *previous; 91/* origins are put in a list linked via `next' hanging off the 92 * corresponding commit's util field in order to make finding 93 * them fast. The presence in this chain does not count 94 * towards the origin's reference count. It is tempting to 95 * let it count as long as the commit is pending examination, 96 * but even under circumstances where the commit will be 97 * present multiple times in the priority queue of unexamined 98 * commits, processing the first instance will not leave any 99 * work requiring the origin data for the second instance. An 100 * interspersed commit changing that would have to be 101 * preexisting with a different ancestry and with the same 102 * commit date in order to wedge itself between two instances 103 * of the same commit in the priority queue _and_ produce 104 * blame entries relevant for it. While we don't want to let 105 * us get tripped up by this case, it certainly does not seem 106 * worth optimizing for. 107 */ 108struct origin *next; 109struct commit *commit; 110/* `suspects' contains blame entries that may be attributed to 111 * this origin's commit or to parent commits. When a commit 112 * is being processed, all suspects will be moved, either by 113 * assigning them to an origin in a different commit, or by 114 * shipping them to the scoreboard's ent list because they 115 * cannot be attributed to a different commit. 116 */ 117struct blame_entry *suspects; 118 mmfile_t file; 119unsigned char blob_sha1[20]; 120unsigned mode; 121/* guilty gets set when shipping any suspects to the final 122 * blame list instead of other commits 123 */ 124char guilty; 125char path[FLEX_ARRAY]; 126}; 127 128static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b,long ctxlen, 129 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data) 130{ 131 xpparam_t xpp = {0}; 132 xdemitconf_t xecfg = {0}; 133 xdemitcb_t ecb = {NULL}; 134 135 xpp.flags = xdl_opts; 136 xecfg.ctxlen = ctxlen; 137 xecfg.hunk_func = hunk_func; 138 ecb.priv = cb_data; 139returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 140} 141 142/* 143 * Prepare diff_filespec and convert it using diff textconv API 144 * if the textconv driver exists. 145 * Return 1 if the conversion succeeds, 0 otherwise. 146 */ 147inttextconv_object(const char*path, 148unsigned mode, 149const unsigned char*sha1, 150int sha1_valid, 151char**buf, 152unsigned long*buf_size) 153{ 154struct diff_filespec *df; 155struct userdiff_driver *textconv; 156 157 df =alloc_filespec(path); 158fill_filespec(df, sha1, sha1_valid, mode); 159 textconv =get_textconv(df); 160if(!textconv) { 161free_filespec(df); 162return0; 163} 164 165*buf_size =fill_textconv(textconv, df, buf); 166free_filespec(df); 167return1; 168} 169 170/* 171 * Given an origin, prepare mmfile_t structure to be used by the 172 * diff machinery 173 */ 174static voidfill_origin_blob(struct diff_options *opt, 175struct origin *o, mmfile_t *file) 176{ 177if(!o->file.ptr) { 178enum object_type type; 179unsigned long file_size; 180 181 num_read_blob++; 182if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 183textconv_object(o->path, o->mode, o->blob_sha1,1, &file->ptr, &file_size)) 184; 185else 186 file->ptr =read_sha1_file(o->blob_sha1, &type, &file_size); 187 file->size = file_size; 188 189if(!file->ptr) 190die("Cannot read blob%sfor path%s", 191sha1_to_hex(o->blob_sha1), 192 o->path); 193 o->file = *file; 194} 195else 196*file = o->file; 197} 198 199/* 200 * Origin is refcounted and usually we keep the blob contents to be 201 * reused. 202 */ 203staticinlinestruct origin *origin_incref(struct origin *o) 204{ 205if(o) 206 o->refcnt++; 207return o; 208} 209 210static voidorigin_decref(struct origin *o) 211{ 212if(o && --o->refcnt <=0) { 213struct origin *p, *l = NULL; 214if(o->previous) 215origin_decref(o->previous); 216free(o->file.ptr); 217/* Should be present exactly once in commit chain */ 218for(p = o->commit->util; p; l = p, p = p->next) { 219if(p == o) { 220if(l) 221 l->next = p->next; 222else 223 o->commit->util = p->next; 224free(o); 225return; 226} 227} 228die("internal error in blame::origin_decref"); 229} 230} 231 232static voiddrop_origin_blob(struct origin *o) 233{ 234if(o->file.ptr) { 235free(o->file.ptr); 236 o->file.ptr = NULL; 237} 238} 239 240/* 241 * Each group of lines is described by a blame_entry; it can be split 242 * as we pass blame to the parents. They are arranged in linked lists 243 * kept as `suspects' of some unprocessed origin, or entered (when the 244 * blame origin has been finalized) into the scoreboard structure. 245 * While the scoreboard structure is only sorted at the end of 246 * processing (according to final image line number), the lists 247 * attached to an origin are sorted by the target line number. 248 */ 249struct blame_entry { 250struct blame_entry *next; 251 252/* the first line of this group in the final image; 253 * internally all line numbers are 0 based. 254 */ 255int lno; 256 257/* how many lines this group has */ 258int num_lines; 259 260/* the commit that introduced this group into the final image */ 261struct origin *suspect; 262 263/* the line number of the first line of this group in the 264 * suspect's file; internally all line numbers are 0 based. 265 */ 266int s_lno; 267 268/* how significant this entry is -- cached to avoid 269 * scanning the lines over and over. 270 */ 271unsigned score; 272}; 273 274/* 275 * Any merge of blames happens on lists of blames that arrived via 276 * different parents in a single suspect. In this case, we want to 277 * sort according to the suspect line numbers as opposed to the final 278 * image line numbers. The function body is somewhat longish because 279 * it avoids unnecessary writes. 280 */ 281 282static struct blame_entry *blame_merge(struct blame_entry *list1, 283struct blame_entry *list2) 284{ 285struct blame_entry *p1 = list1, *p2 = list2, 286**tail = &list1; 287 288if(!p1) 289return p2; 290if(!p2) 291return p1; 292 293if(p1->s_lno <= p2->s_lno) { 294do{ 295 tail = &p1->next; 296if((p1 = *tail) == NULL) { 297*tail = p2; 298return list1; 299} 300}while(p1->s_lno <= p2->s_lno); 301} 302for(;;) { 303*tail = p2; 304do{ 305 tail = &p2->next; 306if((p2 = *tail) == NULL) { 307*tail = p1; 308return list1; 309} 310}while(p1->s_lno > p2->s_lno); 311*tail = p1; 312do{ 313 tail = &p1->next; 314if((p1 = *tail) == NULL) { 315*tail = p2; 316return list1; 317} 318}while(p1->s_lno <= p2->s_lno); 319} 320} 321 322static void*get_next_blame(const void*p) 323{ 324return((struct blame_entry *)p)->next; 325} 326 327static voidset_next_blame(void*p1,void*p2) 328{ 329((struct blame_entry *)p1)->next = p2; 330} 331 332/* 333 * Final image line numbers are all different, so we don't need a 334 * three-way comparison here. 335 */ 336 337static intcompare_blame_final(const void*p1,const void*p2) 338{ 339return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 340?1: -1; 341} 342 343static intcompare_blame_suspect(const void*p1,const void*p2) 344{ 345const struct blame_entry *s1 = p1, *s2 = p2; 346/* 347 * to allow for collating suspects, we sort according to the 348 * respective pointer value as the primary sorting criterion. 349 * The actual relation is pretty unimportant as long as it 350 * establishes a total order. Comparing as integers gives us 351 * that. 352 */ 353if(s1->suspect != s2->suspect) 354return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 355if(s1->s_lno == s2->s_lno) 356return0; 357return s1->s_lno > s2->s_lno ?1: -1; 358} 359 360static struct blame_entry *blame_sort(struct blame_entry *head, 361int(*compare_fn)(const void*,const void*)) 362{ 363returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 364} 365 366static intcompare_commits_by_reverse_commit_date(const void*a, 367const void*b, 368void*c) 369{ 370return-compare_commits_by_commit_date(a, b, c); 371} 372 373/* 374 * The current state of the blame assignment. 375 */ 376struct scoreboard { 377/* the final commit (i.e. where we started digging from) */ 378struct commit *final; 379/* Priority queue for commits with unassigned blame records */ 380struct prio_queue commits; 381struct rev_info *revs; 382const char*path; 383 384/* 385 * The contents in the final image. 386 * Used by many functions to obtain contents of the nth line, 387 * indexed with scoreboard.lineno[blame_entry.lno]. 388 */ 389const char*final_buf; 390unsigned long final_buf_size; 391 392/* linked list of blames */ 393struct blame_entry *ent; 394 395/* look-up a line in the final buffer */ 396int num_lines; 397int*lineno; 398}; 399 400static voidsanity_check_refcnt(struct scoreboard *); 401 402/* 403 * If two blame entries that are next to each other came from 404 * contiguous lines in the same origin (i.e. <commit, path> pair), 405 * merge them together. 406 */ 407static voidcoalesce(struct scoreboard *sb) 408{ 409struct blame_entry *ent, *next; 410 411for(ent = sb->ent; ent && (next = ent->next); ent = next) { 412if(ent->suspect == next->suspect && 413 ent->s_lno + ent->num_lines == next->s_lno) { 414 ent->num_lines += next->num_lines; 415 ent->next = next->next; 416origin_decref(next->suspect); 417free(next); 418 ent->score =0; 419 next = ent;/* again */ 420} 421} 422 423if(DEBUG)/* sanity */ 424sanity_check_refcnt(sb); 425} 426 427/* 428 * Merge the given sorted list of blames into a preexisting origin. 429 * If there were no previous blames to that commit, it is entered into 430 * the commit priority queue of the score board. 431 */ 432 433static voidqueue_blames(struct scoreboard *sb,struct origin *porigin, 434struct blame_entry *sorted) 435{ 436if(porigin->suspects) 437 porigin->suspects =blame_merge(porigin->suspects, sorted); 438else{ 439struct origin *o; 440for(o = porigin->commit->util; o; o = o->next) { 441if(o->suspects) { 442 porigin->suspects = sorted; 443return; 444} 445} 446 porigin->suspects = sorted; 447prio_queue_put(&sb->commits, porigin->commit); 448} 449} 450 451/* 452 * Given a commit and a path in it, create a new origin structure. 453 * The callers that add blame to the scoreboard should use 454 * get_origin() to obtain shared, refcounted copy instead of calling 455 * this function directly. 456 */ 457static struct origin *make_origin(struct commit *commit,const char*path) 458{ 459struct origin *o; 460 o =xcalloc(1,sizeof(*o) +strlen(path) +1); 461 o->commit = commit; 462 o->refcnt =1; 463 o->next = commit->util; 464 commit->util = o; 465strcpy(o->path, path); 466return o; 467} 468 469/* 470 * Locate an existing origin or create a new one. 471 * This moves the origin to front position in the commit util list. 472 */ 473static struct origin *get_origin(struct scoreboard *sb, 474struct commit *commit, 475const char*path) 476{ 477struct origin *o, *l; 478 479for(o = commit->util, l = NULL; o; l = o, o = o->next) { 480if(!strcmp(o->path, path)) { 481/* bump to front */ 482if(l) { 483 l->next = o->next; 484 o->next = commit->util; 485 commit->util = o; 486} 487returnorigin_incref(o); 488} 489} 490returnmake_origin(commit, path); 491} 492 493/* 494 * Fill the blob_sha1 field of an origin if it hasn't, so that later 495 * call to fill_origin_blob() can use it to locate the data. blob_sha1 496 * for an origin is also used to pass the blame for the entire file to 497 * the parent to detect the case where a child's blob is identical to 498 * that of its parent's. 499 * 500 * This also fills origin->mode for corresponding tree path. 501 */ 502static intfill_blob_sha1_and_mode(struct origin *origin) 503{ 504if(!is_null_sha1(origin->blob_sha1)) 505return0; 506if(get_tree_entry(origin->commit->object.sha1, 507 origin->path, 508 origin->blob_sha1, &origin->mode)) 509goto error_out; 510if(sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB) 511goto error_out; 512return0; 513 error_out: 514hashclr(origin->blob_sha1); 515 origin->mode = S_IFINVALID; 516return-1; 517} 518 519/* 520 * We have an origin -- check if the same path exists in the 521 * parent and return an origin structure to represent it. 522 */ 523static struct origin *find_origin(struct scoreboard *sb, 524struct commit *parent, 525struct origin *origin) 526{ 527struct origin *porigin; 528struct diff_options diff_opts; 529const char*paths[2]; 530 531/* First check any existing origins */ 532for(porigin = parent->util; porigin; porigin = porigin->next) 533if(!strcmp(porigin->path, origin->path)) { 534/* 535 * The same path between origin and its parent 536 * without renaming -- the most common case. 537 */ 538returnorigin_incref(porigin); 539} 540 541/* See if the origin->path is different between parent 542 * and origin first. Most of the time they are the 543 * same and diff-tree is fairly efficient about this. 544 */ 545diff_setup(&diff_opts); 546DIFF_OPT_SET(&diff_opts, RECURSIVE); 547 diff_opts.detect_rename =0; 548 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 549 paths[0] = origin->path; 550 paths[1] = NULL; 551 552parse_pathspec(&diff_opts.pathspec, 553 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 554 PATHSPEC_LITERAL_PATH,"", paths); 555diff_setup_done(&diff_opts); 556 557if(is_null_sha1(origin->commit->object.sha1)) 558do_diff_cache(parent->tree->object.sha1, &diff_opts); 559else 560diff_tree_sha1(parent->tree->object.sha1, 561 origin->commit->tree->object.sha1, 562"", &diff_opts); 563diffcore_std(&diff_opts); 564 565if(!diff_queued_diff.nr) { 566/* The path is the same as parent */ 567 porigin =get_origin(sb, parent, origin->path); 568hashcpy(porigin->blob_sha1, origin->blob_sha1); 569 porigin->mode = origin->mode; 570}else{ 571/* 572 * Since origin->path is a pathspec, if the parent 573 * commit had it as a directory, we will see a whole 574 * bunch of deletion of files in the directory that we 575 * do not care about. 576 */ 577int i; 578struct diff_filepair *p = NULL; 579for(i =0; i < diff_queued_diff.nr; i++) { 580const char*name; 581 p = diff_queued_diff.queue[i]; 582 name = p->one->path ? p->one->path : p->two->path; 583if(!strcmp(name, origin->path)) 584break; 585} 586if(!p) 587die("internal error in blame::find_origin"); 588switch(p->status) { 589default: 590die("internal error in blame::find_origin (%c)", 591 p->status); 592case'M': 593 porigin =get_origin(sb, parent, origin->path); 594hashcpy(porigin->blob_sha1, p->one->sha1); 595 porigin->mode = p->one->mode; 596break; 597case'A': 598case'T': 599/* Did not exist in parent, or type changed */ 600break; 601} 602} 603diff_flush(&diff_opts); 604free_pathspec(&diff_opts.pathspec); 605return porigin; 606} 607 608/* 609 * We have an origin -- find the path that corresponds to it in its 610 * parent and return an origin structure to represent it. 611 */ 612static struct origin *find_rename(struct scoreboard *sb, 613struct commit *parent, 614struct origin *origin) 615{ 616struct origin *porigin = NULL; 617struct diff_options diff_opts; 618int i; 619 620diff_setup(&diff_opts); 621DIFF_OPT_SET(&diff_opts, RECURSIVE); 622 diff_opts.detect_rename = DIFF_DETECT_RENAME; 623 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 624 diff_opts.single_follow = origin->path; 625diff_setup_done(&diff_opts); 626 627if(is_null_sha1(origin->commit->object.sha1)) 628do_diff_cache(parent->tree->object.sha1, &diff_opts); 629else 630diff_tree_sha1(parent->tree->object.sha1, 631 origin->commit->tree->object.sha1, 632"", &diff_opts); 633diffcore_std(&diff_opts); 634 635for(i =0; i < diff_queued_diff.nr; i++) { 636struct diff_filepair *p = diff_queued_diff.queue[i]; 637if((p->status =='R'|| p->status =='C') && 638!strcmp(p->two->path, origin->path)) { 639 porigin =get_origin(sb, parent, p->one->path); 640hashcpy(porigin->blob_sha1, p->one->sha1); 641 porigin->mode = p->one->mode; 642break; 643} 644} 645diff_flush(&diff_opts); 646free_pathspec(&diff_opts.pathspec); 647return porigin; 648} 649 650/* 651 * Append a new blame entry to a given output queue. 652 */ 653static voidadd_blame_entry(struct blame_entry ***queue,struct blame_entry *e) 654{ 655origin_incref(e->suspect); 656 657 e->next = **queue; 658**queue = e; 659*queue = &e->next; 660} 661 662/* 663 * src typically is on-stack; we want to copy the information in it to 664 * a malloced blame_entry that gets added to the given queue. The 665 * origin of dst loses a refcnt. 666 */ 667static voiddup_entry(struct blame_entry ***queue, 668struct blame_entry *dst,struct blame_entry *src) 669{ 670origin_incref(src->suspect); 671origin_decref(dst->suspect); 672memcpy(dst, src,sizeof(*src)); 673 dst->next = **queue; 674**queue = dst; 675*queue = &dst->next; 676} 677 678static const char*nth_line(struct scoreboard *sb,long lno) 679{ 680return sb->final_buf + sb->lineno[lno]; 681} 682 683static const char*nth_line_cb(void*data,long lno) 684{ 685returnnth_line((struct scoreboard *)data, lno); 686} 687 688/* 689 * It is known that lines between tlno to same came from parent, and e 690 * has an overlap with that range. it also is known that parent's 691 * line plno corresponds to e's line tlno. 692 * 693 * <---- e -----> 694 * <------> 695 * <------------> 696 * <------------> 697 * <------------------> 698 * 699 * Split e into potentially three parts; before this chunk, the chunk 700 * to be blamed for the parent, and after that portion. 701 */ 702static voidsplit_overlap(struct blame_entry *split, 703struct blame_entry *e, 704int tlno,int plno,int same, 705struct origin *parent) 706{ 707int chunk_end_lno; 708memset(split,0,sizeof(struct blame_entry [3])); 709 710if(e->s_lno < tlno) { 711/* there is a pre-chunk part not blamed on parent */ 712 split[0].suspect =origin_incref(e->suspect); 713 split[0].lno = e->lno; 714 split[0].s_lno = e->s_lno; 715 split[0].num_lines = tlno - e->s_lno; 716 split[1].lno = e->lno + tlno - e->s_lno; 717 split[1].s_lno = plno; 718} 719else{ 720 split[1].lno = e->lno; 721 split[1].s_lno = plno + (e->s_lno - tlno); 722} 723 724if(same < e->s_lno + e->num_lines) { 725/* there is a post-chunk part not blamed on parent */ 726 split[2].suspect =origin_incref(e->suspect); 727 split[2].lno = e->lno + (same - e->s_lno); 728 split[2].s_lno = e->s_lno + (same - e->s_lno); 729 split[2].num_lines = e->s_lno + e->num_lines - same; 730 chunk_end_lno = split[2].lno; 731} 732else 733 chunk_end_lno = e->lno + e->num_lines; 734 split[1].num_lines = chunk_end_lno - split[1].lno; 735 736/* 737 * if it turns out there is nothing to blame the parent for, 738 * forget about the splitting. !split[1].suspect signals this. 739 */ 740if(split[1].num_lines <1) 741return; 742 split[1].suspect =origin_incref(parent); 743} 744 745/* 746 * split_overlap() divided an existing blame e into up to three parts 747 * in split. Any assigned blame is moved to queue to 748 * reflect the split. 749 */ 750static voidsplit_blame(struct blame_entry ***blamed, 751struct blame_entry ***unblamed, 752struct blame_entry *split, 753struct blame_entry *e) 754{ 755struct blame_entry *new_entry; 756 757if(split[0].suspect && split[2].suspect) { 758/* The first part (reuse storage for the existing entry e) */ 759dup_entry(unblamed, e, &split[0]); 760 761/* The last part -- me */ 762 new_entry =xmalloc(sizeof(*new_entry)); 763memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 764add_blame_entry(unblamed, new_entry); 765 766/* ... and the middle part -- parent */ 767 new_entry =xmalloc(sizeof(*new_entry)); 768memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 769add_blame_entry(blamed, new_entry); 770} 771else if(!split[0].suspect && !split[2].suspect) 772/* 773 * The parent covers the entire area; reuse storage for 774 * e and replace it with the parent. 775 */ 776dup_entry(blamed, e, &split[1]); 777else if(split[0].suspect) { 778/* me and then parent */ 779dup_entry(unblamed, e, &split[0]); 780 781 new_entry =xmalloc(sizeof(*new_entry)); 782memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 783add_blame_entry(blamed, new_entry); 784} 785else{ 786/* parent and then me */ 787dup_entry(blamed, e, &split[1]); 788 789 new_entry =xmalloc(sizeof(*new_entry)); 790memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 791add_blame_entry(unblamed, new_entry); 792} 793} 794 795/* 796 * After splitting the blame, the origins used by the 797 * on-stack blame_entry should lose one refcnt each. 798 */ 799static voiddecref_split(struct blame_entry *split) 800{ 801int i; 802 803for(i =0; i <3; i++) 804origin_decref(split[i].suspect); 805} 806 807/* 808 * reverse_blame reverses the list given in head, appending tail. 809 * That allows us to build lists in reverse order, then reverse them 810 * afterwards. This can be faster than building the list in proper 811 * order right away. The reason is that building in proper order 812 * requires writing a link in the _previous_ element, while building 813 * in reverse order just requires placing the list head into the 814 * _current_ element. 815 */ 816 817static struct blame_entry *reverse_blame(struct blame_entry *head, 818struct blame_entry *tail) 819{ 820while(head) { 821struct blame_entry *next = head->next; 822 head->next = tail; 823 tail = head; 824 head = next; 825} 826return tail; 827} 828 829/* 830 * Process one hunk from the patch between the current suspect for 831 * blame_entry e and its parent. This first blames any unfinished 832 * entries before the chunk (which is where target and parent start 833 * differing) on the parent, and then splits blame entries at the 834 * start and at the end of the difference region. Since use of -M and 835 * -C options may lead to overlapping/duplicate source line number 836 * ranges, all we can rely on from sorting/merging is the order of the 837 * first suspect line number. 838 */ 839static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 840int tlno,int offset,int same, 841struct origin *parent) 842{ 843struct blame_entry *e = **srcq; 844struct blame_entry *samep = NULL, *diffp = NULL; 845 846while(e && e->s_lno < tlno) { 847struct blame_entry *next = e->next; 848/* 849 * current record starts before differing portion. If 850 * it reaches into it, we need to split it up and 851 * examine the second part separately. 852 */ 853if(e->s_lno + e->num_lines > tlno) { 854/* Move second half to a new record */ 855int len = tlno - e->s_lno; 856struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 857 n->suspect = e->suspect; 858 n->lno = e->lno + len; 859 n->s_lno = e->s_lno + len; 860 n->num_lines = e->num_lines - len; 861 e->num_lines = len; 862 e->score =0; 863/* Push new record to diffp */ 864 n->next = diffp; 865 diffp = n; 866}else 867origin_decref(e->suspect); 868/* Pass blame for everything before the differing 869 * chunk to the parent */ 870 e->suspect =origin_incref(parent); 871 e->s_lno += offset; 872 e->next = samep; 873 samep = e; 874 e = next; 875} 876/* 877 * As we don't know how much of a common stretch after this 878 * diff will occur, the currently blamed parts are all that we 879 * can assign to the parent for now. 880 */ 881 882if(samep) { 883**dstq =reverse_blame(samep, **dstq); 884*dstq = &samep->next; 885} 886/* 887 * Prepend the split off portions: everything after e starts 888 * after the blameable portion. 889 */ 890 e =reverse_blame(diffp, e); 891 892/* 893 * Now retain records on the target while parts are different 894 * from the parent. 895 */ 896 samep = NULL; 897 diffp = NULL; 898while(e && e->s_lno < same) { 899struct blame_entry *next = e->next; 900 901/* 902 * If current record extends into sameness, need to split. 903 */ 904if(e->s_lno + e->num_lines > same) { 905/* 906 * Move second half to a new record to be 907 * processed by later chunks 908 */ 909int len = same - e->s_lno; 910struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 911 n->suspect =origin_incref(e->suspect); 912 n->lno = e->lno + len; 913 n->s_lno = e->s_lno + len; 914 n->num_lines = e->num_lines - len; 915 e->num_lines = len; 916 e->score =0; 917/* Push new record to samep */ 918 n->next = samep; 919 samep = n; 920} 921 e->next = diffp; 922 diffp = e; 923 e = next; 924} 925**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 926/* Move across elements that are in the unblamable portion */ 927if(diffp) 928*srcq = &diffp->next; 929} 930 931struct blame_chunk_cb_data { 932struct origin *parent; 933long offset; 934struct blame_entry **dstq; 935struct blame_entry **srcq; 936}; 937 938/* diff chunks are from parent to target */ 939static intblame_chunk_cb(long start_a,long count_a, 940long start_b,long count_b,void*data) 941{ 942struct blame_chunk_cb_data *d = data; 943if(start_a - start_b != d->offset) 944die("internal error in blame::blame_chunk_cb"); 945blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 946 start_b + count_b, d->parent); 947 d->offset = start_a + count_a - (start_b + count_b); 948return0; 949} 950 951/* 952 * We are looking at the origin 'target' and aiming to pass blame 953 * for the lines it is suspected to its parent. Run diff to find 954 * which lines came from parent and pass blame for them. 955 */ 956static voidpass_blame_to_parent(struct scoreboard *sb, 957struct origin *target, 958struct origin *parent) 959{ 960 mmfile_t file_p, file_o; 961struct blame_chunk_cb_data d; 962struct blame_entry *newdest = NULL; 963 964if(!target->suspects) 965return;/* nothing remains for this target */ 966 967 d.parent = parent; 968 d.offset =0; 969 d.dstq = &newdest; d.srcq = &target->suspects; 970 971fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 972fill_origin_blob(&sb->revs->diffopt, target, &file_o); 973 num_get_patch++; 974 975diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d); 976/* The rest are the same as the parent */ 977blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 978*d.dstq = NULL; 979queue_blames(sb, parent, newdest); 980 981return; 982} 983 984/* 985 * The lines in blame_entry after splitting blames many times can become 986 * very small and trivial, and at some point it becomes pointless to 987 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 988 * ordinary C program, and it is not worth to say it was copied from 989 * totally unrelated file in the parent. 990 * 991 * Compute how trivial the lines in the blame_entry are. 992 */ 993static unsignedent_score(struct scoreboard *sb,struct blame_entry *e) 994{ 995unsigned score; 996const char*cp, *ep; 997 998if(e->score) 999return e->score;10001001 score =1;1002 cp =nth_line(sb, e->lno);1003 ep =nth_line(sb, e->lno + e->num_lines);1004while(cp < ep) {1005unsigned ch = *((unsigned char*)cp);1006if(isalnum(ch))1007 score++;1008 cp++;1009}1010 e->score = score;1011return score;1012}10131014/*1015 * best_so_far[] and this[] are both a split of an existing blame_entry1016 * that passes blame to the parent. Maintain best_so_far the best split1017 * so far, by comparing this and best_so_far and copying this into1018 * bst_so_far as needed.1019 */1020static voidcopy_split_if_better(struct scoreboard *sb,1021struct blame_entry *best_so_far,1022struct blame_entry *this)1023{1024int i;10251026if(!this[1].suspect)1027return;1028if(best_so_far[1].suspect) {1029if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1030return;1031}10321033for(i =0; i <3; i++)1034origin_incref(this[i].suspect);1035decref_split(best_so_far);1036memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1037}10381039/*1040 * We are looking at a part of the final image represented by1041 * ent (tlno and same are offset by ent->s_lno).1042 * tlno is where we are looking at in the final image.1043 * up to (but not including) same match preimage.1044 * plno is where we are looking at in the preimage.1045 *1046 * <-------------- final image ---------------------->1047 * <------ent------>1048 * ^tlno ^same1049 * <---------preimage----->1050 * ^plno1051 *1052 * All line numbers are 0-based.1053 */1054static voidhandle_split(struct scoreboard *sb,1055struct blame_entry *ent,1056int tlno,int plno,int same,1057struct origin *parent,1058struct blame_entry *split)1059{1060if(ent->num_lines <= tlno)1061return;1062if(tlno < same) {1063struct blame_entry this[3];1064 tlno += ent->s_lno;1065 same += ent->s_lno;1066split_overlap(this, ent, tlno, plno, same, parent);1067copy_split_if_better(sb, split,this);1068decref_split(this);1069}1070}10711072struct handle_split_cb_data {1073struct scoreboard *sb;1074struct blame_entry *ent;1075struct origin *parent;1076struct blame_entry *split;1077long plno;1078long tlno;1079};10801081static inthandle_split_cb(long start_a,long count_a,1082long start_b,long count_b,void*data)1083{1084struct handle_split_cb_data *d = data;1085handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1086 d->split);1087 d->plno = start_a + count_a;1088 d->tlno = start_b + count_b;1089return0;1090}10911092/*1093 * Find the lines from parent that are the same as ent so that1094 * we can pass blames to it. file_p has the blob contents for1095 * the parent.1096 */1097static voidfind_copy_in_blob(struct scoreboard *sb,1098struct blame_entry *ent,1099struct origin *parent,1100struct blame_entry *split,1101 mmfile_t *file_p)1102{1103const char*cp;1104 mmfile_t file_o;1105struct handle_split_cb_data d;11061107memset(&d,0,sizeof(d));1108 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1109/*1110 * Prepare mmfile that contains only the lines in ent.1111 */1112 cp =nth_line(sb, ent->lno);1113 file_o.ptr = (char*) cp;1114 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11151116/*1117 * file_o is a part of final image we are annotating.1118 * file_p partially may match that image.1119 */1120memset(split,0,sizeof(struct blame_entry [3]));1121diff_hunks(file_p, &file_o,1, handle_split_cb, &d);1122/* remainder, if any, all match the preimage */1123handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1124}11251126/* Move all blame entries from list *source that have a score smaller1127 * than score_min to the front of list *small.1128 * Returns a pointer to the link pointing to the old head of the small list.1129 */11301131static struct blame_entry **filter_small(struct scoreboard *sb,1132struct blame_entry **small,1133struct blame_entry **source,1134unsigned score_min)1135{1136struct blame_entry *p = *source;1137struct blame_entry *oldsmall = *small;1138while(p) {1139if(ent_score(sb, p) <= score_min) {1140*small = p;1141 small = &p->next;1142 p = *small;1143}else{1144*source = p;1145 source = &p->next;1146 p = *source;1147}1148}1149*small = oldsmall;1150*source = NULL;1151return small;1152}11531154/*1155 * See if lines currently target is suspected for can be attributed to1156 * parent.1157 */1158static voidfind_move_in_parent(struct scoreboard *sb,1159struct blame_entry ***blamed,1160struct blame_entry **toosmall,1161struct origin *target,1162struct origin *parent)1163{1164struct blame_entry *e, split[3];1165struct blame_entry *unblamed = target->suspects;1166struct blame_entry *leftover = NULL;1167 mmfile_t file_p;11681169if(!unblamed)1170return;/* nothing remains for this target */11711172fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1173if(!file_p.ptr)1174return;11751176/* At each iteration, unblamed has a NULL-terminated list of1177 * entries that have not yet been tested for blame. leftover1178 * contains the reversed list of entries that have been tested1179 * without being assignable to the parent.1180 */1181do{1182struct blame_entry **unblamedtail = &unblamed;1183struct blame_entry *next;1184for(e = unblamed; e; e = next) {1185 next = e->next;1186find_copy_in_blob(sb, e, parent, split, &file_p);1187if(split[1].suspect &&1188 blame_move_score <ent_score(sb, &split[1])) {1189split_blame(blamed, &unblamedtail, split, e);1190}else{1191 e->next = leftover;1192 leftover = e;1193}1194decref_split(split);1195}1196*unblamedtail = NULL;1197 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1198}while(unblamed);1199 target->suspects =reverse_blame(leftover, NULL);1200}12011202struct blame_list {1203struct blame_entry *ent;1204struct blame_entry split[3];1205};12061207/*1208 * Count the number of entries the target is suspected for,1209 * and prepare a list of entry and the best split.1210 */1211static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1212int*num_ents_p)1213{1214struct blame_entry *e;1215int num_ents, i;1216struct blame_list *blame_list = NULL;12171218for(e = unblamed, num_ents =0; e; e = e->next)1219 num_ents++;1220if(num_ents) {1221 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1222for(e = unblamed, i =0; e; e = e->next)1223 blame_list[i++].ent = e;1224}1225*num_ents_p = num_ents;1226return blame_list;1227}12281229/*1230 * For lines target is suspected for, see if we can find code movement1231 * across file boundary from the parent commit. porigin is the path1232 * in the parent we already tried.1233 */1234static voidfind_copy_in_parent(struct scoreboard *sb,1235struct blame_entry ***blamed,1236struct blame_entry **toosmall,1237struct origin *target,1238struct commit *parent,1239struct origin *porigin,1240int opt)1241{1242struct diff_options diff_opts;1243int i, j;1244struct blame_list *blame_list;1245int num_ents;1246struct blame_entry *unblamed = target->suspects;1247struct blame_entry *leftover = NULL;12481249if(!unblamed)1250return;/* nothing remains for this target */12511252diff_setup(&diff_opts);1253DIFF_OPT_SET(&diff_opts, RECURSIVE);1254 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12551256diff_setup_done(&diff_opts);12571258/* Try "find copies harder" on new path if requested;1259 * we do not want to use diffcore_rename() actually to1260 * match things up; find_copies_harder is set only to1261 * force diff_tree_sha1() to feed all filepairs to diff_queue,1262 * and this code needs to be after diff_setup_done(), which1263 * usually makes find-copies-harder imply copy detection.1264 */1265if((opt & PICKAXE_BLAME_COPY_HARDEST)1266|| ((opt & PICKAXE_BLAME_COPY_HARDER)1267&& (!porigin ||strcmp(target->path, porigin->path))))1268DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12691270if(is_null_sha1(target->commit->object.sha1))1271do_diff_cache(parent->tree->object.sha1, &diff_opts);1272else1273diff_tree_sha1(parent->tree->object.sha1,1274 target->commit->tree->object.sha1,1275"", &diff_opts);12761277if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1278diffcore_std(&diff_opts);12791280do{1281struct blame_entry **unblamedtail = &unblamed;1282 blame_list =setup_blame_list(unblamed, &num_ents);12831284for(i =0; i < diff_queued_diff.nr; i++) {1285struct diff_filepair *p = diff_queued_diff.queue[i];1286struct origin *norigin;1287 mmfile_t file_p;1288struct blame_entry this[3];12891290if(!DIFF_FILE_VALID(p->one))1291continue;/* does not exist in parent */1292if(S_ISGITLINK(p->one->mode))1293continue;/* ignore git links */1294if(porigin && !strcmp(p->one->path, porigin->path))1295/* find_move already dealt with this path */1296continue;12971298 norigin =get_origin(sb, parent, p->one->path);1299hashcpy(norigin->blob_sha1, p->one->sha1);1300 norigin->mode = p->one->mode;1301fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1302if(!file_p.ptr)1303continue;13041305for(j =0; j < num_ents; j++) {1306find_copy_in_blob(sb, blame_list[j].ent,1307 norigin,this, &file_p);1308copy_split_if_better(sb, blame_list[j].split,1309this);1310decref_split(this);1311}1312origin_decref(norigin);1313}13141315for(j =0; j < num_ents; j++) {1316struct blame_entry *split = blame_list[j].split;1317if(split[1].suspect &&1318 blame_copy_score <ent_score(sb, &split[1])) {1319split_blame(blamed, &unblamedtail, split,1320 blame_list[j].ent);1321}else{1322 blame_list[j].ent->next = leftover;1323 leftover = blame_list[j].ent;1324}1325decref_split(split);1326}1327free(blame_list);1328*unblamedtail = NULL;1329 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1330}while(unblamed);1331 target->suspects =reverse_blame(leftover, NULL);1332diff_flush(&diff_opts);1333free_pathspec(&diff_opts.pathspec);1334}13351336/*1337 * The blobs of origin and porigin exactly match, so everything1338 * origin is suspected for can be blamed on the parent.1339 */1340static voidpass_whole_blame(struct scoreboard *sb,1341struct origin *origin,struct origin *porigin)1342{1343struct blame_entry *e, *suspects;13441345if(!porigin->file.ptr && origin->file.ptr) {1346/* Steal its file */1347 porigin->file = origin->file;1348 origin->file.ptr = NULL;1349}1350 suspects = origin->suspects;1351 origin->suspects = NULL;1352for(e = suspects; e; e = e->next) {1353origin_incref(porigin);1354origin_decref(e->suspect);1355 e->suspect = porigin;1356}1357queue_blames(sb, porigin, suspects);1358}13591360/*1361 * We pass blame from the current commit to its parents. We keep saying1362 * "parent" (and "porigin"), but what we mean is to find scapegoat to1363 * exonerate ourselves.1364 */1365static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1366{1367if(!reverse)1368return commit->parents;1369returnlookup_decoration(&revs->children, &commit->object);1370}13711372static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1373{1374struct commit_list *l =first_scapegoat(revs, commit);1375returncommit_list_count(l);1376}13771378/* Distribute collected unsorted blames to the respected sorted lists1379 * in the various origins.1380 */1381static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1382{1383 blamed =blame_sort(blamed, compare_blame_suspect);1384while(blamed)1385{1386struct origin *porigin = blamed->suspect;1387struct blame_entry *suspects = NULL;1388do{1389struct blame_entry *next = blamed->next;1390 blamed->next = suspects;1391 suspects = blamed;1392 blamed = next;1393}while(blamed && blamed->suspect == porigin);1394 suspects =reverse_blame(suspects, NULL);1395queue_blames(sb, porigin, suspects);1396}1397}13981399#define MAXSG 1614001401static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1402{1403struct rev_info *revs = sb->revs;1404int i, pass, num_sg;1405struct commit *commit = origin->commit;1406struct commit_list *sg;1407struct origin *sg_buf[MAXSG];1408struct origin *porigin, **sg_origin = sg_buf;1409struct blame_entry *toosmall = NULL;1410struct blame_entry *blames, **blametail = &blames;14111412 num_sg =num_scapegoats(revs, commit);1413if(!num_sg)1414goto finish;1415else if(num_sg <ARRAY_SIZE(sg_buf))1416memset(sg_buf,0,sizeof(sg_buf));1417else1418 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14191420/*1421 * The first pass looks for unrenamed path to optimize for1422 * common cases, then we look for renames in the second pass.1423 */1424for(pass =0; pass <2- no_whole_file_rename; pass++) {1425struct origin *(*find)(struct scoreboard *,1426struct commit *,struct origin *);1427 find = pass ? find_rename : find_origin;14281429for(i =0, sg =first_scapegoat(revs, commit);1430 i < num_sg && sg;1431 sg = sg->next, i++) {1432struct commit *p = sg->item;1433int j, same;14341435if(sg_origin[i])1436continue;1437if(parse_commit(p))1438continue;1439 porigin =find(sb, p, origin);1440if(!porigin)1441continue;1442if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1443pass_whole_blame(sb, origin, porigin);1444origin_decref(porigin);1445goto finish;1446}1447for(j = same =0; j < i; j++)1448if(sg_origin[j] &&1449!hashcmp(sg_origin[j]->blob_sha1,1450 porigin->blob_sha1)) {1451 same =1;1452break;1453}1454if(!same)1455 sg_origin[i] = porigin;1456else1457origin_decref(porigin);1458}1459}14601461 num_commits++;1462for(i =0, sg =first_scapegoat(revs, commit);1463 i < num_sg && sg;1464 sg = sg->next, i++) {1465struct origin *porigin = sg_origin[i];1466if(!porigin)1467continue;1468if(!origin->previous) {1469origin_incref(porigin);1470 origin->previous = porigin;1471}1472pass_blame_to_parent(sb, origin, porigin);1473if(!origin->suspects)1474goto finish;1475}14761477/*1478 * Optionally find moves in parents' files.1479 */1480if(opt & PICKAXE_BLAME_MOVE) {1481filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1482if(origin->suspects) {1483for(i =0, sg =first_scapegoat(revs, commit);1484 i < num_sg && sg;1485 sg = sg->next, i++) {1486struct origin *porigin = sg_origin[i];1487if(!porigin)1488continue;1489find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1490if(!origin->suspects)1491break;1492}1493}1494}14951496/*1497 * Optionally find copies from parents' files.1498 */1499if(opt & PICKAXE_BLAME_COPY) {1500if(blame_copy_score > blame_move_score)1501filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1502else if(blame_copy_score < blame_move_score) {1503 origin->suspects =blame_merge(origin->suspects, toosmall);1504 toosmall = NULL;1505filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1506}1507if(!origin->suspects)1508goto finish;15091510for(i =0, sg =first_scapegoat(revs, commit);1511 i < num_sg && sg;1512 sg = sg->next, i++) {1513struct origin *porigin = sg_origin[i];1514find_copy_in_parent(sb, &blametail, &toosmall,1515 origin, sg->item, porigin, opt);1516if(!origin->suspects)1517goto finish;1518}1519}15201521finish:1522*blametail = NULL;1523distribute_blame(sb, blames);1524/*1525 * prepend toosmall to origin->suspects1526 *1527 * There is no point in sorting: this ends up on a big1528 * unsorted list in the caller anyway.1529 */1530if(toosmall) {1531struct blame_entry **tail = &toosmall;1532while(*tail)1533 tail = &(*tail)->next;1534*tail = origin->suspects;1535 origin->suspects = toosmall;1536}1537for(i =0; i < num_sg; i++) {1538if(sg_origin[i]) {1539drop_origin_blob(sg_origin[i]);1540origin_decref(sg_origin[i]);1541}1542}1543drop_origin_blob(origin);1544if(sg_buf != sg_origin)1545free(sg_origin);1546}15471548/*1549 * Information on commits, used for output.1550 */1551struct commit_info {1552struct strbuf author;1553struct strbuf author_mail;1554unsigned long author_time;1555struct strbuf author_tz;15561557/* filled only when asked for details */1558struct strbuf committer;1559struct strbuf committer_mail;1560unsigned long committer_time;1561struct strbuf committer_tz;15621563struct strbuf summary;1564};15651566/*1567 * Parse author/committer line in the commit object buffer1568 */1569static voidget_ac_line(const char*inbuf,const char*what,1570struct strbuf *name,struct strbuf *mail,1571unsigned long*time,struct strbuf *tz)1572{1573struct ident_split ident;1574size_t len, maillen, namelen;1575char*tmp, *endp;1576const char*namebuf, *mailbuf;15771578 tmp =strstr(inbuf, what);1579if(!tmp)1580goto error_out;1581 tmp +=strlen(what);1582 endp =strchr(tmp,'\n');1583if(!endp)1584 len =strlen(tmp);1585else1586 len = endp - tmp;15871588if(split_ident_line(&ident, tmp, len)) {1589 error_out:1590/* Ugh */1591 tmp ="(unknown)";1592strbuf_addstr(name, tmp);1593strbuf_addstr(mail, tmp);1594strbuf_addstr(tz, tmp);1595*time =0;1596return;1597}15981599 namelen = ident.name_end - ident.name_begin;1600 namebuf = ident.name_begin;16011602 maillen = ident.mail_end - ident.mail_begin;1603 mailbuf = ident.mail_begin;16041605if(ident.date_begin && ident.date_end)1606*time =strtoul(ident.date_begin, NULL,10);1607else1608*time =0;16091610if(ident.tz_begin && ident.tz_end)1611strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1612else1613strbuf_addstr(tz,"(unknown)");16141615/*1616 * Now, convert both name and e-mail using mailmap1617 */1618map_user(&mailmap, &mailbuf, &maillen,1619&namebuf, &namelen);16201621strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1622strbuf_add(name, namebuf, namelen);1623}16241625static voidcommit_info_init(struct commit_info *ci)1626{16271628strbuf_init(&ci->author,0);1629strbuf_init(&ci->author_mail,0);1630strbuf_init(&ci->author_tz,0);1631strbuf_init(&ci->committer,0);1632strbuf_init(&ci->committer_mail,0);1633strbuf_init(&ci->committer_tz,0);1634strbuf_init(&ci->summary,0);1635}16361637static voidcommit_info_destroy(struct commit_info *ci)1638{16391640strbuf_release(&ci->author);1641strbuf_release(&ci->author_mail);1642strbuf_release(&ci->author_tz);1643strbuf_release(&ci->committer);1644strbuf_release(&ci->committer_mail);1645strbuf_release(&ci->committer_tz);1646strbuf_release(&ci->summary);1647}16481649static voidget_commit_info(struct commit *commit,1650struct commit_info *ret,1651int detailed)1652{1653int len;1654const char*subject, *encoding;1655const char*message;16561657commit_info_init(ret);16581659 encoding =get_log_output_encoding();1660 message =logmsg_reencode(commit, NULL, encoding);1661get_ac_line(message,"\nauthor ",1662&ret->author, &ret->author_mail,1663&ret->author_time, &ret->author_tz);16641665if(!detailed) {1666unuse_commit_buffer(commit, message);1667return;1668}16691670get_ac_line(message,"\ncommitter ",1671&ret->committer, &ret->committer_mail,1672&ret->committer_time, &ret->committer_tz);16731674 len =find_commit_subject(message, &subject);1675if(len)1676strbuf_add(&ret->summary, subject, len);1677else1678strbuf_addf(&ret->summary,"(%s)",sha1_to_hex(commit->object.sha1));16791680unuse_commit_buffer(commit, message);1681}16821683/*1684 * To allow LF and other nonportable characters in pathnames,1685 * they are c-style quoted as needed.1686 */1687static voidwrite_filename_info(const char*path)1688{1689printf("filename ");1690write_name_quoted(path, stdout,'\n');1691}16921693/*1694 * Porcelain/Incremental format wants to show a lot of details per1695 * commit. Instead of repeating this every line, emit it only once,1696 * the first time each commit appears in the output (unless the1697 * user has specifically asked for us to repeat).1698 */1699static intemit_one_suspect_detail(struct origin *suspect,int repeat)1700{1701struct commit_info ci;17021703if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1704return0;17051706 suspect->commit->object.flags |= METAINFO_SHOWN;1707get_commit_info(suspect->commit, &ci,1);1708printf("author%s\n", ci.author.buf);1709printf("author-mail%s\n", ci.author_mail.buf);1710printf("author-time%lu\n", ci.author_time);1711printf("author-tz%s\n", ci.author_tz.buf);1712printf("committer%s\n", ci.committer.buf);1713printf("committer-mail%s\n", ci.committer_mail.buf);1714printf("committer-time%lu\n", ci.committer_time);1715printf("committer-tz%s\n", ci.committer_tz.buf);1716printf("summary%s\n", ci.summary.buf);1717if(suspect->commit->object.flags & UNINTERESTING)1718printf("boundary\n");1719if(suspect->previous) {1720struct origin *prev = suspect->previous;1721printf("previous%s",sha1_to_hex(prev->commit->object.sha1));1722write_name_quoted(prev->path, stdout,'\n');1723}17241725commit_info_destroy(&ci);17261727return1;1728}17291730/*1731 * The blame_entry is found to be guilty for the range.1732 * Show it in incremental output.1733 */1734static voidfound_guilty_entry(struct blame_entry *ent)1735{1736if(incremental) {1737struct origin *suspect = ent->suspect;17381739printf("%s %d %d %d\n",1740sha1_to_hex(suspect->commit->object.sha1),1741 ent->s_lno +1, ent->lno +1, ent->num_lines);1742emit_one_suspect_detail(suspect,0);1743write_filename_info(suspect->path);1744maybe_flush_or_die(stdout,"stdout");1745}1746}17471748/*1749 * The main loop -- while we have blobs with lines whose true origin1750 * is still unknown, pick one blob, and allow its lines to pass blames1751 * to its parents. */1752static voidassign_blame(struct scoreboard *sb,int opt)1753{1754struct rev_info *revs = sb->revs;1755struct commit *commit =prio_queue_get(&sb->commits);17561757while(commit) {1758struct blame_entry *ent;1759struct origin *suspect = commit->util;17601761/* find one suspect to break down */1762while(suspect && !suspect->suspects)1763 suspect = suspect->next;17641765if(!suspect) {1766 commit =prio_queue_get(&sb->commits);1767continue;1768}17691770assert(commit == suspect->commit);17711772/*1773 * We will use this suspect later in the loop,1774 * so hold onto it in the meantime.1775 */1776origin_incref(suspect);1777parse_commit(commit);1778if(reverse ||1779(!(commit->object.flags & UNINTERESTING) &&1780!(revs->max_age != -1&& commit->date < revs->max_age)))1781pass_blame(sb, suspect, opt);1782else{1783 commit->object.flags |= UNINTERESTING;1784if(commit->object.parsed)1785mark_parents_uninteresting(commit);1786}1787/* treat root commit as boundary */1788if(!commit->parents && !show_root)1789 commit->object.flags |= UNINTERESTING;17901791/* Take responsibility for the remaining entries */1792 ent = suspect->suspects;1793if(ent) {1794 suspect->guilty =1;1795for(;;) {1796struct blame_entry *next = ent->next;1797found_guilty_entry(ent);1798if(next) {1799 ent = next;1800continue;1801}1802 ent->next = sb->ent;1803 sb->ent = suspect->suspects;1804 suspect->suspects = NULL;1805break;1806}1807}1808origin_decref(suspect);18091810if(DEBUG)/* sanity */1811sanity_check_refcnt(sb);1812}1813}18141815static const char*format_time(unsigned long time,const char*tz_str,1816int show_raw_time)1817{1818static struct strbuf time_buf = STRBUF_INIT;18191820strbuf_reset(&time_buf);1821if(show_raw_time) {1822strbuf_addf(&time_buf,"%lu%s", time, tz_str);1823}1824else{1825const char*time_str;1826size_t time_width;1827int tz;1828 tz =atoi(tz_str);1829 time_str =show_date(time, tz, blame_date_mode);1830strbuf_addstr(&time_buf, time_str);1831/*1832 * Add space paddings to time_buf to display a fixed width1833 * string, and use time_width for display width calibration.1834 */1835for(time_width =utf8_strwidth(time_str);1836 time_width < blame_date_width;1837 time_width++)1838strbuf_addch(&time_buf,' ');1839}1840return time_buf.buf;1841}18421843#define OUTPUT_ANNOTATE_COMPAT 0011844#define OUTPUT_LONG_OBJECT_NAME 0021845#define OUTPUT_RAW_TIMESTAMP 0041846#define OUTPUT_PORCELAIN 0101847#define OUTPUT_SHOW_NAME 0201848#define OUTPUT_SHOW_NUMBER 0401849#define OUTPUT_SHOW_SCORE 01001850#define OUTPUT_NO_AUTHOR 02001851#define OUTPUT_SHOW_EMAIL 04001852#define OUTPUT_LINE_PORCELAIN 0100018531854static voidemit_porcelain_details(struct origin *suspect,int repeat)1855{1856if(emit_one_suspect_detail(suspect, repeat) ||1857(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1858write_filename_info(suspect->path);1859}18601861static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1862int opt)1863{1864int repeat = opt & OUTPUT_LINE_PORCELAIN;1865int cnt;1866const char*cp;1867struct origin *suspect = ent->suspect;1868char hex[41];18691870strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));1871printf("%s %d %d %d\n",1872 hex,1873 ent->s_lno +1,1874 ent->lno +1,1875 ent->num_lines);1876emit_porcelain_details(suspect, repeat);18771878 cp =nth_line(sb, ent->lno);1879for(cnt =0; cnt < ent->num_lines; cnt++) {1880char ch;1881if(cnt) {1882printf("%s %d %d\n", hex,1883 ent->s_lno +1+ cnt,1884 ent->lno +1+ cnt);1885if(repeat)1886emit_porcelain_details(suspect,1);1887}1888putchar('\t');1889do{1890 ch = *cp++;1891putchar(ch);1892}while(ch !='\n'&&1893 cp < sb->final_buf + sb->final_buf_size);1894}18951896if(sb->final_buf_size && cp[-1] !='\n')1897putchar('\n');1898}18991900static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1901{1902int cnt;1903const char*cp;1904struct origin *suspect = ent->suspect;1905struct commit_info ci;1906char hex[41];1907int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19081909get_commit_info(suspect->commit, &ci,1);1910strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));19111912 cp =nth_line(sb, ent->lno);1913for(cnt =0; cnt < ent->num_lines; cnt++) {1914char ch;1915int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19161917if(suspect->commit->object.flags & UNINTERESTING) {1918if(blank_boundary)1919memset(hex,' ', length);1920else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1921 length--;1922putchar('^');1923}1924}19251926printf("%.*s", length, hex);1927if(opt & OUTPUT_ANNOTATE_COMPAT) {1928const char*name;1929if(opt & OUTPUT_SHOW_EMAIL)1930 name = ci.author_mail.buf;1931else1932 name = ci.author.buf;1933printf("\t(%10s\t%10s\t%d)", name,1934format_time(ci.author_time, ci.author_tz.buf,1935 show_raw_time),1936 ent->lno +1+ cnt);1937}else{1938if(opt & OUTPUT_SHOW_SCORE)1939printf(" %*d%02d",1940 max_score_digits, ent->score,1941 ent->suspect->refcnt);1942if(opt & OUTPUT_SHOW_NAME)1943printf(" %-*.*s", longest_file, longest_file,1944 suspect->path);1945if(opt & OUTPUT_SHOW_NUMBER)1946printf(" %*d", max_orig_digits,1947 ent->s_lno +1+ cnt);19481949if(!(opt & OUTPUT_NO_AUTHOR)) {1950const char*name;1951int pad;1952if(opt & OUTPUT_SHOW_EMAIL)1953 name = ci.author_mail.buf;1954else1955 name = ci.author.buf;1956 pad = longest_author -utf8_strwidth(name);1957printf(" (%s%*s%10s",1958 name, pad,"",1959format_time(ci.author_time,1960 ci.author_tz.buf,1961 show_raw_time));1962}1963printf(" %*d) ",1964 max_digits, ent->lno +1+ cnt);1965}1966do{1967 ch = *cp++;1968putchar(ch);1969}while(ch !='\n'&&1970 cp < sb->final_buf + sb->final_buf_size);1971}19721973if(sb->final_buf_size && cp[-1] !='\n')1974putchar('\n');19751976commit_info_destroy(&ci);1977}19781979static voidoutput(struct scoreboard *sb,int option)1980{1981struct blame_entry *ent;19821983if(option & OUTPUT_PORCELAIN) {1984for(ent = sb->ent; ent; ent = ent->next) {1985int count =0;1986struct origin *suspect;1987struct commit *commit = ent->suspect->commit;1988if(commit->object.flags & MORE_THAN_ONE_PATH)1989continue;1990for(suspect = commit->util; suspect; suspect = suspect->next) {1991if(suspect->guilty && count++) {1992 commit->object.flags |= MORE_THAN_ONE_PATH;1993break;1994}1995}1996}1997}19981999for(ent = sb->ent; ent; ent = ent->next) {2000if(option & OUTPUT_PORCELAIN)2001emit_porcelain(sb, ent, option);2002else{2003emit_other(sb, ent, option);2004}2005}2006}20072008static const char*get_next_line(const char*start,const char*end)2009{2010const char*nl =memchr(start,'\n', end - start);2011return nl ? nl +1: end;2012}20132014/*2015 * To allow quick access to the contents of nth line in the2016 * final image, prepare an index in the scoreboard.2017 */2018static intprepare_lines(struct scoreboard *sb)2019{2020const char*buf = sb->final_buf;2021unsigned long len = sb->final_buf_size;2022const char*end = buf + len;2023const char*p;2024int*lineno;2025int num =0;20262027for(p = buf; p < end; p =get_next_line(p, end))2028 num++;20292030 sb->lineno = lineno =xmalloc(sizeof(*sb->lineno) * (num +1));20312032for(p = buf; p < end; p =get_next_line(p, end))2033*lineno++ = p - buf;20342035*lineno = len;20362037 sb->num_lines = num;2038return sb->num_lines;2039}20402041/*2042 * Add phony grafts for use with -S; this is primarily to2043 * support git's cvsserver that wants to give a linear history2044 * to its clients.2045 */2046static intread_ancestry(const char*graft_file)2047{2048FILE*fp =fopen(graft_file,"r");2049struct strbuf buf = STRBUF_INIT;2050if(!fp)2051return-1;2052while(!strbuf_getwholeline(&buf, fp,'\n')) {2053/* The format is just "Commit Parent1 Parent2 ...\n" */2054struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2055if(graft)2056register_commit_graft(graft,0);2057}2058fclose(fp);2059strbuf_release(&buf);2060return0;2061}20622063static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2064{2065const char*uniq =find_unique_abbrev(suspect->commit->object.sha1,2066 auto_abbrev);2067int len =strlen(uniq);2068if(auto_abbrev < len)2069return len;2070return auto_abbrev;2071}20722073/*2074 * How many columns do we need to show line numbers, authors,2075 * and filenames?2076 */2077static voidfind_alignment(struct scoreboard *sb,int*option)2078{2079int longest_src_lines =0;2080int longest_dst_lines =0;2081unsigned largest_score =0;2082struct blame_entry *e;2083int compute_auto_abbrev = (abbrev <0);2084int auto_abbrev = default_abbrev;20852086for(e = sb->ent; e; e = e->next) {2087struct origin *suspect = e->suspect;2088struct commit_info ci;2089int num;20902091if(compute_auto_abbrev)2092 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2093if(strcmp(suspect->path, sb->path))2094*option |= OUTPUT_SHOW_NAME;2095 num =strlen(suspect->path);2096if(longest_file < num)2097 longest_file = num;2098if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2099 suspect->commit->object.flags |= METAINFO_SHOWN;2100get_commit_info(suspect->commit, &ci,1);2101if(*option & OUTPUT_SHOW_EMAIL)2102 num =utf8_strwidth(ci.author_mail.buf);2103else2104 num =utf8_strwidth(ci.author.buf);2105if(longest_author < num)2106 longest_author = num;2107}2108 num = e->s_lno + e->num_lines;2109if(longest_src_lines < num)2110 longest_src_lines = num;2111 num = e->lno + e->num_lines;2112if(longest_dst_lines < num)2113 longest_dst_lines = num;2114if(largest_score <ent_score(sb, e))2115 largest_score =ent_score(sb, e);21162117commit_info_destroy(&ci);2118}2119 max_orig_digits =decimal_width(longest_src_lines);2120 max_digits =decimal_width(longest_dst_lines);2121 max_score_digits =decimal_width(largest_score);21222123if(compute_auto_abbrev)2124/* one more abbrev length is needed for the boundary commit */2125 abbrev = auto_abbrev +1;2126}21272128/*2129 * For debugging -- origin is refcounted, and this asserts that2130 * we do not underflow.2131 */2132static voidsanity_check_refcnt(struct scoreboard *sb)2133{2134int baa =0;2135struct blame_entry *ent;21362137for(ent = sb->ent; ent; ent = ent->next) {2138/* Nobody should have zero or negative refcnt */2139if(ent->suspect->refcnt <=0) {2140fprintf(stderr,"%sin%shas negative refcnt%d\n",2141 ent->suspect->path,2142sha1_to_hex(ent->suspect->commit->object.sha1),2143 ent->suspect->refcnt);2144 baa =1;2145}2146}2147if(baa) {2148int opt =0160;2149find_alignment(sb, &opt);2150output(sb, opt);2151die("Baa%d!", baa);2152}2153}21542155/*2156 * Used for the command line parsing; check if the path exists2157 * in the working tree.2158 */2159static inthas_string_in_work_tree(const char*path)2160{2161struct stat st;2162return!lstat(path, &st);2163}21642165static unsignedparse_score(const char*arg)2166{2167char*end;2168unsigned long score =strtoul(arg, &end,10);2169if(*end)2170return0;2171return score;2172}21732174static const char*add_prefix(const char*prefix,const char*path)2175{2176returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2177}21782179static intgit_blame_config(const char*var,const char*value,void*cb)2180{2181if(!strcmp(var,"blame.showroot")) {2182 show_root =git_config_bool(var, value);2183return0;2184}2185if(!strcmp(var,"blame.blankboundary")) {2186 blank_boundary =git_config_bool(var, value);2187return0;2188}2189if(!strcmp(var,"blame.date")) {2190if(!value)2191returnconfig_error_nonbool(var);2192 blame_date_mode =parse_date_format(value);2193return0;2194}21952196if(userdiff_config(var, value) <0)2197return-1;21982199returngit_default_config(var, value, cb);2200}22012202static voidverify_working_tree_path(struct commit *work_tree,const char*path)2203{2204struct commit_list *parents;22052206for(parents = work_tree->parents; parents; parents = parents->next) {2207const unsigned char*commit_sha1 = parents->item->object.sha1;2208unsigned char blob_sha1[20];2209unsigned mode;22102211if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2212sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2213return;2214}2215die("no such path '%s' in HEAD", path);2216}22172218static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2219{2220struct commit *parent;22212222 parent =lookup_commit_reference(sha1);2223if(!parent)2224die("no such commit%s",sha1_to_hex(sha1));2225return&commit_list_insert(parent, tail)->next;2226}22272228static voidappend_merge_parents(struct commit_list **tail)2229{2230int merge_head;2231const char*merge_head_file =git_path("MERGE_HEAD");2232struct strbuf line = STRBUF_INIT;22332234 merge_head =open(merge_head_file, O_RDONLY);2235if(merge_head <0) {2236if(errno == ENOENT)2237return;2238die("cannot open '%s' for reading", merge_head_file);2239}22402241while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2242unsigned char sha1[20];2243if(line.len <40||get_sha1_hex(line.buf, sha1))2244die("unknown line in '%s':%s", merge_head_file, line.buf);2245 tail =append_parent(tail, sha1);2246}2247close(merge_head);2248strbuf_release(&line);2249}22502251/*2252 * This isn't as simple as passing sb->buf and sb->len, because we2253 * want to transfer ownership of the buffer to the commit (so we2254 * must use detach).2255 */2256static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2257{2258size_t len;2259void*buf =strbuf_detach(sb, &len);2260set_commit_buffer(c, buf, len);2261}22622263/*2264 * Prepare a dummy commit that represents the work tree (or staged) item.2265 * Note that annotating work tree item never works in the reverse.2266 */2267static struct commit *fake_working_tree_commit(struct diff_options *opt,2268const char*path,2269const char*contents_from)2270{2271struct commit *commit;2272struct origin *origin;2273struct commit_list **parent_tail, *parent;2274unsigned char head_sha1[20];2275struct strbuf buf = STRBUF_INIT;2276const char*ident;2277time_t now;2278int size, len;2279struct cache_entry *ce;2280unsigned mode;2281struct strbuf msg = STRBUF_INIT;22822283time(&now);2284 commit =alloc_commit_node();2285 commit->object.parsed =1;2286 commit->date = now;2287 parent_tail = &commit->parents;22882289if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2290die("no such ref: HEAD");22912292 parent_tail =append_parent(parent_tail, head_sha1);2293append_merge_parents(parent_tail);2294verify_working_tree_path(commit, path);22952296 origin =make_origin(commit, path);22972298 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2299strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2300for(parent = commit->parents; parent; parent = parent->next)2301strbuf_addf(&msg,"parent%s\n",2302sha1_to_hex(parent->item->object.sha1));2303strbuf_addf(&msg,2304"author%s\n"2305"committer%s\n\n"2306"Version of%sfrom%s\n",2307 ident, ident, path,2308(!contents_from ? path :2309(!strcmp(contents_from,"-") ?"standard input": contents_from)));2310set_commit_buffer_from_strbuf(commit, &msg);23112312if(!contents_from ||strcmp("-", contents_from)) {2313struct stat st;2314const char*read_from;2315char*buf_ptr;2316unsigned long buf_len;23172318if(contents_from) {2319if(stat(contents_from, &st) <0)2320die_errno("Cannot stat '%s'", contents_from);2321 read_from = contents_from;2322}2323else{2324if(lstat(path, &st) <0)2325die_errno("Cannot lstat '%s'", path);2326 read_from = path;2327}2328 mode =canon_mode(st.st_mode);23292330switch(st.st_mode & S_IFMT) {2331case S_IFREG:2332if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2333textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2334strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2335else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2336die_errno("cannot open or read '%s'", read_from);2337break;2338case S_IFLNK:2339if(strbuf_readlink(&buf, read_from, st.st_size) <0)2340die_errno("cannot readlink '%s'", read_from);2341break;2342default:2343die("unsupported file type%s", read_from);2344}2345}2346else{2347/* Reading from stdin */2348 mode =0;2349if(strbuf_read(&buf,0,0) <0)2350die_errno("failed to read from stdin");2351}2352 origin->file.ptr = buf.buf;2353 origin->file.size = buf.len;2354pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23552356/*2357 * Read the current index, replace the path entry with2358 * origin->blob_sha1 without mucking with its mode or type2359 * bits; we are not going to write this index out -- we just2360 * want to run "diff-index --cached".2361 */2362discard_cache();2363read_cache();23642365 len =strlen(path);2366if(!mode) {2367int pos =cache_name_pos(path, len);2368if(0<= pos)2369 mode = active_cache[pos]->ce_mode;2370else2371/* Let's not bother reading from HEAD tree */2372 mode = S_IFREG |0644;2373}2374 size =cache_entry_size(len);2375 ce =xcalloc(1, size);2376hashcpy(ce->sha1, origin->blob_sha1);2377memcpy(ce->name, path, len);2378 ce->ce_flags =create_ce_flags(0);2379 ce->ce_namelen = len;2380 ce->ce_mode =create_ce_mode(mode);2381add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23822383/*2384 * We are not going to write this out, so this does not matter2385 * right now, but someday we might optimize diff-index --cached2386 * with cache-tree information.2387 */2388cache_tree_invalidate_path(&the_index, path);23892390return commit;2391}23922393static char*prepare_final(struct scoreboard *sb)2394{2395int i;2396const char*final_commit_name = NULL;2397struct rev_info *revs = sb->revs;23982399/*2400 * There must be one and only one positive commit in the2401 * revs->pending array.2402 */2403for(i =0; i < revs->pending.nr; i++) {2404struct object *obj = revs->pending.objects[i].item;2405if(obj->flags & UNINTERESTING)2406continue;2407while(obj->type == OBJ_TAG)2408 obj =deref_tag(obj, NULL,0);2409if(obj->type != OBJ_COMMIT)2410die("Non commit%s?", revs->pending.objects[i].name);2411if(sb->final)2412die("More than one commit to dig from%sand%s?",2413 revs->pending.objects[i].name,2414 final_commit_name);2415 sb->final = (struct commit *) obj;2416 final_commit_name = revs->pending.objects[i].name;2417}2418returnxstrdup_or_null(final_commit_name);2419}24202421static char*prepare_initial(struct scoreboard *sb)2422{2423int i;2424const char*final_commit_name = NULL;2425struct rev_info *revs = sb->revs;24262427/*2428 * There must be one and only one negative commit, and it must be2429 * the boundary.2430 */2431for(i =0; i < revs->pending.nr; i++) {2432struct object *obj = revs->pending.objects[i].item;2433if(!(obj->flags & UNINTERESTING))2434continue;2435while(obj->type == OBJ_TAG)2436 obj =deref_tag(obj, NULL,0);2437if(obj->type != OBJ_COMMIT)2438die("Non commit%s?", revs->pending.objects[i].name);2439if(sb->final)2440die("More than one commit to dig down to%sand%s?",2441 revs->pending.objects[i].name,2442 final_commit_name);2443 sb->final = (struct commit *) obj;2444 final_commit_name = revs->pending.objects[i].name;2445}2446if(!final_commit_name)2447die("No commit to dig down to?");2448returnxstrdup(final_commit_name);2449}24502451static intblame_copy_callback(const struct option *option,const char*arg,int unset)2452{2453int*opt = option->value;24542455/*2456 * -C enables copy from removed files;2457 * -C -C enables copy from existing files, but only2458 * when blaming a new file;2459 * -C -C -C enables copy from existing files for2460 * everybody2461 */2462if(*opt & PICKAXE_BLAME_COPY_HARDER)2463*opt |= PICKAXE_BLAME_COPY_HARDEST;2464if(*opt & PICKAXE_BLAME_COPY)2465*opt |= PICKAXE_BLAME_COPY_HARDER;2466*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;24672468if(arg)2469 blame_copy_score =parse_score(arg);2470return0;2471}24722473static intblame_move_callback(const struct option *option,const char*arg,int unset)2474{2475int*opt = option->value;24762477*opt |= PICKAXE_BLAME_MOVE;24782479if(arg)2480 blame_move_score =parse_score(arg);2481return0;2482}24832484intcmd_blame(int argc,const char**argv,const char*prefix)2485{2486struct rev_info revs;2487const char*path;2488struct scoreboard sb;2489struct origin *o;2490struct blame_entry *ent = NULL;2491long dashdash_pos, lno;2492char*final_commit_name = NULL;2493enum object_type type;24942495static struct string_list range_list;2496static int output_option =0, opt =0;2497static int show_stats =0;2498static const char*revs_file = NULL;2499static const char*contents_from = NULL;2500static const struct option options[] = {2501OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2502OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2503OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2504OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2505OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2506OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2507OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2508OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2509OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2510OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2511OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2512OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2513OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2514OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2515OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2516OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2517OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2518OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2519{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2520{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2521OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2522OPT__ABBREV(&abbrev),2523OPT_END()2524};25252526struct parse_opt_ctx_t ctx;2527int cmd_is_annotate = !strcmp(argv[0],"annotate");2528struct range_set ranges;2529unsigned int range_i;2530long anchor;25312532git_config(git_blame_config, NULL);2533init_revisions(&revs, NULL);2534 revs.date_mode = blame_date_mode;2535DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2536DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25372538 save_commit_buffer =0;2539 dashdash_pos =0;25402541parse_options_start(&ctx, argc, argv, prefix, options,2542 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2543for(;;) {2544switch(parse_options_step(&ctx, options, blame_opt_usage)) {2545case PARSE_OPT_HELP:2546exit(129);2547case PARSE_OPT_DONE:2548if(ctx.argv[0])2549 dashdash_pos = ctx.cpidx;2550goto parse_done;2551}25522553if(!strcmp(ctx.argv[0],"--reverse")) {2554 ctx.argv[0] ="--children";2555 reverse =1;2556}2557parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2558}2559parse_done:2560 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2561DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2562 argc =parse_options_end(&ctx);25632564if(0< abbrev)2565/* one more abbrev length is needed for the boundary commit */2566 abbrev++;25672568if(revs_file &&read_ancestry(revs_file))2569die_errno("reading graft file '%s' failed", revs_file);25702571if(cmd_is_annotate) {2572 output_option |= OUTPUT_ANNOTATE_COMPAT;2573 blame_date_mode = DATE_ISO8601;2574}else{2575 blame_date_mode = revs.date_mode;2576}25772578/* The maximum width used to show the dates */2579switch(blame_date_mode) {2580case DATE_RFC2822:2581 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2582break;2583case DATE_ISO8601_STRICT:2584 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2585break;2586case DATE_ISO8601:2587 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2588break;2589case DATE_RAW:2590 blame_date_width =sizeof("1161298804 -0700");2591break;2592case DATE_SHORT:2593 blame_date_width =sizeof("2006-10-19");2594break;2595case DATE_RELATIVE:2596/* TRANSLATORS: This string is used to tell us the maximum2597 display width for a relative timestamp in "git blame"2598 output. For C locale, "4 years, 11 months ago", which2599 takes 22 places, is the longest among various forms of2600 relative timestamps, but your language may need more or2601 fewer display columns. */2602 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2603break;2604case DATE_LOCAL:2605case DATE_NORMAL:2606 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2607break;2608}2609 blame_date_width -=1;/* strip the null */26102611if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2612 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2613 PICKAXE_BLAME_COPY_HARDER);26142615if(!blame_move_score)2616 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2617if(!blame_copy_score)2618 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26192620/*2621 * We have collected options unknown to us in argv[1..unk]2622 * which are to be passed to revision machinery if we are2623 * going to do the "bottom" processing.2624 *2625 * The remaining are:2626 *2627 * (1) if dashdash_pos != 0, it is either2628 * "blame [revisions] -- <path>" or2629 * "blame -- <path> <rev>"2630 *2631 * (2) otherwise, it is one of the two:2632 * "blame [revisions] <path>"2633 * "blame <path> <rev>"2634 *2635 * Note that we must strip out <path> from the arguments: we do not2636 * want the path pruning but we may want "bottom" processing.2637 */2638if(dashdash_pos) {2639switch(argc - dashdash_pos -1) {2640case2:/* (1b) */2641if(argc !=4)2642usage_with_options(blame_opt_usage, options);2643/* reorder for the new way: <rev> -- <path> */2644 argv[1] = argv[3];2645 argv[3] = argv[2];2646 argv[2] ="--";2647/* FALLTHROUGH */2648case1:/* (1a) */2649 path =add_prefix(prefix, argv[--argc]);2650 argv[argc] = NULL;2651break;2652default:2653usage_with_options(blame_opt_usage, options);2654}2655}else{2656if(argc <2)2657usage_with_options(blame_opt_usage, options);2658 path =add_prefix(prefix, argv[argc -1]);2659if(argc ==3&& !has_string_in_work_tree(path)) {/* (2b) */2660 path =add_prefix(prefix, argv[1]);2661 argv[1] = argv[2];2662}2663 argv[argc -1] ="--";26642665setup_work_tree();2666if(!has_string_in_work_tree(path))2667die_errno("cannot stat path '%s'", path);2668}26692670 revs.disable_stdin =1;2671setup_revisions(argc, argv, &revs, NULL);2672memset(&sb,0,sizeof(sb));26732674 sb.revs = &revs;2675if(!reverse) {2676 final_commit_name =prepare_final(&sb);2677 sb.commits.compare = compare_commits_by_commit_date;2678}2679else if(contents_from)2680die("--contents and --children do not blend well.");2681else{2682 final_commit_name =prepare_initial(&sb);2683 sb.commits.compare = compare_commits_by_reverse_commit_date;2684}26852686if(!sb.final) {2687/*2688 * "--not A B -- path" without anything positive;2689 * do not default to HEAD, but use the working tree2690 * or "--contents".2691 */2692setup_work_tree();2693 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2694 path, contents_from);2695add_pending_object(&revs, &(sb.final->object),":");2696}2697else if(contents_from)2698die("Cannot use --contents with final commit object name");26992700/*2701 * If we have bottom, this will mark the ancestors of the2702 * bottom commits we would reach while traversing as2703 * uninteresting.2704 */2705if(prepare_revision_walk(&revs))2706die(_("revision walk setup failed"));27072708if(is_null_sha1(sb.final->object.sha1)) {2709 o = sb.final->util;2710 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2711 sb.final_buf_size = o->file.size;2712}2713else{2714 o =get_origin(&sb, sb.final, path);2715if(fill_blob_sha1_and_mode(o))2716die("no such path%sin%s", path, final_commit_name);27172718if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2719textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2720&sb.final_buf_size))2721;2722else2723 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2724&sb.final_buf_size);27252726if(!sb.final_buf)2727die("Cannot read blob%sfor path%s",2728sha1_to_hex(o->blob_sha1),2729 path);2730}2731 num_read_blob++;2732 lno =prepare_lines(&sb);27332734if(lno && !range_list.nr)2735string_list_append(&range_list,xstrdup("1"));27362737 anchor =1;2738range_set_init(&ranges, range_list.nr);2739for(range_i =0; range_i < range_list.nr; ++range_i) {2740long bottom, top;2741if(parse_range_arg(range_list.items[range_i].string,2742 nth_line_cb, &sb, lno, anchor,2743&bottom, &top, sb.path))2744usage(blame_usage);2745if(lno < top || ((lno || bottom) && lno < bottom))2746die("file%shas only%lu lines", path, lno);2747if(bottom <1)2748 bottom =1;2749if(top <1)2750 top = lno;2751 bottom--;2752range_set_append_unsafe(&ranges, bottom, top);2753 anchor = top +1;2754}2755sort_and_merge_range_set(&ranges);27562757for(range_i = ranges.nr; range_i >0; --range_i) {2758const struct range *r = &ranges.ranges[range_i -1];2759long bottom = r->start;2760long top = r->end;2761struct blame_entry *next = ent;2762 ent =xcalloc(1,sizeof(*ent));2763 ent->lno = bottom;2764 ent->num_lines = top - bottom;2765 ent->suspect = o;2766 ent->s_lno = bottom;2767 ent->next = next;2768origin_incref(o);2769}27702771 o->suspects = ent;2772prio_queue_put(&sb.commits, o->commit);27732774origin_decref(o);27752776range_set_release(&ranges);2777string_list_clear(&range_list,0);27782779 sb.ent = NULL;2780 sb.path = path;27812782read_mailmap(&mailmap, NULL);27832784if(!incremental)2785setup_pager();27862787assign_blame(&sb, opt);27882789free(final_commit_name);27902791if(incremental)2792return0;27932794 sb.ent =blame_sort(sb.ent, compare_blame_final);27952796coalesce(&sb);27972798if(!(output_option & OUTPUT_PORCELAIN))2799find_alignment(&sb, &output_option);28002801output(&sb, output_option);2802free((void*)sb.final_buf);2803for(ent = sb.ent; ent; ) {2804struct blame_entry *e = ent->next;2805free(ent);2806 ent = e;2807}28082809if(show_stats) {2810printf("num read blob:%d\n", num_read_blob);2811printf("num get patch:%d\n", num_get_patch);2812printf("num commits:%d\n", num_commits);2813}2814return0;2815}