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 977if(diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d)) 978die("unable to generate diff (%s->%s)", 979sha1_to_hex(parent->commit->object.sha1), 980sha1_to_hex(target->commit->object.sha1)); 981/* The rest are the same as the parent */ 982blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 983*d.dstq = NULL; 984queue_blames(sb, parent, newdest); 985 986return; 987} 988 989/* 990 * The lines in blame_entry after splitting blames many times can become 991 * very small and trivial, and at some point it becomes pointless to 992 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 993 * ordinary C program, and it is not worth to say it was copied from 994 * totally unrelated file in the parent. 995 * 996 * Compute how trivial the lines in the blame_entry are. 997 */ 998static unsignedent_score(struct scoreboard *sb,struct blame_entry *e) 999{1000unsigned score;1001const char*cp, *ep;10021003if(e->score)1004return e->score;10051006 score =1;1007 cp =nth_line(sb, e->lno);1008 ep =nth_line(sb, e->lno + e->num_lines);1009while(cp < ep) {1010unsigned ch = *((unsigned char*)cp);1011if(isalnum(ch))1012 score++;1013 cp++;1014}1015 e->score = score;1016return score;1017}10181019/*1020 * best_so_far[] and this[] are both a split of an existing blame_entry1021 * that passes blame to the parent. Maintain best_so_far the best split1022 * so far, by comparing this and best_so_far and copying this into1023 * bst_so_far as needed.1024 */1025static voidcopy_split_if_better(struct scoreboard *sb,1026struct blame_entry *best_so_far,1027struct blame_entry *this)1028{1029int i;10301031if(!this[1].suspect)1032return;1033if(best_so_far[1].suspect) {1034if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1035return;1036}10371038for(i =0; i <3; i++)1039origin_incref(this[i].suspect);1040decref_split(best_so_far);1041memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1042}10431044/*1045 * We are looking at a part of the final image represented by1046 * ent (tlno and same are offset by ent->s_lno).1047 * tlno is where we are looking at in the final image.1048 * up to (but not including) same match preimage.1049 * plno is where we are looking at in the preimage.1050 *1051 * <-------------- final image ---------------------->1052 * <------ent------>1053 * ^tlno ^same1054 * <---------preimage----->1055 * ^plno1056 *1057 * All line numbers are 0-based.1058 */1059static voidhandle_split(struct scoreboard *sb,1060struct blame_entry *ent,1061int tlno,int plno,int same,1062struct origin *parent,1063struct blame_entry *split)1064{1065if(ent->num_lines <= tlno)1066return;1067if(tlno < same) {1068struct blame_entry this[3];1069 tlno += ent->s_lno;1070 same += ent->s_lno;1071split_overlap(this, ent, tlno, plno, same, parent);1072copy_split_if_better(sb, split,this);1073decref_split(this);1074}1075}10761077struct handle_split_cb_data {1078struct scoreboard *sb;1079struct blame_entry *ent;1080struct origin *parent;1081struct blame_entry *split;1082long plno;1083long tlno;1084};10851086static inthandle_split_cb(long start_a,long count_a,1087long start_b,long count_b,void*data)1088{1089struct handle_split_cb_data *d = data;1090handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1091 d->split);1092 d->plno = start_a + count_a;1093 d->tlno = start_b + count_b;1094return0;1095}10961097/*1098 * Find the lines from parent that are the same as ent so that1099 * we can pass blames to it. file_p has the blob contents for1100 * the parent.1101 */1102static voidfind_copy_in_blob(struct scoreboard *sb,1103struct blame_entry *ent,1104struct origin *parent,1105struct blame_entry *split,1106 mmfile_t *file_p)1107{1108const char*cp;1109 mmfile_t file_o;1110struct handle_split_cb_data d;11111112memset(&d,0,sizeof(d));1113 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1114/*1115 * Prepare mmfile that contains only the lines in ent.1116 */1117 cp =nth_line(sb, ent->lno);1118 file_o.ptr = (char*) cp;1119 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11201121/*1122 * file_o is a part of final image we are annotating.1123 * file_p partially may match that image.1124 */1125memset(split,0,sizeof(struct blame_entry [3]));1126if(diff_hunks(file_p, &file_o,1, handle_split_cb, &d))1127die("unable to generate diff (%s)",1128sha1_to_hex(parent->commit->object.sha1));1129/* remainder, if any, all match the preimage */1130handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1131}11321133/* Move all blame entries from list *source that have a score smaller1134 * than score_min to the front of list *small.1135 * Returns a pointer to the link pointing to the old head of the small list.1136 */11371138static struct blame_entry **filter_small(struct scoreboard *sb,1139struct blame_entry **small,1140struct blame_entry **source,1141unsigned score_min)1142{1143struct blame_entry *p = *source;1144struct blame_entry *oldsmall = *small;1145while(p) {1146if(ent_score(sb, p) <= score_min) {1147*small = p;1148 small = &p->next;1149 p = *small;1150}else{1151*source = p;1152 source = &p->next;1153 p = *source;1154}1155}1156*small = oldsmall;1157*source = NULL;1158return small;1159}11601161/*1162 * See if lines currently target is suspected for can be attributed to1163 * parent.1164 */1165static voidfind_move_in_parent(struct scoreboard *sb,1166struct blame_entry ***blamed,1167struct blame_entry **toosmall,1168struct origin *target,1169struct origin *parent)1170{1171struct blame_entry *e, split[3];1172struct blame_entry *unblamed = target->suspects;1173struct blame_entry *leftover = NULL;1174 mmfile_t file_p;11751176if(!unblamed)1177return;/* nothing remains for this target */11781179fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1180if(!file_p.ptr)1181return;11821183/* At each iteration, unblamed has a NULL-terminated list of1184 * entries that have not yet been tested for blame. leftover1185 * contains the reversed list of entries that have been tested1186 * without being assignable to the parent.1187 */1188do{1189struct blame_entry **unblamedtail = &unblamed;1190struct blame_entry *next;1191for(e = unblamed; e; e = next) {1192 next = e->next;1193find_copy_in_blob(sb, e, parent, split, &file_p);1194if(split[1].suspect &&1195 blame_move_score <ent_score(sb, &split[1])) {1196split_blame(blamed, &unblamedtail, split, e);1197}else{1198 e->next = leftover;1199 leftover = e;1200}1201decref_split(split);1202}1203*unblamedtail = NULL;1204 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1205}while(unblamed);1206 target->suspects =reverse_blame(leftover, NULL);1207}12081209struct blame_list {1210struct blame_entry *ent;1211struct blame_entry split[3];1212};12131214/*1215 * Count the number of entries the target is suspected for,1216 * and prepare a list of entry and the best split.1217 */1218static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1219int*num_ents_p)1220{1221struct blame_entry *e;1222int num_ents, i;1223struct blame_list *blame_list = NULL;12241225for(e = unblamed, num_ents =0; e; e = e->next)1226 num_ents++;1227if(num_ents) {1228 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1229for(e = unblamed, i =0; e; e = e->next)1230 blame_list[i++].ent = e;1231}1232*num_ents_p = num_ents;1233return blame_list;1234}12351236/*1237 * For lines target is suspected for, see if we can find code movement1238 * across file boundary from the parent commit. porigin is the path1239 * in the parent we already tried.1240 */1241static voidfind_copy_in_parent(struct scoreboard *sb,1242struct blame_entry ***blamed,1243struct blame_entry **toosmall,1244struct origin *target,1245struct commit *parent,1246struct origin *porigin,1247int opt)1248{1249struct diff_options diff_opts;1250int i, j;1251struct blame_list *blame_list;1252int num_ents;1253struct blame_entry *unblamed = target->suspects;1254struct blame_entry *leftover = NULL;12551256if(!unblamed)1257return;/* nothing remains for this target */12581259diff_setup(&diff_opts);1260DIFF_OPT_SET(&diff_opts, RECURSIVE);1261 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12621263diff_setup_done(&diff_opts);12641265/* Try "find copies harder" on new path if requested;1266 * we do not want to use diffcore_rename() actually to1267 * match things up; find_copies_harder is set only to1268 * force diff_tree_sha1() to feed all filepairs to diff_queue,1269 * and this code needs to be after diff_setup_done(), which1270 * usually makes find-copies-harder imply copy detection.1271 */1272if((opt & PICKAXE_BLAME_COPY_HARDEST)1273|| ((opt & PICKAXE_BLAME_COPY_HARDER)1274&& (!porigin ||strcmp(target->path, porigin->path))))1275DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12761277if(is_null_sha1(target->commit->object.sha1))1278do_diff_cache(parent->tree->object.sha1, &diff_opts);1279else1280diff_tree_sha1(parent->tree->object.sha1,1281 target->commit->tree->object.sha1,1282"", &diff_opts);12831284if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1285diffcore_std(&diff_opts);12861287do{1288struct blame_entry **unblamedtail = &unblamed;1289 blame_list =setup_blame_list(unblamed, &num_ents);12901291for(i =0; i < diff_queued_diff.nr; i++) {1292struct diff_filepair *p = diff_queued_diff.queue[i];1293struct origin *norigin;1294 mmfile_t file_p;1295struct blame_entry this[3];12961297if(!DIFF_FILE_VALID(p->one))1298continue;/* does not exist in parent */1299if(S_ISGITLINK(p->one->mode))1300continue;/* ignore git links */1301if(porigin && !strcmp(p->one->path, porigin->path))1302/* find_move already dealt with this path */1303continue;13041305 norigin =get_origin(sb, parent, p->one->path);1306hashcpy(norigin->blob_sha1, p->one->sha1);1307 norigin->mode = p->one->mode;1308fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1309if(!file_p.ptr)1310continue;13111312for(j =0; j < num_ents; j++) {1313find_copy_in_blob(sb, blame_list[j].ent,1314 norigin,this, &file_p);1315copy_split_if_better(sb, blame_list[j].split,1316this);1317decref_split(this);1318}1319origin_decref(norigin);1320}13211322for(j =0; j < num_ents; j++) {1323struct blame_entry *split = blame_list[j].split;1324if(split[1].suspect &&1325 blame_copy_score <ent_score(sb, &split[1])) {1326split_blame(blamed, &unblamedtail, split,1327 blame_list[j].ent);1328}else{1329 blame_list[j].ent->next = leftover;1330 leftover = blame_list[j].ent;1331}1332decref_split(split);1333}1334free(blame_list);1335*unblamedtail = NULL;1336 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1337}while(unblamed);1338 target->suspects =reverse_blame(leftover, NULL);1339diff_flush(&diff_opts);1340free_pathspec(&diff_opts.pathspec);1341}13421343/*1344 * The blobs of origin and porigin exactly match, so everything1345 * origin is suspected for can be blamed on the parent.1346 */1347static voidpass_whole_blame(struct scoreboard *sb,1348struct origin *origin,struct origin *porigin)1349{1350struct blame_entry *e, *suspects;13511352if(!porigin->file.ptr && origin->file.ptr) {1353/* Steal its file */1354 porigin->file = origin->file;1355 origin->file.ptr = NULL;1356}1357 suspects = origin->suspects;1358 origin->suspects = NULL;1359for(e = suspects; e; e = e->next) {1360origin_incref(porigin);1361origin_decref(e->suspect);1362 e->suspect = porigin;1363}1364queue_blames(sb, porigin, suspects);1365}13661367/*1368 * We pass blame from the current commit to its parents. We keep saying1369 * "parent" (and "porigin"), but what we mean is to find scapegoat to1370 * exonerate ourselves.1371 */1372static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1373{1374if(!reverse)1375return commit->parents;1376returnlookup_decoration(&revs->children, &commit->object);1377}13781379static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1380{1381struct commit_list *l =first_scapegoat(revs, commit);1382returncommit_list_count(l);1383}13841385/* Distribute collected unsorted blames to the respected sorted lists1386 * in the various origins.1387 */1388static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1389{1390 blamed =blame_sort(blamed, compare_blame_suspect);1391while(blamed)1392{1393struct origin *porigin = blamed->suspect;1394struct blame_entry *suspects = NULL;1395do{1396struct blame_entry *next = blamed->next;1397 blamed->next = suspects;1398 suspects = blamed;1399 blamed = next;1400}while(blamed && blamed->suspect == porigin);1401 suspects =reverse_blame(suspects, NULL);1402queue_blames(sb, porigin, suspects);1403}1404}14051406#define MAXSG 1614071408static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1409{1410struct rev_info *revs = sb->revs;1411int i, pass, num_sg;1412struct commit *commit = origin->commit;1413struct commit_list *sg;1414struct origin *sg_buf[MAXSG];1415struct origin *porigin, **sg_origin = sg_buf;1416struct blame_entry *toosmall = NULL;1417struct blame_entry *blames, **blametail = &blames;14181419 num_sg =num_scapegoats(revs, commit);1420if(!num_sg)1421goto finish;1422else if(num_sg <ARRAY_SIZE(sg_buf))1423memset(sg_buf,0,sizeof(sg_buf));1424else1425 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14261427/*1428 * The first pass looks for unrenamed path to optimize for1429 * common cases, then we look for renames in the second pass.1430 */1431for(pass =0; pass <2- no_whole_file_rename; pass++) {1432struct origin *(*find)(struct scoreboard *,1433struct commit *,struct origin *);1434 find = pass ? find_rename : find_origin;14351436for(i =0, sg =first_scapegoat(revs, commit);1437 i < num_sg && sg;1438 sg = sg->next, i++) {1439struct commit *p = sg->item;1440int j, same;14411442if(sg_origin[i])1443continue;1444if(parse_commit(p))1445continue;1446 porigin =find(sb, p, origin);1447if(!porigin)1448continue;1449if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1450pass_whole_blame(sb, origin, porigin);1451origin_decref(porigin);1452goto finish;1453}1454for(j = same =0; j < i; j++)1455if(sg_origin[j] &&1456!hashcmp(sg_origin[j]->blob_sha1,1457 porigin->blob_sha1)) {1458 same =1;1459break;1460}1461if(!same)1462 sg_origin[i] = porigin;1463else1464origin_decref(porigin);1465}1466}14671468 num_commits++;1469for(i =0, sg =first_scapegoat(revs, commit);1470 i < num_sg && sg;1471 sg = sg->next, i++) {1472struct origin *porigin = sg_origin[i];1473if(!porigin)1474continue;1475if(!origin->previous) {1476origin_incref(porigin);1477 origin->previous = porigin;1478}1479pass_blame_to_parent(sb, origin, porigin);1480if(!origin->suspects)1481goto finish;1482}14831484/*1485 * Optionally find moves in parents' files.1486 */1487if(opt & PICKAXE_BLAME_MOVE) {1488filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1489if(origin->suspects) {1490for(i =0, sg =first_scapegoat(revs, commit);1491 i < num_sg && sg;1492 sg = sg->next, i++) {1493struct origin *porigin = sg_origin[i];1494if(!porigin)1495continue;1496find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1497if(!origin->suspects)1498break;1499}1500}1501}15021503/*1504 * Optionally find copies from parents' files.1505 */1506if(opt & PICKAXE_BLAME_COPY) {1507if(blame_copy_score > blame_move_score)1508filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1509else if(blame_copy_score < blame_move_score) {1510 origin->suspects =blame_merge(origin->suspects, toosmall);1511 toosmall = NULL;1512filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1513}1514if(!origin->suspects)1515goto finish;15161517for(i =0, sg =first_scapegoat(revs, commit);1518 i < num_sg && sg;1519 sg = sg->next, i++) {1520struct origin *porigin = sg_origin[i];1521find_copy_in_parent(sb, &blametail, &toosmall,1522 origin, sg->item, porigin, opt);1523if(!origin->suspects)1524goto finish;1525}1526}15271528finish:1529*blametail = NULL;1530distribute_blame(sb, blames);1531/*1532 * prepend toosmall to origin->suspects1533 *1534 * There is no point in sorting: this ends up on a big1535 * unsorted list in the caller anyway.1536 */1537if(toosmall) {1538struct blame_entry **tail = &toosmall;1539while(*tail)1540 tail = &(*tail)->next;1541*tail = origin->suspects;1542 origin->suspects = toosmall;1543}1544for(i =0; i < num_sg; i++) {1545if(sg_origin[i]) {1546drop_origin_blob(sg_origin[i]);1547origin_decref(sg_origin[i]);1548}1549}1550drop_origin_blob(origin);1551if(sg_buf != sg_origin)1552free(sg_origin);1553}15541555/*1556 * Information on commits, used for output.1557 */1558struct commit_info {1559struct strbuf author;1560struct strbuf author_mail;1561unsigned long author_time;1562struct strbuf author_tz;15631564/* filled only when asked for details */1565struct strbuf committer;1566struct strbuf committer_mail;1567unsigned long committer_time;1568struct strbuf committer_tz;15691570struct strbuf summary;1571};15721573/*1574 * Parse author/committer line in the commit object buffer1575 */1576static voidget_ac_line(const char*inbuf,const char*what,1577struct strbuf *name,struct strbuf *mail,1578unsigned long*time,struct strbuf *tz)1579{1580struct ident_split ident;1581size_t len, maillen, namelen;1582char*tmp, *endp;1583const char*namebuf, *mailbuf;15841585 tmp =strstr(inbuf, what);1586if(!tmp)1587goto error_out;1588 tmp +=strlen(what);1589 endp =strchr(tmp,'\n');1590if(!endp)1591 len =strlen(tmp);1592else1593 len = endp - tmp;15941595if(split_ident_line(&ident, tmp, len)) {1596 error_out:1597/* Ugh */1598 tmp ="(unknown)";1599strbuf_addstr(name, tmp);1600strbuf_addstr(mail, tmp);1601strbuf_addstr(tz, tmp);1602*time =0;1603return;1604}16051606 namelen = ident.name_end - ident.name_begin;1607 namebuf = ident.name_begin;16081609 maillen = ident.mail_end - ident.mail_begin;1610 mailbuf = ident.mail_begin;16111612if(ident.date_begin && ident.date_end)1613*time =strtoul(ident.date_begin, NULL,10);1614else1615*time =0;16161617if(ident.tz_begin && ident.tz_end)1618strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1619else1620strbuf_addstr(tz,"(unknown)");16211622/*1623 * Now, convert both name and e-mail using mailmap1624 */1625map_user(&mailmap, &mailbuf, &maillen,1626&namebuf, &namelen);16271628strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1629strbuf_add(name, namebuf, namelen);1630}16311632static voidcommit_info_init(struct commit_info *ci)1633{16341635strbuf_init(&ci->author,0);1636strbuf_init(&ci->author_mail,0);1637strbuf_init(&ci->author_tz,0);1638strbuf_init(&ci->committer,0);1639strbuf_init(&ci->committer_mail,0);1640strbuf_init(&ci->committer_tz,0);1641strbuf_init(&ci->summary,0);1642}16431644static voidcommit_info_destroy(struct commit_info *ci)1645{16461647strbuf_release(&ci->author);1648strbuf_release(&ci->author_mail);1649strbuf_release(&ci->author_tz);1650strbuf_release(&ci->committer);1651strbuf_release(&ci->committer_mail);1652strbuf_release(&ci->committer_tz);1653strbuf_release(&ci->summary);1654}16551656static voidget_commit_info(struct commit *commit,1657struct commit_info *ret,1658int detailed)1659{1660int len;1661const char*subject, *encoding;1662const char*message;16631664commit_info_init(ret);16651666 encoding =get_log_output_encoding();1667 message =logmsg_reencode(commit, NULL, encoding);1668get_ac_line(message,"\nauthor ",1669&ret->author, &ret->author_mail,1670&ret->author_time, &ret->author_tz);16711672if(!detailed) {1673unuse_commit_buffer(commit, message);1674return;1675}16761677get_ac_line(message,"\ncommitter ",1678&ret->committer, &ret->committer_mail,1679&ret->committer_time, &ret->committer_tz);16801681 len =find_commit_subject(message, &subject);1682if(len)1683strbuf_add(&ret->summary, subject, len);1684else1685strbuf_addf(&ret->summary,"(%s)",sha1_to_hex(commit->object.sha1));16861687unuse_commit_buffer(commit, message);1688}16891690/*1691 * To allow LF and other nonportable characters in pathnames,1692 * they are c-style quoted as needed.1693 */1694static voidwrite_filename_info(const char*path)1695{1696printf("filename ");1697write_name_quoted(path, stdout,'\n');1698}16991700/*1701 * Porcelain/Incremental format wants to show a lot of details per1702 * commit. Instead of repeating this every line, emit it only once,1703 * the first time each commit appears in the output (unless the1704 * user has specifically asked for us to repeat).1705 */1706static intemit_one_suspect_detail(struct origin *suspect,int repeat)1707{1708struct commit_info ci;17091710if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1711return0;17121713 suspect->commit->object.flags |= METAINFO_SHOWN;1714get_commit_info(suspect->commit, &ci,1);1715printf("author%s\n", ci.author.buf);1716printf("author-mail%s\n", ci.author_mail.buf);1717printf("author-time%lu\n", ci.author_time);1718printf("author-tz%s\n", ci.author_tz.buf);1719printf("committer%s\n", ci.committer.buf);1720printf("committer-mail%s\n", ci.committer_mail.buf);1721printf("committer-time%lu\n", ci.committer_time);1722printf("committer-tz%s\n", ci.committer_tz.buf);1723printf("summary%s\n", ci.summary.buf);1724if(suspect->commit->object.flags & UNINTERESTING)1725printf("boundary\n");1726if(suspect->previous) {1727struct origin *prev = suspect->previous;1728printf("previous%s",sha1_to_hex(prev->commit->object.sha1));1729write_name_quoted(prev->path, stdout,'\n');1730}17311732commit_info_destroy(&ci);17331734return1;1735}17361737/*1738 * The blame_entry is found to be guilty for the range.1739 * Show it in incremental output.1740 */1741static voidfound_guilty_entry(struct blame_entry *ent)1742{1743if(incremental) {1744struct origin *suspect = ent->suspect;17451746printf("%s %d %d %d\n",1747sha1_to_hex(suspect->commit->object.sha1),1748 ent->s_lno +1, ent->lno +1, ent->num_lines);1749emit_one_suspect_detail(suspect,0);1750write_filename_info(suspect->path);1751maybe_flush_or_die(stdout,"stdout");1752}1753}17541755/*1756 * The main loop -- while we have blobs with lines whose true origin1757 * is still unknown, pick one blob, and allow its lines to pass blames1758 * to its parents. */1759static voidassign_blame(struct scoreboard *sb,int opt)1760{1761struct rev_info *revs = sb->revs;1762struct commit *commit =prio_queue_get(&sb->commits);17631764while(commit) {1765struct blame_entry *ent;1766struct origin *suspect = commit->util;17671768/* find one suspect to break down */1769while(suspect && !suspect->suspects)1770 suspect = suspect->next;17711772if(!suspect) {1773 commit =prio_queue_get(&sb->commits);1774continue;1775}17761777assert(commit == suspect->commit);17781779/*1780 * We will use this suspect later in the loop,1781 * so hold onto it in the meantime.1782 */1783origin_incref(suspect);1784parse_commit(commit);1785if(reverse ||1786(!(commit->object.flags & UNINTERESTING) &&1787!(revs->max_age != -1&& commit->date < revs->max_age)))1788pass_blame(sb, suspect, opt);1789else{1790 commit->object.flags |= UNINTERESTING;1791if(commit->object.parsed)1792mark_parents_uninteresting(commit);1793}1794/* treat root commit as boundary */1795if(!commit->parents && !show_root)1796 commit->object.flags |= UNINTERESTING;17971798/* Take responsibility for the remaining entries */1799 ent = suspect->suspects;1800if(ent) {1801 suspect->guilty =1;1802for(;;) {1803struct blame_entry *next = ent->next;1804found_guilty_entry(ent);1805if(next) {1806 ent = next;1807continue;1808}1809 ent->next = sb->ent;1810 sb->ent = suspect->suspects;1811 suspect->suspects = NULL;1812break;1813}1814}1815origin_decref(suspect);18161817if(DEBUG)/* sanity */1818sanity_check_refcnt(sb);1819}1820}18211822static const char*format_time(unsigned long time,const char*tz_str,1823int show_raw_time)1824{1825static struct strbuf time_buf = STRBUF_INIT;18261827strbuf_reset(&time_buf);1828if(show_raw_time) {1829strbuf_addf(&time_buf,"%lu%s", time, tz_str);1830}1831else{1832const char*time_str;1833size_t time_width;1834int tz;1835 tz =atoi(tz_str);1836 time_str =show_date(time, tz, &blame_date_mode);1837strbuf_addstr(&time_buf, time_str);1838/*1839 * Add space paddings to time_buf to display a fixed width1840 * string, and use time_width for display width calibration.1841 */1842for(time_width =utf8_strwidth(time_str);1843 time_width < blame_date_width;1844 time_width++)1845strbuf_addch(&time_buf,' ');1846}1847return time_buf.buf;1848}18491850#define OUTPUT_ANNOTATE_COMPAT 0011851#define OUTPUT_LONG_OBJECT_NAME 0021852#define OUTPUT_RAW_TIMESTAMP 0041853#define OUTPUT_PORCELAIN 0101854#define OUTPUT_SHOW_NAME 0201855#define OUTPUT_SHOW_NUMBER 0401856#define OUTPUT_SHOW_SCORE 01001857#define OUTPUT_NO_AUTHOR 02001858#define OUTPUT_SHOW_EMAIL 04001859#define OUTPUT_LINE_PORCELAIN 0100018601861static voidemit_porcelain_details(struct origin *suspect,int repeat)1862{1863if(emit_one_suspect_detail(suspect, repeat) ||1864(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1865write_filename_info(suspect->path);1866}18671868static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1869int opt)1870{1871int repeat = opt & OUTPUT_LINE_PORCELAIN;1872int cnt;1873const char*cp;1874struct origin *suspect = ent->suspect;1875char hex[41];18761877strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));1878printf("%s %d %d %d\n",1879 hex,1880 ent->s_lno +1,1881 ent->lno +1,1882 ent->num_lines);1883emit_porcelain_details(suspect, repeat);18841885 cp =nth_line(sb, ent->lno);1886for(cnt =0; cnt < ent->num_lines; cnt++) {1887char ch;1888if(cnt) {1889printf("%s %d %d\n", hex,1890 ent->s_lno +1+ cnt,1891 ent->lno +1+ cnt);1892if(repeat)1893emit_porcelain_details(suspect,1);1894}1895putchar('\t');1896do{1897 ch = *cp++;1898putchar(ch);1899}while(ch !='\n'&&1900 cp < sb->final_buf + sb->final_buf_size);1901}19021903if(sb->final_buf_size && cp[-1] !='\n')1904putchar('\n');1905}19061907static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1908{1909int cnt;1910const char*cp;1911struct origin *suspect = ent->suspect;1912struct commit_info ci;1913char hex[41];1914int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19151916get_commit_info(suspect->commit, &ci,1);1917strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));19181919 cp =nth_line(sb, ent->lno);1920for(cnt =0; cnt < ent->num_lines; cnt++) {1921char ch;1922int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19231924if(suspect->commit->object.flags & UNINTERESTING) {1925if(blank_boundary)1926memset(hex,' ', length);1927else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1928 length--;1929putchar('^');1930}1931}19321933printf("%.*s", length, hex);1934if(opt & OUTPUT_ANNOTATE_COMPAT) {1935const char*name;1936if(opt & OUTPUT_SHOW_EMAIL)1937 name = ci.author_mail.buf;1938else1939 name = ci.author.buf;1940printf("\t(%10s\t%10s\t%d)", name,1941format_time(ci.author_time, ci.author_tz.buf,1942 show_raw_time),1943 ent->lno +1+ cnt);1944}else{1945if(opt & OUTPUT_SHOW_SCORE)1946printf(" %*d%02d",1947 max_score_digits, ent->score,1948 ent->suspect->refcnt);1949if(opt & OUTPUT_SHOW_NAME)1950printf(" %-*.*s", longest_file, longest_file,1951 suspect->path);1952if(opt & OUTPUT_SHOW_NUMBER)1953printf(" %*d", max_orig_digits,1954 ent->s_lno +1+ cnt);19551956if(!(opt & OUTPUT_NO_AUTHOR)) {1957const char*name;1958int pad;1959if(opt & OUTPUT_SHOW_EMAIL)1960 name = ci.author_mail.buf;1961else1962 name = ci.author.buf;1963 pad = longest_author -utf8_strwidth(name);1964printf(" (%s%*s%10s",1965 name, pad,"",1966format_time(ci.author_time,1967 ci.author_tz.buf,1968 show_raw_time));1969}1970printf(" %*d) ",1971 max_digits, ent->lno +1+ cnt);1972}1973do{1974 ch = *cp++;1975putchar(ch);1976}while(ch !='\n'&&1977 cp < sb->final_buf + sb->final_buf_size);1978}19791980if(sb->final_buf_size && cp[-1] !='\n')1981putchar('\n');19821983commit_info_destroy(&ci);1984}19851986static voidoutput(struct scoreboard *sb,int option)1987{1988struct blame_entry *ent;19891990if(option & OUTPUT_PORCELAIN) {1991for(ent = sb->ent; ent; ent = ent->next) {1992int count =0;1993struct origin *suspect;1994struct commit *commit = ent->suspect->commit;1995if(commit->object.flags & MORE_THAN_ONE_PATH)1996continue;1997for(suspect = commit->util; suspect; suspect = suspect->next) {1998if(suspect->guilty && count++) {1999 commit->object.flags |= MORE_THAN_ONE_PATH;2000break;2001}2002}2003}2004}20052006for(ent = sb->ent; ent; ent = ent->next) {2007if(option & OUTPUT_PORCELAIN)2008emit_porcelain(sb, ent, option);2009else{2010emit_other(sb, ent, option);2011}2012}2013}20142015static const char*get_next_line(const char*start,const char*end)2016{2017const char*nl =memchr(start,'\n', end - start);2018return nl ? nl +1: end;2019}20202021/*2022 * To allow quick access to the contents of nth line in the2023 * final image, prepare an index in the scoreboard.2024 */2025static intprepare_lines(struct scoreboard *sb)2026{2027const char*buf = sb->final_buf;2028unsigned long len = sb->final_buf_size;2029const char*end = buf + len;2030const char*p;2031int*lineno;2032int num =0;20332034for(p = buf; p < end; p =get_next_line(p, end))2035 num++;20362037 sb->lineno = lineno =xmalloc(sizeof(*sb->lineno) * (num +1));20382039for(p = buf; p < end; p =get_next_line(p, end))2040*lineno++ = p - buf;20412042*lineno = len;20432044 sb->num_lines = num;2045return sb->num_lines;2046}20472048/*2049 * Add phony grafts for use with -S; this is primarily to2050 * support git's cvsserver that wants to give a linear history2051 * to its clients.2052 */2053static intread_ancestry(const char*graft_file)2054{2055FILE*fp =fopen(graft_file,"r");2056struct strbuf buf = STRBUF_INIT;2057if(!fp)2058return-1;2059while(!strbuf_getwholeline(&buf, fp,'\n')) {2060/* The format is just "Commit Parent1 Parent2 ...\n" */2061struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2062if(graft)2063register_commit_graft(graft,0);2064}2065fclose(fp);2066strbuf_release(&buf);2067return0;2068}20692070static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2071{2072const char*uniq =find_unique_abbrev(suspect->commit->object.sha1,2073 auto_abbrev);2074int len =strlen(uniq);2075if(auto_abbrev < len)2076return len;2077return auto_abbrev;2078}20792080/*2081 * How many columns do we need to show line numbers, authors,2082 * and filenames?2083 */2084static voidfind_alignment(struct scoreboard *sb,int*option)2085{2086int longest_src_lines =0;2087int longest_dst_lines =0;2088unsigned largest_score =0;2089struct blame_entry *e;2090int compute_auto_abbrev = (abbrev <0);2091int auto_abbrev = default_abbrev;20922093for(e = sb->ent; e; e = e->next) {2094struct origin *suspect = e->suspect;2095int num;20962097if(compute_auto_abbrev)2098 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2099if(strcmp(suspect->path, sb->path))2100*option |= OUTPUT_SHOW_NAME;2101 num =strlen(suspect->path);2102if(longest_file < num)2103 longest_file = num;2104if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2105struct commit_info ci;2106 suspect->commit->object.flags |= METAINFO_SHOWN;2107get_commit_info(suspect->commit, &ci,1);2108if(*option & OUTPUT_SHOW_EMAIL)2109 num =utf8_strwidth(ci.author_mail.buf);2110else2111 num =utf8_strwidth(ci.author.buf);2112if(longest_author < num)2113 longest_author = num;2114commit_info_destroy(&ci);2115}2116 num = e->s_lno + e->num_lines;2117if(longest_src_lines < num)2118 longest_src_lines = num;2119 num = e->lno + e->num_lines;2120if(longest_dst_lines < num)2121 longest_dst_lines = num;2122if(largest_score <ent_score(sb, e))2123 largest_score =ent_score(sb, e);2124}2125 max_orig_digits =decimal_width(longest_src_lines);2126 max_digits =decimal_width(longest_dst_lines);2127 max_score_digits =decimal_width(largest_score);21282129if(compute_auto_abbrev)2130/* one more abbrev length is needed for the boundary commit */2131 abbrev = auto_abbrev +1;2132}21332134/*2135 * For debugging -- origin is refcounted, and this asserts that2136 * we do not underflow.2137 */2138static voidsanity_check_refcnt(struct scoreboard *sb)2139{2140int baa =0;2141struct blame_entry *ent;21422143for(ent = sb->ent; ent; ent = ent->next) {2144/* Nobody should have zero or negative refcnt */2145if(ent->suspect->refcnt <=0) {2146fprintf(stderr,"%sin%shas negative refcnt%d\n",2147 ent->suspect->path,2148sha1_to_hex(ent->suspect->commit->object.sha1),2149 ent->suspect->refcnt);2150 baa =1;2151}2152}2153if(baa) {2154int opt =0160;2155find_alignment(sb, &opt);2156output(sb, opt);2157die("Baa%d!", baa);2158}2159}21602161static unsignedparse_score(const char*arg)2162{2163char*end;2164unsigned long score =strtoul(arg, &end,10);2165if(*end)2166return0;2167return score;2168}21692170static const char*add_prefix(const char*prefix,const char*path)2171{2172returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2173}21742175static intgit_blame_config(const char*var,const char*value,void*cb)2176{2177if(!strcmp(var,"blame.showroot")) {2178 show_root =git_config_bool(var, value);2179return0;2180}2181if(!strcmp(var,"blame.blankboundary")) {2182 blank_boundary =git_config_bool(var, value);2183return0;2184}2185if(!strcmp(var,"blame.showemail")) {2186int*output_option = cb;2187if(git_config_bool(var, value))2188*output_option |= OUTPUT_SHOW_EMAIL;2189else2190*output_option &= ~OUTPUT_SHOW_EMAIL;2191return0;2192}2193if(!strcmp(var,"blame.date")) {2194if(!value)2195returnconfig_error_nonbool(var);2196parse_date_format(value, &blame_date_mode);2197return0;2198}21992200if(userdiff_config(var, value) <0)2201return-1;22022203returngit_default_config(var, value, cb);2204}22052206static voidverify_working_tree_path(struct commit *work_tree,const char*path)2207{2208struct commit_list *parents;22092210for(parents = work_tree->parents; parents; parents = parents->next) {2211const unsigned char*commit_sha1 = parents->item->object.sha1;2212unsigned char blob_sha1[20];2213unsigned mode;22142215if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2216sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2217return;2218}2219die("no such path '%s' in HEAD", path);2220}22212222static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2223{2224struct commit *parent;22252226 parent =lookup_commit_reference(sha1);2227if(!parent)2228die("no such commit%s",sha1_to_hex(sha1));2229return&commit_list_insert(parent, tail)->next;2230}22312232static voidappend_merge_parents(struct commit_list **tail)2233{2234int merge_head;2235struct strbuf line = STRBUF_INIT;22362237 merge_head =open(git_path_merge_head(), O_RDONLY);2238if(merge_head <0) {2239if(errno == ENOENT)2240return;2241die("cannot open '%s' for reading",git_path_merge_head());2242}22432244while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2245unsigned char sha1[20];2246if(line.len <40||get_sha1_hex(line.buf, sha1))2247die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2248 tail =append_parent(tail, sha1);2249}2250close(merge_head);2251strbuf_release(&line);2252}22532254/*2255 * This isn't as simple as passing sb->buf and sb->len, because we2256 * want to transfer ownership of the buffer to the commit (so we2257 * must use detach).2258 */2259static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2260{2261size_t len;2262void*buf =strbuf_detach(sb, &len);2263set_commit_buffer(c, buf, len);2264}22652266/*2267 * Prepare a dummy commit that represents the work tree (or staged) item.2268 * Note that annotating work tree item never works in the reverse.2269 */2270static struct commit *fake_working_tree_commit(struct diff_options *opt,2271const char*path,2272const char*contents_from)2273{2274struct commit *commit;2275struct origin *origin;2276struct commit_list **parent_tail, *parent;2277unsigned char head_sha1[20];2278struct strbuf buf = STRBUF_INIT;2279const char*ident;2280time_t now;2281int size, len;2282struct cache_entry *ce;2283unsigned mode;2284struct strbuf msg = STRBUF_INIT;22852286time(&now);2287 commit =alloc_commit_node();2288 commit->object.parsed =1;2289 commit->date = now;2290 parent_tail = &commit->parents;22912292if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2293die("no such ref: HEAD");22942295 parent_tail =append_parent(parent_tail, head_sha1);2296append_merge_parents(parent_tail);2297verify_working_tree_path(commit, path);22982299 origin =make_origin(commit, path);23002301 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2302strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2303for(parent = commit->parents; parent; parent = parent->next)2304strbuf_addf(&msg,"parent%s\n",2305sha1_to_hex(parent->item->object.sha1));2306strbuf_addf(&msg,2307"author%s\n"2308"committer%s\n\n"2309"Version of%sfrom%s\n",2310 ident, ident, path,2311(!contents_from ? path :2312(!strcmp(contents_from,"-") ?"standard input": contents_from)));2313set_commit_buffer_from_strbuf(commit, &msg);23142315if(!contents_from ||strcmp("-", contents_from)) {2316struct stat st;2317const char*read_from;2318char*buf_ptr;2319unsigned long buf_len;23202321if(contents_from) {2322if(stat(contents_from, &st) <0)2323die_errno("Cannot stat '%s'", contents_from);2324 read_from = contents_from;2325}2326else{2327if(lstat(path, &st) <0)2328die_errno("Cannot lstat '%s'", path);2329 read_from = path;2330}2331 mode =canon_mode(st.st_mode);23322333switch(st.st_mode & S_IFMT) {2334case S_IFREG:2335if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2336textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2337strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2338else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2339die_errno("cannot open or read '%s'", read_from);2340break;2341case S_IFLNK:2342if(strbuf_readlink(&buf, read_from, st.st_size) <0)2343die_errno("cannot readlink '%s'", read_from);2344break;2345default:2346die("unsupported file type%s", read_from);2347}2348}2349else{2350/* Reading from stdin */2351 mode =0;2352if(strbuf_read(&buf,0,0) <0)2353die_errno("failed to read from stdin");2354}2355convert_to_git(path, buf.buf, buf.len, &buf,0);2356 origin->file.ptr = buf.buf;2357 origin->file.size = buf.len;2358pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23592360/*2361 * Read the current index, replace the path entry with2362 * origin->blob_sha1 without mucking with its mode or type2363 * bits; we are not going to write this index out -- we just2364 * want to run "diff-index --cached".2365 */2366discard_cache();2367read_cache();23682369 len =strlen(path);2370if(!mode) {2371int pos =cache_name_pos(path, len);2372if(0<= pos)2373 mode = active_cache[pos]->ce_mode;2374else2375/* Let's not bother reading from HEAD tree */2376 mode = S_IFREG |0644;2377}2378 size =cache_entry_size(len);2379 ce =xcalloc(1, size);2380hashcpy(ce->sha1, origin->blob_sha1);2381memcpy(ce->name, path, len);2382 ce->ce_flags =create_ce_flags(0);2383 ce->ce_namelen = len;2384 ce->ce_mode =create_ce_mode(mode);2385add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23862387/*2388 * We are not going to write this out, so this does not matter2389 * right now, but someday we might optimize diff-index --cached2390 * with cache-tree information.2391 */2392cache_tree_invalidate_path(&the_index, path);23932394return commit;2395}23962397static char*prepare_final(struct scoreboard *sb)2398{2399int i;2400const char*final_commit_name = NULL;2401struct rev_info *revs = sb->revs;24022403/*2404 * There must be one and only one positive commit in the2405 * revs->pending array.2406 */2407for(i =0; i < revs->pending.nr; i++) {2408struct object *obj = revs->pending.objects[i].item;2409if(obj->flags & UNINTERESTING)2410continue;2411while(obj->type == OBJ_TAG)2412 obj =deref_tag(obj, NULL,0);2413if(obj->type != OBJ_COMMIT)2414die("Non commit%s?", revs->pending.objects[i].name);2415if(sb->final)2416die("More than one commit to dig from%sand%s?",2417 revs->pending.objects[i].name,2418 final_commit_name);2419 sb->final = (struct commit *) obj;2420 final_commit_name = revs->pending.objects[i].name;2421}2422returnxstrdup_or_null(final_commit_name);2423}24242425static char*prepare_initial(struct scoreboard *sb)2426{2427int i;2428const char*final_commit_name = NULL;2429struct rev_info *revs = sb->revs;24302431/*2432 * There must be one and only one negative commit, and it must be2433 * the boundary.2434 */2435for(i =0; i < revs->pending.nr; i++) {2436struct object *obj = revs->pending.objects[i].item;2437if(!(obj->flags & UNINTERESTING))2438continue;2439while(obj->type == OBJ_TAG)2440 obj =deref_tag(obj, NULL,0);2441if(obj->type != OBJ_COMMIT)2442die("Non commit%s?", revs->pending.objects[i].name);2443if(sb->final)2444die("More than one commit to dig down to%sand%s?",2445 revs->pending.objects[i].name,2446 final_commit_name);2447 sb->final = (struct commit *) obj;2448 final_commit_name = revs->pending.objects[i].name;2449}2450if(!final_commit_name)2451die("No commit to dig down to?");2452returnxstrdup(final_commit_name);2453}24542455static intblame_copy_callback(const struct option *option,const char*arg,int unset)2456{2457int*opt = option->value;24582459/*2460 * -C enables copy from removed files;2461 * -C -C enables copy from existing files, but only2462 * when blaming a new file;2463 * -C -C -C enables copy from existing files for2464 * everybody2465 */2466if(*opt & PICKAXE_BLAME_COPY_HARDER)2467*opt |= PICKAXE_BLAME_COPY_HARDEST;2468if(*opt & PICKAXE_BLAME_COPY)2469*opt |= PICKAXE_BLAME_COPY_HARDER;2470*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;24712472if(arg)2473 blame_copy_score =parse_score(arg);2474return0;2475}24762477static intblame_move_callback(const struct option *option,const char*arg,int unset)2478{2479int*opt = option->value;24802481*opt |= PICKAXE_BLAME_MOVE;24822483if(arg)2484 blame_move_score =parse_score(arg);2485return0;2486}24872488intcmd_blame(int argc,const char**argv,const char*prefix)2489{2490struct rev_info revs;2491const char*path;2492struct scoreboard sb;2493struct origin *o;2494struct blame_entry *ent = NULL;2495long dashdash_pos, lno;2496char*final_commit_name = NULL;2497enum object_type type;24982499static struct string_list range_list;2500static int output_option =0, opt =0;2501static int show_stats =0;2502static const char*revs_file = NULL;2503static const char*contents_from = NULL;2504static const struct option options[] = {2505OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2506OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2507OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2508OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2509OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2510OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2511OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2512OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2513OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2514OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2515OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2516OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2517OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2518OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2519OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2520OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2521OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2522OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2523{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2524{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2525OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2526OPT__ABBREV(&abbrev),2527OPT_END()2528};25292530struct parse_opt_ctx_t ctx;2531int cmd_is_annotate = !strcmp(argv[0],"annotate");2532struct range_set ranges;2533unsigned int range_i;2534long anchor;25352536git_config(git_blame_config, &output_option);2537init_revisions(&revs, NULL);2538 revs.date_mode = blame_date_mode;2539DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2540DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25412542 save_commit_buffer =0;2543 dashdash_pos =0;25442545parse_options_start(&ctx, argc, argv, prefix, options,2546 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2547for(;;) {2548switch(parse_options_step(&ctx, options, blame_opt_usage)) {2549case PARSE_OPT_HELP:2550exit(129);2551case PARSE_OPT_DONE:2552if(ctx.argv[0])2553 dashdash_pos = ctx.cpidx;2554goto parse_done;2555}25562557if(!strcmp(ctx.argv[0],"--reverse")) {2558 ctx.argv[0] ="--children";2559 reverse =1;2560}2561parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2562}2563parse_done:2564 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2565DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2566 argc =parse_options_end(&ctx);25672568if(0< abbrev)2569/* one more abbrev length is needed for the boundary commit */2570 abbrev++;25712572if(revs_file &&read_ancestry(revs_file))2573die_errno("reading graft file '%s' failed", revs_file);25742575if(cmd_is_annotate) {2576 output_option |= OUTPUT_ANNOTATE_COMPAT;2577 blame_date_mode.type = DATE_ISO8601;2578}else{2579 blame_date_mode = revs.date_mode;2580}25812582/* The maximum width used to show the dates */2583switch(blame_date_mode.type) {2584case DATE_RFC2822:2585 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2586break;2587case DATE_ISO8601_STRICT:2588 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2589break;2590case DATE_ISO8601:2591 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2592break;2593case DATE_RAW:2594 blame_date_width =sizeof("1161298804 -0700");2595break;2596case DATE_SHORT:2597 blame_date_width =sizeof("2006-10-19");2598break;2599case DATE_RELATIVE:2600/* TRANSLATORS: This string is used to tell us the maximum2601 display width for a relative timestamp in "git blame"2602 output. For C locale, "4 years, 11 months ago", which2603 takes 22 places, is the longest among various forms of2604 relative timestamps, but your language may need more or2605 fewer display columns. */2606 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2607break;2608case DATE_LOCAL:2609case DATE_NORMAL:2610 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2611break;2612case DATE_STRFTIME:2613 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2614break;2615}2616 blame_date_width -=1;/* strip the null */26172618if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2619 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2620 PICKAXE_BLAME_COPY_HARDER);26212622if(!blame_move_score)2623 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2624if(!blame_copy_score)2625 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26262627/*2628 * We have collected options unknown to us in argv[1..unk]2629 * which are to be passed to revision machinery if we are2630 * going to do the "bottom" processing.2631 *2632 * The remaining are:2633 *2634 * (1) if dashdash_pos != 0, it is either2635 * "blame [revisions] -- <path>" or2636 * "blame -- <path> <rev>"2637 *2638 * (2) otherwise, it is one of the two:2639 * "blame [revisions] <path>"2640 * "blame <path> <rev>"2641 *2642 * Note that we must strip out <path> from the arguments: we do not2643 * want the path pruning but we may want "bottom" processing.2644 */2645if(dashdash_pos) {2646switch(argc - dashdash_pos -1) {2647case2:/* (1b) */2648if(argc !=4)2649usage_with_options(blame_opt_usage, options);2650/* reorder for the new way: <rev> -- <path> */2651 argv[1] = argv[3];2652 argv[3] = argv[2];2653 argv[2] ="--";2654/* FALLTHROUGH */2655case1:/* (1a) */2656 path =add_prefix(prefix, argv[--argc]);2657 argv[argc] = NULL;2658break;2659default:2660usage_with_options(blame_opt_usage, options);2661}2662}else{2663if(argc <2)2664usage_with_options(blame_opt_usage, options);2665 path =add_prefix(prefix, argv[argc -1]);2666if(argc ==3&& !file_exists(path)) {/* (2b) */2667 path =add_prefix(prefix, argv[1]);2668 argv[1] = argv[2];2669}2670 argv[argc -1] ="--";26712672setup_work_tree();2673if(!file_exists(path))2674die_errno("cannot stat path '%s'", path);2675}26762677 revs.disable_stdin =1;2678setup_revisions(argc, argv, &revs, NULL);2679memset(&sb,0,sizeof(sb));26802681 sb.revs = &revs;2682if(!reverse) {2683 final_commit_name =prepare_final(&sb);2684 sb.commits.compare = compare_commits_by_commit_date;2685}2686else if(contents_from)2687die("--contents and --children do not blend well.");2688else{2689 final_commit_name =prepare_initial(&sb);2690 sb.commits.compare = compare_commits_by_reverse_commit_date;2691}26922693if(!sb.final) {2694/*2695 * "--not A B -- path" without anything positive;2696 * do not default to HEAD, but use the working tree2697 * or "--contents".2698 */2699setup_work_tree();2700 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2701 path, contents_from);2702add_pending_object(&revs, &(sb.final->object),":");2703}2704else if(contents_from)2705die("Cannot use --contents with final commit object name");27062707/*2708 * If we have bottom, this will mark the ancestors of the2709 * bottom commits we would reach while traversing as2710 * uninteresting.2711 */2712if(prepare_revision_walk(&revs))2713die(_("revision walk setup failed"));27142715if(is_null_sha1(sb.final->object.sha1)) {2716 o = sb.final->util;2717 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2718 sb.final_buf_size = o->file.size;2719}2720else{2721 o =get_origin(&sb, sb.final, path);2722if(fill_blob_sha1_and_mode(o))2723die("no such path%sin%s", path, final_commit_name);27242725if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2726textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2727&sb.final_buf_size))2728;2729else2730 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2731&sb.final_buf_size);27322733if(!sb.final_buf)2734die("Cannot read blob%sfor path%s",2735sha1_to_hex(o->blob_sha1),2736 path);2737}2738 num_read_blob++;2739 lno =prepare_lines(&sb);27402741if(lno && !range_list.nr)2742string_list_append(&range_list,xstrdup("1"));27432744 anchor =1;2745range_set_init(&ranges, range_list.nr);2746for(range_i =0; range_i < range_list.nr; ++range_i) {2747long bottom, top;2748if(parse_range_arg(range_list.items[range_i].string,2749 nth_line_cb, &sb, lno, anchor,2750&bottom, &top, sb.path))2751usage(blame_usage);2752if(lno < top || ((lno || bottom) && lno < bottom))2753die("file%shas only%lu lines", path, lno);2754if(bottom <1)2755 bottom =1;2756if(top <1)2757 top = lno;2758 bottom--;2759range_set_append_unsafe(&ranges, bottom, top);2760 anchor = top +1;2761}2762sort_and_merge_range_set(&ranges);27632764for(range_i = ranges.nr; range_i >0; --range_i) {2765const struct range *r = &ranges.ranges[range_i -1];2766long bottom = r->start;2767long top = r->end;2768struct blame_entry *next = ent;2769 ent =xcalloc(1,sizeof(*ent));2770 ent->lno = bottom;2771 ent->num_lines = top - bottom;2772 ent->suspect = o;2773 ent->s_lno = bottom;2774 ent->next = next;2775origin_incref(o);2776}27772778 o->suspects = ent;2779prio_queue_put(&sb.commits, o->commit);27802781origin_decref(o);27822783range_set_release(&ranges);2784string_list_clear(&range_list,0);27852786 sb.ent = NULL;2787 sb.path = path;27882789read_mailmap(&mailmap, NULL);27902791if(!incremental)2792setup_pager();27932794assign_blame(&sb, opt);27952796free(final_commit_name);27972798if(incremental)2799return0;28002801 sb.ent =blame_sort(sb.ent, compare_blame_final);28022803coalesce(&sb);28042805if(!(output_option & OUTPUT_PORCELAIN))2806find_alignment(&sb, &output_option);28072808output(&sb, output_option);2809free((void*)sb.final_buf);2810for(ent = sb.ent; ent; ) {2811struct blame_entry *e = ent->next;2812free(ent);2813 ent = e;2814}28152816if(show_stats) {2817printf("num read blob:%d\n", num_read_blob);2818printf("num get patch:%d\n", num_get_patch);2819printf("num commits:%d\n", num_commits);2820}2821return0;2822}