1/* 2 * Blame 3 * 4 * Copyright (c) 2006, 2014 by its authors 5 * See COPYING for licensing conditions 6 */ 7 8#include"cache.h" 9#include"refs.h" 10#include"builtin.h" 11#include"blob.h" 12#include"commit.h" 13#include"tag.h" 14#include"tree-walk.h" 15#include"diff.h" 16#include"diffcore.h" 17#include"revision.h" 18#include"quote.h" 19#include"xdiff-interface.h" 20#include"cache-tree.h" 21#include"string-list.h" 22#include"mailmap.h" 23#include"mergesort.h" 24#include"parse-options.h" 25#include"prio-queue.h" 26#include"utf8.h" 27#include"userdiff.h" 28#include"line-range.h" 29#include"line-log.h" 30#include"dir.h" 31#include"progress.h" 32 33static char blame_usage[] =N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>"); 34 35static const char*blame_opt_usage[] = { 36 blame_usage, 37"", 38N_("<rev-opts> are documented in git-rev-list(1)"), 39 NULL 40}; 41 42static int longest_file; 43static int longest_author; 44static int max_orig_digits; 45static int max_digits; 46static int max_score_digits; 47static int show_root; 48static int reverse; 49static int blank_boundary; 50static int incremental; 51static int xdl_opts; 52static int abbrev = -1; 53static int no_whole_file_rename; 54static int show_progress; 55 56static struct date_mode blame_date_mode = { DATE_ISO8601 }; 57static size_t blame_date_width; 58 59static struct string_list mailmap; 60 61#ifndef DEBUG 62#define DEBUG 0 63#endif 64 65/* stats */ 66static int num_read_blob; 67static int num_get_patch; 68static int num_commits; 69 70#define PICKAXE_BLAME_MOVE 01 71#define PICKAXE_BLAME_COPY 02 72#define PICKAXE_BLAME_COPY_HARDER 04 73#define PICKAXE_BLAME_COPY_HARDEST 010 74 75/* 76 * blame for a blame_entry with score lower than these thresholds 77 * is not passed to the parent using move/copy logic. 78 */ 79static unsigned blame_move_score; 80static unsigned blame_copy_score; 81#define BLAME_DEFAULT_MOVE_SCORE 20 82#define BLAME_DEFAULT_COPY_SCORE 40 83 84/* Remember to update object flag allocation in object.h */ 85#define METAINFO_SHOWN (1u<<12) 86#define MORE_THAN_ONE_PATH (1u<<13) 87 88/* 89 * One blob in a commit that is being suspected 90 */ 91struct origin { 92int refcnt; 93/* Record preceding blame record for this blob */ 94struct origin *previous; 95/* origins are put in a list linked via `next' hanging off the 96 * corresponding commit's util field in order to make finding 97 * them fast. The presence in this chain does not count 98 * towards the origin's reference count. It is tempting to 99 * let it count as long as the commit is pending examination, 100 * but even under circumstances where the commit will be 101 * present multiple times in the priority queue of unexamined 102 * commits, processing the first instance will not leave any 103 * work requiring the origin data for the second instance. An 104 * interspersed commit changing that would have to be 105 * preexisting with a different ancestry and with the same 106 * commit date in order to wedge itself between two instances 107 * of the same commit in the priority queue _and_ produce 108 * blame entries relevant for it. While we don't want to let 109 * us get tripped up by this case, it certainly does not seem 110 * worth optimizing for. 111 */ 112struct origin *next; 113struct commit *commit; 114/* `suspects' contains blame entries that may be attributed to 115 * this origin's commit or to parent commits. When a commit 116 * is being processed, all suspects will be moved, either by 117 * assigning them to an origin in a different commit, or by 118 * shipping them to the scoreboard's ent list because they 119 * cannot be attributed to a different commit. 120 */ 121struct blame_entry *suspects; 122 mmfile_t file; 123unsigned char blob_sha1[20]; 124unsigned mode; 125/* guilty gets set when shipping any suspects to the final 126 * blame list instead of other commits 127 */ 128char guilty; 129char path[FLEX_ARRAY]; 130}; 131 132struct progress_info { 133struct progress *progress; 134int blamed_lines; 135}; 136 137static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b,long ctxlen, 138 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data) 139{ 140 xpparam_t xpp = {0}; 141 xdemitconf_t xecfg = {0}; 142 xdemitcb_t ecb = {NULL}; 143 144 xpp.flags = xdl_opts; 145 xecfg.ctxlen = ctxlen; 146 xecfg.hunk_func = hunk_func; 147 ecb.priv = cb_data; 148returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 149} 150 151/* 152 * Prepare diff_filespec and convert it using diff textconv API 153 * if the textconv driver exists. 154 * Return 1 if the conversion succeeds, 0 otherwise. 155 */ 156inttextconv_object(const char*path, 157unsigned mode, 158const unsigned char*sha1, 159int sha1_valid, 160char**buf, 161unsigned long*buf_size) 162{ 163struct diff_filespec *df; 164struct userdiff_driver *textconv; 165 166 df =alloc_filespec(path); 167fill_filespec(df, sha1, sha1_valid, mode); 168 textconv =get_textconv(df); 169if(!textconv) { 170free_filespec(df); 171return0; 172} 173 174*buf_size =fill_textconv(textconv, df, buf); 175free_filespec(df); 176return1; 177} 178 179/* 180 * Given an origin, prepare mmfile_t structure to be used by the 181 * diff machinery 182 */ 183static voidfill_origin_blob(struct diff_options *opt, 184struct origin *o, mmfile_t *file) 185{ 186if(!o->file.ptr) { 187enum object_type type; 188unsigned long file_size; 189 190 num_read_blob++; 191if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 192textconv_object(o->path, o->mode, o->blob_sha1,1, &file->ptr, &file_size)) 193; 194else 195 file->ptr =read_sha1_file(o->blob_sha1, &type, &file_size); 196 file->size = file_size; 197 198if(!file->ptr) 199die("Cannot read blob%sfor path%s", 200sha1_to_hex(o->blob_sha1), 201 o->path); 202 o->file = *file; 203} 204else 205*file = o->file; 206} 207 208/* 209 * Origin is refcounted and usually we keep the blob contents to be 210 * reused. 211 */ 212staticinlinestruct origin *origin_incref(struct origin *o) 213{ 214if(o) 215 o->refcnt++; 216return o; 217} 218 219static voidorigin_decref(struct origin *o) 220{ 221if(o && --o->refcnt <=0) { 222struct origin *p, *l = NULL; 223if(o->previous) 224origin_decref(o->previous); 225free(o->file.ptr); 226/* Should be present exactly once in commit chain */ 227for(p = o->commit->util; p; l = p, p = p->next) { 228if(p == o) { 229if(l) 230 l->next = p->next; 231else 232 o->commit->util = p->next; 233free(o); 234return; 235} 236} 237die("internal error in blame::origin_decref"); 238} 239} 240 241static voiddrop_origin_blob(struct origin *o) 242{ 243if(o->file.ptr) { 244free(o->file.ptr); 245 o->file.ptr = NULL; 246} 247} 248 249/* 250 * Each group of lines is described by a blame_entry; it can be split 251 * as we pass blame to the parents. They are arranged in linked lists 252 * kept as `suspects' of some unprocessed origin, or entered (when the 253 * blame origin has been finalized) into the scoreboard structure. 254 * While the scoreboard structure is only sorted at the end of 255 * processing (according to final image line number), the lists 256 * attached to an origin are sorted by the target line number. 257 */ 258struct blame_entry { 259struct blame_entry *next; 260 261/* the first line of this group in the final image; 262 * internally all line numbers are 0 based. 263 */ 264int lno; 265 266/* how many lines this group has */ 267int num_lines; 268 269/* the commit that introduced this group into the final image */ 270struct origin *suspect; 271 272/* the line number of the first line of this group in the 273 * suspect's file; internally all line numbers are 0 based. 274 */ 275int s_lno; 276 277/* how significant this entry is -- cached to avoid 278 * scanning the lines over and over. 279 */ 280unsigned score; 281}; 282 283/* 284 * Any merge of blames happens on lists of blames that arrived via 285 * different parents in a single suspect. In this case, we want to 286 * sort according to the suspect line numbers as opposed to the final 287 * image line numbers. The function body is somewhat longish because 288 * it avoids unnecessary writes. 289 */ 290 291static struct blame_entry *blame_merge(struct blame_entry *list1, 292struct blame_entry *list2) 293{ 294struct blame_entry *p1 = list1, *p2 = list2, 295**tail = &list1; 296 297if(!p1) 298return p2; 299if(!p2) 300return p1; 301 302if(p1->s_lno <= p2->s_lno) { 303do{ 304 tail = &p1->next; 305if((p1 = *tail) == NULL) { 306*tail = p2; 307return list1; 308} 309}while(p1->s_lno <= p2->s_lno); 310} 311for(;;) { 312*tail = p2; 313do{ 314 tail = &p2->next; 315if((p2 = *tail) == NULL) { 316*tail = p1; 317return list1; 318} 319}while(p1->s_lno > p2->s_lno); 320*tail = p1; 321do{ 322 tail = &p1->next; 323if((p1 = *tail) == NULL) { 324*tail = p2; 325return list1; 326} 327}while(p1->s_lno <= p2->s_lno); 328} 329} 330 331static void*get_next_blame(const void*p) 332{ 333return((struct blame_entry *)p)->next; 334} 335 336static voidset_next_blame(void*p1,void*p2) 337{ 338((struct blame_entry *)p1)->next = p2; 339} 340 341/* 342 * Final image line numbers are all different, so we don't need a 343 * three-way comparison here. 344 */ 345 346static intcompare_blame_final(const void*p1,const void*p2) 347{ 348return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 349?1: -1; 350} 351 352static intcompare_blame_suspect(const void*p1,const void*p2) 353{ 354const struct blame_entry *s1 = p1, *s2 = p2; 355/* 356 * to allow for collating suspects, we sort according to the 357 * respective pointer value as the primary sorting criterion. 358 * The actual relation is pretty unimportant as long as it 359 * establishes a total order. Comparing as integers gives us 360 * that. 361 */ 362if(s1->suspect != s2->suspect) 363return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 364if(s1->s_lno == s2->s_lno) 365return0; 366return s1->s_lno > s2->s_lno ?1: -1; 367} 368 369static struct blame_entry *blame_sort(struct blame_entry *head, 370int(*compare_fn)(const void*,const void*)) 371{ 372returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 373} 374 375static intcompare_commits_by_reverse_commit_date(const void*a, 376const void*b, 377void*c) 378{ 379return-compare_commits_by_commit_date(a, b, c); 380} 381 382/* 383 * The current state of the blame assignment. 384 */ 385struct scoreboard { 386/* the final commit (i.e. where we started digging from) */ 387struct commit *final; 388/* Priority queue for commits with unassigned blame records */ 389struct prio_queue commits; 390struct rev_info *revs; 391const char*path; 392 393/* 394 * The contents in the final image. 395 * Used by many functions to obtain contents of the nth line, 396 * indexed with scoreboard.lineno[blame_entry.lno]. 397 */ 398const char*final_buf; 399unsigned long final_buf_size; 400 401/* linked list of blames */ 402struct blame_entry *ent; 403 404/* look-up a line in the final buffer */ 405int num_lines; 406int*lineno; 407}; 408 409static voidsanity_check_refcnt(struct scoreboard *); 410 411/* 412 * If two blame entries that are next to each other came from 413 * contiguous lines in the same origin (i.e. <commit, path> pair), 414 * merge them together. 415 */ 416static voidcoalesce(struct scoreboard *sb) 417{ 418struct blame_entry *ent, *next; 419 420for(ent = sb->ent; ent && (next = ent->next); ent = next) { 421if(ent->suspect == next->suspect && 422 ent->s_lno + ent->num_lines == next->s_lno) { 423 ent->num_lines += next->num_lines; 424 ent->next = next->next; 425origin_decref(next->suspect); 426free(next); 427 ent->score =0; 428 next = ent;/* again */ 429} 430} 431 432if(DEBUG)/* sanity */ 433sanity_check_refcnt(sb); 434} 435 436/* 437 * Merge the given sorted list of blames into a preexisting origin. 438 * If there were no previous blames to that commit, it is entered into 439 * the commit priority queue of the score board. 440 */ 441 442static voidqueue_blames(struct scoreboard *sb,struct origin *porigin, 443struct blame_entry *sorted) 444{ 445if(porigin->suspects) 446 porigin->suspects =blame_merge(porigin->suspects, sorted); 447else{ 448struct origin *o; 449for(o = porigin->commit->util; o; o = o->next) { 450if(o->suspects) { 451 porigin->suspects = sorted; 452return; 453} 454} 455 porigin->suspects = sorted; 456prio_queue_put(&sb->commits, porigin->commit); 457} 458} 459 460/* 461 * Given a commit and a path in it, create a new origin structure. 462 * The callers that add blame to the scoreboard should use 463 * get_origin() to obtain shared, refcounted copy instead of calling 464 * this function directly. 465 */ 466static struct origin *make_origin(struct commit *commit,const char*path) 467{ 468struct origin *o; 469FLEX_ALLOC_STR(o, path, path); 470 o->commit = commit; 471 o->refcnt =1; 472 o->next = commit->util; 473 commit->util = o; 474return o; 475} 476 477/* 478 * Locate an existing origin or create a new one. 479 * This moves the origin to front position in the commit util list. 480 */ 481static struct origin *get_origin(struct scoreboard *sb, 482struct commit *commit, 483const char*path) 484{ 485struct origin *o, *l; 486 487for(o = commit->util, l = NULL; o; l = o, o = o->next) { 488if(!strcmp(o->path, path)) { 489/* bump to front */ 490if(l) { 491 l->next = o->next; 492 o->next = commit->util; 493 commit->util = o; 494} 495returnorigin_incref(o); 496} 497} 498returnmake_origin(commit, path); 499} 500 501/* 502 * Fill the blob_sha1 field of an origin if it hasn't, so that later 503 * call to fill_origin_blob() can use it to locate the data. blob_sha1 504 * for an origin is also used to pass the blame for the entire file to 505 * the parent to detect the case where a child's blob is identical to 506 * that of its parent's. 507 * 508 * This also fills origin->mode for corresponding tree path. 509 */ 510static intfill_blob_sha1_and_mode(struct origin *origin) 511{ 512if(!is_null_sha1(origin->blob_sha1)) 513return0; 514if(get_tree_entry(origin->commit->object.oid.hash, 515 origin->path, 516 origin->blob_sha1, &origin->mode)) 517goto error_out; 518if(sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB) 519goto error_out; 520return0; 521 error_out: 522hashclr(origin->blob_sha1); 523 origin->mode = S_IFINVALID; 524return-1; 525} 526 527/* 528 * We have an origin -- check if the same path exists in the 529 * parent and return an origin structure to represent it. 530 */ 531static struct origin *find_origin(struct scoreboard *sb, 532struct commit *parent, 533struct origin *origin) 534{ 535struct origin *porigin; 536struct diff_options diff_opts; 537const char*paths[2]; 538 539/* First check any existing origins */ 540for(porigin = parent->util; porigin; porigin = porigin->next) 541if(!strcmp(porigin->path, origin->path)) { 542/* 543 * The same path between origin and its parent 544 * without renaming -- the most common case. 545 */ 546returnorigin_incref(porigin); 547} 548 549/* See if the origin->path is different between parent 550 * and origin first. Most of the time they are the 551 * same and diff-tree is fairly efficient about this. 552 */ 553diff_setup(&diff_opts); 554DIFF_OPT_SET(&diff_opts, RECURSIVE); 555 diff_opts.detect_rename =0; 556 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 557 paths[0] = origin->path; 558 paths[1] = NULL; 559 560parse_pathspec(&diff_opts.pathspec, 561 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 562 PATHSPEC_LITERAL_PATH,"", paths); 563diff_setup_done(&diff_opts); 564 565if(is_null_oid(&origin->commit->object.oid)) 566do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 567else 568diff_tree_sha1(parent->tree->object.oid.hash, 569 origin->commit->tree->object.oid.hash, 570"", &diff_opts); 571diffcore_std(&diff_opts); 572 573if(!diff_queued_diff.nr) { 574/* The path is the same as parent */ 575 porigin =get_origin(sb, parent, origin->path); 576hashcpy(porigin->blob_sha1, origin->blob_sha1); 577 porigin->mode = origin->mode; 578}else{ 579/* 580 * Since origin->path is a pathspec, if the parent 581 * commit had it as a directory, we will see a whole 582 * bunch of deletion of files in the directory that we 583 * do not care about. 584 */ 585int i; 586struct diff_filepair *p = NULL; 587for(i =0; i < diff_queued_diff.nr; i++) { 588const char*name; 589 p = diff_queued_diff.queue[i]; 590 name = p->one->path ? p->one->path : p->two->path; 591if(!strcmp(name, origin->path)) 592break; 593} 594if(!p) 595die("internal error in blame::find_origin"); 596switch(p->status) { 597default: 598die("internal error in blame::find_origin (%c)", 599 p->status); 600case'M': 601 porigin =get_origin(sb, parent, origin->path); 602hashcpy(porigin->blob_sha1, p->one->sha1); 603 porigin->mode = p->one->mode; 604break; 605case'A': 606case'T': 607/* Did not exist in parent, or type changed */ 608break; 609} 610} 611diff_flush(&diff_opts); 612free_pathspec(&diff_opts.pathspec); 613return porigin; 614} 615 616/* 617 * We have an origin -- find the path that corresponds to it in its 618 * parent and return an origin structure to represent it. 619 */ 620static struct origin *find_rename(struct scoreboard *sb, 621struct commit *parent, 622struct origin *origin) 623{ 624struct origin *porigin = NULL; 625struct diff_options diff_opts; 626int i; 627 628diff_setup(&diff_opts); 629DIFF_OPT_SET(&diff_opts, RECURSIVE); 630 diff_opts.detect_rename = DIFF_DETECT_RENAME; 631 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 632 diff_opts.single_follow = origin->path; 633diff_setup_done(&diff_opts); 634 635if(is_null_oid(&origin->commit->object.oid)) 636do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 637else 638diff_tree_sha1(parent->tree->object.oid.hash, 639 origin->commit->tree->object.oid.hash, 640"", &diff_opts); 641diffcore_std(&diff_opts); 642 643for(i =0; i < diff_queued_diff.nr; i++) { 644struct diff_filepair *p = diff_queued_diff.queue[i]; 645if((p->status =='R'|| p->status =='C') && 646!strcmp(p->two->path, origin->path)) { 647 porigin =get_origin(sb, parent, p->one->path); 648hashcpy(porigin->blob_sha1, p->one->sha1); 649 porigin->mode = p->one->mode; 650break; 651} 652} 653diff_flush(&diff_opts); 654free_pathspec(&diff_opts.pathspec); 655return porigin; 656} 657 658/* 659 * Append a new blame entry to a given output queue. 660 */ 661static voidadd_blame_entry(struct blame_entry ***queue,struct blame_entry *e) 662{ 663origin_incref(e->suspect); 664 665 e->next = **queue; 666**queue = e; 667*queue = &e->next; 668} 669 670/* 671 * src typically is on-stack; we want to copy the information in it to 672 * a malloced blame_entry that gets added to the given queue. The 673 * origin of dst loses a refcnt. 674 */ 675static voiddup_entry(struct blame_entry ***queue, 676struct blame_entry *dst,struct blame_entry *src) 677{ 678origin_incref(src->suspect); 679origin_decref(dst->suspect); 680memcpy(dst, src,sizeof(*src)); 681 dst->next = **queue; 682**queue = dst; 683*queue = &dst->next; 684} 685 686static const char*nth_line(struct scoreboard *sb,long lno) 687{ 688return sb->final_buf + sb->lineno[lno]; 689} 690 691static const char*nth_line_cb(void*data,long lno) 692{ 693returnnth_line((struct scoreboard *)data, lno); 694} 695 696/* 697 * It is known that lines between tlno to same came from parent, and e 698 * has an overlap with that range. it also is known that parent's 699 * line plno corresponds to e's line tlno. 700 * 701 * <---- e -----> 702 * <------> 703 * <------------> 704 * <------------> 705 * <------------------> 706 * 707 * Split e into potentially three parts; before this chunk, the chunk 708 * to be blamed for the parent, and after that portion. 709 */ 710static voidsplit_overlap(struct blame_entry *split, 711struct blame_entry *e, 712int tlno,int plno,int same, 713struct origin *parent) 714{ 715int chunk_end_lno; 716memset(split,0,sizeof(struct blame_entry [3])); 717 718if(e->s_lno < tlno) { 719/* there is a pre-chunk part not blamed on parent */ 720 split[0].suspect =origin_incref(e->suspect); 721 split[0].lno = e->lno; 722 split[0].s_lno = e->s_lno; 723 split[0].num_lines = tlno - e->s_lno; 724 split[1].lno = e->lno + tlno - e->s_lno; 725 split[1].s_lno = plno; 726} 727else{ 728 split[1].lno = e->lno; 729 split[1].s_lno = plno + (e->s_lno - tlno); 730} 731 732if(same < e->s_lno + e->num_lines) { 733/* there is a post-chunk part not blamed on parent */ 734 split[2].suspect =origin_incref(e->suspect); 735 split[2].lno = e->lno + (same - e->s_lno); 736 split[2].s_lno = e->s_lno + (same - e->s_lno); 737 split[2].num_lines = e->s_lno + e->num_lines - same; 738 chunk_end_lno = split[2].lno; 739} 740else 741 chunk_end_lno = e->lno + e->num_lines; 742 split[1].num_lines = chunk_end_lno - split[1].lno; 743 744/* 745 * if it turns out there is nothing to blame the parent for, 746 * forget about the splitting. !split[1].suspect signals this. 747 */ 748if(split[1].num_lines <1) 749return; 750 split[1].suspect =origin_incref(parent); 751} 752 753/* 754 * split_overlap() divided an existing blame e into up to three parts 755 * in split. Any assigned blame is moved to queue to 756 * reflect the split. 757 */ 758static voidsplit_blame(struct blame_entry ***blamed, 759struct blame_entry ***unblamed, 760struct blame_entry *split, 761struct blame_entry *e) 762{ 763struct blame_entry *new_entry; 764 765if(split[0].suspect && split[2].suspect) { 766/* The first part (reuse storage for the existing entry e) */ 767dup_entry(unblamed, e, &split[0]); 768 769/* The last part -- me */ 770 new_entry =xmalloc(sizeof(*new_entry)); 771memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 772add_blame_entry(unblamed, new_entry); 773 774/* ... and the middle part -- parent */ 775 new_entry =xmalloc(sizeof(*new_entry)); 776memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 777add_blame_entry(blamed, new_entry); 778} 779else if(!split[0].suspect && !split[2].suspect) 780/* 781 * The parent covers the entire area; reuse storage for 782 * e and replace it with the parent. 783 */ 784dup_entry(blamed, e, &split[1]); 785else if(split[0].suspect) { 786/* me and then parent */ 787dup_entry(unblamed, e, &split[0]); 788 789 new_entry =xmalloc(sizeof(*new_entry)); 790memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 791add_blame_entry(blamed, new_entry); 792} 793else{ 794/* parent and then me */ 795dup_entry(blamed, e, &split[1]); 796 797 new_entry =xmalloc(sizeof(*new_entry)); 798memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 799add_blame_entry(unblamed, new_entry); 800} 801} 802 803/* 804 * After splitting the blame, the origins used by the 805 * on-stack blame_entry should lose one refcnt each. 806 */ 807static voiddecref_split(struct blame_entry *split) 808{ 809int i; 810 811for(i =0; i <3; i++) 812origin_decref(split[i].suspect); 813} 814 815/* 816 * reverse_blame reverses the list given in head, appending tail. 817 * That allows us to build lists in reverse order, then reverse them 818 * afterwards. This can be faster than building the list in proper 819 * order right away. The reason is that building in proper order 820 * requires writing a link in the _previous_ element, while building 821 * in reverse order just requires placing the list head into the 822 * _current_ element. 823 */ 824 825static struct blame_entry *reverse_blame(struct blame_entry *head, 826struct blame_entry *tail) 827{ 828while(head) { 829struct blame_entry *next = head->next; 830 head->next = tail; 831 tail = head; 832 head = next; 833} 834return tail; 835} 836 837/* 838 * Process one hunk from the patch between the current suspect for 839 * blame_entry e and its parent. This first blames any unfinished 840 * entries before the chunk (which is where target and parent start 841 * differing) on the parent, and then splits blame entries at the 842 * start and at the end of the difference region. Since use of -M and 843 * -C options may lead to overlapping/duplicate source line number 844 * ranges, all we can rely on from sorting/merging is the order of the 845 * first suspect line number. 846 */ 847static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 848int tlno,int offset,int same, 849struct origin *parent) 850{ 851struct blame_entry *e = **srcq; 852struct blame_entry *samep = NULL, *diffp = NULL; 853 854while(e && e->s_lno < tlno) { 855struct blame_entry *next = e->next; 856/* 857 * current record starts before differing portion. If 858 * it reaches into it, we need to split it up and 859 * examine the second part separately. 860 */ 861if(e->s_lno + e->num_lines > tlno) { 862/* Move second half to a new record */ 863int len = tlno - e->s_lno; 864struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 865 n->suspect = e->suspect; 866 n->lno = e->lno + len; 867 n->s_lno = e->s_lno + len; 868 n->num_lines = e->num_lines - len; 869 e->num_lines = len; 870 e->score =0; 871/* Push new record to diffp */ 872 n->next = diffp; 873 diffp = n; 874}else 875origin_decref(e->suspect); 876/* Pass blame for everything before the differing 877 * chunk to the parent */ 878 e->suspect =origin_incref(parent); 879 e->s_lno += offset; 880 e->next = samep; 881 samep = e; 882 e = next; 883} 884/* 885 * As we don't know how much of a common stretch after this 886 * diff will occur, the currently blamed parts are all that we 887 * can assign to the parent for now. 888 */ 889 890if(samep) { 891**dstq =reverse_blame(samep, **dstq); 892*dstq = &samep->next; 893} 894/* 895 * Prepend the split off portions: everything after e starts 896 * after the blameable portion. 897 */ 898 e =reverse_blame(diffp, e); 899 900/* 901 * Now retain records on the target while parts are different 902 * from the parent. 903 */ 904 samep = NULL; 905 diffp = NULL; 906while(e && e->s_lno < same) { 907struct blame_entry *next = e->next; 908 909/* 910 * If current record extends into sameness, need to split. 911 */ 912if(e->s_lno + e->num_lines > same) { 913/* 914 * Move second half to a new record to be 915 * processed by later chunks 916 */ 917int len = same - e->s_lno; 918struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 919 n->suspect =origin_incref(e->suspect); 920 n->lno = e->lno + len; 921 n->s_lno = e->s_lno + len; 922 n->num_lines = e->num_lines - len; 923 e->num_lines = len; 924 e->score =0; 925/* Push new record to samep */ 926 n->next = samep; 927 samep = n; 928} 929 e->next = diffp; 930 diffp = e; 931 e = next; 932} 933**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 934/* Move across elements that are in the unblamable portion */ 935if(diffp) 936*srcq = &diffp->next; 937} 938 939struct blame_chunk_cb_data { 940struct origin *parent; 941long offset; 942struct blame_entry **dstq; 943struct blame_entry **srcq; 944}; 945 946/* diff chunks are from parent to target */ 947static intblame_chunk_cb(long start_a,long count_a, 948long start_b,long count_b,void*data) 949{ 950struct blame_chunk_cb_data *d = data; 951if(start_a - start_b != d->offset) 952die("internal error in blame::blame_chunk_cb"); 953blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 954 start_b + count_b, d->parent); 955 d->offset = start_a + count_a - (start_b + count_b); 956return0; 957} 958 959/* 960 * We are looking at the origin 'target' and aiming to pass blame 961 * for the lines it is suspected to its parent. Run diff to find 962 * which lines came from parent and pass blame for them. 963 */ 964static voidpass_blame_to_parent(struct scoreboard *sb, 965struct origin *target, 966struct origin *parent) 967{ 968 mmfile_t file_p, file_o; 969struct blame_chunk_cb_data d; 970struct blame_entry *newdest = NULL; 971 972if(!target->suspects) 973return;/* nothing remains for this target */ 974 975 d.parent = parent; 976 d.offset =0; 977 d.dstq = &newdest; d.srcq = &target->suspects; 978 979fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 980fill_origin_blob(&sb->revs->diffopt, target, &file_o); 981 num_get_patch++; 982 983if(diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d)) 984die("unable to generate diff (%s->%s)", 985oid_to_hex(&parent->commit->object.oid), 986oid_to_hex(&target->commit->object.oid)); 987/* The rest are the same as the parent */ 988blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 989*d.dstq = NULL; 990queue_blames(sb, parent, newdest); 991 992return; 993} 994 995/* 996 * The lines in blame_entry after splitting blames many times can become 997 * very small and trivial, and at some point it becomes pointless to 998 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 999 * ordinary C program, and it is not worth to say it was copied from1000 * totally unrelated file in the parent.1001 *1002 * Compute how trivial the lines in the blame_entry are.1003 */1004static unsignedent_score(struct scoreboard *sb,struct blame_entry *e)1005{1006unsigned score;1007const char*cp, *ep;10081009if(e->score)1010return e->score;10111012 score =1;1013 cp =nth_line(sb, e->lno);1014 ep =nth_line(sb, e->lno + e->num_lines);1015while(cp < ep) {1016unsigned ch = *((unsigned char*)cp);1017if(isalnum(ch))1018 score++;1019 cp++;1020}1021 e->score = score;1022return score;1023}10241025/*1026 * best_so_far[] and this[] are both a split of an existing blame_entry1027 * that passes blame to the parent. Maintain best_so_far the best split1028 * so far, by comparing this and best_so_far and copying this into1029 * bst_so_far as needed.1030 */1031static voidcopy_split_if_better(struct scoreboard *sb,1032struct blame_entry *best_so_far,1033struct blame_entry *this)1034{1035int i;10361037if(!this[1].suspect)1038return;1039if(best_so_far[1].suspect) {1040if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1041return;1042}10431044for(i =0; i <3; i++)1045origin_incref(this[i].suspect);1046decref_split(best_so_far);1047memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1048}10491050/*1051 * We are looking at a part of the final image represented by1052 * ent (tlno and same are offset by ent->s_lno).1053 * tlno is where we are looking at in the final image.1054 * up to (but not including) same match preimage.1055 * plno is where we are looking at in the preimage.1056 *1057 * <-------------- final image ---------------------->1058 * <------ent------>1059 * ^tlno ^same1060 * <---------preimage----->1061 * ^plno1062 *1063 * All line numbers are 0-based.1064 */1065static voidhandle_split(struct scoreboard *sb,1066struct blame_entry *ent,1067int tlno,int plno,int same,1068struct origin *parent,1069struct blame_entry *split)1070{1071if(ent->num_lines <= tlno)1072return;1073if(tlno < same) {1074struct blame_entry this[3];1075 tlno += ent->s_lno;1076 same += ent->s_lno;1077split_overlap(this, ent, tlno, plno, same, parent);1078copy_split_if_better(sb, split,this);1079decref_split(this);1080}1081}10821083struct handle_split_cb_data {1084struct scoreboard *sb;1085struct blame_entry *ent;1086struct origin *parent;1087struct blame_entry *split;1088long plno;1089long tlno;1090};10911092static inthandle_split_cb(long start_a,long count_a,1093long start_b,long count_b,void*data)1094{1095struct handle_split_cb_data *d = data;1096handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1097 d->split);1098 d->plno = start_a + count_a;1099 d->tlno = start_b + count_b;1100return0;1101}11021103/*1104 * Find the lines from parent that are the same as ent so that1105 * we can pass blames to it. file_p has the blob contents for1106 * the parent.1107 */1108static voidfind_copy_in_blob(struct scoreboard *sb,1109struct blame_entry *ent,1110struct origin *parent,1111struct blame_entry *split,1112 mmfile_t *file_p)1113{1114const char*cp;1115 mmfile_t file_o;1116struct handle_split_cb_data d;11171118memset(&d,0,sizeof(d));1119 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1120/*1121 * Prepare mmfile that contains only the lines in ent.1122 */1123 cp =nth_line(sb, ent->lno);1124 file_o.ptr = (char*) cp;1125 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11261127/*1128 * file_o is a part of final image we are annotating.1129 * file_p partially may match that image.1130 */1131memset(split,0,sizeof(struct blame_entry [3]));1132if(diff_hunks(file_p, &file_o,1, handle_split_cb, &d))1133die("unable to generate diff (%s)",1134oid_to_hex(&parent->commit->object.oid));1135/* remainder, if any, all match the preimage */1136handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1137}11381139/* Move all blame entries from list *source that have a score smaller1140 * than score_min to the front of list *small.1141 * Returns a pointer to the link pointing to the old head of the small list.1142 */11431144static struct blame_entry **filter_small(struct scoreboard *sb,1145struct blame_entry **small,1146struct blame_entry **source,1147unsigned score_min)1148{1149struct blame_entry *p = *source;1150struct blame_entry *oldsmall = *small;1151while(p) {1152if(ent_score(sb, p) <= score_min) {1153*small = p;1154 small = &p->next;1155 p = *small;1156}else{1157*source = p;1158 source = &p->next;1159 p = *source;1160}1161}1162*small = oldsmall;1163*source = NULL;1164return small;1165}11661167/*1168 * See if lines currently target is suspected for can be attributed to1169 * parent.1170 */1171static voidfind_move_in_parent(struct scoreboard *sb,1172struct blame_entry ***blamed,1173struct blame_entry **toosmall,1174struct origin *target,1175struct origin *parent)1176{1177struct blame_entry *e, split[3];1178struct blame_entry *unblamed = target->suspects;1179struct blame_entry *leftover = NULL;1180 mmfile_t file_p;11811182if(!unblamed)1183return;/* nothing remains for this target */11841185fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1186if(!file_p.ptr)1187return;11881189/* At each iteration, unblamed has a NULL-terminated list of1190 * entries that have not yet been tested for blame. leftover1191 * contains the reversed list of entries that have been tested1192 * without being assignable to the parent.1193 */1194do{1195struct blame_entry **unblamedtail = &unblamed;1196struct blame_entry *next;1197for(e = unblamed; e; e = next) {1198 next = e->next;1199find_copy_in_blob(sb, e, parent, split, &file_p);1200if(split[1].suspect &&1201 blame_move_score <ent_score(sb, &split[1])) {1202split_blame(blamed, &unblamedtail, split, e);1203}else{1204 e->next = leftover;1205 leftover = e;1206}1207decref_split(split);1208}1209*unblamedtail = NULL;1210 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1211}while(unblamed);1212 target->suspects =reverse_blame(leftover, NULL);1213}12141215struct blame_list {1216struct blame_entry *ent;1217struct blame_entry split[3];1218};12191220/*1221 * Count the number of entries the target is suspected for,1222 * and prepare a list of entry and the best split.1223 */1224static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1225int*num_ents_p)1226{1227struct blame_entry *e;1228int num_ents, i;1229struct blame_list *blame_list = NULL;12301231for(e = unblamed, num_ents =0; e; e = e->next)1232 num_ents++;1233if(num_ents) {1234 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1235for(e = unblamed, i =0; e; e = e->next)1236 blame_list[i++].ent = e;1237}1238*num_ents_p = num_ents;1239return blame_list;1240}12411242/*1243 * For lines target is suspected for, see if we can find code movement1244 * across file boundary from the parent commit. porigin is the path1245 * in the parent we already tried.1246 */1247static voidfind_copy_in_parent(struct scoreboard *sb,1248struct blame_entry ***blamed,1249struct blame_entry **toosmall,1250struct origin *target,1251struct commit *parent,1252struct origin *porigin,1253int opt)1254{1255struct diff_options diff_opts;1256int i, j;1257struct blame_list *blame_list;1258int num_ents;1259struct blame_entry *unblamed = target->suspects;1260struct blame_entry *leftover = NULL;12611262if(!unblamed)1263return;/* nothing remains for this target */12641265diff_setup(&diff_opts);1266DIFF_OPT_SET(&diff_opts, RECURSIVE);1267 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12681269diff_setup_done(&diff_opts);12701271/* Try "find copies harder" on new path if requested;1272 * we do not want to use diffcore_rename() actually to1273 * match things up; find_copies_harder is set only to1274 * force diff_tree_sha1() to feed all filepairs to diff_queue,1275 * and this code needs to be after diff_setup_done(), which1276 * usually makes find-copies-harder imply copy detection.1277 */1278if((opt & PICKAXE_BLAME_COPY_HARDEST)1279|| ((opt & PICKAXE_BLAME_COPY_HARDER)1280&& (!porigin ||strcmp(target->path, porigin->path))))1281DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12821283if(is_null_oid(&target->commit->object.oid))1284do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1285else1286diff_tree_sha1(parent->tree->object.oid.hash,1287 target->commit->tree->object.oid.hash,1288"", &diff_opts);12891290if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1291diffcore_std(&diff_opts);12921293do{1294struct blame_entry **unblamedtail = &unblamed;1295 blame_list =setup_blame_list(unblamed, &num_ents);12961297for(i =0; i < diff_queued_diff.nr; i++) {1298struct diff_filepair *p = diff_queued_diff.queue[i];1299struct origin *norigin;1300 mmfile_t file_p;1301struct blame_entry this[3];13021303if(!DIFF_FILE_VALID(p->one))1304continue;/* does not exist in parent */1305if(S_ISGITLINK(p->one->mode))1306continue;/* ignore git links */1307if(porigin && !strcmp(p->one->path, porigin->path))1308/* find_move already dealt with this path */1309continue;13101311 norigin =get_origin(sb, parent, p->one->path);1312hashcpy(norigin->blob_sha1, p->one->sha1);1313 norigin->mode = p->one->mode;1314fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1315if(!file_p.ptr)1316continue;13171318for(j =0; j < num_ents; j++) {1319find_copy_in_blob(sb, blame_list[j].ent,1320 norigin,this, &file_p);1321copy_split_if_better(sb, blame_list[j].split,1322this);1323decref_split(this);1324}1325origin_decref(norigin);1326}13271328for(j =0; j < num_ents; j++) {1329struct blame_entry *split = blame_list[j].split;1330if(split[1].suspect &&1331 blame_copy_score <ent_score(sb, &split[1])) {1332split_blame(blamed, &unblamedtail, split,1333 blame_list[j].ent);1334}else{1335 blame_list[j].ent->next = leftover;1336 leftover = blame_list[j].ent;1337}1338decref_split(split);1339}1340free(blame_list);1341*unblamedtail = NULL;1342 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1343}while(unblamed);1344 target->suspects =reverse_blame(leftover, NULL);1345diff_flush(&diff_opts);1346free_pathspec(&diff_opts.pathspec);1347}13481349/*1350 * The blobs of origin and porigin exactly match, so everything1351 * origin is suspected for can be blamed on the parent.1352 */1353static voidpass_whole_blame(struct scoreboard *sb,1354struct origin *origin,struct origin *porigin)1355{1356struct blame_entry *e, *suspects;13571358if(!porigin->file.ptr && origin->file.ptr) {1359/* Steal its file */1360 porigin->file = origin->file;1361 origin->file.ptr = NULL;1362}1363 suspects = origin->suspects;1364 origin->suspects = NULL;1365for(e = suspects; e; e = e->next) {1366origin_incref(porigin);1367origin_decref(e->suspect);1368 e->suspect = porigin;1369}1370queue_blames(sb, porigin, suspects);1371}13721373/*1374 * We pass blame from the current commit to its parents. We keep saying1375 * "parent" (and "porigin"), but what we mean is to find scapegoat to1376 * exonerate ourselves.1377 */1378static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1379{1380if(!reverse) {1381if(revs->first_parent_only &&1382 commit->parents &&1383 commit->parents->next) {1384free_commit_list(commit->parents->next);1385 commit->parents->next = NULL;1386}1387return commit->parents;1388}1389returnlookup_decoration(&revs->children, &commit->object);1390}13911392static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1393{1394struct commit_list *l =first_scapegoat(revs, commit);1395returncommit_list_count(l);1396}13971398/* Distribute collected unsorted blames to the respected sorted lists1399 * in the various origins.1400 */1401static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1402{1403 blamed =blame_sort(blamed, compare_blame_suspect);1404while(blamed)1405{1406struct origin *porigin = blamed->suspect;1407struct blame_entry *suspects = NULL;1408do{1409struct blame_entry *next = blamed->next;1410 blamed->next = suspects;1411 suspects = blamed;1412 blamed = next;1413}while(blamed && blamed->suspect == porigin);1414 suspects =reverse_blame(suspects, NULL);1415queue_blames(sb, porigin, suspects);1416}1417}14181419#define MAXSG 1614201421static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1422{1423struct rev_info *revs = sb->revs;1424int i, pass, num_sg;1425struct commit *commit = origin->commit;1426struct commit_list *sg;1427struct origin *sg_buf[MAXSG];1428struct origin *porigin, **sg_origin = sg_buf;1429struct blame_entry *toosmall = NULL;1430struct blame_entry *blames, **blametail = &blames;14311432 num_sg =num_scapegoats(revs, commit);1433if(!num_sg)1434goto finish;1435else if(num_sg <ARRAY_SIZE(sg_buf))1436memset(sg_buf,0,sizeof(sg_buf));1437else1438 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14391440/*1441 * The first pass looks for unrenamed path to optimize for1442 * common cases, then we look for renames in the second pass.1443 */1444for(pass =0; pass <2- no_whole_file_rename; pass++) {1445struct origin *(*find)(struct scoreboard *,1446struct commit *,struct origin *);1447 find = pass ? find_rename : find_origin;14481449for(i =0, sg =first_scapegoat(revs, commit);1450 i < num_sg && sg;1451 sg = sg->next, i++) {1452struct commit *p = sg->item;1453int j, same;14541455if(sg_origin[i])1456continue;1457if(parse_commit(p))1458continue;1459 porigin =find(sb, p, origin);1460if(!porigin)1461continue;1462if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1463pass_whole_blame(sb, origin, porigin);1464origin_decref(porigin);1465goto finish;1466}1467for(j = same =0; j < i; j++)1468if(sg_origin[j] &&1469!hashcmp(sg_origin[j]->blob_sha1,1470 porigin->blob_sha1)) {1471 same =1;1472break;1473}1474if(!same)1475 sg_origin[i] = porigin;1476else1477origin_decref(porigin);1478}1479}14801481 num_commits++;1482for(i =0, sg =first_scapegoat(revs, commit);1483 i < num_sg && sg;1484 sg = sg->next, i++) {1485struct origin *porigin = sg_origin[i];1486if(!porigin)1487continue;1488if(!origin->previous) {1489origin_incref(porigin);1490 origin->previous = porigin;1491}1492pass_blame_to_parent(sb, origin, porigin);1493if(!origin->suspects)1494goto finish;1495}14961497/*1498 * Optionally find moves in parents' files.1499 */1500if(opt & PICKAXE_BLAME_MOVE) {1501filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1502if(origin->suspects) {1503for(i =0, sg =first_scapegoat(revs, commit);1504 i < num_sg && sg;1505 sg = sg->next, i++) {1506struct origin *porigin = sg_origin[i];1507if(!porigin)1508continue;1509find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1510if(!origin->suspects)1511break;1512}1513}1514}15151516/*1517 * Optionally find copies from parents' files.1518 */1519if(opt & PICKAXE_BLAME_COPY) {1520if(blame_copy_score > blame_move_score)1521filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1522else if(blame_copy_score < blame_move_score) {1523 origin->suspects =blame_merge(origin->suspects, toosmall);1524 toosmall = NULL;1525filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1526}1527if(!origin->suspects)1528goto finish;15291530for(i =0, sg =first_scapegoat(revs, commit);1531 i < num_sg && sg;1532 sg = sg->next, i++) {1533struct origin *porigin = sg_origin[i];1534find_copy_in_parent(sb, &blametail, &toosmall,1535 origin, sg->item, porigin, opt);1536if(!origin->suspects)1537goto finish;1538}1539}15401541finish:1542*blametail = NULL;1543distribute_blame(sb, blames);1544/*1545 * prepend toosmall to origin->suspects1546 *1547 * There is no point in sorting: this ends up on a big1548 * unsorted list in the caller anyway.1549 */1550if(toosmall) {1551struct blame_entry **tail = &toosmall;1552while(*tail)1553 tail = &(*tail)->next;1554*tail = origin->suspects;1555 origin->suspects = toosmall;1556}1557for(i =0; i < num_sg; i++) {1558if(sg_origin[i]) {1559drop_origin_blob(sg_origin[i]);1560origin_decref(sg_origin[i]);1561}1562}1563drop_origin_blob(origin);1564if(sg_buf != sg_origin)1565free(sg_origin);1566}15671568/*1569 * Information on commits, used for output.1570 */1571struct commit_info {1572struct strbuf author;1573struct strbuf author_mail;1574unsigned long author_time;1575struct strbuf author_tz;15761577/* filled only when asked for details */1578struct strbuf committer;1579struct strbuf committer_mail;1580unsigned long committer_time;1581struct strbuf committer_tz;15821583struct strbuf summary;1584};15851586/*1587 * Parse author/committer line in the commit object buffer1588 */1589static voidget_ac_line(const char*inbuf,const char*what,1590struct strbuf *name,struct strbuf *mail,1591unsigned long*time,struct strbuf *tz)1592{1593struct ident_split ident;1594size_t len, maillen, namelen;1595char*tmp, *endp;1596const char*namebuf, *mailbuf;15971598 tmp =strstr(inbuf, what);1599if(!tmp)1600goto error_out;1601 tmp +=strlen(what);1602 endp =strchr(tmp,'\n');1603if(!endp)1604 len =strlen(tmp);1605else1606 len = endp - tmp;16071608if(split_ident_line(&ident, tmp, len)) {1609 error_out:1610/* Ugh */1611 tmp ="(unknown)";1612strbuf_addstr(name, tmp);1613strbuf_addstr(mail, tmp);1614strbuf_addstr(tz, tmp);1615*time =0;1616return;1617}16181619 namelen = ident.name_end - ident.name_begin;1620 namebuf = ident.name_begin;16211622 maillen = ident.mail_end - ident.mail_begin;1623 mailbuf = ident.mail_begin;16241625if(ident.date_begin && ident.date_end)1626*time =strtoul(ident.date_begin, NULL,10);1627else1628*time =0;16291630if(ident.tz_begin && ident.tz_end)1631strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1632else1633strbuf_addstr(tz,"(unknown)");16341635/*1636 * Now, convert both name and e-mail using mailmap1637 */1638map_user(&mailmap, &mailbuf, &maillen,1639&namebuf, &namelen);16401641strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1642strbuf_add(name, namebuf, namelen);1643}16441645static voidcommit_info_init(struct commit_info *ci)1646{16471648strbuf_init(&ci->author,0);1649strbuf_init(&ci->author_mail,0);1650strbuf_init(&ci->author_tz,0);1651strbuf_init(&ci->committer,0);1652strbuf_init(&ci->committer_mail,0);1653strbuf_init(&ci->committer_tz,0);1654strbuf_init(&ci->summary,0);1655}16561657static voidcommit_info_destroy(struct commit_info *ci)1658{16591660strbuf_release(&ci->author);1661strbuf_release(&ci->author_mail);1662strbuf_release(&ci->author_tz);1663strbuf_release(&ci->committer);1664strbuf_release(&ci->committer_mail);1665strbuf_release(&ci->committer_tz);1666strbuf_release(&ci->summary);1667}16681669static voidget_commit_info(struct commit *commit,1670struct commit_info *ret,1671int detailed)1672{1673int len;1674const char*subject, *encoding;1675const char*message;16761677commit_info_init(ret);16781679 encoding =get_log_output_encoding();1680 message =logmsg_reencode(commit, NULL, encoding);1681get_ac_line(message,"\nauthor ",1682&ret->author, &ret->author_mail,1683&ret->author_time, &ret->author_tz);16841685if(!detailed) {1686unuse_commit_buffer(commit, message);1687return;1688}16891690get_ac_line(message,"\ncommitter ",1691&ret->committer, &ret->committer_mail,1692&ret->committer_time, &ret->committer_tz);16931694 len =find_commit_subject(message, &subject);1695if(len)1696strbuf_add(&ret->summary, subject, len);1697else1698strbuf_addf(&ret->summary,"(%s)",oid_to_hex(&commit->object.oid));16991700unuse_commit_buffer(commit, message);1701}17021703/*1704 * To allow LF and other nonportable characters in pathnames,1705 * they are c-style quoted as needed.1706 */1707static voidwrite_filename_info(const char*path)1708{1709printf("filename ");1710write_name_quoted(path, stdout,'\n');1711}17121713/*1714 * Porcelain/Incremental format wants to show a lot of details per1715 * commit. Instead of repeating this every line, emit it only once,1716 * the first time each commit appears in the output (unless the1717 * user has specifically asked for us to repeat).1718 */1719static intemit_one_suspect_detail(struct origin *suspect,int repeat)1720{1721struct commit_info ci;17221723if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1724return0;17251726 suspect->commit->object.flags |= METAINFO_SHOWN;1727get_commit_info(suspect->commit, &ci,1);1728printf("author%s\n", ci.author.buf);1729printf("author-mail%s\n", ci.author_mail.buf);1730printf("author-time%lu\n", ci.author_time);1731printf("author-tz%s\n", ci.author_tz.buf);1732printf("committer%s\n", ci.committer.buf);1733printf("committer-mail%s\n", ci.committer_mail.buf);1734printf("committer-time%lu\n", ci.committer_time);1735printf("committer-tz%s\n", ci.committer_tz.buf);1736printf("summary%s\n", ci.summary.buf);1737if(suspect->commit->object.flags & UNINTERESTING)1738printf("boundary\n");1739if(suspect->previous) {1740struct origin *prev = suspect->previous;1741printf("previous%s",oid_to_hex(&prev->commit->object.oid));1742write_name_quoted(prev->path, stdout,'\n');1743}17441745commit_info_destroy(&ci);17461747return1;1748}17491750/*1751 * The blame_entry is found to be guilty for the range.1752 * Show it in incremental output.1753 */1754static voidfound_guilty_entry(struct blame_entry *ent,1755struct progress_info *pi)1756{1757if(incremental) {1758struct origin *suspect = ent->suspect;17591760printf("%s %d %d %d\n",1761oid_to_hex(&suspect->commit->object.oid),1762 ent->s_lno +1, ent->lno +1, ent->num_lines);1763emit_one_suspect_detail(suspect,0);1764write_filename_info(suspect->path);1765maybe_flush_or_die(stdout,"stdout");1766}1767 pi->blamed_lines += ent->num_lines;1768display_progress(pi->progress, pi->blamed_lines);1769}17701771/*1772 * The main loop -- while we have blobs with lines whose true origin1773 * is still unknown, pick one blob, and allow its lines to pass blames1774 * to its parents. */1775static voidassign_blame(struct scoreboard *sb,int opt)1776{1777struct rev_info *revs = sb->revs;1778struct commit *commit =prio_queue_get(&sb->commits);1779struct progress_info pi = { NULL,0};17801781if(show_progress)1782 pi.progress =start_progress_delay(_("Blaming lines"),1783 sb->num_lines,50,1);17841785while(commit) {1786struct blame_entry *ent;1787struct origin *suspect = commit->util;17881789/* find one suspect to break down */1790while(suspect && !suspect->suspects)1791 suspect = suspect->next;17921793if(!suspect) {1794 commit =prio_queue_get(&sb->commits);1795continue;1796}17971798assert(commit == suspect->commit);17991800/*1801 * We will use this suspect later in the loop,1802 * so hold onto it in the meantime.1803 */1804origin_incref(suspect);1805parse_commit(commit);1806if(reverse ||1807(!(commit->object.flags & UNINTERESTING) &&1808!(revs->max_age != -1&& commit->date < revs->max_age)))1809pass_blame(sb, suspect, opt);1810else{1811 commit->object.flags |= UNINTERESTING;1812if(commit->object.parsed)1813mark_parents_uninteresting(commit);1814}1815/* treat root commit as boundary */1816if(!commit->parents && !show_root)1817 commit->object.flags |= UNINTERESTING;18181819/* Take responsibility for the remaining entries */1820 ent = suspect->suspects;1821if(ent) {1822 suspect->guilty =1;1823for(;;) {1824struct blame_entry *next = ent->next;1825found_guilty_entry(ent, &pi);1826if(next) {1827 ent = next;1828continue;1829}1830 ent->next = sb->ent;1831 sb->ent = suspect->suspects;1832 suspect->suspects = NULL;1833break;1834}1835}1836origin_decref(suspect);18371838if(DEBUG)/* sanity */1839sanity_check_refcnt(sb);1840}18411842stop_progress(&pi.progress);1843}18441845static const char*format_time(unsigned long time,const char*tz_str,1846int show_raw_time)1847{1848static struct strbuf time_buf = STRBUF_INIT;18491850strbuf_reset(&time_buf);1851if(show_raw_time) {1852strbuf_addf(&time_buf,"%lu%s", time, tz_str);1853}1854else{1855const char*time_str;1856size_t time_width;1857int tz;1858 tz =atoi(tz_str);1859 time_str =show_date(time, tz, &blame_date_mode);1860strbuf_addstr(&time_buf, time_str);1861/*1862 * Add space paddings to time_buf to display a fixed width1863 * string, and use time_width for display width calibration.1864 */1865for(time_width =utf8_strwidth(time_str);1866 time_width < blame_date_width;1867 time_width++)1868strbuf_addch(&time_buf,' ');1869}1870return time_buf.buf;1871}18721873#define OUTPUT_ANNOTATE_COMPAT 0011874#define OUTPUT_LONG_OBJECT_NAME 0021875#define OUTPUT_RAW_TIMESTAMP 0041876#define OUTPUT_PORCELAIN 0101877#define OUTPUT_SHOW_NAME 0201878#define OUTPUT_SHOW_NUMBER 0401879#define OUTPUT_SHOW_SCORE 01001880#define OUTPUT_NO_AUTHOR 02001881#define OUTPUT_SHOW_EMAIL 04001882#define OUTPUT_LINE_PORCELAIN 0100018831884static voidemit_porcelain_details(struct origin *suspect,int repeat)1885{1886if(emit_one_suspect_detail(suspect, repeat) ||1887(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1888write_filename_info(suspect->path);1889}18901891static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1892int opt)1893{1894int repeat = opt & OUTPUT_LINE_PORCELAIN;1895int cnt;1896const char*cp;1897struct origin *suspect = ent->suspect;1898char hex[GIT_SHA1_HEXSZ +1];18991900sha1_to_hex_r(hex, suspect->commit->object.oid.hash);1901printf("%s %d %d %d\n",1902 hex,1903 ent->s_lno +1,1904 ent->lno +1,1905 ent->num_lines);1906emit_porcelain_details(suspect, repeat);19071908 cp =nth_line(sb, ent->lno);1909for(cnt =0; cnt < ent->num_lines; cnt++) {1910char ch;1911if(cnt) {1912printf("%s %d %d\n", hex,1913 ent->s_lno +1+ cnt,1914 ent->lno +1+ cnt);1915if(repeat)1916emit_porcelain_details(suspect,1);1917}1918putchar('\t');1919do{1920 ch = *cp++;1921putchar(ch);1922}while(ch !='\n'&&1923 cp < sb->final_buf + sb->final_buf_size);1924}19251926if(sb->final_buf_size && cp[-1] !='\n')1927putchar('\n');1928}19291930static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1931{1932int cnt;1933const char*cp;1934struct origin *suspect = ent->suspect;1935struct commit_info ci;1936char hex[GIT_SHA1_HEXSZ +1];1937int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19381939get_commit_info(suspect->commit, &ci,1);1940sha1_to_hex_r(hex, suspect->commit->object.oid.hash);19411942 cp =nth_line(sb, ent->lno);1943for(cnt =0; cnt < ent->num_lines; cnt++) {1944char ch;1945int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19461947if(suspect->commit->object.flags & UNINTERESTING) {1948if(blank_boundary)1949memset(hex,' ', length);1950else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1951 length--;1952putchar('^');1953}1954}19551956printf("%.*s", length, hex);1957if(opt & OUTPUT_ANNOTATE_COMPAT) {1958const char*name;1959if(opt & OUTPUT_SHOW_EMAIL)1960 name = ci.author_mail.buf;1961else1962 name = ci.author.buf;1963printf("\t(%10s\t%10s\t%d)", name,1964format_time(ci.author_time, ci.author_tz.buf,1965 show_raw_time),1966 ent->lno +1+ cnt);1967}else{1968if(opt & OUTPUT_SHOW_SCORE)1969printf(" %*d%02d",1970 max_score_digits, ent->score,1971 ent->suspect->refcnt);1972if(opt & OUTPUT_SHOW_NAME)1973printf(" %-*.*s", longest_file, longest_file,1974 suspect->path);1975if(opt & OUTPUT_SHOW_NUMBER)1976printf(" %*d", max_orig_digits,1977 ent->s_lno +1+ cnt);19781979if(!(opt & OUTPUT_NO_AUTHOR)) {1980const char*name;1981int pad;1982if(opt & OUTPUT_SHOW_EMAIL)1983 name = ci.author_mail.buf;1984else1985 name = ci.author.buf;1986 pad = longest_author -utf8_strwidth(name);1987printf(" (%s%*s%10s",1988 name, pad,"",1989format_time(ci.author_time,1990 ci.author_tz.buf,1991 show_raw_time));1992}1993printf(" %*d) ",1994 max_digits, ent->lno +1+ cnt);1995}1996do{1997 ch = *cp++;1998putchar(ch);1999}while(ch !='\n'&&2000 cp < sb->final_buf + sb->final_buf_size);2001}20022003if(sb->final_buf_size && cp[-1] !='\n')2004putchar('\n');20052006commit_info_destroy(&ci);2007}20082009static voidoutput(struct scoreboard *sb,int option)2010{2011struct blame_entry *ent;20122013if(option & OUTPUT_PORCELAIN) {2014for(ent = sb->ent; ent; ent = ent->next) {2015int count =0;2016struct origin *suspect;2017struct commit *commit = ent->suspect->commit;2018if(commit->object.flags & MORE_THAN_ONE_PATH)2019continue;2020for(suspect = commit->util; suspect; suspect = suspect->next) {2021if(suspect->guilty && count++) {2022 commit->object.flags |= MORE_THAN_ONE_PATH;2023break;2024}2025}2026}2027}20282029for(ent = sb->ent; ent; ent = ent->next) {2030if(option & OUTPUT_PORCELAIN)2031emit_porcelain(sb, ent, option);2032else{2033emit_other(sb, ent, option);2034}2035}2036}20372038static const char*get_next_line(const char*start,const char*end)2039{2040const char*nl =memchr(start,'\n', end - start);2041return nl ? nl +1: end;2042}20432044/*2045 * To allow quick access to the contents of nth line in the2046 * final image, prepare an index in the scoreboard.2047 */2048static intprepare_lines(struct scoreboard *sb)2049{2050const char*buf = sb->final_buf;2051unsigned long len = sb->final_buf_size;2052const char*end = buf + len;2053const char*p;2054int*lineno;2055int num =0;20562057for(p = buf; p < end; p =get_next_line(p, end))2058 num++;20592060ALLOC_ARRAY(sb->lineno, num +1);2061 lineno = sb->lineno;20622063for(p = buf; p < end; p =get_next_line(p, end))2064*lineno++ = p - buf;20652066*lineno = len;20672068 sb->num_lines = num;2069return sb->num_lines;2070}20712072/*2073 * Add phony grafts for use with -S; this is primarily to2074 * support git's cvsserver that wants to give a linear history2075 * to its clients.2076 */2077static intread_ancestry(const char*graft_file)2078{2079FILE*fp =fopen(graft_file,"r");2080struct strbuf buf = STRBUF_INIT;2081if(!fp)2082return-1;2083while(!strbuf_getwholeline(&buf, fp,'\n')) {2084/* The format is just "Commit Parent1 Parent2 ...\n" */2085struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2086if(graft)2087register_commit_graft(graft,0);2088}2089fclose(fp);2090strbuf_release(&buf);2091return0;2092}20932094static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2095{2096const char*uniq =find_unique_abbrev(suspect->commit->object.oid.hash,2097 auto_abbrev);2098int len =strlen(uniq);2099if(auto_abbrev < len)2100return len;2101return auto_abbrev;2102}21032104/*2105 * How many columns do we need to show line numbers, authors,2106 * and filenames?2107 */2108static voidfind_alignment(struct scoreboard *sb,int*option)2109{2110int longest_src_lines =0;2111int longest_dst_lines =0;2112unsigned largest_score =0;2113struct blame_entry *e;2114int compute_auto_abbrev = (abbrev <0);2115int auto_abbrev = default_abbrev;21162117for(e = sb->ent; e; e = e->next) {2118struct origin *suspect = e->suspect;2119int num;21202121if(compute_auto_abbrev)2122 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2123if(strcmp(suspect->path, sb->path))2124*option |= OUTPUT_SHOW_NAME;2125 num =strlen(suspect->path);2126if(longest_file < num)2127 longest_file = num;2128if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2129struct commit_info ci;2130 suspect->commit->object.flags |= METAINFO_SHOWN;2131get_commit_info(suspect->commit, &ci,1);2132if(*option & OUTPUT_SHOW_EMAIL)2133 num =utf8_strwidth(ci.author_mail.buf);2134else2135 num =utf8_strwidth(ci.author.buf);2136if(longest_author < num)2137 longest_author = num;2138commit_info_destroy(&ci);2139}2140 num = e->s_lno + e->num_lines;2141if(longest_src_lines < num)2142 longest_src_lines = num;2143 num = e->lno + e->num_lines;2144if(longest_dst_lines < num)2145 longest_dst_lines = num;2146if(largest_score <ent_score(sb, e))2147 largest_score =ent_score(sb, e);2148}2149 max_orig_digits =decimal_width(longest_src_lines);2150 max_digits =decimal_width(longest_dst_lines);2151 max_score_digits =decimal_width(largest_score);21522153if(compute_auto_abbrev)2154/* one more abbrev length is needed for the boundary commit */2155 abbrev = auto_abbrev +1;2156}21572158/*2159 * For debugging -- origin is refcounted, and this asserts that2160 * we do not underflow.2161 */2162static voidsanity_check_refcnt(struct scoreboard *sb)2163{2164int baa =0;2165struct blame_entry *ent;21662167for(ent = sb->ent; ent; ent = ent->next) {2168/* Nobody should have zero or negative refcnt */2169if(ent->suspect->refcnt <=0) {2170fprintf(stderr,"%sin%shas negative refcnt%d\n",2171 ent->suspect->path,2172oid_to_hex(&ent->suspect->commit->object.oid),2173 ent->suspect->refcnt);2174 baa =1;2175}2176}2177if(baa) {2178int opt =0160;2179find_alignment(sb, &opt);2180output(sb, opt);2181die("Baa%d!", baa);2182}2183}21842185static unsignedparse_score(const char*arg)2186{2187char*end;2188unsigned long score =strtoul(arg, &end,10);2189if(*end)2190return0;2191return score;2192}21932194static const char*add_prefix(const char*prefix,const char*path)2195{2196returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2197}21982199static intgit_blame_config(const char*var,const char*value,void*cb)2200{2201if(!strcmp(var,"blame.showroot")) {2202 show_root =git_config_bool(var, value);2203return0;2204}2205if(!strcmp(var,"blame.blankboundary")) {2206 blank_boundary =git_config_bool(var, value);2207return0;2208}2209if(!strcmp(var,"blame.showemail")) {2210int*output_option = cb;2211if(git_config_bool(var, value))2212*output_option |= OUTPUT_SHOW_EMAIL;2213else2214*output_option &= ~OUTPUT_SHOW_EMAIL;2215return0;2216}2217if(!strcmp(var,"blame.date")) {2218if(!value)2219returnconfig_error_nonbool(var);2220parse_date_format(value, &blame_date_mode);2221return0;2222}22232224if(userdiff_config(var, value) <0)2225return-1;22262227returngit_default_config(var, value, cb);2228}22292230static voidverify_working_tree_path(struct commit *work_tree,const char*path)2231{2232struct commit_list *parents;22332234for(parents = work_tree->parents; parents; parents = parents->next) {2235const unsigned char*commit_sha1 = parents->item->object.oid.hash;2236unsigned char blob_sha1[20];2237unsigned mode;22382239if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2240sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2241return;2242}2243die("no such path '%s' in HEAD", path);2244}22452246static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2247{2248struct commit *parent;22492250 parent =lookup_commit_reference(sha1);2251if(!parent)2252die("no such commit%s",sha1_to_hex(sha1));2253return&commit_list_insert(parent, tail)->next;2254}22552256static voidappend_merge_parents(struct commit_list **tail)2257{2258int merge_head;2259struct strbuf line = STRBUF_INIT;22602261 merge_head =open(git_path_merge_head(), O_RDONLY);2262if(merge_head <0) {2263if(errno == ENOENT)2264return;2265die("cannot open '%s' for reading",git_path_merge_head());2266}22672268while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2269unsigned char sha1[20];2270if(line.len <40||get_sha1_hex(line.buf, sha1))2271die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2272 tail =append_parent(tail, sha1);2273}2274close(merge_head);2275strbuf_release(&line);2276}22772278/*2279 * This isn't as simple as passing sb->buf and sb->len, because we2280 * want to transfer ownership of the buffer to the commit (so we2281 * must use detach).2282 */2283static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2284{2285size_t len;2286void*buf =strbuf_detach(sb, &len);2287set_commit_buffer(c, buf, len);2288}22892290/*2291 * Prepare a dummy commit that represents the work tree (or staged) item.2292 * Note that annotating work tree item never works in the reverse.2293 */2294static struct commit *fake_working_tree_commit(struct diff_options *opt,2295const char*path,2296const char*contents_from)2297{2298struct commit *commit;2299struct origin *origin;2300struct commit_list **parent_tail, *parent;2301unsigned char head_sha1[20];2302struct strbuf buf = STRBUF_INIT;2303const char*ident;2304time_t now;2305int size, len;2306struct cache_entry *ce;2307unsigned mode;2308struct strbuf msg = STRBUF_INIT;23092310read_cache();2311time(&now);2312 commit =alloc_commit_node();2313 commit->object.parsed =1;2314 commit->date = now;2315 parent_tail = &commit->parents;23162317if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2318die("no such ref: HEAD");23192320 parent_tail =append_parent(parent_tail, head_sha1);2321append_merge_parents(parent_tail);2322verify_working_tree_path(commit, path);23232324 origin =make_origin(commit, path);23252326 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2327strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2328for(parent = commit->parents; parent; parent = parent->next)2329strbuf_addf(&msg,"parent%s\n",2330oid_to_hex(&parent->item->object.oid));2331strbuf_addf(&msg,2332"author%s\n"2333"committer%s\n\n"2334"Version of%sfrom%s\n",2335 ident, ident, path,2336(!contents_from ? path :2337(!strcmp(contents_from,"-") ?"standard input": contents_from)));2338set_commit_buffer_from_strbuf(commit, &msg);23392340if(!contents_from ||strcmp("-", contents_from)) {2341struct stat st;2342const char*read_from;2343char*buf_ptr;2344unsigned long buf_len;23452346if(contents_from) {2347if(stat(contents_from, &st) <0)2348die_errno("Cannot stat '%s'", contents_from);2349 read_from = contents_from;2350}2351else{2352if(lstat(path, &st) <0)2353die_errno("Cannot lstat '%s'", path);2354 read_from = path;2355}2356 mode =canon_mode(st.st_mode);23572358switch(st.st_mode & S_IFMT) {2359case S_IFREG:2360if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2361textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2362strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2363else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2364die_errno("cannot open or read '%s'", read_from);2365break;2366case S_IFLNK:2367if(strbuf_readlink(&buf, read_from, st.st_size) <0)2368die_errno("cannot readlink '%s'", read_from);2369break;2370default:2371die("unsupported file type%s", read_from);2372}2373}2374else{2375/* Reading from stdin */2376 mode =0;2377if(strbuf_read(&buf,0,0) <0)2378die_errno("failed to read from stdin");2379}2380convert_to_git(path, buf.buf, buf.len, &buf,0);2381 origin->file.ptr = buf.buf;2382 origin->file.size = buf.len;2383pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23842385/*2386 * Read the current index, replace the path entry with2387 * origin->blob_sha1 without mucking with its mode or type2388 * bits; we are not going to write this index out -- we just2389 * want to run "diff-index --cached".2390 */2391discard_cache();2392read_cache();23932394 len =strlen(path);2395if(!mode) {2396int pos =cache_name_pos(path, len);2397if(0<= pos)2398 mode = active_cache[pos]->ce_mode;2399else2400/* Let's not bother reading from HEAD tree */2401 mode = S_IFREG |0644;2402}2403 size =cache_entry_size(len);2404 ce =xcalloc(1, size);2405hashcpy(ce->sha1, origin->blob_sha1);2406memcpy(ce->name, path, len);2407 ce->ce_flags =create_ce_flags(0);2408 ce->ce_namelen = len;2409 ce->ce_mode =create_ce_mode(mode);2410add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);24112412cache_tree_invalidate_path(&the_index, path);24132414return commit;2415}24162417static struct commit *find_single_final(struct rev_info *revs,2418const char**name_p)2419{2420int i;2421struct commit *found = NULL;2422const char*name = NULL;24232424for(i =0; i < revs->pending.nr; i++) {2425struct object *obj = revs->pending.objects[i].item;2426if(obj->flags & UNINTERESTING)2427continue;2428while(obj->type == OBJ_TAG)2429 obj =deref_tag(obj, NULL,0);2430if(obj->type != OBJ_COMMIT)2431die("Non commit%s?", revs->pending.objects[i].name);2432if(found)2433die("More than one commit to dig from%sand%s?",2434 revs->pending.objects[i].name, name);2435 found = (struct commit *)obj;2436 name = revs->pending.objects[i].name;2437}2438if(name_p)2439*name_p = name;2440return found;2441}24422443static char*prepare_final(struct scoreboard *sb)2444{2445const char*name;2446 sb->final =find_single_final(sb->revs, &name);2447returnxstrdup_or_null(name);2448}24492450static char*prepare_initial(struct scoreboard *sb)2451{2452int i;2453const char*final_commit_name = NULL;2454struct rev_info *revs = sb->revs;24552456/*2457 * There must be one and only one negative commit, and it must be2458 * the boundary.2459 */2460for(i =0; i < revs->pending.nr; i++) {2461struct object *obj = revs->pending.objects[i].item;2462if(!(obj->flags & UNINTERESTING))2463continue;2464while(obj->type == OBJ_TAG)2465 obj =deref_tag(obj, NULL,0);2466if(obj->type != OBJ_COMMIT)2467die("Non commit%s?", revs->pending.objects[i].name);2468if(sb->final)2469die("More than one commit to dig up from,%sand%s?",2470 revs->pending.objects[i].name,2471 final_commit_name);2472 sb->final = (struct commit *) obj;2473 final_commit_name = revs->pending.objects[i].name;2474}2475if(!final_commit_name)2476die("No commit to dig up from?");2477returnxstrdup(final_commit_name);2478}24792480static intblame_copy_callback(const struct option *option,const char*arg,int unset)2481{2482int*opt = option->value;24832484/*2485 * -C enables copy from removed files;2486 * -C -C enables copy from existing files, but only2487 * when blaming a new file;2488 * -C -C -C enables copy from existing files for2489 * everybody2490 */2491if(*opt & PICKAXE_BLAME_COPY_HARDER)2492*opt |= PICKAXE_BLAME_COPY_HARDEST;2493if(*opt & PICKAXE_BLAME_COPY)2494*opt |= PICKAXE_BLAME_COPY_HARDER;2495*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;24962497if(arg)2498 blame_copy_score =parse_score(arg);2499return0;2500}25012502static intblame_move_callback(const struct option *option,const char*arg,int unset)2503{2504int*opt = option->value;25052506*opt |= PICKAXE_BLAME_MOVE;25072508if(arg)2509 blame_move_score =parse_score(arg);2510return0;2511}25122513intcmd_blame(int argc,const char**argv,const char*prefix)2514{2515struct rev_info revs;2516const char*path;2517struct scoreboard sb;2518struct origin *o;2519struct blame_entry *ent = NULL;2520long dashdash_pos, lno;2521char*final_commit_name = NULL;2522enum object_type type;2523struct commit *final_commit = NULL;25242525static struct string_list range_list;2526static int output_option =0, opt =0;2527static int show_stats =0;2528static const char*revs_file = NULL;2529static const char*contents_from = NULL;2530static const struct option options[] = {2531OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2532OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2533OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2534OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2535OPT_BOOL(0,"progress", &show_progress,N_("Force progress reporting")),2536OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2537OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2538OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2539OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2540OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2541OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2542OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2543OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2544OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2545OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2546OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2547OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2548OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2549OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2550{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2551{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2552OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2553OPT__ABBREV(&abbrev),2554OPT_END()2555};25562557struct parse_opt_ctx_t ctx;2558int cmd_is_annotate = !strcmp(argv[0],"annotate");2559struct range_set ranges;2560unsigned int range_i;2561long anchor;25622563git_config(git_blame_config, &output_option);2564init_revisions(&revs, NULL);2565 revs.date_mode = blame_date_mode;2566DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2567DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25682569 save_commit_buffer =0;2570 dashdash_pos =0;2571 show_progress = -1;25722573parse_options_start(&ctx, argc, argv, prefix, options,2574 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2575for(;;) {2576switch(parse_options_step(&ctx, options, blame_opt_usage)) {2577case PARSE_OPT_HELP:2578exit(129);2579case PARSE_OPT_DONE:2580if(ctx.argv[0])2581 dashdash_pos = ctx.cpidx;2582goto parse_done;2583}25842585if(!strcmp(ctx.argv[0],"--reverse")) {2586 ctx.argv[0] ="--children";2587 reverse =1;2588}2589parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2590}2591parse_done:2592 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2593DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2594 argc =parse_options_end(&ctx);25952596if(incremental || (output_option & OUTPUT_PORCELAIN)) {2597if(show_progress >0)2598die("--progress can't be used with --incremental or porcelain formats");2599 show_progress =0;2600}else if(show_progress <0)2601 show_progress =isatty(2);26022603if(0< abbrev)2604/* one more abbrev length is needed for the boundary commit */2605 abbrev++;26062607if(revs_file &&read_ancestry(revs_file))2608die_errno("reading graft file '%s' failed", revs_file);26092610if(cmd_is_annotate) {2611 output_option |= OUTPUT_ANNOTATE_COMPAT;2612 blame_date_mode.type = DATE_ISO8601;2613}else{2614 blame_date_mode = revs.date_mode;2615}26162617/* The maximum width used to show the dates */2618switch(blame_date_mode.type) {2619case DATE_RFC2822:2620 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2621break;2622case DATE_ISO8601_STRICT:2623 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2624break;2625case DATE_ISO8601:2626 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2627break;2628case DATE_RAW:2629 blame_date_width =sizeof("1161298804 -0700");2630break;2631case DATE_SHORT:2632 blame_date_width =sizeof("2006-10-19");2633break;2634case DATE_RELATIVE:2635/* TRANSLATORS: This string is used to tell us the maximum2636 display width for a relative timestamp in "git blame"2637 output. For C locale, "4 years, 11 months ago", which2638 takes 22 places, is the longest among various forms of2639 relative timestamps, but your language may need more or2640 fewer display columns. */2641 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2642break;2643case DATE_NORMAL:2644 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2645break;2646case DATE_STRFTIME:2647 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2648break;2649}2650 blame_date_width -=1;/* strip the null */26512652if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2653 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2654 PICKAXE_BLAME_COPY_HARDER);26552656if(!blame_move_score)2657 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2658if(!blame_copy_score)2659 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26602661/*2662 * We have collected options unknown to us in argv[1..unk]2663 * which are to be passed to revision machinery if we are2664 * going to do the "bottom" processing.2665 *2666 * The remaining are:2667 *2668 * (1) if dashdash_pos != 0, it is either2669 * "blame [revisions] -- <path>" or2670 * "blame -- <path> <rev>"2671 *2672 * (2) otherwise, it is one of the two:2673 * "blame [revisions] <path>"2674 * "blame <path> <rev>"2675 *2676 * Note that we must strip out <path> from the arguments: we do not2677 * want the path pruning but we may want "bottom" processing.2678 */2679if(dashdash_pos) {2680switch(argc - dashdash_pos -1) {2681case2:/* (1b) */2682if(argc !=4)2683usage_with_options(blame_opt_usage, options);2684/* reorder for the new way: <rev> -- <path> */2685 argv[1] = argv[3];2686 argv[3] = argv[2];2687 argv[2] ="--";2688/* FALLTHROUGH */2689case1:/* (1a) */2690 path =add_prefix(prefix, argv[--argc]);2691 argv[argc] = NULL;2692break;2693default:2694usage_with_options(blame_opt_usage, options);2695}2696}else{2697if(argc <2)2698usage_with_options(blame_opt_usage, options);2699 path =add_prefix(prefix, argv[argc -1]);2700if(argc ==3&& !file_exists(path)) {/* (2b) */2701 path =add_prefix(prefix, argv[1]);2702 argv[1] = argv[2];2703}2704 argv[argc -1] ="--";27052706setup_work_tree();2707if(!file_exists(path))2708die_errno("cannot stat path '%s'", path);2709}27102711 revs.disable_stdin =1;2712setup_revisions(argc, argv, &revs, NULL);2713memset(&sb,0,sizeof(sb));27142715 sb.revs = &revs;2716if(!reverse) {2717 final_commit_name =prepare_final(&sb);2718 sb.commits.compare = compare_commits_by_commit_date;2719}2720else if(contents_from)2721die("--contents and --reverse do not blend well.");2722else{2723 final_commit_name =prepare_initial(&sb);2724 sb.commits.compare = compare_commits_by_reverse_commit_date;2725if(revs.first_parent_only)2726 revs.children.name = NULL;2727}27282729if(!sb.final) {2730/*2731 * "--not A B -- path" without anything positive;2732 * do not default to HEAD, but use the working tree2733 * or "--contents".2734 */2735setup_work_tree();2736 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2737 path, contents_from);2738add_pending_object(&revs, &(sb.final->object),":");2739}2740else if(contents_from)2741die("Cannot use --contents with final commit object name");27422743if(reverse && revs.first_parent_only) {2744 final_commit =find_single_final(sb.revs, NULL);2745if(!final_commit)2746die("--reverse and --first-parent together require specified latest commit");2747}27482749/*2750 * If we have bottom, this will mark the ancestors of the2751 * bottom commits we would reach while traversing as2752 * uninteresting.2753 */2754if(prepare_revision_walk(&revs))2755die(_("revision walk setup failed"));27562757if(reverse && revs.first_parent_only) {2758struct commit *c = final_commit;27592760 sb.revs->children.name ="children";2761while(c->parents &&2762oidcmp(&c->object.oid, &sb.final->object.oid)) {2763struct commit_list *l =xcalloc(1,sizeof(*l));27642765 l->item = c;2766if(add_decoration(&sb.revs->children,2767&c->parents->item->object, l))2768die("BUG: not unique item in first-parent chain");2769 c = c->parents->item;2770}27712772if(oidcmp(&c->object.oid, &sb.final->object.oid))2773die("--reverse --first-parent together require range along first-parent chain");2774}27752776if(is_null_oid(&sb.final->object.oid)) {2777 o = sb.final->util;2778 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2779 sb.final_buf_size = o->file.size;2780}2781else{2782 o =get_origin(&sb, sb.final, path);2783if(fill_blob_sha1_and_mode(o))2784die("no such path%sin%s", path, final_commit_name);27852786if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2787textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2788&sb.final_buf_size))2789;2790else2791 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2792&sb.final_buf_size);27932794if(!sb.final_buf)2795die("Cannot read blob%sfor path%s",2796sha1_to_hex(o->blob_sha1),2797 path);2798}2799 num_read_blob++;2800 lno =prepare_lines(&sb);28012802if(lno && !range_list.nr)2803string_list_append(&range_list,xstrdup("1"));28042805 anchor =1;2806range_set_init(&ranges, range_list.nr);2807for(range_i =0; range_i < range_list.nr; ++range_i) {2808long bottom, top;2809if(parse_range_arg(range_list.items[range_i].string,2810 nth_line_cb, &sb, lno, anchor,2811&bottom, &top, sb.path))2812usage(blame_usage);2813if(lno < top || ((lno || bottom) && lno < bottom))2814die("file%shas only%lu lines", path, lno);2815if(bottom <1)2816 bottom =1;2817if(top <1)2818 top = lno;2819 bottom--;2820range_set_append_unsafe(&ranges, bottom, top);2821 anchor = top +1;2822}2823sort_and_merge_range_set(&ranges);28242825for(range_i = ranges.nr; range_i >0; --range_i) {2826const struct range *r = &ranges.ranges[range_i -1];2827long bottom = r->start;2828long top = r->end;2829struct blame_entry *next = ent;2830 ent =xcalloc(1,sizeof(*ent));2831 ent->lno = bottom;2832 ent->num_lines = top - bottom;2833 ent->suspect = o;2834 ent->s_lno = bottom;2835 ent->next = next;2836origin_incref(o);2837}28382839 o->suspects = ent;2840prio_queue_put(&sb.commits, o->commit);28412842origin_decref(o);28432844range_set_release(&ranges);2845string_list_clear(&range_list,0);28462847 sb.ent = NULL;2848 sb.path = path;28492850read_mailmap(&mailmap, NULL);28512852assign_blame(&sb, opt);28532854if(!incremental)2855setup_pager();28562857free(final_commit_name);28582859if(incremental)2860return0;28612862 sb.ent =blame_sort(sb.ent, compare_blame_final);28632864coalesce(&sb);28652866if(!(output_option & OUTPUT_PORCELAIN))2867find_alignment(&sb, &output_option);28682869output(&sb, output_option);2870free((void*)sb.final_buf);2871for(ent = sb.ent; ent; ) {2872struct blame_entry *e = ent->next;2873free(ent);2874 ent = e;2875}28762877if(show_stats) {2878printf("num read blob:%d\n", num_read_blob);2879printf("num get patch:%d\n", num_get_patch);2880printf("num commits:%d\n", num_commits);2881}2882return0;2883}