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"commit.h" 12#include"tag.h" 13#include"tree-walk.h" 14#include"diff.h" 15#include"diffcore.h" 16#include"revision.h" 17#include"quote.h" 18#include"xdiff-interface.h" 19#include"cache-tree.h" 20#include"string-list.h" 21#include"mailmap.h" 22#include"mergesort.h" 23#include"parse-options.h" 24#include"prio-queue.h" 25#include"utf8.h" 26#include"userdiff.h" 27#include"line-range.h" 28#include"line-log.h" 29#include"dir.h" 30#include"progress.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; 53static int show_progress; 54 55static struct date_mode blame_date_mode = { DATE_ISO8601 }; 56static size_t blame_date_width; 57 58static struct string_list mailmap = STRING_LIST_INIT_NODUP; 59 60#ifndef DEBUG 61#define DEBUG 0 62#endif 63 64#define PICKAXE_BLAME_MOVE 01 65#define PICKAXE_BLAME_COPY 02 66#define PICKAXE_BLAME_COPY_HARDER 04 67#define PICKAXE_BLAME_COPY_HARDEST 010 68 69static unsigned blame_move_score; 70static unsigned blame_copy_score; 71#define BLAME_DEFAULT_MOVE_SCORE 20 72#define BLAME_DEFAULT_COPY_SCORE 40 73 74/* Remember to update object flag allocation in object.h */ 75#define METAINFO_SHOWN (1u<<12) 76#define MORE_THAN_ONE_PATH (1u<<13) 77 78/* 79 * One blob in a commit that is being suspected 80 */ 81struct blame_origin { 82int refcnt; 83/* Record preceding blame record for this blob */ 84struct blame_origin *previous; 85/* origins are put in a list linked via `next' hanging off the 86 * corresponding commit's util field in order to make finding 87 * them fast. The presence in this chain does not count 88 * towards the origin's reference count. It is tempting to 89 * let it count as long as the commit is pending examination, 90 * but even under circumstances where the commit will be 91 * present multiple times in the priority queue of unexamined 92 * commits, processing the first instance will not leave any 93 * work requiring the origin data for the second instance. An 94 * interspersed commit changing that would have to be 95 * preexisting with a different ancestry and with the same 96 * commit date in order to wedge itself between two instances 97 * of the same commit in the priority queue _and_ produce 98 * blame entries relevant for it. While we don't want to let 99 * us get tripped up by this case, it certainly does not seem 100 * worth optimizing for. 101 */ 102struct blame_origin *next; 103struct commit *commit; 104/* `suspects' contains blame entries that may be attributed to 105 * this origin's commit or to parent commits. When a commit 106 * is being processed, all suspects will be moved, either by 107 * assigning them to an origin in a different commit, or by 108 * shipping them to the scoreboard's ent list because they 109 * cannot be attributed to a different commit. 110 */ 111struct blame_entry *suspects; 112 mmfile_t file; 113struct object_id blob_oid; 114unsigned mode; 115/* guilty gets set when shipping any suspects to the final 116 * blame list instead of other commits 117 */ 118char guilty; 119char path[FLEX_ARRAY]; 120}; 121 122struct progress_info { 123struct progress *progress; 124int blamed_lines; 125}; 126 127static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b, 128 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data) 129{ 130 xpparam_t xpp = {0}; 131 xdemitconf_t xecfg = {0}; 132 xdemitcb_t ecb = {NULL}; 133 134 xpp.flags = xdl_opts; 135 xecfg.hunk_func = hunk_func; 136 ecb.priv = cb_data; 137returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 138} 139 140/* 141 * Given an origin, prepare mmfile_t structure to be used by the 142 * diff machinery 143 */ 144static voidfill_origin_blob(struct diff_options *opt, 145struct blame_origin *o, mmfile_t *file,int*num_read_blob) 146{ 147if(!o->file.ptr) { 148enum object_type type; 149unsigned long file_size; 150 151(*num_read_blob)++; 152if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 153textconv_object(o->path, o->mode, &o->blob_oid,1, &file->ptr, &file_size)) 154; 155else 156 file->ptr =read_sha1_file(o->blob_oid.hash, &type, 157&file_size); 158 file->size = file_size; 159 160if(!file->ptr) 161die("Cannot read blob%sfor path%s", 162oid_to_hex(&o->blob_oid), 163 o->path); 164 o->file = *file; 165} 166else 167*file = o->file; 168} 169 170/* 171 * Origin is refcounted and usually we keep the blob contents to be 172 * reused. 173 */ 174staticinlinestruct blame_origin *blame_origin_incref(struct blame_origin *o) 175{ 176if(o) 177 o->refcnt++; 178return o; 179} 180 181static voidblame_origin_decref(struct blame_origin *o) 182{ 183if(o && --o->refcnt <=0) { 184struct blame_origin *p, *l = NULL; 185if(o->previous) 186blame_origin_decref(o->previous); 187free(o->file.ptr); 188/* Should be present exactly once in commit chain */ 189for(p = o->commit->util; p; l = p, p = p->next) { 190if(p == o) { 191if(l) 192 l->next = p->next; 193else 194 o->commit->util = p->next; 195free(o); 196return; 197} 198} 199die("internal error in blame_origin_decref"); 200} 201} 202 203static voiddrop_origin_blob(struct blame_origin *o) 204{ 205if(o->file.ptr) { 206free(o->file.ptr); 207 o->file.ptr = NULL; 208} 209} 210 211/* 212 * Each group of lines is described by a blame_entry; it can be split 213 * as we pass blame to the parents. They are arranged in linked lists 214 * kept as `suspects' of some unprocessed origin, or entered (when the 215 * blame origin has been finalized) into the scoreboard structure. 216 * While the scoreboard structure is only sorted at the end of 217 * processing (according to final image line number), the lists 218 * attached to an origin are sorted by the target line number. 219 */ 220struct blame_entry { 221struct blame_entry *next; 222 223/* the first line of this group in the final image; 224 * internally all line numbers are 0 based. 225 */ 226int lno; 227 228/* how many lines this group has */ 229int num_lines; 230 231/* the commit that introduced this group into the final image */ 232struct blame_origin *suspect; 233 234/* the line number of the first line of this group in the 235 * suspect's file; internally all line numbers are 0 based. 236 */ 237int s_lno; 238 239/* how significant this entry is -- cached to avoid 240 * scanning the lines over and over. 241 */ 242unsigned score; 243}; 244 245/* 246 * Any merge of blames happens on lists of blames that arrived via 247 * different parents in a single suspect. In this case, we want to 248 * sort according to the suspect line numbers as opposed to the final 249 * image line numbers. The function body is somewhat longish because 250 * it avoids unnecessary writes. 251 */ 252 253static struct blame_entry *blame_merge(struct blame_entry *list1, 254struct blame_entry *list2) 255{ 256struct blame_entry *p1 = list1, *p2 = list2, 257**tail = &list1; 258 259if(!p1) 260return p2; 261if(!p2) 262return p1; 263 264if(p1->s_lno <= p2->s_lno) { 265do{ 266 tail = &p1->next; 267if((p1 = *tail) == NULL) { 268*tail = p2; 269return list1; 270} 271}while(p1->s_lno <= p2->s_lno); 272} 273for(;;) { 274*tail = p2; 275do{ 276 tail = &p2->next; 277if((p2 = *tail) == NULL) { 278*tail = p1; 279return list1; 280} 281}while(p1->s_lno > p2->s_lno); 282*tail = p1; 283do{ 284 tail = &p1->next; 285if((p1 = *tail) == NULL) { 286*tail = p2; 287return list1; 288} 289}while(p1->s_lno <= p2->s_lno); 290} 291} 292 293static void*get_next_blame(const void*p) 294{ 295return((struct blame_entry *)p)->next; 296} 297 298static voidset_next_blame(void*p1,void*p2) 299{ 300((struct blame_entry *)p1)->next = p2; 301} 302 303/* 304 * Final image line numbers are all different, so we don't need a 305 * three-way comparison here. 306 */ 307 308static intcompare_blame_final(const void*p1,const void*p2) 309{ 310return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 311?1: -1; 312} 313 314static intcompare_blame_suspect(const void*p1,const void*p2) 315{ 316const struct blame_entry *s1 = p1, *s2 = p2; 317/* 318 * to allow for collating suspects, we sort according to the 319 * respective pointer value as the primary sorting criterion. 320 * The actual relation is pretty unimportant as long as it 321 * establishes a total order. Comparing as integers gives us 322 * that. 323 */ 324if(s1->suspect != s2->suspect) 325return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 326if(s1->s_lno == s2->s_lno) 327return0; 328return s1->s_lno > s2->s_lno ?1: -1; 329} 330 331static struct blame_entry *blame_sort(struct blame_entry *head, 332int(*compare_fn)(const void*,const void*)) 333{ 334returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 335} 336 337static intcompare_commits_by_reverse_commit_date(const void*a, 338const void*b, 339void*c) 340{ 341return-compare_commits_by_commit_date(a, b, c); 342} 343 344/* 345 * The current state of the blame assignment. 346 */ 347struct blame_scoreboard { 348/* the final commit (i.e. where we started digging from) */ 349struct commit *final; 350/* Priority queue for commits with unassigned blame records */ 351struct prio_queue commits; 352struct rev_info *revs; 353const char*path; 354 355/* 356 * The contents in the final image. 357 * Used by many functions to obtain contents of the nth line, 358 * indexed with scoreboard.lineno[blame_entry.lno]. 359 */ 360const char*final_buf; 361unsigned long final_buf_size; 362 363/* linked list of blames */ 364struct blame_entry *ent; 365 366/* look-up a line in the final buffer */ 367int num_lines; 368int*lineno; 369 370/* stats */ 371int num_read_blob; 372int num_get_patch; 373int num_commits; 374 375/* 376 * blame for a blame_entry with score lower than these thresholds 377 * is not passed to the parent using move/copy logic. 378 */ 379unsigned move_score; 380unsigned copy_score; 381 382/* use this file's contents as the final image */ 383const char*contents_from; 384}; 385 386static voidsanity_check_refcnt(struct blame_scoreboard *); 387 388/* 389 * If two blame entries that are next to each other came from 390 * contiguous lines in the same origin (i.e. <commit, path> pair), 391 * merge them together. 392 */ 393static voidblame_coalesce(struct blame_scoreboard *sb) 394{ 395struct blame_entry *ent, *next; 396 397for(ent = sb->ent; ent && (next = ent->next); ent = next) { 398if(ent->suspect == next->suspect && 399 ent->s_lno + ent->num_lines == next->s_lno) { 400 ent->num_lines += next->num_lines; 401 ent->next = next->next; 402blame_origin_decref(next->suspect); 403free(next); 404 ent->score =0; 405 next = ent;/* again */ 406} 407} 408 409if(DEBUG)/* sanity */ 410sanity_check_refcnt(sb); 411} 412 413/* 414 * Merge the given sorted list of blames into a preexisting origin. 415 * If there were no previous blames to that commit, it is entered into 416 * the commit priority queue of the score board. 417 */ 418 419static voidqueue_blames(struct blame_scoreboard *sb,struct blame_origin *porigin, 420struct blame_entry *sorted) 421{ 422if(porigin->suspects) 423 porigin->suspects =blame_merge(porigin->suspects, sorted); 424else{ 425struct blame_origin *o; 426for(o = porigin->commit->util; o; o = o->next) { 427if(o->suspects) { 428 porigin->suspects = sorted; 429return; 430} 431} 432 porigin->suspects = sorted; 433prio_queue_put(&sb->commits, porigin->commit); 434} 435} 436 437/* 438 * Given a commit and a path in it, create a new origin structure. 439 * The callers that add blame to the scoreboard should use 440 * get_origin() to obtain shared, refcounted copy instead of calling 441 * this function directly. 442 */ 443static struct blame_origin *make_origin(struct commit *commit,const char*path) 444{ 445struct blame_origin *o; 446FLEX_ALLOC_STR(o, path, path); 447 o->commit = commit; 448 o->refcnt =1; 449 o->next = commit->util; 450 commit->util = o; 451return o; 452} 453 454/* 455 * Locate an existing origin or create a new one. 456 * This moves the origin to front position in the commit util list. 457 */ 458static struct blame_origin *get_origin(struct commit *commit,const char*path) 459{ 460struct blame_origin *o, *l; 461 462for(o = commit->util, l = NULL; o; l = o, o = o->next) { 463if(!strcmp(o->path, path)) { 464/* bump to front */ 465if(l) { 466 l->next = o->next; 467 o->next = commit->util; 468 commit->util = o; 469} 470returnblame_origin_incref(o); 471} 472} 473returnmake_origin(commit, path); 474} 475 476/* 477 * Fill the blob_sha1 field of an origin if it hasn't, so that later 478 * call to fill_origin_blob() can use it to locate the data. blob_sha1 479 * for an origin is also used to pass the blame for the entire file to 480 * the parent to detect the case where a child's blob is identical to 481 * that of its parent's. 482 * 483 * This also fills origin->mode for corresponding tree path. 484 */ 485static intfill_blob_sha1_and_mode(struct blame_origin *origin) 486{ 487if(!is_null_oid(&origin->blob_oid)) 488return0; 489if(get_tree_entry(origin->commit->object.oid.hash, 490 origin->path, 491 origin->blob_oid.hash, &origin->mode)) 492goto error_out; 493if(sha1_object_info(origin->blob_oid.hash, NULL) != OBJ_BLOB) 494goto error_out; 495return0; 496 error_out: 497oidclr(&origin->blob_oid); 498 origin->mode = S_IFINVALID; 499return-1; 500} 501 502/* 503 * We have an origin -- check if the same path exists in the 504 * parent and return an origin structure to represent it. 505 */ 506static struct blame_origin *find_origin(struct commit *parent, 507struct blame_origin *origin) 508{ 509struct blame_origin *porigin; 510struct diff_options diff_opts; 511const char*paths[2]; 512 513/* First check any existing origins */ 514for(porigin = parent->util; porigin; porigin = porigin->next) 515if(!strcmp(porigin->path, origin->path)) { 516/* 517 * The same path between origin and its parent 518 * without renaming -- the most common case. 519 */ 520returnblame_origin_incref(porigin); 521} 522 523/* See if the origin->path is different between parent 524 * and origin first. Most of the time they are the 525 * same and diff-tree is fairly efficient about this. 526 */ 527diff_setup(&diff_opts); 528DIFF_OPT_SET(&diff_opts, RECURSIVE); 529 diff_opts.detect_rename =0; 530 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 531 paths[0] = origin->path; 532 paths[1] = NULL; 533 534parse_pathspec(&diff_opts.pathspec, 535 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 536 PATHSPEC_LITERAL_PATH,"", paths); 537diff_setup_done(&diff_opts); 538 539if(is_null_oid(&origin->commit->object.oid)) 540do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 541else 542diff_tree_sha1(parent->tree->object.oid.hash, 543 origin->commit->tree->object.oid.hash, 544"", &diff_opts); 545diffcore_std(&diff_opts); 546 547if(!diff_queued_diff.nr) { 548/* The path is the same as parent */ 549 porigin =get_origin(parent, origin->path); 550oidcpy(&porigin->blob_oid, &origin->blob_oid); 551 porigin->mode = origin->mode; 552}else{ 553/* 554 * Since origin->path is a pathspec, if the parent 555 * commit had it as a directory, we will see a whole 556 * bunch of deletion of files in the directory that we 557 * do not care about. 558 */ 559int i; 560struct diff_filepair *p = NULL; 561for(i =0; i < diff_queued_diff.nr; i++) { 562const char*name; 563 p = diff_queued_diff.queue[i]; 564 name = p->one->path ? p->one->path : p->two->path; 565if(!strcmp(name, origin->path)) 566break; 567} 568if(!p) 569die("internal error in blame::find_origin"); 570switch(p->status) { 571default: 572die("internal error in blame::find_origin (%c)", 573 p->status); 574case'M': 575 porigin =get_origin(parent, origin->path); 576oidcpy(&porigin->blob_oid, &p->one->oid); 577 porigin->mode = p->one->mode; 578break; 579case'A': 580case'T': 581/* Did not exist in parent, or type changed */ 582break; 583} 584} 585diff_flush(&diff_opts); 586clear_pathspec(&diff_opts.pathspec); 587return porigin; 588} 589 590/* 591 * We have an origin -- find the path that corresponds to it in its 592 * parent and return an origin structure to represent it. 593 */ 594static struct blame_origin *find_rename(struct commit *parent, 595struct blame_origin *origin) 596{ 597struct blame_origin *porigin = NULL; 598struct diff_options diff_opts; 599int i; 600 601diff_setup(&diff_opts); 602DIFF_OPT_SET(&diff_opts, RECURSIVE); 603 diff_opts.detect_rename = DIFF_DETECT_RENAME; 604 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 605 diff_opts.single_follow = origin->path; 606diff_setup_done(&diff_opts); 607 608if(is_null_oid(&origin->commit->object.oid)) 609do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 610else 611diff_tree_sha1(parent->tree->object.oid.hash, 612 origin->commit->tree->object.oid.hash, 613"", &diff_opts); 614diffcore_std(&diff_opts); 615 616for(i =0; i < diff_queued_diff.nr; i++) { 617struct diff_filepair *p = diff_queued_diff.queue[i]; 618if((p->status =='R'|| p->status =='C') && 619!strcmp(p->two->path, origin->path)) { 620 porigin =get_origin(parent, p->one->path); 621oidcpy(&porigin->blob_oid, &p->one->oid); 622 porigin->mode = p->one->mode; 623break; 624} 625} 626diff_flush(&diff_opts); 627clear_pathspec(&diff_opts.pathspec); 628return porigin; 629} 630 631/* 632 * Append a new blame entry to a given output queue. 633 */ 634static voidadd_blame_entry(struct blame_entry ***queue, 635const struct blame_entry *src) 636{ 637struct blame_entry *e =xmalloc(sizeof(*e)); 638memcpy(e, src,sizeof(*e)); 639blame_origin_incref(e->suspect); 640 641 e->next = **queue; 642**queue = e; 643*queue = &e->next; 644} 645 646/* 647 * src typically is on-stack; we want to copy the information in it to 648 * a malloced blame_entry that gets added to the given queue. The 649 * origin of dst loses a refcnt. 650 */ 651static voiddup_entry(struct blame_entry ***queue, 652struct blame_entry *dst,struct blame_entry *src) 653{ 654blame_origin_incref(src->suspect); 655blame_origin_decref(dst->suspect); 656memcpy(dst, src,sizeof(*src)); 657 dst->next = **queue; 658**queue = dst; 659*queue = &dst->next; 660} 661 662static const char*blame_nth_line(struct blame_scoreboard *sb,long lno) 663{ 664return sb->final_buf + sb->lineno[lno]; 665} 666 667static const char*nth_line_cb(void*data,long lno) 668{ 669returnblame_nth_line((struct blame_scoreboard *)data, lno); 670} 671 672/* 673 * It is known that lines between tlno to same came from parent, and e 674 * has an overlap with that range. it also is known that parent's 675 * line plno corresponds to e's line tlno. 676 * 677 * <---- e -----> 678 * <------> 679 * <------------> 680 * <------------> 681 * <------------------> 682 * 683 * Split e into potentially three parts; before this chunk, the chunk 684 * to be blamed for the parent, and after that portion. 685 */ 686static voidsplit_overlap(struct blame_entry *split, 687struct blame_entry *e, 688int tlno,int plno,int same, 689struct blame_origin *parent) 690{ 691int chunk_end_lno; 692memset(split,0,sizeof(struct blame_entry [3])); 693 694if(e->s_lno < tlno) { 695/* there is a pre-chunk part not blamed on parent */ 696 split[0].suspect =blame_origin_incref(e->suspect); 697 split[0].lno = e->lno; 698 split[0].s_lno = e->s_lno; 699 split[0].num_lines = tlno - e->s_lno; 700 split[1].lno = e->lno + tlno - e->s_lno; 701 split[1].s_lno = plno; 702} 703else{ 704 split[1].lno = e->lno; 705 split[1].s_lno = plno + (e->s_lno - tlno); 706} 707 708if(same < e->s_lno + e->num_lines) { 709/* there is a post-chunk part not blamed on parent */ 710 split[2].suspect =blame_origin_incref(e->suspect); 711 split[2].lno = e->lno + (same - e->s_lno); 712 split[2].s_lno = e->s_lno + (same - e->s_lno); 713 split[2].num_lines = e->s_lno + e->num_lines - same; 714 chunk_end_lno = split[2].lno; 715} 716else 717 chunk_end_lno = e->lno + e->num_lines; 718 split[1].num_lines = chunk_end_lno - split[1].lno; 719 720/* 721 * if it turns out there is nothing to blame the parent for, 722 * forget about the splitting. !split[1].suspect signals this. 723 */ 724if(split[1].num_lines <1) 725return; 726 split[1].suspect =blame_origin_incref(parent); 727} 728 729/* 730 * split_overlap() divided an existing blame e into up to three parts 731 * in split. Any assigned blame is moved to queue to 732 * reflect the split. 733 */ 734static voidsplit_blame(struct blame_entry ***blamed, 735struct blame_entry ***unblamed, 736struct blame_entry *split, 737struct blame_entry *e) 738{ 739if(split[0].suspect && split[2].suspect) { 740/* The first part (reuse storage for the existing entry e) */ 741dup_entry(unblamed, e, &split[0]); 742 743/* The last part -- me */ 744add_blame_entry(unblamed, &split[2]); 745 746/* ... and the middle part -- parent */ 747add_blame_entry(blamed, &split[1]); 748} 749else if(!split[0].suspect && !split[2].suspect) 750/* 751 * The parent covers the entire area; reuse storage for 752 * e and replace it with the parent. 753 */ 754dup_entry(blamed, e, &split[1]); 755else if(split[0].suspect) { 756/* me and then parent */ 757dup_entry(unblamed, e, &split[0]); 758add_blame_entry(blamed, &split[1]); 759} 760else{ 761/* parent and then me */ 762dup_entry(blamed, e, &split[1]); 763add_blame_entry(unblamed, &split[2]); 764} 765} 766 767/* 768 * After splitting the blame, the origins used by the 769 * on-stack blame_entry should lose one refcnt each. 770 */ 771static voiddecref_split(struct blame_entry *split) 772{ 773int i; 774 775for(i =0; i <3; i++) 776blame_origin_decref(split[i].suspect); 777} 778 779/* 780 * reverse_blame reverses the list given in head, appending tail. 781 * That allows us to build lists in reverse order, then reverse them 782 * afterwards. This can be faster than building the list in proper 783 * order right away. The reason is that building in proper order 784 * requires writing a link in the _previous_ element, while building 785 * in reverse order just requires placing the list head into the 786 * _current_ element. 787 */ 788 789static struct blame_entry *reverse_blame(struct blame_entry *head, 790struct blame_entry *tail) 791{ 792while(head) { 793struct blame_entry *next = head->next; 794 head->next = tail; 795 tail = head; 796 head = next; 797} 798return tail; 799} 800 801/* 802 * Process one hunk from the patch between the current suspect for 803 * blame_entry e and its parent. This first blames any unfinished 804 * entries before the chunk (which is where target and parent start 805 * differing) on the parent, and then splits blame entries at the 806 * start and at the end of the difference region. Since use of -M and 807 * -C options may lead to overlapping/duplicate source line number 808 * ranges, all we can rely on from sorting/merging is the order of the 809 * first suspect line number. 810 */ 811static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 812int tlno,int offset,int same, 813struct blame_origin *parent) 814{ 815struct blame_entry *e = **srcq; 816struct blame_entry *samep = NULL, *diffp = NULL; 817 818while(e && e->s_lno < tlno) { 819struct blame_entry *next = e->next; 820/* 821 * current record starts before differing portion. If 822 * it reaches into it, we need to split it up and 823 * examine the second part separately. 824 */ 825if(e->s_lno + e->num_lines > tlno) { 826/* Move second half to a new record */ 827int len = tlno - e->s_lno; 828struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 829 n->suspect = e->suspect; 830 n->lno = e->lno + len; 831 n->s_lno = e->s_lno + len; 832 n->num_lines = e->num_lines - len; 833 e->num_lines = len; 834 e->score =0; 835/* Push new record to diffp */ 836 n->next = diffp; 837 diffp = n; 838}else 839blame_origin_decref(e->suspect); 840/* Pass blame for everything before the differing 841 * chunk to the parent */ 842 e->suspect =blame_origin_incref(parent); 843 e->s_lno += offset; 844 e->next = samep; 845 samep = e; 846 e = next; 847} 848/* 849 * As we don't know how much of a common stretch after this 850 * diff will occur, the currently blamed parts are all that we 851 * can assign to the parent for now. 852 */ 853 854if(samep) { 855**dstq =reverse_blame(samep, **dstq); 856*dstq = &samep->next; 857} 858/* 859 * Prepend the split off portions: everything after e starts 860 * after the blameable portion. 861 */ 862 e =reverse_blame(diffp, e); 863 864/* 865 * Now retain records on the target while parts are different 866 * from the parent. 867 */ 868 samep = NULL; 869 diffp = NULL; 870while(e && e->s_lno < same) { 871struct blame_entry *next = e->next; 872 873/* 874 * If current record extends into sameness, need to split. 875 */ 876if(e->s_lno + e->num_lines > same) { 877/* 878 * Move second half to a new record to be 879 * processed by later chunks 880 */ 881int len = same - e->s_lno; 882struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 883 n->suspect =blame_origin_incref(e->suspect); 884 n->lno = e->lno + len; 885 n->s_lno = e->s_lno + len; 886 n->num_lines = e->num_lines - len; 887 e->num_lines = len; 888 e->score =0; 889/* Push new record to samep */ 890 n->next = samep; 891 samep = n; 892} 893 e->next = diffp; 894 diffp = e; 895 e = next; 896} 897**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 898/* Move across elements that are in the unblamable portion */ 899if(diffp) 900*srcq = &diffp->next; 901} 902 903struct blame_chunk_cb_data { 904struct blame_origin *parent; 905long offset; 906struct blame_entry **dstq; 907struct blame_entry **srcq; 908}; 909 910/* diff chunks are from parent to target */ 911static intblame_chunk_cb(long start_a,long count_a, 912long start_b,long count_b,void*data) 913{ 914struct blame_chunk_cb_data *d = data; 915if(start_a - start_b != d->offset) 916die("internal error in blame::blame_chunk_cb"); 917blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 918 start_b + count_b, d->parent); 919 d->offset = start_a + count_a - (start_b + count_b); 920return0; 921} 922 923/* 924 * We are looking at the origin 'target' and aiming to pass blame 925 * for the lines it is suspected to its parent. Run diff to find 926 * which lines came from parent and pass blame for them. 927 */ 928static voidpass_blame_to_parent(struct blame_scoreboard *sb, 929struct blame_origin *target, 930struct blame_origin *parent) 931{ 932 mmfile_t file_p, file_o; 933struct blame_chunk_cb_data d; 934struct blame_entry *newdest = NULL; 935 936if(!target->suspects) 937return;/* nothing remains for this target */ 938 939 d.parent = parent; 940 d.offset =0; 941 d.dstq = &newdest; d.srcq = &target->suspects; 942 943fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob); 944fill_origin_blob(&sb->revs->diffopt, target, &file_o, &sb->num_read_blob); 945 sb->num_get_patch++; 946 947if(diff_hunks(&file_p, &file_o, blame_chunk_cb, &d)) 948die("unable to generate diff (%s->%s)", 949oid_to_hex(&parent->commit->object.oid), 950oid_to_hex(&target->commit->object.oid)); 951/* The rest are the same as the parent */ 952blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 953*d.dstq = NULL; 954queue_blames(sb, parent, newdest); 955 956return; 957} 958 959/* 960 * The lines in blame_entry after splitting blames many times can become 961 * very small and trivial, and at some point it becomes pointless to 962 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 963 * ordinary C program, and it is not worth to say it was copied from 964 * totally unrelated file in the parent. 965 * 966 * Compute how trivial the lines in the blame_entry are. 967 */ 968static unsignedblame_entry_score(struct blame_scoreboard *sb,struct blame_entry *e) 969{ 970unsigned score; 971const char*cp, *ep; 972 973if(e->score) 974return e->score; 975 976 score =1; 977 cp =blame_nth_line(sb, e->lno); 978 ep =blame_nth_line(sb, e->lno + e->num_lines); 979while(cp < ep) { 980unsigned ch = *((unsigned char*)cp); 981if(isalnum(ch)) 982 score++; 983 cp++; 984} 985 e->score = score; 986return score; 987} 988 989/* 990 * best_so_far[] and this[] are both a split of an existing blame_entry 991 * that passes blame to the parent. Maintain best_so_far the best split 992 * so far, by comparing this and best_so_far and copying this into 993 * bst_so_far as needed. 994 */ 995static voidcopy_split_if_better(struct blame_scoreboard *sb, 996struct blame_entry *best_so_far, 997struct blame_entry *this) 998{ 999int i;10001001if(!this[1].suspect)1002return;1003if(best_so_far[1].suspect) {1004if(blame_entry_score(sb, &this[1]) <blame_entry_score(sb, &best_so_far[1]))1005return;1006}10071008for(i =0; i <3; i++)1009blame_origin_incref(this[i].suspect);1010decref_split(best_so_far);1011memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1012}10131014/*1015 * We are looking at a part of the final image represented by1016 * ent (tlno and same are offset by ent->s_lno).1017 * tlno is where we are looking at in the final image.1018 * up to (but not including) same match preimage.1019 * plno is where we are looking at in the preimage.1020 *1021 * <-------------- final image ---------------------->1022 * <------ent------>1023 * ^tlno ^same1024 * <---------preimage----->1025 * ^plno1026 *1027 * All line numbers are 0-based.1028 */1029static voidhandle_split(struct blame_scoreboard *sb,1030struct blame_entry *ent,1031int tlno,int plno,int same,1032struct blame_origin *parent,1033struct blame_entry *split)1034{1035if(ent->num_lines <= tlno)1036return;1037if(tlno < same) {1038struct blame_entry this[3];1039 tlno += ent->s_lno;1040 same += ent->s_lno;1041split_overlap(this, ent, tlno, plno, same, parent);1042copy_split_if_better(sb, split,this);1043decref_split(this);1044}1045}10461047struct handle_split_cb_data {1048struct blame_scoreboard *sb;1049struct blame_entry *ent;1050struct blame_origin *parent;1051struct blame_entry *split;1052long plno;1053long tlno;1054};10551056static inthandle_split_cb(long start_a,long count_a,1057long start_b,long count_b,void*data)1058{1059struct handle_split_cb_data *d = data;1060handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1061 d->split);1062 d->plno = start_a + count_a;1063 d->tlno = start_b + count_b;1064return0;1065}10661067/*1068 * Find the lines from parent that are the same as ent so that1069 * we can pass blames to it. file_p has the blob contents for1070 * the parent.1071 */1072static voidfind_copy_in_blob(struct blame_scoreboard *sb,1073struct blame_entry *ent,1074struct blame_origin *parent,1075struct blame_entry *split,1076 mmfile_t *file_p)1077{1078const char*cp;1079 mmfile_t file_o;1080struct handle_split_cb_data d;10811082memset(&d,0,sizeof(d));1083 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1084/*1085 * Prepare mmfile that contains only the lines in ent.1086 */1087 cp =blame_nth_line(sb, ent->lno);1088 file_o.ptr = (char*) cp;1089 file_o.size =blame_nth_line(sb, ent->lno + ent->num_lines) - cp;10901091/*1092 * file_o is a part of final image we are annotating.1093 * file_p partially may match that image.1094 */1095memset(split,0,sizeof(struct blame_entry [3]));1096if(diff_hunks(file_p, &file_o, handle_split_cb, &d))1097die("unable to generate diff (%s)",1098oid_to_hex(&parent->commit->object.oid));1099/* remainder, if any, all match the preimage */1100handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1101}11021103/* Move all blame entries from list *source that have a score smaller1104 * than score_min to the front of list *small.1105 * Returns a pointer to the link pointing to the old head of the small list.1106 */11071108static struct blame_entry **filter_small(struct blame_scoreboard *sb,1109struct blame_entry **small,1110struct blame_entry **source,1111unsigned score_min)1112{1113struct blame_entry *p = *source;1114struct blame_entry *oldsmall = *small;1115while(p) {1116if(blame_entry_score(sb, p) <= score_min) {1117*small = p;1118 small = &p->next;1119 p = *small;1120}else{1121*source = p;1122 source = &p->next;1123 p = *source;1124}1125}1126*small = oldsmall;1127*source = NULL;1128return small;1129}11301131/*1132 * See if lines currently target is suspected for can be attributed to1133 * parent.1134 */1135static voidfind_move_in_parent(struct blame_scoreboard *sb,1136struct blame_entry ***blamed,1137struct blame_entry **toosmall,1138struct blame_origin *target,1139struct blame_origin *parent)1140{1141struct blame_entry *e, split[3];1142struct blame_entry *unblamed = target->suspects;1143struct blame_entry *leftover = NULL;1144 mmfile_t file_p;11451146if(!unblamed)1147return;/* nothing remains for this target */11481149fill_origin_blob(&sb->revs->diffopt, parent, &file_p, &sb->num_read_blob);1150if(!file_p.ptr)1151return;11521153/* At each iteration, unblamed has a NULL-terminated list of1154 * entries that have not yet been tested for blame. leftover1155 * contains the reversed list of entries that have been tested1156 * without being assignable to the parent.1157 */1158do{1159struct blame_entry **unblamedtail = &unblamed;1160struct blame_entry *next;1161for(e = unblamed; e; e = next) {1162 next = e->next;1163find_copy_in_blob(sb, e, parent, split, &file_p);1164if(split[1].suspect &&1165 sb->move_score <blame_entry_score(sb, &split[1])) {1166split_blame(blamed, &unblamedtail, split, e);1167}else{1168 e->next = leftover;1169 leftover = e;1170}1171decref_split(split);1172}1173*unblamedtail = NULL;1174 toosmall =filter_small(sb, toosmall, &unblamed, sb->move_score);1175}while(unblamed);1176 target->suspects =reverse_blame(leftover, NULL);1177}11781179struct blame_list {1180struct blame_entry *ent;1181struct blame_entry split[3];1182};11831184/*1185 * Count the number of entries the target is suspected for,1186 * and prepare a list of entry and the best split.1187 */1188static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1189int*num_ents_p)1190{1191struct blame_entry *e;1192int num_ents, i;1193struct blame_list *blame_list = NULL;11941195for(e = unblamed, num_ents =0; e; e = e->next)1196 num_ents++;1197if(num_ents) {1198 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1199for(e = unblamed, i =0; e; e = e->next)1200 blame_list[i++].ent = e;1201}1202*num_ents_p = num_ents;1203return blame_list;1204}12051206/*1207 * For lines target is suspected for, see if we can find code movement1208 * across file boundary from the parent commit. porigin is the path1209 * in the parent we already tried.1210 */1211static voidfind_copy_in_parent(struct blame_scoreboard *sb,1212struct blame_entry ***blamed,1213struct blame_entry **toosmall,1214struct blame_origin *target,1215struct commit *parent,1216struct blame_origin *porigin,1217int opt)1218{1219struct diff_options diff_opts;1220int i, j;1221struct blame_list *blame_list;1222int num_ents;1223struct blame_entry *unblamed = target->suspects;1224struct blame_entry *leftover = NULL;12251226if(!unblamed)1227return;/* nothing remains for this target */12281229diff_setup(&diff_opts);1230DIFF_OPT_SET(&diff_opts, RECURSIVE);1231 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12321233diff_setup_done(&diff_opts);12341235/* Try "find copies harder" on new path if requested;1236 * we do not want to use diffcore_rename() actually to1237 * match things up; find_copies_harder is set only to1238 * force diff_tree_sha1() to feed all filepairs to diff_queue,1239 * and this code needs to be after diff_setup_done(), which1240 * usually makes find-copies-harder imply copy detection.1241 */1242if((opt & PICKAXE_BLAME_COPY_HARDEST)1243|| ((opt & PICKAXE_BLAME_COPY_HARDER)1244&& (!porigin ||strcmp(target->path, porigin->path))))1245DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12461247if(is_null_oid(&target->commit->object.oid))1248do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1249else1250diff_tree_sha1(parent->tree->object.oid.hash,1251 target->commit->tree->object.oid.hash,1252"", &diff_opts);12531254if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1255diffcore_std(&diff_opts);12561257do{1258struct blame_entry **unblamedtail = &unblamed;1259 blame_list =setup_blame_list(unblamed, &num_ents);12601261for(i =0; i < diff_queued_diff.nr; i++) {1262struct diff_filepair *p = diff_queued_diff.queue[i];1263struct blame_origin *norigin;1264 mmfile_t file_p;1265struct blame_entry this[3];12661267if(!DIFF_FILE_VALID(p->one))1268continue;/* does not exist in parent */1269if(S_ISGITLINK(p->one->mode))1270continue;/* ignore git links */1271if(porigin && !strcmp(p->one->path, porigin->path))1272/* find_move already dealt with this path */1273continue;12741275 norigin =get_origin(parent, p->one->path);1276oidcpy(&norigin->blob_oid, &p->one->oid);1277 norigin->mode = p->one->mode;1278fill_origin_blob(&sb->revs->diffopt, norigin, &file_p, &sb->num_read_blob);1279if(!file_p.ptr)1280continue;12811282for(j =0; j < num_ents; j++) {1283find_copy_in_blob(sb, blame_list[j].ent,1284 norigin,this, &file_p);1285copy_split_if_better(sb, blame_list[j].split,1286this);1287decref_split(this);1288}1289blame_origin_decref(norigin);1290}12911292for(j =0; j < num_ents; j++) {1293struct blame_entry *split = blame_list[j].split;1294if(split[1].suspect &&1295 sb->copy_score <blame_entry_score(sb, &split[1])) {1296split_blame(blamed, &unblamedtail, split,1297 blame_list[j].ent);1298}else{1299 blame_list[j].ent->next = leftover;1300 leftover = blame_list[j].ent;1301}1302decref_split(split);1303}1304free(blame_list);1305*unblamedtail = NULL;1306 toosmall =filter_small(sb, toosmall, &unblamed, sb->copy_score);1307}while(unblamed);1308 target->suspects =reverse_blame(leftover, NULL);1309diff_flush(&diff_opts);1310clear_pathspec(&diff_opts.pathspec);1311}13121313/*1314 * The blobs of origin and porigin exactly match, so everything1315 * origin is suspected for can be blamed on the parent.1316 */1317static voidpass_whole_blame(struct blame_scoreboard *sb,1318struct blame_origin *origin,struct blame_origin *porigin)1319{1320struct blame_entry *e, *suspects;13211322if(!porigin->file.ptr && origin->file.ptr) {1323/* Steal its file */1324 porigin->file = origin->file;1325 origin->file.ptr = NULL;1326}1327 suspects = origin->suspects;1328 origin->suspects = NULL;1329for(e = suspects; e; e = e->next) {1330blame_origin_incref(porigin);1331blame_origin_decref(e->suspect);1332 e->suspect = porigin;1333}1334queue_blames(sb, porigin, suspects);1335}13361337/*1338 * We pass blame from the current commit to its parents. We keep saying1339 * "parent" (and "porigin"), but what we mean is to find scapegoat to1340 * exonerate ourselves.1341 */1342static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1343{1344if(!reverse) {1345if(revs->first_parent_only &&1346 commit->parents &&1347 commit->parents->next) {1348free_commit_list(commit->parents->next);1349 commit->parents->next = NULL;1350}1351return commit->parents;1352}1353returnlookup_decoration(&revs->children, &commit->object);1354}13551356static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1357{1358struct commit_list *l =first_scapegoat(revs, commit);1359returncommit_list_count(l);1360}13611362/* Distribute collected unsorted blames to the respected sorted lists1363 * in the various origins.1364 */1365static voiddistribute_blame(struct blame_scoreboard *sb,struct blame_entry *blamed)1366{1367 blamed =blame_sort(blamed, compare_blame_suspect);1368while(blamed)1369{1370struct blame_origin *porigin = blamed->suspect;1371struct blame_entry *suspects = NULL;1372do{1373struct blame_entry *next = blamed->next;1374 blamed->next = suspects;1375 suspects = blamed;1376 blamed = next;1377}while(blamed && blamed->suspect == porigin);1378 suspects =reverse_blame(suspects, NULL);1379queue_blames(sb, porigin, suspects);1380}1381}13821383#define MAXSG 1613841385static voidpass_blame(struct blame_scoreboard *sb,struct blame_origin *origin,int opt)1386{1387struct rev_info *revs = sb->revs;1388int i, pass, num_sg;1389struct commit *commit = origin->commit;1390struct commit_list *sg;1391struct blame_origin *sg_buf[MAXSG];1392struct blame_origin *porigin, **sg_origin = sg_buf;1393struct blame_entry *toosmall = NULL;1394struct blame_entry *blames, **blametail = &blames;13951396 num_sg =num_scapegoats(revs, commit);1397if(!num_sg)1398goto finish;1399else if(num_sg <ARRAY_SIZE(sg_buf))1400memset(sg_buf,0,sizeof(sg_buf));1401else1402 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14031404/*1405 * The first pass looks for unrenamed path to optimize for1406 * common cases, then we look for renames in the second pass.1407 */1408for(pass =0; pass <2- no_whole_file_rename; pass++) {1409struct blame_origin *(*find)(struct commit *,struct blame_origin *);1410 find = pass ? find_rename : find_origin;14111412for(i =0, sg =first_scapegoat(revs, commit);1413 i < num_sg && sg;1414 sg = sg->next, i++) {1415struct commit *p = sg->item;1416int j, same;14171418if(sg_origin[i])1419continue;1420if(parse_commit(p))1421continue;1422 porigin =find(p, origin);1423if(!porigin)1424continue;1425if(!oidcmp(&porigin->blob_oid, &origin->blob_oid)) {1426pass_whole_blame(sb, origin, porigin);1427blame_origin_decref(porigin);1428goto finish;1429}1430for(j = same =0; j < i; j++)1431if(sg_origin[j] &&1432!oidcmp(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {1433 same =1;1434break;1435}1436if(!same)1437 sg_origin[i] = porigin;1438else1439blame_origin_decref(porigin);1440}1441}14421443 sb->num_commits++;1444for(i =0, sg =first_scapegoat(revs, commit);1445 i < num_sg && sg;1446 sg = sg->next, i++) {1447struct blame_origin *porigin = sg_origin[i];1448if(!porigin)1449continue;1450if(!origin->previous) {1451blame_origin_incref(porigin);1452 origin->previous = porigin;1453}1454pass_blame_to_parent(sb, origin, porigin);1455if(!origin->suspects)1456goto finish;1457}14581459/*1460 * Optionally find moves in parents' files.1461 */1462if(opt & PICKAXE_BLAME_MOVE) {1463filter_small(sb, &toosmall, &origin->suspects, sb->move_score);1464if(origin->suspects) {1465for(i =0, sg =first_scapegoat(revs, commit);1466 i < num_sg && sg;1467 sg = sg->next, i++) {1468struct blame_origin *porigin = sg_origin[i];1469if(!porigin)1470continue;1471find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1472if(!origin->suspects)1473break;1474}1475}1476}14771478/*1479 * Optionally find copies from parents' files.1480 */1481if(opt & PICKAXE_BLAME_COPY) {1482if(sb->copy_score > sb->move_score)1483filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);1484else if(sb->copy_score < sb->move_score) {1485 origin->suspects =blame_merge(origin->suspects, toosmall);1486 toosmall = NULL;1487filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);1488}1489if(!origin->suspects)1490goto finish;14911492for(i =0, sg =first_scapegoat(revs, commit);1493 i < num_sg && sg;1494 sg = sg->next, i++) {1495struct blame_origin *porigin = sg_origin[i];1496find_copy_in_parent(sb, &blametail, &toosmall,1497 origin, sg->item, porigin, opt);1498if(!origin->suspects)1499goto finish;1500}1501}15021503finish:1504*blametail = NULL;1505distribute_blame(sb, blames);1506/*1507 * prepend toosmall to origin->suspects1508 *1509 * There is no point in sorting: this ends up on a big1510 * unsorted list in the caller anyway.1511 */1512if(toosmall) {1513struct blame_entry **tail = &toosmall;1514while(*tail)1515 tail = &(*tail)->next;1516*tail = origin->suspects;1517 origin->suspects = toosmall;1518}1519for(i =0; i < num_sg; i++) {1520if(sg_origin[i]) {1521drop_origin_blob(sg_origin[i]);1522blame_origin_decref(sg_origin[i]);1523}1524}1525drop_origin_blob(origin);1526if(sg_buf != sg_origin)1527free(sg_origin);1528}15291530/*1531 * Information on commits, used for output.1532 */1533struct commit_info {1534struct strbuf author;1535struct strbuf author_mail;1536 timestamp_t author_time;1537struct strbuf author_tz;15381539/* filled only when asked for details */1540struct strbuf committer;1541struct strbuf committer_mail;1542 timestamp_t committer_time;1543struct strbuf committer_tz;15441545struct strbuf summary;1546};15471548/*1549 * Parse author/committer line in the commit object buffer1550 */1551static voidget_ac_line(const char*inbuf,const char*what,1552struct strbuf *name,struct strbuf *mail,1553 timestamp_t *time,struct strbuf *tz)1554{1555struct ident_split ident;1556size_t len, maillen, namelen;1557char*tmp, *endp;1558const char*namebuf, *mailbuf;15591560 tmp =strstr(inbuf, what);1561if(!tmp)1562goto error_out;1563 tmp +=strlen(what);1564 endp =strchr(tmp,'\n');1565if(!endp)1566 len =strlen(tmp);1567else1568 len = endp - tmp;15691570if(split_ident_line(&ident, tmp, len)) {1571 error_out:1572/* Ugh */1573 tmp ="(unknown)";1574strbuf_addstr(name, tmp);1575strbuf_addstr(mail, tmp);1576strbuf_addstr(tz, tmp);1577*time =0;1578return;1579}15801581 namelen = ident.name_end - ident.name_begin;1582 namebuf = ident.name_begin;15831584 maillen = ident.mail_end - ident.mail_begin;1585 mailbuf = ident.mail_begin;15861587if(ident.date_begin && ident.date_end)1588*time =strtoul(ident.date_begin, NULL,10);1589else1590*time =0;15911592if(ident.tz_begin && ident.tz_end)1593strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1594else1595strbuf_addstr(tz,"(unknown)");15961597/*1598 * Now, convert both name and e-mail using mailmap1599 */1600map_user(&mailmap, &mailbuf, &maillen,1601&namebuf, &namelen);16021603strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1604strbuf_add(name, namebuf, namelen);1605}16061607static voidcommit_info_init(struct commit_info *ci)1608{16091610strbuf_init(&ci->author,0);1611strbuf_init(&ci->author_mail,0);1612strbuf_init(&ci->author_tz,0);1613strbuf_init(&ci->committer,0);1614strbuf_init(&ci->committer_mail,0);1615strbuf_init(&ci->committer_tz,0);1616strbuf_init(&ci->summary,0);1617}16181619static voidcommit_info_destroy(struct commit_info *ci)1620{16211622strbuf_release(&ci->author);1623strbuf_release(&ci->author_mail);1624strbuf_release(&ci->author_tz);1625strbuf_release(&ci->committer);1626strbuf_release(&ci->committer_mail);1627strbuf_release(&ci->committer_tz);1628strbuf_release(&ci->summary);1629}16301631static voidget_commit_info(struct commit *commit,1632struct commit_info *ret,1633int detailed)1634{1635int len;1636const char*subject, *encoding;1637const char*message;16381639commit_info_init(ret);16401641 encoding =get_log_output_encoding();1642 message =logmsg_reencode(commit, NULL, encoding);1643get_ac_line(message,"\nauthor ",1644&ret->author, &ret->author_mail,1645&ret->author_time, &ret->author_tz);16461647if(!detailed) {1648unuse_commit_buffer(commit, message);1649return;1650}16511652get_ac_line(message,"\ncommitter ",1653&ret->committer, &ret->committer_mail,1654&ret->committer_time, &ret->committer_tz);16551656 len =find_commit_subject(message, &subject);1657if(len)1658strbuf_add(&ret->summary, subject, len);1659else1660strbuf_addf(&ret->summary,"(%s)",oid_to_hex(&commit->object.oid));16611662unuse_commit_buffer(commit, message);1663}16641665/*1666 * Write out any suspect information which depends on the path. This must be1667 * handled separately from emit_one_suspect_detail(), because a given commit1668 * may have changes in multiple paths. So this needs to appear each time1669 * we mention a new group.1670 *1671 * To allow LF and other nonportable characters in pathnames,1672 * they are c-style quoted as needed.1673 */1674static voidwrite_filename_info(struct blame_origin *suspect)1675{1676if(suspect->previous) {1677struct blame_origin *prev = suspect->previous;1678printf("previous%s",oid_to_hex(&prev->commit->object.oid));1679write_name_quoted(prev->path, stdout,'\n');1680}1681printf("filename ");1682write_name_quoted(suspect->path, stdout,'\n');1683}16841685/*1686 * Porcelain/Incremental format wants to show a lot of details per1687 * commit. Instead of repeating this every line, emit it only once,1688 * the first time each commit appears in the output (unless the1689 * user has specifically asked for us to repeat).1690 */1691static intemit_one_suspect_detail(struct blame_origin *suspect,int repeat)1692{1693struct commit_info ci;16941695if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1696return0;16971698 suspect->commit->object.flags |= METAINFO_SHOWN;1699get_commit_info(suspect->commit, &ci,1);1700printf("author%s\n", ci.author.buf);1701printf("author-mail%s\n", ci.author_mail.buf);1702printf("author-time %"PRItime"\n", ci.author_time);1703printf("author-tz%s\n", ci.author_tz.buf);1704printf("committer%s\n", ci.committer.buf);1705printf("committer-mail%s\n", ci.committer_mail.buf);1706printf("committer-time %"PRItime"\n", ci.committer_time);1707printf("committer-tz%s\n", ci.committer_tz.buf);1708printf("summary%s\n", ci.summary.buf);1709if(suspect->commit->object.flags & UNINTERESTING)1710printf("boundary\n");17111712commit_info_destroy(&ci);17131714return1;1715}17161717/*1718 * The blame_entry is found to be guilty for the range.1719 * Show it in incremental output.1720 */1721static voidfound_guilty_entry(struct blame_entry *ent,1722struct progress_info *pi)1723{1724if(incremental) {1725struct blame_origin *suspect = ent->suspect;17261727printf("%s %d %d %d\n",1728oid_to_hex(&suspect->commit->object.oid),1729 ent->s_lno +1, ent->lno +1, ent->num_lines);1730emit_one_suspect_detail(suspect,0);1731write_filename_info(suspect);1732maybe_flush_or_die(stdout,"stdout");1733}1734 pi->blamed_lines += ent->num_lines;1735display_progress(pi->progress, pi->blamed_lines);1736}17371738/*1739 * The main loop -- while we have blobs with lines whose true origin1740 * is still unknown, pick one blob, and allow its lines to pass blames1741 * to its parents. */1742static voidassign_blame(struct blame_scoreboard *sb,int opt)1743{1744struct rev_info *revs = sb->revs;1745struct commit *commit =prio_queue_get(&sb->commits);1746struct progress_info pi = { NULL,0};17471748if(show_progress)1749 pi.progress =start_progress_delay(_("Blaming lines"),1750 sb->num_lines,50,1);17511752while(commit) {1753struct blame_entry *ent;1754struct blame_origin *suspect = commit->util;17551756/* find one suspect to break down */1757while(suspect && !suspect->suspects)1758 suspect = suspect->next;17591760if(!suspect) {1761 commit =prio_queue_get(&sb->commits);1762continue;1763}17641765assert(commit == suspect->commit);17661767/*1768 * We will use this suspect later in the loop,1769 * so hold onto it in the meantime.1770 */1771blame_origin_incref(suspect);1772parse_commit(commit);1773if(reverse ||1774(!(commit->object.flags & UNINTERESTING) &&1775!(revs->max_age != -1&& commit->date < revs->max_age)))1776pass_blame(sb, suspect, opt);1777else{1778 commit->object.flags |= UNINTERESTING;1779if(commit->object.parsed)1780mark_parents_uninteresting(commit);1781}1782/* treat root commit as boundary */1783if(!commit->parents && !show_root)1784 commit->object.flags |= UNINTERESTING;17851786/* Take responsibility for the remaining entries */1787 ent = suspect->suspects;1788if(ent) {1789 suspect->guilty =1;1790for(;;) {1791struct blame_entry *next = ent->next;1792found_guilty_entry(ent, &pi);1793if(next) {1794 ent = next;1795continue;1796}1797 ent->next = sb->ent;1798 sb->ent = suspect->suspects;1799 suspect->suspects = NULL;1800break;1801}1802}1803blame_origin_decref(suspect);18041805if(DEBUG)/* sanity */1806sanity_check_refcnt(sb);1807}18081809stop_progress(&pi.progress);1810}18111812static const char*format_time(timestamp_t time,const char*tz_str,1813int show_raw_time)1814{1815static struct strbuf time_buf = STRBUF_INIT;18161817strbuf_reset(&time_buf);1818if(show_raw_time) {1819strbuf_addf(&time_buf,"%"PRItime"%s", time, tz_str);1820}1821else{1822const char*time_str;1823size_t time_width;1824int tz;1825 tz =atoi(tz_str);1826 time_str =show_date(time, tz, &blame_date_mode);1827strbuf_addstr(&time_buf, time_str);1828/*1829 * Add space paddings to time_buf to display a fixed width1830 * string, and use time_width for display width calibration.1831 */1832for(time_width =utf8_strwidth(time_str);1833 time_width < blame_date_width;1834 time_width++)1835strbuf_addch(&time_buf,' ');1836}1837return time_buf.buf;1838}18391840#define OUTPUT_ANNOTATE_COMPAT 0011841#define OUTPUT_LONG_OBJECT_NAME 0021842#define OUTPUT_RAW_TIMESTAMP 0041843#define OUTPUT_PORCELAIN 0101844#define OUTPUT_SHOW_NAME 0201845#define OUTPUT_SHOW_NUMBER 0401846#define OUTPUT_SHOW_SCORE 01001847#define OUTPUT_NO_AUTHOR 02001848#define OUTPUT_SHOW_EMAIL 04001849#define OUTPUT_LINE_PORCELAIN 0100018501851static voidemit_porcelain_details(struct blame_origin *suspect,int repeat)1852{1853if(emit_one_suspect_detail(suspect, repeat) ||1854(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1855write_filename_info(suspect);1856}18571858static voidemit_porcelain(struct blame_scoreboard *sb,struct blame_entry *ent,1859int opt)1860{1861int repeat = opt & OUTPUT_LINE_PORCELAIN;1862int cnt;1863const char*cp;1864struct blame_origin *suspect = ent->suspect;1865char hex[GIT_MAX_HEXSZ +1];18661867oid_to_hex_r(hex, &suspect->commit->object.oid);1868printf("%s %d %d %d\n",1869 hex,1870 ent->s_lno +1,1871 ent->lno +1,1872 ent->num_lines);1873emit_porcelain_details(suspect, repeat);18741875 cp =blame_nth_line(sb, ent->lno);1876for(cnt =0; cnt < ent->num_lines; cnt++) {1877char ch;1878if(cnt) {1879printf("%s %d %d\n", hex,1880 ent->s_lno +1+ cnt,1881 ent->lno +1+ cnt);1882if(repeat)1883emit_porcelain_details(suspect,1);1884}1885putchar('\t');1886do{1887 ch = *cp++;1888putchar(ch);1889}while(ch !='\n'&&1890 cp < sb->final_buf + sb->final_buf_size);1891}18921893if(sb->final_buf_size && cp[-1] !='\n')1894putchar('\n');1895}18961897static voidemit_other(struct blame_scoreboard *sb,struct blame_entry *ent,int opt)1898{1899int cnt;1900const char*cp;1901struct blame_origin *suspect = ent->suspect;1902struct commit_info ci;1903char hex[GIT_MAX_HEXSZ +1];1904int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19051906get_commit_info(suspect->commit, &ci,1);1907oid_to_hex_r(hex, &suspect->commit->object.oid);19081909 cp =blame_nth_line(sb, ent->lno);1910for(cnt =0; cnt < ent->num_lines; cnt++) {1911char ch;1912int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? GIT_SHA1_HEXSZ : abbrev;19131914if(suspect->commit->object.flags & UNINTERESTING) {1915if(blank_boundary)1916memset(hex,' ', length);1917else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1918 length--;1919putchar('^');1920}1921}19221923printf("%.*s", length, hex);1924if(opt & OUTPUT_ANNOTATE_COMPAT) {1925const char*name;1926if(opt & OUTPUT_SHOW_EMAIL)1927 name = ci.author_mail.buf;1928else1929 name = ci.author.buf;1930printf("\t(%10s\t%10s\t%d)", name,1931format_time(ci.author_time, ci.author_tz.buf,1932 show_raw_time),1933 ent->lno +1+ cnt);1934}else{1935if(opt & OUTPUT_SHOW_SCORE)1936printf(" %*d%02d",1937 max_score_digits, ent->score,1938 ent->suspect->refcnt);1939if(opt & OUTPUT_SHOW_NAME)1940printf(" %-*.*s", longest_file, longest_file,1941 suspect->path);1942if(opt & OUTPUT_SHOW_NUMBER)1943printf(" %*d", max_orig_digits,1944 ent->s_lno +1+ cnt);19451946if(!(opt & OUTPUT_NO_AUTHOR)) {1947const char*name;1948int pad;1949if(opt & OUTPUT_SHOW_EMAIL)1950 name = ci.author_mail.buf;1951else1952 name = ci.author.buf;1953 pad = longest_author -utf8_strwidth(name);1954printf(" (%s%*s%10s",1955 name, pad,"",1956format_time(ci.author_time,1957 ci.author_tz.buf,1958 show_raw_time));1959}1960printf(" %*d) ",1961 max_digits, ent->lno +1+ cnt);1962}1963do{1964 ch = *cp++;1965putchar(ch);1966}while(ch !='\n'&&1967 cp < sb->final_buf + sb->final_buf_size);1968}19691970if(sb->final_buf_size && cp[-1] !='\n')1971putchar('\n');19721973commit_info_destroy(&ci);1974}19751976static voidoutput(struct blame_scoreboard *sb,int option)1977{1978struct blame_entry *ent;19791980if(option & OUTPUT_PORCELAIN) {1981for(ent = sb->ent; ent; ent = ent->next) {1982int count =0;1983struct blame_origin *suspect;1984struct commit *commit = ent->suspect->commit;1985if(commit->object.flags & MORE_THAN_ONE_PATH)1986continue;1987for(suspect = commit->util; suspect; suspect = suspect->next) {1988if(suspect->guilty && count++) {1989 commit->object.flags |= MORE_THAN_ONE_PATH;1990break;1991}1992}1993}1994}19951996for(ent = sb->ent; ent; ent = ent->next) {1997if(option & OUTPUT_PORCELAIN)1998emit_porcelain(sb, ent, option);1999else{2000emit_other(sb, ent, option);2001}2002}2003}20042005static const char*get_next_line(const char*start,const char*end)2006{2007const char*nl =memchr(start,'\n', end - start);2008return nl ? nl +1: end;2009}20102011/*2012 * To allow quick access to the contents of nth line in the2013 * final image, prepare an index in the scoreboard.2014 */2015static intprepare_lines(struct blame_scoreboard *sb)2016{2017const char*buf = sb->final_buf;2018unsigned long len = sb->final_buf_size;2019const char*end = buf + len;2020const char*p;2021int*lineno;2022int num =0;20232024for(p = buf; p < end; p =get_next_line(p, end))2025 num++;20262027ALLOC_ARRAY(sb->lineno, num +1);2028 lineno = sb->lineno;20292030for(p = buf; p < end; p =get_next_line(p, end))2031*lineno++ = p - buf;20322033*lineno = len;20342035 sb->num_lines = num;2036return sb->num_lines;2037}20382039/*2040 * Add phony grafts for use with -S; this is primarily to2041 * support git's cvsserver that wants to give a linear history2042 * to its clients.2043 */2044static intread_ancestry(const char*graft_file)2045{2046FILE*fp =fopen(graft_file,"r");2047struct strbuf buf = STRBUF_INIT;2048if(!fp)2049return-1;2050while(!strbuf_getwholeline(&buf, fp,'\n')) {2051/* The format is just "Commit Parent1 Parent2 ...\n" */2052struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2053if(graft)2054register_commit_graft(graft,0);2055}2056fclose(fp);2057strbuf_release(&buf);2058return0;2059}20602061static intupdate_auto_abbrev(int auto_abbrev,struct blame_origin *suspect)2062{2063const char*uniq =find_unique_abbrev(suspect->commit->object.oid.hash,2064 auto_abbrev);2065int len =strlen(uniq);2066if(auto_abbrev < len)2067return len;2068return auto_abbrev;2069}20702071/*2072 * How many columns do we need to show line numbers, authors,2073 * and filenames?2074 */2075static voidfind_alignment(struct blame_scoreboard *sb,int*option)2076{2077int longest_src_lines =0;2078int longest_dst_lines =0;2079unsigned largest_score =0;2080struct blame_entry *e;2081int compute_auto_abbrev = (abbrev <0);2082int auto_abbrev = DEFAULT_ABBREV;20832084for(e = sb->ent; e; e = e->next) {2085struct blame_origin *suspect = e->suspect;2086int num;20872088if(compute_auto_abbrev)2089 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2090if(strcmp(suspect->path, sb->path))2091*option |= OUTPUT_SHOW_NAME;2092 num =strlen(suspect->path);2093if(longest_file < num)2094 longest_file = num;2095if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2096struct commit_info ci;2097 suspect->commit->object.flags |= METAINFO_SHOWN;2098get_commit_info(suspect->commit, &ci,1);2099if(*option & OUTPUT_SHOW_EMAIL)2100 num =utf8_strwidth(ci.author_mail.buf);2101else2102 num =utf8_strwidth(ci.author.buf);2103if(longest_author < num)2104 longest_author = num;2105commit_info_destroy(&ci);2106}2107 num = e->s_lno + e->num_lines;2108if(longest_src_lines < num)2109 longest_src_lines = num;2110 num = e->lno + e->num_lines;2111if(longest_dst_lines < num)2112 longest_dst_lines = num;2113if(largest_score <blame_entry_score(sb, e))2114 largest_score =blame_entry_score(sb, e);2115}2116 max_orig_digits =decimal_width(longest_src_lines);2117 max_digits =decimal_width(longest_dst_lines);2118 max_score_digits =decimal_width(largest_score);21192120if(compute_auto_abbrev)2121/* one more abbrev length is needed for the boundary commit */2122 abbrev = auto_abbrev +1;2123}21242125/*2126 * For debugging -- origin is refcounted, and this asserts that2127 * we do not underflow.2128 */2129static voidsanity_check_refcnt(struct blame_scoreboard *sb)2130{2131int baa =0;2132struct blame_entry *ent;21332134for(ent = sb->ent; ent; ent = ent->next) {2135/* Nobody should have zero or negative refcnt */2136if(ent->suspect->refcnt <=0) {2137fprintf(stderr,"%sin%shas negative refcnt%d\n",2138 ent->suspect->path,2139oid_to_hex(&ent->suspect->commit->object.oid),2140 ent->suspect->refcnt);2141 baa =1;2142}2143}2144if(baa) {2145int opt =0160;2146find_alignment(sb, &opt);2147output(sb, opt);2148die("Baa%d!", baa);2149}2150}21512152static unsignedparse_score(const char*arg)2153{2154char*end;2155unsigned long score =strtoul(arg, &end,10);2156if(*end)2157return0;2158return score;2159}21602161static const char*add_prefix(const char*prefix,const char*path)2162{2163returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2164}21652166static intgit_blame_config(const char*var,const char*value,void*cb)2167{2168if(!strcmp(var,"blame.showroot")) {2169 show_root =git_config_bool(var, value);2170return0;2171}2172if(!strcmp(var,"blame.blankboundary")) {2173 blank_boundary =git_config_bool(var, value);2174return0;2175}2176if(!strcmp(var,"blame.showemail")) {2177int*output_option = cb;2178if(git_config_bool(var, value))2179*output_option |= OUTPUT_SHOW_EMAIL;2180else2181*output_option &= ~OUTPUT_SHOW_EMAIL;2182return0;2183}2184if(!strcmp(var,"blame.date")) {2185if(!value)2186returnconfig_error_nonbool(var);2187parse_date_format(value, &blame_date_mode);2188return0;2189}21902191if(git_diff_heuristic_config(var, value, cb) <0)2192return-1;2193if(userdiff_config(var, value) <0)2194return-1;21952196returngit_default_config(var, value, cb);2197}21982199static voidverify_working_tree_path(struct commit *work_tree,const char*path)2200{2201struct commit_list *parents;2202int pos;22032204for(parents = work_tree->parents; parents; parents = parents->next) {2205const struct object_id *commit_oid = &parents->item->object.oid;2206struct object_id blob_oid;2207unsigned mode;22082209if(!get_tree_entry(commit_oid->hash, path, blob_oid.hash, &mode) &&2210sha1_object_info(blob_oid.hash, NULL) == OBJ_BLOB)2211return;2212}22132214 pos =cache_name_pos(path,strlen(path));2215if(pos >=0)2216;/* path is in the index */2217else if(-1- pos < active_nr &&2218!strcmp(active_cache[-1- pos]->name, path))2219;/* path is in the index, unmerged */2220else2221die("no such path '%s' in HEAD", path);2222}22232224static struct commit_list **append_parent(struct commit_list **tail,const struct object_id *oid)2225{2226struct commit *parent;22272228 parent =lookup_commit_reference(oid->hash);2229if(!parent)2230die("no such commit%s",oid_to_hex(oid));2231return&commit_list_insert(parent, tail)->next;2232}22332234static voidappend_merge_parents(struct commit_list **tail)2235{2236int merge_head;2237struct strbuf line = STRBUF_INIT;22382239 merge_head =open(git_path_merge_head(), O_RDONLY);2240if(merge_head <0) {2241if(errno == ENOENT)2242return;2243die("cannot open '%s' for reading",git_path_merge_head());2244}22452246while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2247struct object_id oid;2248if(line.len < GIT_SHA1_HEXSZ ||get_oid_hex(line.buf, &oid))2249die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2250 tail =append_parent(tail, &oid);2251}2252close(merge_head);2253strbuf_release(&line);2254}22552256/*2257 * This isn't as simple as passing sb->buf and sb->len, because we2258 * want to transfer ownership of the buffer to the commit (so we2259 * must use detach).2260 */2261static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2262{2263size_t len;2264void*buf =strbuf_detach(sb, &len);2265set_commit_buffer(c, buf, len);2266}22672268/*2269 * Prepare a dummy commit that represents the work tree (or staged) item.2270 * Note that annotating work tree item never works in the reverse.2271 */2272static struct commit *fake_working_tree_commit(struct diff_options *opt,2273const char*path,2274const char*contents_from)2275{2276struct commit *commit;2277struct blame_origin *origin;2278struct commit_list **parent_tail, *parent;2279struct object_id head_oid;2280struct strbuf buf = STRBUF_INIT;2281const char*ident;2282time_t now;2283int size, len;2284struct cache_entry *ce;2285unsigned mode;2286struct strbuf msg = STRBUF_INIT;22872288read_cache();2289time(&now);2290 commit =alloc_commit_node();2291 commit->object.parsed =1;2292 commit->date = now;2293 parent_tail = &commit->parents;22942295if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_oid.hash, NULL))2296die("no such ref: HEAD");22972298 parent_tail =append_parent(parent_tail, &head_oid);2299append_merge_parents(parent_tail);2300verify_working_tree_path(commit, path);23012302 origin =make_origin(commit, path);23032304 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2305strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2306for(parent = commit->parents; parent; parent = parent->next)2307strbuf_addf(&msg,"parent%s\n",2308oid_to_hex(&parent->item->object.oid));2309strbuf_addf(&msg,2310"author%s\n"2311"committer%s\n\n"2312"Version of%sfrom%s\n",2313 ident, ident, path,2314(!contents_from ? path :2315(!strcmp(contents_from,"-") ?"standard input": contents_from)));2316set_commit_buffer_from_strbuf(commit, &msg);23172318if(!contents_from ||strcmp("-", contents_from)) {2319struct stat st;2320const char*read_from;2321char*buf_ptr;2322unsigned long buf_len;23232324if(contents_from) {2325if(stat(contents_from, &st) <0)2326die_errno("Cannot stat '%s'", contents_from);2327 read_from = contents_from;2328}2329else{2330if(lstat(path, &st) <0)2331die_errno("Cannot lstat '%s'", path);2332 read_from = path;2333}2334 mode =canon_mode(st.st_mode);23352336switch(st.st_mode & S_IFMT) {2337case S_IFREG:2338if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2339textconv_object(read_from, mode, &null_oid,0, &buf_ptr, &buf_len))2340strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2341else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2342die_errno("cannot open or read '%s'", read_from);2343break;2344case S_IFLNK:2345if(strbuf_readlink(&buf, read_from, st.st_size) <0)2346die_errno("cannot readlink '%s'", read_from);2347break;2348default:2349die("unsupported file type%s", read_from);2350}2351}2352else{2353/* Reading from stdin */2354 mode =0;2355if(strbuf_read(&buf,0,0) <0)2356die_errno("failed to read from stdin");2357}2358convert_to_git(path, buf.buf, buf.len, &buf,0);2359 origin->file.ptr = buf.buf;2360 origin->file.size = buf.len;2361pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_oid.hash);23622363/*2364 * Read the current index, replace the path entry with2365 * origin->blob_sha1 without mucking with its mode or type2366 * bits; we are not going to write this index out -- we just2367 * want to run "diff-index --cached".2368 */2369discard_cache();2370read_cache();23712372 len =strlen(path);2373if(!mode) {2374int pos =cache_name_pos(path, len);2375if(0<= pos)2376 mode = active_cache[pos]->ce_mode;2377else2378/* Let's not bother reading from HEAD tree */2379 mode = S_IFREG |0644;2380}2381 size =cache_entry_size(len);2382 ce =xcalloc(1, size);2383oidcpy(&ce->oid, &origin->blob_oid);2384memcpy(ce->name, path, len);2385 ce->ce_flags =create_ce_flags(0);2386 ce->ce_namelen = len;2387 ce->ce_mode =create_ce_mode(mode);2388add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23892390cache_tree_invalidate_path(&the_index, path);23912392return commit;2393}23942395static struct commit *find_single_final(struct rev_info *revs,2396const char**name_p)2397{2398int i;2399struct commit *found = NULL;2400const char*name = NULL;24012402for(i =0; i < revs->pending.nr; i++) {2403struct object *obj = revs->pending.objects[i].item;2404if(obj->flags & UNINTERESTING)2405continue;2406 obj =deref_tag(obj, NULL,0);2407if(obj->type != OBJ_COMMIT)2408die("Non commit%s?", revs->pending.objects[i].name);2409if(found)2410die("More than one commit to dig from%sand%s?",2411 revs->pending.objects[i].name, name);2412 found = (struct commit *)obj;2413 name = revs->pending.objects[i].name;2414}2415if(name_p)2416*name_p = name;2417return found;2418}24192420static char*prepare_final(struct blame_scoreboard *sb)2421{2422const char*name;2423 sb->final =find_single_final(sb->revs, &name);2424returnxstrdup_or_null(name);2425}24262427static const char*dwim_reverse_initial(struct blame_scoreboard *sb)2428{2429/*2430 * DWIM "git blame --reverse ONE -- PATH" as2431 * "git blame --reverse ONE..HEAD -- PATH" but only do so2432 * when it makes sense.2433 */2434struct object *obj;2435struct commit *head_commit;2436unsigned char head_sha1[20];24372438if(sb->revs->pending.nr !=1)2439return NULL;24402441/* Is that sole rev a committish? */2442 obj = sb->revs->pending.objects[0].item;2443 obj =deref_tag(obj, NULL,0);2444if(obj->type != OBJ_COMMIT)2445return NULL;24462447/* Do we have HEAD? */2448if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2449return NULL;2450 head_commit =lookup_commit_reference_gently(head_sha1,1);2451if(!head_commit)2452return NULL;24532454/* Turn "ONE" into "ONE..HEAD" then */2455 obj->flags |= UNINTERESTING;2456add_pending_object(sb->revs, &head_commit->object,"HEAD");24572458 sb->final = (struct commit *)obj;2459return sb->revs->pending.objects[0].name;2460}24612462static char*prepare_initial(struct blame_scoreboard *sb)2463{2464int i;2465const char*final_commit_name = NULL;2466struct rev_info *revs = sb->revs;24672468/*2469 * There must be one and only one negative commit, and it must be2470 * the boundary.2471 */2472for(i =0; i < revs->pending.nr; i++) {2473struct object *obj = revs->pending.objects[i].item;2474if(!(obj->flags & UNINTERESTING))2475continue;2476 obj =deref_tag(obj, NULL,0);2477if(obj->type != OBJ_COMMIT)2478die("Non commit%s?", revs->pending.objects[i].name);2479if(sb->final)2480die("More than one commit to dig up from,%sand%s?",2481 revs->pending.objects[i].name,2482 final_commit_name);2483 sb->final = (struct commit *) obj;2484 final_commit_name = revs->pending.objects[i].name;2485}24862487if(!final_commit_name)2488 final_commit_name =dwim_reverse_initial(sb);2489if(!final_commit_name)2490die("No commit to dig up from?");2491returnxstrdup(final_commit_name);2492}24932494static intblame_copy_callback(const struct option *option,const char*arg,int unset)2495{2496int*opt = option->value;24972498/*2499 * -C enables copy from removed files;2500 * -C -C enables copy from existing files, but only2501 * when blaming a new file;2502 * -C -C -C enables copy from existing files for2503 * everybody2504 */2505if(*opt & PICKAXE_BLAME_COPY_HARDER)2506*opt |= PICKAXE_BLAME_COPY_HARDEST;2507if(*opt & PICKAXE_BLAME_COPY)2508*opt |= PICKAXE_BLAME_COPY_HARDER;2509*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;25102511if(arg)2512 blame_copy_score =parse_score(arg);2513return0;2514}25152516static intblame_move_callback(const struct option *option,const char*arg,int unset)2517{2518int*opt = option->value;25192520*opt |= PICKAXE_BLAME_MOVE;25212522if(arg)2523 blame_move_score =parse_score(arg);2524return0;2525}25262527intcmd_blame(int argc,const char**argv,const char*prefix)2528{2529struct rev_info revs;2530const char*path;2531struct blame_scoreboard sb;2532struct blame_origin *o;2533struct blame_entry *ent = NULL;2534long dashdash_pos, lno;2535char*final_commit_name = NULL;2536enum object_type type;2537struct commit *final_commit = NULL;25382539struct string_list range_list = STRING_LIST_INIT_NODUP;2540int output_option =0, opt =0;2541int show_stats =0;2542const char*revs_file = NULL;2543const char*contents_from = NULL;2544const struct option options[] = {2545OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2546OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2547OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2548OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2549OPT_BOOL(0,"progress", &show_progress,N_("Force progress reporting")),2550OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2551OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2552OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2553OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2554OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2555OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2556OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2557OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2558OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2559OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2560OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),25612562/*2563 * The following two options are parsed by parse_revision_opt()2564 * and are only included here to get included in the "-h"2565 * output:2566 */2567{ OPTION_LOWLEVEL_CALLBACK,0,"indent-heuristic", NULL, NULL,N_("Use an experimental heuristic to improve diffs"), PARSE_OPT_NOARG, parse_opt_unknown_cb },25682569OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2570OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2571OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2572{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2573{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2574OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2575OPT__ABBREV(&abbrev),2576OPT_END()2577};25782579struct parse_opt_ctx_t ctx;2580int cmd_is_annotate = !strcmp(argv[0],"annotate");2581struct range_set ranges;2582unsigned int range_i;2583long anchor;25842585git_config(git_blame_config, &output_option);2586init_revisions(&revs, NULL);2587 revs.date_mode = blame_date_mode;2588DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2589DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25902591 save_commit_buffer =0;2592 dashdash_pos =0;2593 show_progress = -1;25942595parse_options_start(&ctx, argc, argv, prefix, options,2596 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2597for(;;) {2598switch(parse_options_step(&ctx, options, blame_opt_usage)) {2599case PARSE_OPT_HELP:2600exit(129);2601case PARSE_OPT_DONE:2602if(ctx.argv[0])2603 dashdash_pos = ctx.cpidx;2604goto parse_done;2605}26062607if(!strcmp(ctx.argv[0],"--reverse")) {2608 ctx.argv[0] ="--children";2609 reverse =1;2610}2611parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2612}2613parse_done:2614 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2615 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;2616DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2617 argc =parse_options_end(&ctx);26182619if(incremental || (output_option & OUTPUT_PORCELAIN)) {2620if(show_progress >0)2621die(_("--progress can't be used with --incremental or porcelain formats"));2622 show_progress =0;2623}else if(show_progress <0)2624 show_progress =isatty(2);26252626if(0< abbrev && abbrev < GIT_SHA1_HEXSZ)2627/* one more abbrev length is needed for the boundary commit */2628 abbrev++;2629else if(!abbrev)2630 abbrev = GIT_SHA1_HEXSZ;26312632if(revs_file &&read_ancestry(revs_file))2633die_errno("reading graft file '%s' failed", revs_file);26342635if(cmd_is_annotate) {2636 output_option |= OUTPUT_ANNOTATE_COMPAT;2637 blame_date_mode.type = DATE_ISO8601;2638}else{2639 blame_date_mode = revs.date_mode;2640}26412642/* The maximum width used to show the dates */2643switch(blame_date_mode.type) {2644case DATE_RFC2822:2645 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2646break;2647case DATE_ISO8601_STRICT:2648 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2649break;2650case DATE_ISO8601:2651 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2652break;2653case DATE_RAW:2654 blame_date_width =sizeof("1161298804 -0700");2655break;2656case DATE_UNIX:2657 blame_date_width =sizeof("1161298804");2658break;2659case DATE_SHORT:2660 blame_date_width =sizeof("2006-10-19");2661break;2662case DATE_RELATIVE:2663/* TRANSLATORS: This string is used to tell us the maximum2664 display width for a relative timestamp in "git blame"2665 output. For C locale, "4 years, 11 months ago", which2666 takes 22 places, is the longest among various forms of2667 relative timestamps, but your language may need more or2668 fewer display columns. */2669 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2670break;2671case DATE_NORMAL:2672 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2673break;2674case DATE_STRFTIME:2675 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2676break;2677}2678 blame_date_width -=1;/* strip the null */26792680if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2681 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2682 PICKAXE_BLAME_COPY_HARDER);26832684/*2685 * We have collected options unknown to us in argv[1..unk]2686 * which are to be passed to revision machinery if we are2687 * going to do the "bottom" processing.2688 *2689 * The remaining are:2690 *2691 * (1) if dashdash_pos != 0, it is either2692 * "blame [revisions] -- <path>" or2693 * "blame -- <path> <rev>"2694 *2695 * (2) otherwise, it is one of the two:2696 * "blame [revisions] <path>"2697 * "blame <path> <rev>"2698 *2699 * Note that we must strip out <path> from the arguments: we do not2700 * want the path pruning but we may want "bottom" processing.2701 */2702if(dashdash_pos) {2703switch(argc - dashdash_pos -1) {2704case2:/* (1b) */2705if(argc !=4)2706usage_with_options(blame_opt_usage, options);2707/* reorder for the new way: <rev> -- <path> */2708 argv[1] = argv[3];2709 argv[3] = argv[2];2710 argv[2] ="--";2711/* FALLTHROUGH */2712case1:/* (1a) */2713 path =add_prefix(prefix, argv[--argc]);2714 argv[argc] = NULL;2715break;2716default:2717usage_with_options(blame_opt_usage, options);2718}2719}else{2720if(argc <2)2721usage_with_options(blame_opt_usage, options);2722 path =add_prefix(prefix, argv[argc -1]);2723if(argc ==3&& !file_exists(path)) {/* (2b) */2724 path =add_prefix(prefix, argv[1]);2725 argv[1] = argv[2];2726}2727 argv[argc -1] ="--";27282729setup_work_tree();2730if(!file_exists(path))2731die_errno("cannot stat path '%s'", path);2732}27332734 revs.disable_stdin =1;2735setup_revisions(argc, argv, &revs, NULL);2736memset(&sb,0,sizeof(sb));2737 sb.move_score = BLAME_DEFAULT_MOVE_SCORE;2738 sb.copy_score = BLAME_DEFAULT_COPY_SCORE;27392740 sb.revs = &revs;2741 sb.contents_from = contents_from;2742if(!reverse) {2743 final_commit_name =prepare_final(&sb);2744 sb.commits.compare = compare_commits_by_commit_date;2745}2746else if(contents_from)2747die(_("--contents and --reverse do not blend well."));2748else{2749 final_commit_name =prepare_initial(&sb);2750 sb.commits.compare = compare_commits_by_reverse_commit_date;2751if(revs.first_parent_only)2752 revs.children.name = NULL;2753}27542755if(!sb.final) {2756/*2757 * "--not A B -- path" without anything positive;2758 * do not default to HEAD, but use the working tree2759 * or "--contents".2760 */2761setup_work_tree();2762 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2763 path, contents_from);2764add_pending_object(&revs, &(sb.final->object),":");2765}2766else if(contents_from)2767die(_("cannot use --contents with final commit object name"));27682769if(reverse && revs.first_parent_only) {2770 final_commit =find_single_final(sb.revs, NULL);2771if(!final_commit)2772die(_("--reverse and --first-parent together require specified latest commit"));2773}27742775/*2776 * If we have bottom, this will mark the ancestors of the2777 * bottom commits we would reach while traversing as2778 * uninteresting.2779 */2780if(prepare_revision_walk(&revs))2781die(_("revision walk setup failed"));27822783if(reverse && revs.first_parent_only) {2784struct commit *c = final_commit;27852786 sb.revs->children.name ="children";2787while(c->parents &&2788oidcmp(&c->object.oid, &sb.final->object.oid)) {2789struct commit_list *l =xcalloc(1,sizeof(*l));27902791 l->item = c;2792if(add_decoration(&sb.revs->children,2793&c->parents->item->object, l))2794die("BUG: not unique item in first-parent chain");2795 c = c->parents->item;2796}27972798if(oidcmp(&c->object.oid, &sb.final->object.oid))2799die(_("--reverse --first-parent together require range along first-parent chain"));2800}28012802if(is_null_oid(&sb.final->object.oid)) {2803 o = sb.final->util;2804 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2805 sb.final_buf_size = o->file.size;2806}2807else{2808 o =get_origin(sb.final, path);2809if(fill_blob_sha1_and_mode(o))2810die(_("no such path%sin%s"), path, final_commit_name);28112812if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2813textconv_object(path, o->mode, &o->blob_oid,1, (char**) &sb.final_buf,2814&sb.final_buf_size))2815;2816else2817 sb.final_buf =read_sha1_file(o->blob_oid.hash, &type,2818&sb.final_buf_size);28192820if(!sb.final_buf)2821die(_("cannot read blob%sfor path%s"),2822oid_to_hex(&o->blob_oid),2823 path);2824}2825 sb.num_read_blob++;2826 lno =prepare_lines(&sb);28272828if(lno && !range_list.nr)2829string_list_append(&range_list,"1");28302831 anchor =1;2832range_set_init(&ranges, range_list.nr);2833for(range_i =0; range_i < range_list.nr; ++range_i) {2834long bottom, top;2835if(parse_range_arg(range_list.items[range_i].string,2836 nth_line_cb, &sb, lno, anchor,2837&bottom, &top, sb.path))2838usage(blame_usage);2839if(lno < top || ((lno || bottom) && lno < bottom))2840die(Q_("file%shas only%lu line",2841"file%shas only%lu lines",2842 lno), path, lno);2843if(bottom <1)2844 bottom =1;2845if(top <1)2846 top = lno;2847 bottom--;2848range_set_append_unsafe(&ranges, bottom, top);2849 anchor = top +1;2850}2851sort_and_merge_range_set(&ranges);28522853for(range_i = ranges.nr; range_i >0; --range_i) {2854const struct range *r = &ranges.ranges[range_i -1];2855long bottom = r->start;2856long top = r->end;2857struct blame_entry *next = ent;2858 ent =xcalloc(1,sizeof(*ent));2859 ent->lno = bottom;2860 ent->num_lines = top - bottom;2861 ent->suspect = o;2862 ent->s_lno = bottom;2863 ent->next = next;2864blame_origin_incref(o);2865}28662867 o->suspects = ent;2868prio_queue_put(&sb.commits, o->commit);28692870blame_origin_decref(o);28712872range_set_release(&ranges);2873string_list_clear(&range_list,0);28742875 sb.ent = NULL;2876 sb.path = path;28772878if(blame_move_score)2879 sb.move_score = blame_move_score;2880if(blame_copy_score)2881 sb.copy_score = blame_copy_score;28822883read_mailmap(&mailmap, NULL);28842885assign_blame(&sb, opt);28862887if(!incremental)2888setup_pager();28892890free(final_commit_name);28912892if(incremental)2893return0;28942895 sb.ent =blame_sort(sb.ent, compare_blame_final);28962897blame_coalesce(&sb);28982899if(!(output_option & OUTPUT_PORCELAIN))2900find_alignment(&sb, &output_option);29012902output(&sb, output_option);2903free((void*)sb.final_buf);2904for(ent = sb.ent; ent; ) {2905struct blame_entry *e = ent->next;2906free(ent);2907 ent = e;2908}29092910if(show_stats) {2911printf("num read blob:%d\n", sb.num_read_blob);2912printf("num get patch:%d\n", sb.num_get_patch);2913printf("num commits:%d\n", sb.num_commits);2914}2915return0;2916}