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 32static char blame_usage[] =N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>"); 33 34static const char*blame_opt_usage[] = { 35 blame_usage, 36"", 37N_("<rev-opts> are documented in git-rev-list(1)"), 38 NULL 39}; 40 41static int longest_file; 42static int longest_author; 43static int max_orig_digits; 44static int max_digits; 45static int max_score_digits; 46static int show_root; 47static int reverse; 48static int blank_boundary; 49static int incremental; 50static int xdl_opts; 51static int abbrev = -1; 52static int no_whole_file_rename; 53 54static struct date_mode blame_date_mode = { DATE_ISO8601 }; 55static size_t blame_date_width; 56 57static struct string_list mailmap; 58 59#ifndef DEBUG 60#define DEBUG 0 61#endif 62 63/* stats */ 64static int num_read_blob; 65static int num_get_patch; 66static int num_commits; 67 68#define PICKAXE_BLAME_MOVE 01 69#define PICKAXE_BLAME_COPY 02 70#define PICKAXE_BLAME_COPY_HARDER 04 71#define PICKAXE_BLAME_COPY_HARDEST 010 72 73/* 74 * blame for a blame_entry with score lower than these thresholds 75 * is not passed to the parent using move/copy logic. 76 */ 77static unsigned blame_move_score; 78static unsigned blame_copy_score; 79#define BLAME_DEFAULT_MOVE_SCORE 20 80#define BLAME_DEFAULT_COPY_SCORE 40 81 82/* Remember to update object flag allocation in object.h */ 83#define METAINFO_SHOWN (1u<<12) 84#define MORE_THAN_ONE_PATH (1u<<13) 85 86/* 87 * One blob in a commit that is being suspected 88 */ 89struct origin { 90int refcnt; 91/* Record preceding blame record for this blob */ 92struct origin *previous; 93/* origins are put in a list linked via `next' hanging off the 94 * corresponding commit's util field in order to make finding 95 * them fast. The presence in this chain does not count 96 * towards the origin's reference count. It is tempting to 97 * let it count as long as the commit is pending examination, 98 * but even under circumstances where the commit will be 99 * present multiple times in the priority queue of unexamined 100 * commits, processing the first instance will not leave any 101 * work requiring the origin data for the second instance. An 102 * interspersed commit changing that would have to be 103 * preexisting with a different ancestry and with the same 104 * commit date in order to wedge itself between two instances 105 * of the same commit in the priority queue _and_ produce 106 * blame entries relevant for it. While we don't want to let 107 * us get tripped up by this case, it certainly does not seem 108 * worth optimizing for. 109 */ 110struct origin *next; 111struct commit *commit; 112/* `suspects' contains blame entries that may be attributed to 113 * this origin's commit or to parent commits. When a commit 114 * is being processed, all suspects will be moved, either by 115 * assigning them to an origin in a different commit, or by 116 * shipping them to the scoreboard's ent list because they 117 * cannot be attributed to a different commit. 118 */ 119struct blame_entry *suspects; 120 mmfile_t file; 121unsigned char blob_sha1[20]; 122unsigned mode; 123/* guilty gets set when shipping any suspects to the final 124 * blame list instead of other commits 125 */ 126char guilty; 127char path[FLEX_ARRAY]; 128}; 129 130static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b,long ctxlen, 131 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data) 132{ 133 xpparam_t xpp = {0}; 134 xdemitconf_t xecfg = {0}; 135 xdemitcb_t ecb = {NULL}; 136 137 xpp.flags = xdl_opts; 138 xecfg.ctxlen = ctxlen; 139 xecfg.hunk_func = hunk_func; 140 ecb.priv = cb_data; 141returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 142} 143 144/* 145 * Prepare diff_filespec and convert it using diff textconv API 146 * if the textconv driver exists. 147 * Return 1 if the conversion succeeds, 0 otherwise. 148 */ 149inttextconv_object(const char*path, 150unsigned mode, 151const unsigned char*sha1, 152int sha1_valid, 153char**buf, 154unsigned long*buf_size) 155{ 156struct diff_filespec *df; 157struct userdiff_driver *textconv; 158 159 df =alloc_filespec(path); 160fill_filespec(df, sha1, sha1_valid, mode); 161 textconv =get_textconv(df); 162if(!textconv) { 163free_filespec(df); 164return0; 165} 166 167*buf_size =fill_textconv(textconv, df, buf); 168free_filespec(df); 169return1; 170} 171 172/* 173 * Given an origin, prepare mmfile_t structure to be used by the 174 * diff machinery 175 */ 176static voidfill_origin_blob(struct diff_options *opt, 177struct origin *o, mmfile_t *file) 178{ 179if(!o->file.ptr) { 180enum object_type type; 181unsigned long file_size; 182 183 num_read_blob++; 184if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 185textconv_object(o->path, o->mode, o->blob_sha1,1, &file->ptr, &file_size)) 186; 187else 188 file->ptr =read_sha1_file(o->blob_sha1, &type, &file_size); 189 file->size = file_size; 190 191if(!file->ptr) 192die("Cannot read blob%sfor path%s", 193sha1_to_hex(o->blob_sha1), 194 o->path); 195 o->file = *file; 196} 197else 198*file = o->file; 199} 200 201/* 202 * Origin is refcounted and usually we keep the blob contents to be 203 * reused. 204 */ 205staticinlinestruct origin *origin_incref(struct origin *o) 206{ 207if(o) 208 o->refcnt++; 209return o; 210} 211 212static voidorigin_decref(struct origin *o) 213{ 214if(o && --o->refcnt <=0) { 215struct origin *p, *l = NULL; 216if(o->previous) 217origin_decref(o->previous); 218free(o->file.ptr); 219/* Should be present exactly once in commit chain */ 220for(p = o->commit->util; p; l = p, p = p->next) { 221if(p == o) { 222if(l) 223 l->next = p->next; 224else 225 o->commit->util = p->next; 226free(o); 227return; 228} 229} 230die("internal error in blame::origin_decref"); 231} 232} 233 234static voiddrop_origin_blob(struct origin *o) 235{ 236if(o->file.ptr) { 237free(o->file.ptr); 238 o->file.ptr = NULL; 239} 240} 241 242/* 243 * Each group of lines is described by a blame_entry; it can be split 244 * as we pass blame to the parents. They are arranged in linked lists 245 * kept as `suspects' of some unprocessed origin, or entered (when the 246 * blame origin has been finalized) into the scoreboard structure. 247 * While the scoreboard structure is only sorted at the end of 248 * processing (according to final image line number), the lists 249 * attached to an origin are sorted by the target line number. 250 */ 251struct blame_entry { 252struct blame_entry *next; 253 254/* the first line of this group in the final image; 255 * internally all line numbers are 0 based. 256 */ 257int lno; 258 259/* how many lines this group has */ 260int num_lines; 261 262/* the commit that introduced this group into the final image */ 263struct origin *suspect; 264 265/* the line number of the first line of this group in the 266 * suspect's file; internally all line numbers are 0 based. 267 */ 268int s_lno; 269 270/* how significant this entry is -- cached to avoid 271 * scanning the lines over and over. 272 */ 273unsigned score; 274}; 275 276/* 277 * Any merge of blames happens on lists of blames that arrived via 278 * different parents in a single suspect. In this case, we want to 279 * sort according to the suspect line numbers as opposed to the final 280 * image line numbers. The function body is somewhat longish because 281 * it avoids unnecessary writes. 282 */ 283 284static struct blame_entry *blame_merge(struct blame_entry *list1, 285struct blame_entry *list2) 286{ 287struct blame_entry *p1 = list1, *p2 = list2, 288**tail = &list1; 289 290if(!p1) 291return p2; 292if(!p2) 293return p1; 294 295if(p1->s_lno <= p2->s_lno) { 296do{ 297 tail = &p1->next; 298if((p1 = *tail) == NULL) { 299*tail = p2; 300return list1; 301} 302}while(p1->s_lno <= p2->s_lno); 303} 304for(;;) { 305*tail = p2; 306do{ 307 tail = &p2->next; 308if((p2 = *tail) == NULL) { 309*tail = p1; 310return list1; 311} 312}while(p1->s_lno > p2->s_lno); 313*tail = p1; 314do{ 315 tail = &p1->next; 316if((p1 = *tail) == NULL) { 317*tail = p2; 318return list1; 319} 320}while(p1->s_lno <= p2->s_lno); 321} 322} 323 324static void*get_next_blame(const void*p) 325{ 326return((struct blame_entry *)p)->next; 327} 328 329static voidset_next_blame(void*p1,void*p2) 330{ 331((struct blame_entry *)p1)->next = p2; 332} 333 334/* 335 * Final image line numbers are all different, so we don't need a 336 * three-way comparison here. 337 */ 338 339static intcompare_blame_final(const void*p1,const void*p2) 340{ 341return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 342?1: -1; 343} 344 345static intcompare_blame_suspect(const void*p1,const void*p2) 346{ 347const struct blame_entry *s1 = p1, *s2 = p2; 348/* 349 * to allow for collating suspects, we sort according to the 350 * respective pointer value as the primary sorting criterion. 351 * The actual relation is pretty unimportant as long as it 352 * establishes a total order. Comparing as integers gives us 353 * that. 354 */ 355if(s1->suspect != s2->suspect) 356return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 357if(s1->s_lno == s2->s_lno) 358return0; 359return s1->s_lno > s2->s_lno ?1: -1; 360} 361 362static struct blame_entry *blame_sort(struct blame_entry *head, 363int(*compare_fn)(const void*,const void*)) 364{ 365returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 366} 367 368static intcompare_commits_by_reverse_commit_date(const void*a, 369const void*b, 370void*c) 371{ 372return-compare_commits_by_commit_date(a, b, c); 373} 374 375/* 376 * The current state of the blame assignment. 377 */ 378struct scoreboard { 379/* the final commit (i.e. where we started digging from) */ 380struct commit *final; 381/* Priority queue for commits with unassigned blame records */ 382struct prio_queue commits; 383struct rev_info *revs; 384const char*path; 385 386/* 387 * The contents in the final image. 388 * Used by many functions to obtain contents of the nth line, 389 * indexed with scoreboard.lineno[blame_entry.lno]. 390 */ 391const char*final_buf; 392unsigned long final_buf_size; 393 394/* linked list of blames */ 395struct blame_entry *ent; 396 397/* look-up a line in the final buffer */ 398int num_lines; 399int*lineno; 400}; 401 402static voidsanity_check_refcnt(struct scoreboard *); 403 404/* 405 * If two blame entries that are next to each other came from 406 * contiguous lines in the same origin (i.e. <commit, path> pair), 407 * merge them together. 408 */ 409static voidcoalesce(struct scoreboard *sb) 410{ 411struct blame_entry *ent, *next; 412 413for(ent = sb->ent; ent && (next = ent->next); ent = next) { 414if(ent->suspect == next->suspect && 415 ent->s_lno + ent->num_lines == next->s_lno) { 416 ent->num_lines += next->num_lines; 417 ent->next = next->next; 418origin_decref(next->suspect); 419free(next); 420 ent->score =0; 421 next = ent;/* again */ 422} 423} 424 425if(DEBUG)/* sanity */ 426sanity_check_refcnt(sb); 427} 428 429/* 430 * Merge the given sorted list of blames into a preexisting origin. 431 * If there were no previous blames to that commit, it is entered into 432 * the commit priority queue of the score board. 433 */ 434 435static voidqueue_blames(struct scoreboard *sb,struct origin *porigin, 436struct blame_entry *sorted) 437{ 438if(porigin->suspects) 439 porigin->suspects =blame_merge(porigin->suspects, sorted); 440else{ 441struct origin *o; 442for(o = porigin->commit->util; o; o = o->next) { 443if(o->suspects) { 444 porigin->suspects = sorted; 445return; 446} 447} 448 porigin->suspects = sorted; 449prio_queue_put(&sb->commits, porigin->commit); 450} 451} 452 453/* 454 * Given a commit and a path in it, create a new origin structure. 455 * The callers that add blame to the scoreboard should use 456 * get_origin() to obtain shared, refcounted copy instead of calling 457 * this function directly. 458 */ 459static struct origin *make_origin(struct commit *commit,const char*path) 460{ 461struct origin *o; 462 o =xcalloc(1,sizeof(*o) +strlen(path) +1); 463 o->commit = commit; 464 o->refcnt =1; 465 o->next = commit->util; 466 commit->util = o; 467strcpy(o->path, path); 468return o; 469} 470 471/* 472 * Locate an existing origin or create a new one. 473 * This moves the origin to front position in the commit util list. 474 */ 475static struct origin *get_origin(struct scoreboard *sb, 476struct commit *commit, 477const char*path) 478{ 479struct origin *o, *l; 480 481for(o = commit->util, l = NULL; o; l = o, o = o->next) { 482if(!strcmp(o->path, path)) { 483/* bump to front */ 484if(l) { 485 l->next = o->next; 486 o->next = commit->util; 487 commit->util = o; 488} 489returnorigin_incref(o); 490} 491} 492returnmake_origin(commit, path); 493} 494 495/* 496 * Fill the blob_sha1 field of an origin if it hasn't, so that later 497 * call to fill_origin_blob() can use it to locate the data. blob_sha1 498 * for an origin is also used to pass the blame for the entire file to 499 * the parent to detect the case where a child's blob is identical to 500 * that of its parent's. 501 * 502 * This also fills origin->mode for corresponding tree path. 503 */ 504static intfill_blob_sha1_and_mode(struct origin *origin) 505{ 506if(!is_null_sha1(origin->blob_sha1)) 507return0; 508if(get_tree_entry(origin->commit->object.sha1, 509 origin->path, 510 origin->blob_sha1, &origin->mode)) 511goto error_out; 512if(sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB) 513goto error_out; 514return0; 515 error_out: 516hashclr(origin->blob_sha1); 517 origin->mode = S_IFINVALID; 518return-1; 519} 520 521/* 522 * We have an origin -- check if the same path exists in the 523 * parent and return an origin structure to represent it. 524 */ 525static struct origin *find_origin(struct scoreboard *sb, 526struct commit *parent, 527struct origin *origin) 528{ 529struct origin *porigin; 530struct diff_options diff_opts; 531const char*paths[2]; 532 533/* First check any existing origins */ 534for(porigin = parent->util; porigin; porigin = porigin->next) 535if(!strcmp(porigin->path, origin->path)) { 536/* 537 * The same path between origin and its parent 538 * without renaming -- the most common case. 539 */ 540returnorigin_incref(porigin); 541} 542 543/* See if the origin->path is different between parent 544 * and origin first. Most of the time they are the 545 * same and diff-tree is fairly efficient about this. 546 */ 547diff_setup(&diff_opts); 548DIFF_OPT_SET(&diff_opts, RECURSIVE); 549 diff_opts.detect_rename =0; 550 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 551 paths[0] = origin->path; 552 paths[1] = NULL; 553 554parse_pathspec(&diff_opts.pathspec, 555 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 556 PATHSPEC_LITERAL_PATH,"", paths); 557diff_setup_done(&diff_opts); 558 559if(is_null_sha1(origin->commit->object.sha1)) 560do_diff_cache(parent->tree->object.sha1, &diff_opts); 561else 562diff_tree_sha1(parent->tree->object.sha1, 563 origin->commit->tree->object.sha1, 564"", &diff_opts); 565diffcore_std(&diff_opts); 566 567if(!diff_queued_diff.nr) { 568/* The path is the same as parent */ 569 porigin =get_origin(sb, parent, origin->path); 570hashcpy(porigin->blob_sha1, origin->blob_sha1); 571 porigin->mode = origin->mode; 572}else{ 573/* 574 * Since origin->path is a pathspec, if the parent 575 * commit had it as a directory, we will see a whole 576 * bunch of deletion of files in the directory that we 577 * do not care about. 578 */ 579int i; 580struct diff_filepair *p = NULL; 581for(i =0; i < diff_queued_diff.nr; i++) { 582const char*name; 583 p = diff_queued_diff.queue[i]; 584 name = p->one->path ? p->one->path : p->two->path; 585if(!strcmp(name, origin->path)) 586break; 587} 588if(!p) 589die("internal error in blame::find_origin"); 590switch(p->status) { 591default: 592die("internal error in blame::find_origin (%c)", 593 p->status); 594case'M': 595 porigin =get_origin(sb, parent, origin->path); 596hashcpy(porigin->blob_sha1, p->one->sha1); 597 porigin->mode = p->one->mode; 598break; 599case'A': 600case'T': 601/* Did not exist in parent, or type changed */ 602break; 603} 604} 605diff_flush(&diff_opts); 606free_pathspec(&diff_opts.pathspec); 607return porigin; 608} 609 610/* 611 * We have an origin -- find the path that corresponds to it in its 612 * parent and return an origin structure to represent it. 613 */ 614static struct origin *find_rename(struct scoreboard *sb, 615struct commit *parent, 616struct origin *origin) 617{ 618struct origin *porigin = NULL; 619struct diff_options diff_opts; 620int i; 621 622diff_setup(&diff_opts); 623DIFF_OPT_SET(&diff_opts, RECURSIVE); 624 diff_opts.detect_rename = DIFF_DETECT_RENAME; 625 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 626 diff_opts.single_follow = origin->path; 627diff_setup_done(&diff_opts); 628 629if(is_null_sha1(origin->commit->object.sha1)) 630do_diff_cache(parent->tree->object.sha1, &diff_opts); 631else 632diff_tree_sha1(parent->tree->object.sha1, 633 origin->commit->tree->object.sha1, 634"", &diff_opts); 635diffcore_std(&diff_opts); 636 637for(i =0; i < diff_queued_diff.nr; i++) { 638struct diff_filepair *p = diff_queued_diff.queue[i]; 639if((p->status =='R'|| p->status =='C') && 640!strcmp(p->two->path, origin->path)) { 641 porigin =get_origin(sb, parent, p->one->path); 642hashcpy(porigin->blob_sha1, p->one->sha1); 643 porigin->mode = p->one->mode; 644break; 645} 646} 647diff_flush(&diff_opts); 648free_pathspec(&diff_opts.pathspec); 649return porigin; 650} 651 652/* 653 * Append a new blame entry to a given output queue. 654 */ 655static voidadd_blame_entry(struct blame_entry ***queue,struct blame_entry *e) 656{ 657origin_incref(e->suspect); 658 659 e->next = **queue; 660**queue = e; 661*queue = &e->next; 662} 663 664/* 665 * src typically is on-stack; we want to copy the information in it to 666 * a malloced blame_entry that gets added to the given queue. The 667 * origin of dst loses a refcnt. 668 */ 669static voiddup_entry(struct blame_entry ***queue, 670struct blame_entry *dst,struct blame_entry *src) 671{ 672origin_incref(src->suspect); 673origin_decref(dst->suspect); 674memcpy(dst, src,sizeof(*src)); 675 dst->next = **queue; 676**queue = dst; 677*queue = &dst->next; 678} 679 680static const char*nth_line(struct scoreboard *sb,long lno) 681{ 682return sb->final_buf + sb->lineno[lno]; 683} 684 685static const char*nth_line_cb(void*data,long lno) 686{ 687returnnth_line((struct scoreboard *)data, lno); 688} 689 690/* 691 * It is known that lines between tlno to same came from parent, and e 692 * has an overlap with that range. it also is known that parent's 693 * line plno corresponds to e's line tlno. 694 * 695 * <---- e -----> 696 * <------> 697 * <------------> 698 * <------------> 699 * <------------------> 700 * 701 * Split e into potentially three parts; before this chunk, the chunk 702 * to be blamed for the parent, and after that portion. 703 */ 704static voidsplit_overlap(struct blame_entry *split, 705struct blame_entry *e, 706int tlno,int plno,int same, 707struct origin *parent) 708{ 709int chunk_end_lno; 710memset(split,0,sizeof(struct blame_entry [3])); 711 712if(e->s_lno < tlno) { 713/* there is a pre-chunk part not blamed on parent */ 714 split[0].suspect =origin_incref(e->suspect); 715 split[0].lno = e->lno; 716 split[0].s_lno = e->s_lno; 717 split[0].num_lines = tlno - e->s_lno; 718 split[1].lno = e->lno + tlno - e->s_lno; 719 split[1].s_lno = plno; 720} 721else{ 722 split[1].lno = e->lno; 723 split[1].s_lno = plno + (e->s_lno - tlno); 724} 725 726if(same < e->s_lno + e->num_lines) { 727/* there is a post-chunk part not blamed on parent */ 728 split[2].suspect =origin_incref(e->suspect); 729 split[2].lno = e->lno + (same - e->s_lno); 730 split[2].s_lno = e->s_lno + (same - e->s_lno); 731 split[2].num_lines = e->s_lno + e->num_lines - same; 732 chunk_end_lno = split[2].lno; 733} 734else 735 chunk_end_lno = e->lno + e->num_lines; 736 split[1].num_lines = chunk_end_lno - split[1].lno; 737 738/* 739 * if it turns out there is nothing to blame the parent for, 740 * forget about the splitting. !split[1].suspect signals this. 741 */ 742if(split[1].num_lines <1) 743return; 744 split[1].suspect =origin_incref(parent); 745} 746 747/* 748 * split_overlap() divided an existing blame e into up to three parts 749 * in split. Any assigned blame is moved to queue to 750 * reflect the split. 751 */ 752static voidsplit_blame(struct blame_entry ***blamed, 753struct blame_entry ***unblamed, 754struct blame_entry *split, 755struct blame_entry *e) 756{ 757struct blame_entry *new_entry; 758 759if(split[0].suspect && split[2].suspect) { 760/* The first part (reuse storage for the existing entry e) */ 761dup_entry(unblamed, e, &split[0]); 762 763/* The last part -- me */ 764 new_entry =xmalloc(sizeof(*new_entry)); 765memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 766add_blame_entry(unblamed, new_entry); 767 768/* ... and the middle part -- parent */ 769 new_entry =xmalloc(sizeof(*new_entry)); 770memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 771add_blame_entry(blamed, new_entry); 772} 773else if(!split[0].suspect && !split[2].suspect) 774/* 775 * The parent covers the entire area; reuse storage for 776 * e and replace it with the parent. 777 */ 778dup_entry(blamed, e, &split[1]); 779else if(split[0].suspect) { 780/* me and then parent */ 781dup_entry(unblamed, e, &split[0]); 782 783 new_entry =xmalloc(sizeof(*new_entry)); 784memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 785add_blame_entry(blamed, new_entry); 786} 787else{ 788/* parent and then me */ 789dup_entry(blamed, e, &split[1]); 790 791 new_entry =xmalloc(sizeof(*new_entry)); 792memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 793add_blame_entry(unblamed, new_entry); 794} 795} 796 797/* 798 * After splitting the blame, the origins used by the 799 * on-stack blame_entry should lose one refcnt each. 800 */ 801static voiddecref_split(struct blame_entry *split) 802{ 803int i; 804 805for(i =0; i <3; i++) 806origin_decref(split[i].suspect); 807} 808 809/* 810 * reverse_blame reverses the list given in head, appending tail. 811 * That allows us to build lists in reverse order, then reverse them 812 * afterwards. This can be faster than building the list in proper 813 * order right away. The reason is that building in proper order 814 * requires writing a link in the _previous_ element, while building 815 * in reverse order just requires placing the list head into the 816 * _current_ element. 817 */ 818 819static struct blame_entry *reverse_blame(struct blame_entry *head, 820struct blame_entry *tail) 821{ 822while(head) { 823struct blame_entry *next = head->next; 824 head->next = tail; 825 tail = head; 826 head = next; 827} 828return tail; 829} 830 831/* 832 * Process one hunk from the patch between the current suspect for 833 * blame_entry e and its parent. This first blames any unfinished 834 * entries before the chunk (which is where target and parent start 835 * differing) on the parent, and then splits blame entries at the 836 * start and at the end of the difference region. Since use of -M and 837 * -C options may lead to overlapping/duplicate source line number 838 * ranges, all we can rely on from sorting/merging is the order of the 839 * first suspect line number. 840 */ 841static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 842int tlno,int offset,int same, 843struct origin *parent) 844{ 845struct blame_entry *e = **srcq; 846struct blame_entry *samep = NULL, *diffp = NULL; 847 848while(e && e->s_lno < tlno) { 849struct blame_entry *next = e->next; 850/* 851 * current record starts before differing portion. If 852 * it reaches into it, we need to split it up and 853 * examine the second part separately. 854 */ 855if(e->s_lno + e->num_lines > tlno) { 856/* Move second half to a new record */ 857int len = tlno - e->s_lno; 858struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 859 n->suspect = e->suspect; 860 n->lno = e->lno + len; 861 n->s_lno = e->s_lno + len; 862 n->num_lines = e->num_lines - len; 863 e->num_lines = len; 864 e->score =0; 865/* Push new record to diffp */ 866 n->next = diffp; 867 diffp = n; 868}else 869origin_decref(e->suspect); 870/* Pass blame for everything before the differing 871 * chunk to the parent */ 872 e->suspect =origin_incref(parent); 873 e->s_lno += offset; 874 e->next = samep; 875 samep = e; 876 e = next; 877} 878/* 879 * As we don't know how much of a common stretch after this 880 * diff will occur, the currently blamed parts are all that we 881 * can assign to the parent for now. 882 */ 883 884if(samep) { 885**dstq =reverse_blame(samep, **dstq); 886*dstq = &samep->next; 887} 888/* 889 * Prepend the split off portions: everything after e starts 890 * after the blameable portion. 891 */ 892 e =reverse_blame(diffp, e); 893 894/* 895 * Now retain records on the target while parts are different 896 * from the parent. 897 */ 898 samep = NULL; 899 diffp = NULL; 900while(e && e->s_lno < same) { 901struct blame_entry *next = e->next; 902 903/* 904 * If current record extends into sameness, need to split. 905 */ 906if(e->s_lno + e->num_lines > same) { 907/* 908 * Move second half to a new record to be 909 * processed by later chunks 910 */ 911int len = same - e->s_lno; 912struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 913 n->suspect =origin_incref(e->suspect); 914 n->lno = e->lno + len; 915 n->s_lno = e->s_lno + len; 916 n->num_lines = e->num_lines - len; 917 e->num_lines = len; 918 e->score =0; 919/* Push new record to samep */ 920 n->next = samep; 921 samep = n; 922} 923 e->next = diffp; 924 diffp = e; 925 e = next; 926} 927**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 928/* Move across elements that are in the unblamable portion */ 929if(diffp) 930*srcq = &diffp->next; 931} 932 933struct blame_chunk_cb_data { 934struct origin *parent; 935long offset; 936struct blame_entry **dstq; 937struct blame_entry **srcq; 938}; 939 940/* diff chunks are from parent to target */ 941static intblame_chunk_cb(long start_a,long count_a, 942long start_b,long count_b,void*data) 943{ 944struct blame_chunk_cb_data *d = data; 945if(start_a - start_b != d->offset) 946die("internal error in blame::blame_chunk_cb"); 947blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 948 start_b + count_b, d->parent); 949 d->offset = start_a + count_a - (start_b + count_b); 950return0; 951} 952 953/* 954 * We are looking at the origin 'target' and aiming to pass blame 955 * for the lines it is suspected to its parent. Run diff to find 956 * which lines came from parent and pass blame for them. 957 */ 958static voidpass_blame_to_parent(struct scoreboard *sb, 959struct origin *target, 960struct origin *parent) 961{ 962 mmfile_t file_p, file_o; 963struct blame_chunk_cb_data d; 964struct blame_entry *newdest = NULL; 965 966if(!target->suspects) 967return;/* nothing remains for this target */ 968 969 d.parent = parent; 970 d.offset =0; 971 d.dstq = &newdest; d.srcq = &target->suspects; 972 973fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 974fill_origin_blob(&sb->revs->diffopt, target, &file_o); 975 num_get_patch++; 976 977diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d); 978/* The rest are the same as the parent */ 979blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 980*d.dstq = NULL; 981queue_blames(sb, parent, newdest); 982 983return; 984} 985 986/* 987 * The lines in blame_entry after splitting blames many times can become 988 * very small and trivial, and at some point it becomes pointless to 989 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 990 * ordinary C program, and it is not worth to say it was copied from 991 * totally unrelated file in the parent. 992 * 993 * Compute how trivial the lines in the blame_entry are. 994 */ 995static unsignedent_score(struct scoreboard *sb,struct blame_entry *e) 996{ 997unsigned score; 998const char*cp, *ep; 9991000if(e->score)1001return e->score;10021003 score =1;1004 cp =nth_line(sb, e->lno);1005 ep =nth_line(sb, e->lno + e->num_lines);1006while(cp < ep) {1007unsigned ch = *((unsigned char*)cp);1008if(isalnum(ch))1009 score++;1010 cp++;1011}1012 e->score = score;1013return score;1014}10151016/*1017 * best_so_far[] and this[] are both a split of an existing blame_entry1018 * that passes blame to the parent. Maintain best_so_far the best split1019 * so far, by comparing this and best_so_far and copying this into1020 * bst_so_far as needed.1021 */1022static voidcopy_split_if_better(struct scoreboard *sb,1023struct blame_entry *best_so_far,1024struct blame_entry *this)1025{1026int i;10271028if(!this[1].suspect)1029return;1030if(best_so_far[1].suspect) {1031if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1032return;1033}10341035for(i =0; i <3; i++)1036origin_incref(this[i].suspect);1037decref_split(best_so_far);1038memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1039}10401041/*1042 * We are looking at a part of the final image represented by1043 * ent (tlno and same are offset by ent->s_lno).1044 * tlno is where we are looking at in the final image.1045 * up to (but not including) same match preimage.1046 * plno is where we are looking at in the preimage.1047 *1048 * <-------------- final image ---------------------->1049 * <------ent------>1050 * ^tlno ^same1051 * <---------preimage----->1052 * ^plno1053 *1054 * All line numbers are 0-based.1055 */1056static voidhandle_split(struct scoreboard *sb,1057struct blame_entry *ent,1058int tlno,int plno,int same,1059struct origin *parent,1060struct blame_entry *split)1061{1062if(ent->num_lines <= tlno)1063return;1064if(tlno < same) {1065struct blame_entry this[3];1066 tlno += ent->s_lno;1067 same += ent->s_lno;1068split_overlap(this, ent, tlno, plno, same, parent);1069copy_split_if_better(sb, split,this);1070decref_split(this);1071}1072}10731074struct handle_split_cb_data {1075struct scoreboard *sb;1076struct blame_entry *ent;1077struct origin *parent;1078struct blame_entry *split;1079long plno;1080long tlno;1081};10821083static inthandle_split_cb(long start_a,long count_a,1084long start_b,long count_b,void*data)1085{1086struct handle_split_cb_data *d = data;1087handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1088 d->split);1089 d->plno = start_a + count_a;1090 d->tlno = start_b + count_b;1091return0;1092}10931094/*1095 * Find the lines from parent that are the same as ent so that1096 * we can pass blames to it. file_p has the blob contents for1097 * the parent.1098 */1099static voidfind_copy_in_blob(struct scoreboard *sb,1100struct blame_entry *ent,1101struct origin *parent,1102struct blame_entry *split,1103 mmfile_t *file_p)1104{1105const char*cp;1106 mmfile_t file_o;1107struct handle_split_cb_data d;11081109memset(&d,0,sizeof(d));1110 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1111/*1112 * Prepare mmfile that contains only the lines in ent.1113 */1114 cp =nth_line(sb, ent->lno);1115 file_o.ptr = (char*) cp;1116 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11171118/*1119 * file_o is a part of final image we are annotating.1120 * file_p partially may match that image.1121 */1122memset(split,0,sizeof(struct blame_entry [3]));1123diff_hunks(file_p, &file_o,1, handle_split_cb, &d);1124/* remainder, if any, all match the preimage */1125handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1126}11271128/* Move all blame entries from list *source that have a score smaller1129 * than score_min to the front of list *small.1130 * Returns a pointer to the link pointing to the old head of the small list.1131 */11321133static struct blame_entry **filter_small(struct scoreboard *sb,1134struct blame_entry **small,1135struct blame_entry **source,1136unsigned score_min)1137{1138struct blame_entry *p = *source;1139struct blame_entry *oldsmall = *small;1140while(p) {1141if(ent_score(sb, p) <= score_min) {1142*small = p;1143 small = &p->next;1144 p = *small;1145}else{1146*source = p;1147 source = &p->next;1148 p = *source;1149}1150}1151*small = oldsmall;1152*source = NULL;1153return small;1154}11551156/*1157 * See if lines currently target is suspected for can be attributed to1158 * parent.1159 */1160static voidfind_move_in_parent(struct scoreboard *sb,1161struct blame_entry ***blamed,1162struct blame_entry **toosmall,1163struct origin *target,1164struct origin *parent)1165{1166struct blame_entry *e, split[3];1167struct blame_entry *unblamed = target->suspects;1168struct blame_entry *leftover = NULL;1169 mmfile_t file_p;11701171if(!unblamed)1172return;/* nothing remains for this target */11731174fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1175if(!file_p.ptr)1176return;11771178/* At each iteration, unblamed has a NULL-terminated list of1179 * entries that have not yet been tested for blame. leftover1180 * contains the reversed list of entries that have been tested1181 * without being assignable to the parent.1182 */1183do{1184struct blame_entry **unblamedtail = &unblamed;1185struct blame_entry *next;1186for(e = unblamed; e; e = next) {1187 next = e->next;1188find_copy_in_blob(sb, e, parent, split, &file_p);1189if(split[1].suspect &&1190 blame_move_score <ent_score(sb, &split[1])) {1191split_blame(blamed, &unblamedtail, split, e);1192}else{1193 e->next = leftover;1194 leftover = e;1195}1196decref_split(split);1197}1198*unblamedtail = NULL;1199 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1200}while(unblamed);1201 target->suspects =reverse_blame(leftover, NULL);1202}12031204struct blame_list {1205struct blame_entry *ent;1206struct blame_entry split[3];1207};12081209/*1210 * Count the number of entries the target is suspected for,1211 * and prepare a list of entry and the best split.1212 */1213static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1214int*num_ents_p)1215{1216struct blame_entry *e;1217int num_ents, i;1218struct blame_list *blame_list = NULL;12191220for(e = unblamed, num_ents =0; e; e = e->next)1221 num_ents++;1222if(num_ents) {1223 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1224for(e = unblamed, i =0; e; e = e->next)1225 blame_list[i++].ent = e;1226}1227*num_ents_p = num_ents;1228return blame_list;1229}12301231/*1232 * For lines target is suspected for, see if we can find code movement1233 * across file boundary from the parent commit. porigin is the path1234 * in the parent we already tried.1235 */1236static voidfind_copy_in_parent(struct scoreboard *sb,1237struct blame_entry ***blamed,1238struct blame_entry **toosmall,1239struct origin *target,1240struct commit *parent,1241struct origin *porigin,1242int opt)1243{1244struct diff_options diff_opts;1245int i, j;1246struct blame_list *blame_list;1247int num_ents;1248struct blame_entry *unblamed = target->suspects;1249struct blame_entry *leftover = NULL;12501251if(!unblamed)1252return;/* nothing remains for this target */12531254diff_setup(&diff_opts);1255DIFF_OPT_SET(&diff_opts, RECURSIVE);1256 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12571258diff_setup_done(&diff_opts);12591260/* Try "find copies harder" on new path if requested;1261 * we do not want to use diffcore_rename() actually to1262 * match things up; find_copies_harder is set only to1263 * force diff_tree_sha1() to feed all filepairs to diff_queue,1264 * and this code needs to be after diff_setup_done(), which1265 * usually makes find-copies-harder imply copy detection.1266 */1267if((opt & PICKAXE_BLAME_COPY_HARDEST)1268|| ((opt & PICKAXE_BLAME_COPY_HARDER)1269&& (!porigin ||strcmp(target->path, porigin->path))))1270DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12711272if(is_null_sha1(target->commit->object.sha1))1273do_diff_cache(parent->tree->object.sha1, &diff_opts);1274else1275diff_tree_sha1(parent->tree->object.sha1,1276 target->commit->tree->object.sha1,1277"", &diff_opts);12781279if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1280diffcore_std(&diff_opts);12811282do{1283struct blame_entry **unblamedtail = &unblamed;1284 blame_list =setup_blame_list(unblamed, &num_ents);12851286for(i =0; i < diff_queued_diff.nr; i++) {1287struct diff_filepair *p = diff_queued_diff.queue[i];1288struct origin *norigin;1289 mmfile_t file_p;1290struct blame_entry this[3];12911292if(!DIFF_FILE_VALID(p->one))1293continue;/* does not exist in parent */1294if(S_ISGITLINK(p->one->mode))1295continue;/* ignore git links */1296if(porigin && !strcmp(p->one->path, porigin->path))1297/* find_move already dealt with this path */1298continue;12991300 norigin =get_origin(sb, parent, p->one->path);1301hashcpy(norigin->blob_sha1, p->one->sha1);1302 norigin->mode = p->one->mode;1303fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1304if(!file_p.ptr)1305continue;13061307for(j =0; j < num_ents; j++) {1308find_copy_in_blob(sb, blame_list[j].ent,1309 norigin,this, &file_p);1310copy_split_if_better(sb, blame_list[j].split,1311this);1312decref_split(this);1313}1314origin_decref(norigin);1315}13161317for(j =0; j < num_ents; j++) {1318struct blame_entry *split = blame_list[j].split;1319if(split[1].suspect &&1320 blame_copy_score <ent_score(sb, &split[1])) {1321split_blame(blamed, &unblamedtail, split,1322 blame_list[j].ent);1323}else{1324 blame_list[j].ent->next = leftover;1325 leftover = blame_list[j].ent;1326}1327decref_split(split);1328}1329free(blame_list);1330*unblamedtail = NULL;1331 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1332}while(unblamed);1333 target->suspects =reverse_blame(leftover, NULL);1334diff_flush(&diff_opts);1335free_pathspec(&diff_opts.pathspec);1336}13371338/*1339 * The blobs of origin and porigin exactly match, so everything1340 * origin is suspected for can be blamed on the parent.1341 */1342static voidpass_whole_blame(struct scoreboard *sb,1343struct origin *origin,struct origin *porigin)1344{1345struct blame_entry *e, *suspects;13461347if(!porigin->file.ptr && origin->file.ptr) {1348/* Steal its file */1349 porigin->file = origin->file;1350 origin->file.ptr = NULL;1351}1352 suspects = origin->suspects;1353 origin->suspects = NULL;1354for(e = suspects; e; e = e->next) {1355origin_incref(porigin);1356origin_decref(e->suspect);1357 e->suspect = porigin;1358}1359queue_blames(sb, porigin, suspects);1360}13611362/*1363 * We pass blame from the current commit to its parents. We keep saying1364 * "parent" (and "porigin"), but what we mean is to find scapegoat to1365 * exonerate ourselves.1366 */1367static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1368{1369if(!reverse)1370return commit->parents;1371returnlookup_decoration(&revs->children, &commit->object);1372}13731374static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1375{1376struct commit_list *l =first_scapegoat(revs, commit);1377returncommit_list_count(l);1378}13791380/* Distribute collected unsorted blames to the respected sorted lists1381 * in the various origins.1382 */1383static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1384{1385 blamed =blame_sort(blamed, compare_blame_suspect);1386while(blamed)1387{1388struct origin *porigin = blamed->suspect;1389struct blame_entry *suspects = NULL;1390do{1391struct blame_entry *next = blamed->next;1392 blamed->next = suspects;1393 suspects = blamed;1394 blamed = next;1395}while(blamed && blamed->suspect == porigin);1396 suspects =reverse_blame(suspects, NULL);1397queue_blames(sb, porigin, suspects);1398}1399}14001401#define MAXSG 1614021403static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1404{1405struct rev_info *revs = sb->revs;1406int i, pass, num_sg;1407struct commit *commit = origin->commit;1408struct commit_list *sg;1409struct origin *sg_buf[MAXSG];1410struct origin *porigin, **sg_origin = sg_buf;1411struct blame_entry *toosmall = NULL;1412struct blame_entry *blames, **blametail = &blames;14131414 num_sg =num_scapegoats(revs, commit);1415if(!num_sg)1416goto finish;1417else if(num_sg <ARRAY_SIZE(sg_buf))1418memset(sg_buf,0,sizeof(sg_buf));1419else1420 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14211422/*1423 * The first pass looks for unrenamed path to optimize for1424 * common cases, then we look for renames in the second pass.1425 */1426for(pass =0; pass <2- no_whole_file_rename; pass++) {1427struct origin *(*find)(struct scoreboard *,1428struct commit *,struct origin *);1429 find = pass ? find_rename : find_origin;14301431for(i =0, sg =first_scapegoat(revs, commit);1432 i < num_sg && sg;1433 sg = sg->next, i++) {1434struct commit *p = sg->item;1435int j, same;14361437if(sg_origin[i])1438continue;1439if(parse_commit(p))1440continue;1441 porigin =find(sb, p, origin);1442if(!porigin)1443continue;1444if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1445pass_whole_blame(sb, origin, porigin);1446origin_decref(porigin);1447goto finish;1448}1449for(j = same =0; j < i; j++)1450if(sg_origin[j] &&1451!hashcmp(sg_origin[j]->blob_sha1,1452 porigin->blob_sha1)) {1453 same =1;1454break;1455}1456if(!same)1457 sg_origin[i] = porigin;1458else1459origin_decref(porigin);1460}1461}14621463 num_commits++;1464for(i =0, sg =first_scapegoat(revs, commit);1465 i < num_sg && sg;1466 sg = sg->next, i++) {1467struct origin *porigin = sg_origin[i];1468if(!porigin)1469continue;1470if(!origin->previous) {1471origin_incref(porigin);1472 origin->previous = porigin;1473}1474pass_blame_to_parent(sb, origin, porigin);1475if(!origin->suspects)1476goto finish;1477}14781479/*1480 * Optionally find moves in parents' files.1481 */1482if(opt & PICKAXE_BLAME_MOVE) {1483filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1484if(origin->suspects) {1485for(i =0, sg =first_scapegoat(revs, commit);1486 i < num_sg && sg;1487 sg = sg->next, i++) {1488struct origin *porigin = sg_origin[i];1489if(!porigin)1490continue;1491find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1492if(!origin->suspects)1493break;1494}1495}1496}14971498/*1499 * Optionally find copies from parents' files.1500 */1501if(opt & PICKAXE_BLAME_COPY) {1502if(blame_copy_score > blame_move_score)1503filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1504else if(blame_copy_score < blame_move_score) {1505 origin->suspects =blame_merge(origin->suspects, toosmall);1506 toosmall = NULL;1507filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1508}1509if(!origin->suspects)1510goto finish;15111512for(i =0, sg =first_scapegoat(revs, commit);1513 i < num_sg && sg;1514 sg = sg->next, i++) {1515struct origin *porigin = sg_origin[i];1516find_copy_in_parent(sb, &blametail, &toosmall,1517 origin, sg->item, porigin, opt);1518if(!origin->suspects)1519goto finish;1520}1521}15221523finish:1524*blametail = NULL;1525distribute_blame(sb, blames);1526/*1527 * prepend toosmall to origin->suspects1528 *1529 * There is no point in sorting: this ends up on a big1530 * unsorted list in the caller anyway.1531 */1532if(toosmall) {1533struct blame_entry **tail = &toosmall;1534while(*tail)1535 tail = &(*tail)->next;1536*tail = origin->suspects;1537 origin->suspects = toosmall;1538}1539for(i =0; i < num_sg; i++) {1540if(sg_origin[i]) {1541drop_origin_blob(sg_origin[i]);1542origin_decref(sg_origin[i]);1543}1544}1545drop_origin_blob(origin);1546if(sg_buf != sg_origin)1547free(sg_origin);1548}15491550/*1551 * Information on commits, used for output.1552 */1553struct commit_info {1554struct strbuf author;1555struct strbuf author_mail;1556unsigned long author_time;1557struct strbuf author_tz;15581559/* filled only when asked for details */1560struct strbuf committer;1561struct strbuf committer_mail;1562unsigned long committer_time;1563struct strbuf committer_tz;15641565struct strbuf summary;1566};15671568/*1569 * Parse author/committer line in the commit object buffer1570 */1571static voidget_ac_line(const char*inbuf,const char*what,1572struct strbuf *name,struct strbuf *mail,1573unsigned long*time,struct strbuf *tz)1574{1575struct ident_split ident;1576size_t len, maillen, namelen;1577char*tmp, *endp;1578const char*namebuf, *mailbuf;15791580 tmp =strstr(inbuf, what);1581if(!tmp)1582goto error_out;1583 tmp +=strlen(what);1584 endp =strchr(tmp,'\n');1585if(!endp)1586 len =strlen(tmp);1587else1588 len = endp - tmp;15891590if(split_ident_line(&ident, tmp, len)) {1591 error_out:1592/* Ugh */1593 tmp ="(unknown)";1594strbuf_addstr(name, tmp);1595strbuf_addstr(mail, tmp);1596strbuf_addstr(tz, tmp);1597*time =0;1598return;1599}16001601 namelen = ident.name_end - ident.name_begin;1602 namebuf = ident.name_begin;16031604 maillen = ident.mail_end - ident.mail_begin;1605 mailbuf = ident.mail_begin;16061607if(ident.date_begin && ident.date_end)1608*time =strtoul(ident.date_begin, NULL,10);1609else1610*time =0;16111612if(ident.tz_begin && ident.tz_end)1613strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1614else1615strbuf_addstr(tz,"(unknown)");16161617/*1618 * Now, convert both name and e-mail using mailmap1619 */1620map_user(&mailmap, &mailbuf, &maillen,1621&namebuf, &namelen);16221623strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1624strbuf_add(name, namebuf, namelen);1625}16261627static voidcommit_info_init(struct commit_info *ci)1628{16291630strbuf_init(&ci->author,0);1631strbuf_init(&ci->author_mail,0);1632strbuf_init(&ci->author_tz,0);1633strbuf_init(&ci->committer,0);1634strbuf_init(&ci->committer_mail,0);1635strbuf_init(&ci->committer_tz,0);1636strbuf_init(&ci->summary,0);1637}16381639static voidcommit_info_destroy(struct commit_info *ci)1640{16411642strbuf_release(&ci->author);1643strbuf_release(&ci->author_mail);1644strbuf_release(&ci->author_tz);1645strbuf_release(&ci->committer);1646strbuf_release(&ci->committer_mail);1647strbuf_release(&ci->committer_tz);1648strbuf_release(&ci->summary);1649}16501651static voidget_commit_info(struct commit *commit,1652struct commit_info *ret,1653int detailed)1654{1655int len;1656const char*subject, *encoding;1657const char*message;16581659commit_info_init(ret);16601661 encoding =get_log_output_encoding();1662 message =logmsg_reencode(commit, NULL, encoding);1663get_ac_line(message,"\nauthor ",1664&ret->author, &ret->author_mail,1665&ret->author_time, &ret->author_tz);16661667if(!detailed) {1668unuse_commit_buffer(commit, message);1669return;1670}16711672get_ac_line(message,"\ncommitter ",1673&ret->committer, &ret->committer_mail,1674&ret->committer_time, &ret->committer_tz);16751676 len =find_commit_subject(message, &subject);1677if(len)1678strbuf_add(&ret->summary, subject, len);1679else1680strbuf_addf(&ret->summary,"(%s)",sha1_to_hex(commit->object.sha1));16811682unuse_commit_buffer(commit, message);1683}16841685/*1686 * To allow LF and other nonportable characters in pathnames,1687 * they are c-style quoted as needed.1688 */1689static voidwrite_filename_info(const char*path)1690{1691printf("filename ");1692write_name_quoted(path, stdout,'\n');1693}16941695/*1696 * Porcelain/Incremental format wants to show a lot of details per1697 * commit. Instead of repeating this every line, emit it only once,1698 * the first time each commit appears in the output (unless the1699 * user has specifically asked for us to repeat).1700 */1701static intemit_one_suspect_detail(struct origin *suspect,int repeat)1702{1703struct commit_info ci;17041705if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1706return0;17071708 suspect->commit->object.flags |= METAINFO_SHOWN;1709get_commit_info(suspect->commit, &ci,1);1710printf("author%s\n", ci.author.buf);1711printf("author-mail%s\n", ci.author_mail.buf);1712printf("author-time%lu\n", ci.author_time);1713printf("author-tz%s\n", ci.author_tz.buf);1714printf("committer%s\n", ci.committer.buf);1715printf("committer-mail%s\n", ci.committer_mail.buf);1716printf("committer-time%lu\n", ci.committer_time);1717printf("committer-tz%s\n", ci.committer_tz.buf);1718printf("summary%s\n", ci.summary.buf);1719if(suspect->commit->object.flags & UNINTERESTING)1720printf("boundary\n");1721if(suspect->previous) {1722struct origin *prev = suspect->previous;1723printf("previous%s",sha1_to_hex(prev->commit->object.sha1));1724write_name_quoted(prev->path, stdout,'\n');1725}17261727commit_info_destroy(&ci);17281729return1;1730}17311732/*1733 * The blame_entry is found to be guilty for the range.1734 * Show it in incremental output.1735 */1736static voidfound_guilty_entry(struct blame_entry *ent)1737{1738if(incremental) {1739struct origin *suspect = ent->suspect;17401741printf("%s %d %d %d\n",1742sha1_to_hex(suspect->commit->object.sha1),1743 ent->s_lno +1, ent->lno +1, ent->num_lines);1744emit_one_suspect_detail(suspect,0);1745write_filename_info(suspect->path);1746maybe_flush_or_die(stdout,"stdout");1747}1748}17491750/*1751 * The main loop -- while we have blobs with lines whose true origin1752 * is still unknown, pick one blob, and allow its lines to pass blames1753 * to its parents. */1754static voidassign_blame(struct scoreboard *sb,int opt)1755{1756struct rev_info *revs = sb->revs;1757struct commit *commit =prio_queue_get(&sb->commits);17581759while(commit) {1760struct blame_entry *ent;1761struct origin *suspect = commit->util;17621763/* find one suspect to break down */1764while(suspect && !suspect->suspects)1765 suspect = suspect->next;17661767if(!suspect) {1768 commit =prio_queue_get(&sb->commits);1769continue;1770}17711772assert(commit == suspect->commit);17731774/*1775 * We will use this suspect later in the loop,1776 * so hold onto it in the meantime.1777 */1778origin_incref(suspect);1779parse_commit(commit);1780if(reverse ||1781(!(commit->object.flags & UNINTERESTING) &&1782!(revs->max_age != -1&& commit->date < revs->max_age)))1783pass_blame(sb, suspect, opt);1784else{1785 commit->object.flags |= UNINTERESTING;1786if(commit->object.parsed)1787mark_parents_uninteresting(commit);1788}1789/* treat root commit as boundary */1790if(!commit->parents && !show_root)1791 commit->object.flags |= UNINTERESTING;17921793/* Take responsibility for the remaining entries */1794 ent = suspect->suspects;1795if(ent) {1796 suspect->guilty =1;1797for(;;) {1798struct blame_entry *next = ent->next;1799found_guilty_entry(ent);1800if(next) {1801 ent = next;1802continue;1803}1804 ent->next = sb->ent;1805 sb->ent = suspect->suspects;1806 suspect->suspects = NULL;1807break;1808}1809}1810origin_decref(suspect);18111812if(DEBUG)/* sanity */1813sanity_check_refcnt(sb);1814}1815}18161817static const char*format_time(unsigned long time,const char*tz_str,1818int show_raw_time)1819{1820static struct strbuf time_buf = STRBUF_INIT;18211822strbuf_reset(&time_buf);1823if(show_raw_time) {1824strbuf_addf(&time_buf,"%lu%s", time, tz_str);1825}1826else{1827const char*time_str;1828size_t time_width;1829int tz;1830 tz =atoi(tz_str);1831 time_str =show_date(time, tz, &blame_date_mode);1832strbuf_addstr(&time_buf, time_str);1833/*1834 * Add space paddings to time_buf to display a fixed width1835 * string, and use time_width for display width calibration.1836 */1837for(time_width =utf8_strwidth(time_str);1838 time_width < blame_date_width;1839 time_width++)1840strbuf_addch(&time_buf,' ');1841}1842return time_buf.buf;1843}18441845#define OUTPUT_ANNOTATE_COMPAT 0011846#define OUTPUT_LONG_OBJECT_NAME 0021847#define OUTPUT_RAW_TIMESTAMP 0041848#define OUTPUT_PORCELAIN 0101849#define OUTPUT_SHOW_NAME 0201850#define OUTPUT_SHOW_NUMBER 0401851#define OUTPUT_SHOW_SCORE 01001852#define OUTPUT_NO_AUTHOR 02001853#define OUTPUT_SHOW_EMAIL 04001854#define OUTPUT_LINE_PORCELAIN 0100018551856static voidemit_porcelain_details(struct origin *suspect,int repeat)1857{1858if(emit_one_suspect_detail(suspect, repeat) ||1859(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1860write_filename_info(suspect->path);1861}18621863static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1864int opt)1865{1866int repeat = opt & OUTPUT_LINE_PORCELAIN;1867int cnt;1868const char*cp;1869struct origin *suspect = ent->suspect;1870char hex[41];18711872strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));1873printf("%s %d %d %d\n",1874 hex,1875 ent->s_lno +1,1876 ent->lno +1,1877 ent->num_lines);1878emit_porcelain_details(suspect, repeat);18791880 cp =nth_line(sb, ent->lno);1881for(cnt =0; cnt < ent->num_lines; cnt++) {1882char ch;1883if(cnt) {1884printf("%s %d %d\n", hex,1885 ent->s_lno +1+ cnt,1886 ent->lno +1+ cnt);1887if(repeat)1888emit_porcelain_details(suspect,1);1889}1890putchar('\t');1891do{1892 ch = *cp++;1893putchar(ch);1894}while(ch !='\n'&&1895 cp < sb->final_buf + sb->final_buf_size);1896}18971898if(sb->final_buf_size && cp[-1] !='\n')1899putchar('\n');1900}19011902static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1903{1904int cnt;1905const char*cp;1906struct origin *suspect = ent->suspect;1907struct commit_info ci;1908char hex[41];1909int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19101911get_commit_info(suspect->commit, &ci,1);1912strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));19131914 cp =nth_line(sb, ent->lno);1915for(cnt =0; cnt < ent->num_lines; cnt++) {1916char ch;1917int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19181919if(suspect->commit->object.flags & UNINTERESTING) {1920if(blank_boundary)1921memset(hex,' ', length);1922else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1923 length--;1924putchar('^');1925}1926}19271928printf("%.*s", length, hex);1929if(opt & OUTPUT_ANNOTATE_COMPAT) {1930const char*name;1931if(opt & OUTPUT_SHOW_EMAIL)1932 name = ci.author_mail.buf;1933else1934 name = ci.author.buf;1935printf("\t(%10s\t%10s\t%d)", name,1936format_time(ci.author_time, ci.author_tz.buf,1937 show_raw_time),1938 ent->lno +1+ cnt);1939}else{1940if(opt & OUTPUT_SHOW_SCORE)1941printf(" %*d%02d",1942 max_score_digits, ent->score,1943 ent->suspect->refcnt);1944if(opt & OUTPUT_SHOW_NAME)1945printf(" %-*.*s", longest_file, longest_file,1946 suspect->path);1947if(opt & OUTPUT_SHOW_NUMBER)1948printf(" %*d", max_orig_digits,1949 ent->s_lno +1+ cnt);19501951if(!(opt & OUTPUT_NO_AUTHOR)) {1952const char*name;1953int pad;1954if(opt & OUTPUT_SHOW_EMAIL)1955 name = ci.author_mail.buf;1956else1957 name = ci.author.buf;1958 pad = longest_author -utf8_strwidth(name);1959printf(" (%s%*s%10s",1960 name, pad,"",1961format_time(ci.author_time,1962 ci.author_tz.buf,1963 show_raw_time));1964}1965printf(" %*d) ",1966 max_digits, ent->lno +1+ cnt);1967}1968do{1969 ch = *cp++;1970putchar(ch);1971}while(ch !='\n'&&1972 cp < sb->final_buf + sb->final_buf_size);1973}19741975if(sb->final_buf_size && cp[-1] !='\n')1976putchar('\n');19771978commit_info_destroy(&ci);1979}19801981static voidoutput(struct scoreboard *sb,int option)1982{1983struct blame_entry *ent;19841985if(option & OUTPUT_PORCELAIN) {1986for(ent = sb->ent; ent; ent = ent->next) {1987int count =0;1988struct origin *suspect;1989struct commit *commit = ent->suspect->commit;1990if(commit->object.flags & MORE_THAN_ONE_PATH)1991continue;1992for(suspect = commit->util; suspect; suspect = suspect->next) {1993if(suspect->guilty && count++) {1994 commit->object.flags |= MORE_THAN_ONE_PATH;1995break;1996}1997}1998}1999}20002001for(ent = sb->ent; ent; ent = ent->next) {2002if(option & OUTPUT_PORCELAIN)2003emit_porcelain(sb, ent, option);2004else{2005emit_other(sb, ent, option);2006}2007}2008}20092010static const char*get_next_line(const char*start,const char*end)2011{2012const char*nl =memchr(start,'\n', end - start);2013return nl ? nl +1: end;2014}20152016/*2017 * To allow quick access to the contents of nth line in the2018 * final image, prepare an index in the scoreboard.2019 */2020static intprepare_lines(struct scoreboard *sb)2021{2022const char*buf = sb->final_buf;2023unsigned long len = sb->final_buf_size;2024const char*end = buf + len;2025const char*p;2026int*lineno;2027int num =0;20282029for(p = buf; p < end; p =get_next_line(p, end))2030 num++;20312032 sb->lineno = lineno =xmalloc(sizeof(*sb->lineno) * (num +1));20332034for(p = buf; p < end; p =get_next_line(p, end))2035*lineno++ = p - buf;20362037*lineno = len;20382039 sb->num_lines = num;2040return sb->num_lines;2041}20422043/*2044 * Add phony grafts for use with -S; this is primarily to2045 * support git's cvsserver that wants to give a linear history2046 * to its clients.2047 */2048static intread_ancestry(const char*graft_file)2049{2050FILE*fp =fopen(graft_file,"r");2051struct strbuf buf = STRBUF_INIT;2052if(!fp)2053return-1;2054while(!strbuf_getwholeline(&buf, fp,'\n')) {2055/* The format is just "Commit Parent1 Parent2 ...\n" */2056struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2057if(graft)2058register_commit_graft(graft,0);2059}2060fclose(fp);2061strbuf_release(&buf);2062return0;2063}20642065static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2066{2067const char*uniq =find_unique_abbrev(suspect->commit->object.sha1,2068 auto_abbrev);2069int len =strlen(uniq);2070if(auto_abbrev < len)2071return len;2072return auto_abbrev;2073}20742075/*2076 * How many columns do we need to show line numbers, authors,2077 * and filenames?2078 */2079static voidfind_alignment(struct scoreboard *sb,int*option)2080{2081int longest_src_lines =0;2082int longest_dst_lines =0;2083unsigned largest_score =0;2084struct blame_entry *e;2085int compute_auto_abbrev = (abbrev <0);2086int auto_abbrev = default_abbrev;20872088for(e = sb->ent; e; e = e->next) {2089struct origin *suspect = e->suspect;2090int num;20912092if(compute_auto_abbrev)2093 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2094if(strcmp(suspect->path, sb->path))2095*option |= OUTPUT_SHOW_NAME;2096 num =strlen(suspect->path);2097if(longest_file < num)2098 longest_file = num;2099if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2100struct commit_info ci;2101 suspect->commit->object.flags |= METAINFO_SHOWN;2102get_commit_info(suspect->commit, &ci,1);2103if(*option & OUTPUT_SHOW_EMAIL)2104 num =utf8_strwidth(ci.author_mail.buf);2105else2106 num =utf8_strwidth(ci.author.buf);2107if(longest_author < num)2108 longest_author = num;2109commit_info_destroy(&ci);2110}2111 num = e->s_lno + e->num_lines;2112if(longest_src_lines < num)2113 longest_src_lines = num;2114 num = e->lno + e->num_lines;2115if(longest_dst_lines < num)2116 longest_dst_lines = num;2117if(largest_score <ent_score(sb, e))2118 largest_score =ent_score(sb, e);2119}2120 max_orig_digits =decimal_width(longest_src_lines);2121 max_digits =decimal_width(longest_dst_lines);2122 max_score_digits =decimal_width(largest_score);21232124if(compute_auto_abbrev)2125/* one more abbrev length is needed for the boundary commit */2126 abbrev = auto_abbrev +1;2127}21282129/*2130 * For debugging -- origin is refcounted, and this asserts that2131 * we do not underflow.2132 */2133static voidsanity_check_refcnt(struct scoreboard *sb)2134{2135int baa =0;2136struct blame_entry *ent;21372138for(ent = sb->ent; ent; ent = ent->next) {2139/* Nobody should have zero or negative refcnt */2140if(ent->suspect->refcnt <=0) {2141fprintf(stderr,"%sin%shas negative refcnt%d\n",2142 ent->suspect->path,2143sha1_to_hex(ent->suspect->commit->object.sha1),2144 ent->suspect->refcnt);2145 baa =1;2146}2147}2148if(baa) {2149int opt =0160;2150find_alignment(sb, &opt);2151output(sb, opt);2152die("Baa%d!", baa);2153}2154}21552156static unsignedparse_score(const char*arg)2157{2158char*end;2159unsigned long score =strtoul(arg, &end,10);2160if(*end)2161return0;2162return score;2163}21642165static const char*add_prefix(const char*prefix,const char*path)2166{2167returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2168}21692170static intgit_blame_config(const char*var,const char*value,void*cb)2171{2172if(!strcmp(var,"blame.showroot")) {2173 show_root =git_config_bool(var, value);2174return0;2175}2176if(!strcmp(var,"blame.blankboundary")) {2177 blank_boundary =git_config_bool(var, value);2178return0;2179}2180if(!strcmp(var,"blame.showemail")) {2181int*output_option = cb;2182if(git_config_bool(var, value))2183*output_option |= OUTPUT_SHOW_EMAIL;2184else2185*output_option &= ~OUTPUT_SHOW_EMAIL;2186return0;2187}2188if(!strcmp(var,"blame.date")) {2189if(!value)2190returnconfig_error_nonbool(var);2191parse_date_format(value, &blame_date_mode);2192return0;2193}21942195if(userdiff_config(var, value) <0)2196return-1;21972198returngit_default_config(var, value, cb);2199}22002201static voidverify_working_tree_path(struct commit *work_tree,const char*path)2202{2203struct commit_list *parents;22042205for(parents = work_tree->parents; parents; parents = parents->next) {2206const unsigned char*commit_sha1 = parents->item->object.sha1;2207unsigned char blob_sha1[20];2208unsigned mode;22092210if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2211sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2212return;2213}2214die("no such path '%s' in HEAD", path);2215}22162217static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2218{2219struct commit *parent;22202221 parent =lookup_commit_reference(sha1);2222if(!parent)2223die("no such commit%s",sha1_to_hex(sha1));2224return&commit_list_insert(parent, tail)->next;2225}22262227static voidappend_merge_parents(struct commit_list **tail)2228{2229int merge_head;2230struct strbuf line = STRBUF_INIT;22312232 merge_head =open(git_path_merge_head(), O_RDONLY);2233if(merge_head <0) {2234if(errno == ENOENT)2235return;2236die("cannot open '%s' for reading",git_path_merge_head());2237}22382239while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2240unsigned char sha1[20];2241if(line.len <40||get_sha1_hex(line.buf, sha1))2242die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2243 tail =append_parent(tail, sha1);2244}2245close(merge_head);2246strbuf_release(&line);2247}22482249/*2250 * This isn't as simple as passing sb->buf and sb->len, because we2251 * want to transfer ownership of the buffer to the commit (so we2252 * must use detach).2253 */2254static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2255{2256size_t len;2257void*buf =strbuf_detach(sb, &len);2258set_commit_buffer(c, buf, len);2259}22602261/*2262 * Prepare a dummy commit that represents the work tree (or staged) item.2263 * Note that annotating work tree item never works in the reverse.2264 */2265static struct commit *fake_working_tree_commit(struct diff_options *opt,2266const char*path,2267const char*contents_from)2268{2269struct commit *commit;2270struct origin *origin;2271struct commit_list **parent_tail, *parent;2272unsigned char head_sha1[20];2273struct strbuf buf = STRBUF_INIT;2274const char*ident;2275time_t now;2276int size, len;2277struct cache_entry *ce;2278unsigned mode;2279struct strbuf msg = STRBUF_INIT;22802281time(&now);2282 commit =alloc_commit_node();2283 commit->object.parsed =1;2284 commit->date = now;2285 parent_tail = &commit->parents;22862287if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2288die("no such ref: HEAD");22892290 parent_tail =append_parent(parent_tail, head_sha1);2291append_merge_parents(parent_tail);2292verify_working_tree_path(commit, path);22932294 origin =make_origin(commit, path);22952296 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2297strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2298for(parent = commit->parents; parent; parent = parent->next)2299strbuf_addf(&msg,"parent%s\n",2300sha1_to_hex(parent->item->object.sha1));2301strbuf_addf(&msg,2302"author%s\n"2303"committer%s\n\n"2304"Version of%sfrom%s\n",2305 ident, ident, path,2306(!contents_from ? path :2307(!strcmp(contents_from,"-") ?"standard input": contents_from)));2308set_commit_buffer_from_strbuf(commit, &msg);23092310if(!contents_from ||strcmp("-", contents_from)) {2311struct stat st;2312const char*read_from;2313char*buf_ptr;2314unsigned long buf_len;23152316if(contents_from) {2317if(stat(contents_from, &st) <0)2318die_errno("Cannot stat '%s'", contents_from);2319 read_from = contents_from;2320}2321else{2322if(lstat(path, &st) <0)2323die_errno("Cannot lstat '%s'", path);2324 read_from = path;2325}2326 mode =canon_mode(st.st_mode);23272328switch(st.st_mode & S_IFMT) {2329case S_IFREG:2330if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2331textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2332strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2333else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2334die_errno("cannot open or read '%s'", read_from);2335break;2336case S_IFLNK:2337if(strbuf_readlink(&buf, read_from, st.st_size) <0)2338die_errno("cannot readlink '%s'", read_from);2339break;2340default:2341die("unsupported file type%s", read_from);2342}2343}2344else{2345/* Reading from stdin */2346 mode =0;2347if(strbuf_read(&buf,0,0) <0)2348die_errno("failed to read from stdin");2349}2350convert_to_git(path, buf.buf, buf.len, &buf,0);2351 origin->file.ptr = buf.buf;2352 origin->file.size = buf.len;2353pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23542355/*2356 * Read the current index, replace the path entry with2357 * origin->blob_sha1 without mucking with its mode or type2358 * bits; we are not going to write this index out -- we just2359 * want to run "diff-index --cached".2360 */2361discard_cache();2362read_cache();23632364 len =strlen(path);2365if(!mode) {2366int pos =cache_name_pos(path, len);2367if(0<= pos)2368 mode = active_cache[pos]->ce_mode;2369else2370/* Let's not bother reading from HEAD tree */2371 mode = S_IFREG |0644;2372}2373 size =cache_entry_size(len);2374 ce =xcalloc(1, size);2375hashcpy(ce->sha1, origin->blob_sha1);2376memcpy(ce->name, path, len);2377 ce->ce_flags =create_ce_flags(0);2378 ce->ce_namelen = len;2379 ce->ce_mode =create_ce_mode(mode);2380add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23812382/*2383 * We are not going to write this out, so this does not matter2384 * right now, but someday we might optimize diff-index --cached2385 * with cache-tree information.2386 */2387cache_tree_invalidate_path(&the_index, path);23882389return commit;2390}23912392static char*prepare_final(struct scoreboard *sb)2393{2394int i;2395const char*final_commit_name = NULL;2396struct rev_info *revs = sb->revs;23972398/*2399 * There must be one and only one positive commit in the2400 * revs->pending array.2401 */2402for(i =0; i < revs->pending.nr; i++) {2403struct object *obj = revs->pending.objects[i].item;2404if(obj->flags & UNINTERESTING)2405continue;2406while(obj->type == OBJ_TAG)2407 obj =deref_tag(obj, NULL,0);2408if(obj->type != OBJ_COMMIT)2409die("Non commit%s?", revs->pending.objects[i].name);2410if(sb->final)2411die("More than one commit to dig from%sand%s?",2412 revs->pending.objects[i].name,2413 final_commit_name);2414 sb->final = (struct commit *) obj;2415 final_commit_name = revs->pending.objects[i].name;2416}2417returnxstrdup_or_null(final_commit_name);2418}24192420static char*prepare_initial(struct scoreboard *sb)2421{2422int i;2423const char*final_commit_name = NULL;2424struct rev_info *revs = sb->revs;24252426/*2427 * There must be one and only one negative commit, and it must be2428 * the boundary.2429 */2430for(i =0; i < revs->pending.nr; i++) {2431struct object *obj = revs->pending.objects[i].item;2432if(!(obj->flags & UNINTERESTING))2433continue;2434while(obj->type == OBJ_TAG)2435 obj =deref_tag(obj, NULL,0);2436if(obj->type != OBJ_COMMIT)2437die("Non commit%s?", revs->pending.objects[i].name);2438if(sb->final)2439die("More than one commit to dig down to%sand%s?",2440 revs->pending.objects[i].name,2441 final_commit_name);2442 sb->final = (struct commit *) obj;2443 final_commit_name = revs->pending.objects[i].name;2444}2445if(!final_commit_name)2446die("No commit to dig down to?");2447returnxstrdup(final_commit_name);2448}24492450static intblame_copy_callback(const struct option *option,const char*arg,int unset)2451{2452int*opt = option->value;24532454/*2455 * -C enables copy from removed files;2456 * -C -C enables copy from existing files, but only2457 * when blaming a new file;2458 * -C -C -C enables copy from existing files for2459 * everybody2460 */2461if(*opt & PICKAXE_BLAME_COPY_HARDER)2462*opt |= PICKAXE_BLAME_COPY_HARDEST;2463if(*opt & PICKAXE_BLAME_COPY)2464*opt |= PICKAXE_BLAME_COPY_HARDER;2465*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;24662467if(arg)2468 blame_copy_score =parse_score(arg);2469return0;2470}24712472static intblame_move_callback(const struct option *option,const char*arg,int unset)2473{2474int*opt = option->value;24752476*opt |= PICKAXE_BLAME_MOVE;24772478if(arg)2479 blame_move_score =parse_score(arg);2480return0;2481}24822483intcmd_blame(int argc,const char**argv,const char*prefix)2484{2485struct rev_info revs;2486const char*path;2487struct scoreboard sb;2488struct origin *o;2489struct blame_entry *ent = NULL;2490long dashdash_pos, lno;2491char*final_commit_name = NULL;2492enum object_type type;24932494static struct string_list range_list;2495static int output_option =0, opt =0;2496static int show_stats =0;2497static const char*revs_file = NULL;2498static const char*contents_from = NULL;2499static const struct option options[] = {2500OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2501OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2502OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2503OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2504OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2505OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2506OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2507OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2508OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2509OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2510OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2511OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2512OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2513OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2514OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2515OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2516OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2517OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2518{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2519{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2520OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2521OPT__ABBREV(&abbrev),2522OPT_END()2523};25242525struct parse_opt_ctx_t ctx;2526int cmd_is_annotate = !strcmp(argv[0],"annotate");2527struct range_set ranges;2528unsigned int range_i;2529long anchor;25302531git_config(git_blame_config, &output_option);2532init_revisions(&revs, NULL);2533 revs.date_mode = blame_date_mode;2534DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2535DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25362537 save_commit_buffer =0;2538 dashdash_pos =0;25392540parse_options_start(&ctx, argc, argv, prefix, options,2541 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2542for(;;) {2543switch(parse_options_step(&ctx, options, blame_opt_usage)) {2544case PARSE_OPT_HELP:2545exit(129);2546case PARSE_OPT_DONE:2547if(ctx.argv[0])2548 dashdash_pos = ctx.cpidx;2549goto parse_done;2550}25512552if(!strcmp(ctx.argv[0],"--reverse")) {2553 ctx.argv[0] ="--children";2554 reverse =1;2555}2556parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2557}2558parse_done:2559 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2560DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2561 argc =parse_options_end(&ctx);25622563if(0< abbrev)2564/* one more abbrev length is needed for the boundary commit */2565 abbrev++;25662567if(revs_file &&read_ancestry(revs_file))2568die_errno("reading graft file '%s' failed", revs_file);25692570if(cmd_is_annotate) {2571 output_option |= OUTPUT_ANNOTATE_COMPAT;2572 blame_date_mode.type = DATE_ISO8601;2573}else{2574 blame_date_mode = revs.date_mode;2575}25762577/* The maximum width used to show the dates */2578switch(blame_date_mode.type) {2579case DATE_RFC2822:2580 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2581break;2582case DATE_ISO8601_STRICT:2583 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2584break;2585case DATE_ISO8601:2586 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2587break;2588case DATE_RAW:2589 blame_date_width =sizeof("1161298804 -0700");2590break;2591case DATE_SHORT:2592 blame_date_width =sizeof("2006-10-19");2593break;2594case DATE_RELATIVE:2595/* TRANSLATORS: This string is used to tell us the maximum2596 display width for a relative timestamp in "git blame"2597 output. For C locale, "4 years, 11 months ago", which2598 takes 22 places, is the longest among various forms of2599 relative timestamps, but your language may need more or2600 fewer display columns. */2601 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2602break;2603case DATE_LOCAL:2604case DATE_NORMAL:2605 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2606break;2607case DATE_STRFTIME:2608 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2609break;2610}2611 blame_date_width -=1;/* strip the null */26122613if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2614 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2615 PICKAXE_BLAME_COPY_HARDER);26162617if(!blame_move_score)2618 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2619if(!blame_copy_score)2620 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26212622/*2623 * We have collected options unknown to us in argv[1..unk]2624 * which are to be passed to revision machinery if we are2625 * going to do the "bottom" processing.2626 *2627 * The remaining are:2628 *2629 * (1) if dashdash_pos != 0, it is either2630 * "blame [revisions] -- <path>" or2631 * "blame -- <path> <rev>"2632 *2633 * (2) otherwise, it is one of the two:2634 * "blame [revisions] <path>"2635 * "blame <path> <rev>"2636 *2637 * Note that we must strip out <path> from the arguments: we do not2638 * want the path pruning but we may want "bottom" processing.2639 */2640if(dashdash_pos) {2641switch(argc - dashdash_pos -1) {2642case2:/* (1b) */2643if(argc !=4)2644usage_with_options(blame_opt_usage, options);2645/* reorder for the new way: <rev> -- <path> */2646 argv[1] = argv[3];2647 argv[3] = argv[2];2648 argv[2] ="--";2649/* FALLTHROUGH */2650case1:/* (1a) */2651 path =add_prefix(prefix, argv[--argc]);2652 argv[argc] = NULL;2653break;2654default:2655usage_with_options(blame_opt_usage, options);2656}2657}else{2658if(argc <2)2659usage_with_options(blame_opt_usage, options);2660 path =add_prefix(prefix, argv[argc -1]);2661if(argc ==3&& !file_exists(path)) {/* (2b) */2662 path =add_prefix(prefix, argv[1]);2663 argv[1] = argv[2];2664}2665 argv[argc -1] ="--";26662667setup_work_tree();2668if(!file_exists(path))2669die_errno("cannot stat path '%s'", path);2670}26712672 revs.disable_stdin =1;2673setup_revisions(argc, argv, &revs, NULL);2674memset(&sb,0,sizeof(sb));26752676 sb.revs = &revs;2677if(!reverse) {2678 final_commit_name =prepare_final(&sb);2679 sb.commits.compare = compare_commits_by_commit_date;2680}2681else if(contents_from)2682die("--contents and --children do not blend well.");2683else{2684 final_commit_name =prepare_initial(&sb);2685 sb.commits.compare = compare_commits_by_reverse_commit_date;2686}26872688if(!sb.final) {2689/*2690 * "--not A B -- path" without anything positive;2691 * do not default to HEAD, but use the working tree2692 * or "--contents".2693 */2694setup_work_tree();2695 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2696 path, contents_from);2697add_pending_object(&revs, &(sb.final->object),":");2698}2699else if(contents_from)2700die("Cannot use --contents with final commit object name");27012702/*2703 * If we have bottom, this will mark the ancestors of the2704 * bottom commits we would reach while traversing as2705 * uninteresting.2706 */2707if(prepare_revision_walk(&revs))2708die(_("revision walk setup failed"));27092710if(is_null_sha1(sb.final->object.sha1)) {2711 o = sb.final->util;2712 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2713 sb.final_buf_size = o->file.size;2714}2715else{2716 o =get_origin(&sb, sb.final, path);2717if(fill_blob_sha1_and_mode(o))2718die("no such path%sin%s", path, final_commit_name);27192720if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2721textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2722&sb.final_buf_size))2723;2724else2725 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2726&sb.final_buf_size);27272728if(!sb.final_buf)2729die("Cannot read blob%sfor path%s",2730sha1_to_hex(o->blob_sha1),2731 path);2732}2733 num_read_blob++;2734 lno =prepare_lines(&sb);27352736if(lno && !range_list.nr)2737string_list_append(&range_list,xstrdup("1"));27382739 anchor =1;2740range_set_init(&ranges, range_list.nr);2741for(range_i =0; range_i < range_list.nr; ++range_i) {2742long bottom, top;2743if(parse_range_arg(range_list.items[range_i].string,2744 nth_line_cb, &sb, lno, anchor,2745&bottom, &top, sb.path))2746usage(blame_usage);2747if(lno < top || ((lno || bottom) && lno < bottom))2748die("file%shas only%lu lines", path, lno);2749if(bottom <1)2750 bottom =1;2751if(top <1)2752 top = lno;2753 bottom--;2754range_set_append_unsafe(&ranges, bottom, top);2755 anchor = top +1;2756}2757sort_and_merge_range_set(&ranges);27582759for(range_i = ranges.nr; range_i >0; --range_i) {2760const struct range *r = &ranges.ranges[range_i -1];2761long bottom = r->start;2762long top = r->end;2763struct blame_entry *next = ent;2764 ent =xcalloc(1,sizeof(*ent));2765 ent->lno = bottom;2766 ent->num_lines = top - bottom;2767 ent->suspect = o;2768 ent->s_lno = bottom;2769 ent->next = next;2770origin_incref(o);2771}27722773 o->suspects = ent;2774prio_queue_put(&sb.commits, o->commit);27752776origin_decref(o);27772778range_set_release(&ranges);2779string_list_clear(&range_list,0);27802781 sb.ent = NULL;2782 sb.path = path;27832784read_mailmap(&mailmap, NULL);27852786if(!incremental)2787setup_pager();27882789assign_blame(&sb, opt);27902791free(final_commit_name);27922793if(incremental)2794return0;27952796 sb.ent =blame_sort(sb.ent, compare_blame_final);27972798coalesce(&sb);27992800if(!(output_option & OUTPUT_PORCELAIN))2801find_alignment(&sb, &output_option);28022803output(&sb, output_option);2804free((void*)sb.final_buf);2805for(ent = sb.ent; ent; ) {2806struct blame_entry *e = ent->next;2807free(ent);2808 ent = e;2809}28102811if(show_stats) {2812printf("num read blob:%d\n", num_read_blob);2813printf("num get patch:%d\n", num_get_patch);2814printf("num commits:%d\n", num_commits);2815}2816return0;2817}