1/* 2 * Blame 3 * 4 * Copyright (c) 2006, 2014 by its authors 5 * See COPYING for licensing conditions 6 */ 7 8#include"cache.h" 9#include"refs.h" 10#include"builtin.h" 11#include"blob.h" 12#include"commit.h" 13#include"tag.h" 14#include"tree-walk.h" 15#include"diff.h" 16#include"diffcore.h" 17#include"revision.h" 18#include"quote.h" 19#include"xdiff-interface.h" 20#include"cache-tree.h" 21#include"string-list.h" 22#include"mailmap.h" 23#include"mergesort.h" 24#include"parse-options.h" 25#include"prio-queue.h" 26#include"utf8.h" 27#include"userdiff.h" 28#include"line-range.h" 29#include"line-log.h" 30#include"dir.h" 31 32static char blame_usage[] =N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>"); 33 34static const char*blame_opt_usage[] = { 35 blame_usage, 36"", 37N_("<rev-opts> are documented in git-rev-list(1)"), 38 NULL 39}; 40 41static int longest_file; 42static int longest_author; 43static int max_orig_digits; 44static int max_digits; 45static int max_score_digits; 46static int show_root; 47static int reverse; 48static int blank_boundary; 49static int incremental; 50static int xdl_opts; 51static int abbrev = -1; 52static int no_whole_file_rename; 53 54static struct date_mode blame_date_mode = { DATE_ISO8601 }; 55static size_t blame_date_width; 56 57static struct string_list mailmap; 58 59#ifndef DEBUG 60#define DEBUG 0 61#endif 62 63/* stats */ 64static int num_read_blob; 65static int num_get_patch; 66static int num_commits; 67 68#define PICKAXE_BLAME_MOVE 01 69#define PICKAXE_BLAME_COPY 02 70#define PICKAXE_BLAME_COPY_HARDER 04 71#define PICKAXE_BLAME_COPY_HARDEST 010 72 73/* 74 * blame for a blame_entry with score lower than these thresholds 75 * is not passed to the parent using move/copy logic. 76 */ 77static unsigned blame_move_score; 78static unsigned blame_copy_score; 79#define BLAME_DEFAULT_MOVE_SCORE 20 80#define BLAME_DEFAULT_COPY_SCORE 40 81 82/* Remember to update object flag allocation in object.h */ 83#define METAINFO_SHOWN (1u<<12) 84#define MORE_THAN_ONE_PATH (1u<<13) 85 86/* 87 * One blob in a commit that is being suspected 88 */ 89struct origin { 90int refcnt; 91/* Record preceding blame record for this blob */ 92struct origin *previous; 93/* origins are put in a list linked via `next' hanging off the 94 * corresponding commit's util field in order to make finding 95 * them fast. The presence in this chain does not count 96 * towards the origin's reference count. It is tempting to 97 * let it count as long as the commit is pending examination, 98 * but even under circumstances where the commit will be 99 * present multiple times in the priority queue of unexamined 100 * commits, processing the first instance will not leave any 101 * work requiring the origin data for the second instance. An 102 * interspersed commit changing that would have to be 103 * preexisting with a different ancestry and with the same 104 * commit date in order to wedge itself between two instances 105 * of the same commit in the priority queue _and_ produce 106 * blame entries relevant for it. While we don't want to let 107 * us get tripped up by this case, it certainly does not seem 108 * worth optimizing for. 109 */ 110struct origin *next; 111struct commit *commit; 112/* `suspects' contains blame entries that may be attributed to 113 * this origin's commit or to parent commits. When a commit 114 * is being processed, all suspects will be moved, either by 115 * assigning them to an origin in a different commit, or by 116 * shipping them to the scoreboard's ent list because they 117 * cannot be attributed to a different commit. 118 */ 119struct blame_entry *suspects; 120 mmfile_t file; 121unsigned char blob_sha1[20]; 122unsigned mode; 123/* guilty gets set when shipping any suspects to the final 124 * blame list instead of other commits 125 */ 126char guilty; 127char path[FLEX_ARRAY]; 128}; 129 130static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b,long ctxlen, 131 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data) 132{ 133 xpparam_t xpp = {0}; 134 xdemitconf_t xecfg = {0}; 135 xdemitcb_t ecb = {NULL}; 136 137 xpp.flags = xdl_opts; 138 xecfg.ctxlen = ctxlen; 139 xecfg.hunk_func = hunk_func; 140 ecb.priv = cb_data; 141returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 142} 143 144/* 145 * Prepare diff_filespec and convert it using diff textconv API 146 * if the textconv driver exists. 147 * Return 1 if the conversion succeeds, 0 otherwise. 148 */ 149inttextconv_object(const char*path, 150unsigned mode, 151const unsigned char*sha1, 152int sha1_valid, 153char**buf, 154unsigned long*buf_size) 155{ 156struct diff_filespec *df; 157struct userdiff_driver *textconv; 158 159 df =alloc_filespec(path); 160fill_filespec(df, sha1, sha1_valid, mode); 161 textconv =get_textconv(df); 162if(!textconv) { 163free_filespec(df); 164return0; 165} 166 167*buf_size =fill_textconv(textconv, df, buf); 168free_filespec(df); 169return1; 170} 171 172/* 173 * Given an origin, prepare mmfile_t structure to be used by the 174 * diff machinery 175 */ 176static voidfill_origin_blob(struct diff_options *opt, 177struct origin *o, mmfile_t *file) 178{ 179if(!o->file.ptr) { 180enum object_type type; 181unsigned long file_size; 182 183 num_read_blob++; 184if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 185textconv_object(o->path, o->mode, o->blob_sha1,1, &file->ptr, &file_size)) 186; 187else 188 file->ptr =read_sha1_file(o->blob_sha1, &type, &file_size); 189 file->size = file_size; 190 191if(!file->ptr) 192die("Cannot read blob%sfor path%s", 193sha1_to_hex(o->blob_sha1), 194 o->path); 195 o->file = *file; 196} 197else 198*file = o->file; 199} 200 201/* 202 * Origin is refcounted and usually we keep the blob contents to be 203 * reused. 204 */ 205staticinlinestruct origin *origin_incref(struct origin *o) 206{ 207if(o) 208 o->refcnt++; 209return o; 210} 211 212static voidorigin_decref(struct origin *o) 213{ 214if(o && --o->refcnt <=0) { 215struct origin *p, *l = NULL; 216if(o->previous) 217origin_decref(o->previous); 218free(o->file.ptr); 219/* Should be present exactly once in commit chain */ 220for(p = o->commit->util; p; l = p, p = p->next) { 221if(p == o) { 222if(l) 223 l->next = p->next; 224else 225 o->commit->util = p->next; 226free(o); 227return; 228} 229} 230die("internal error in blame::origin_decref"); 231} 232} 233 234static voiddrop_origin_blob(struct origin *o) 235{ 236if(o->file.ptr) { 237free(o->file.ptr); 238 o->file.ptr = NULL; 239} 240} 241 242/* 243 * Each group of lines is described by a blame_entry; it can be split 244 * as we pass blame to the parents. They are arranged in linked lists 245 * kept as `suspects' of some unprocessed origin, or entered (when the 246 * blame origin has been finalized) into the scoreboard structure. 247 * While the scoreboard structure is only sorted at the end of 248 * processing (according to final image line number), the lists 249 * attached to an origin are sorted by the target line number. 250 */ 251struct blame_entry { 252struct blame_entry *next; 253 254/* the first line of this group in the final image; 255 * internally all line numbers are 0 based. 256 */ 257int lno; 258 259/* how many lines this group has */ 260int num_lines; 261 262/* the commit that introduced this group into the final image */ 263struct origin *suspect; 264 265/* the line number of the first line of this group in the 266 * suspect's file; internally all line numbers are 0 based. 267 */ 268int s_lno; 269 270/* how significant this entry is -- cached to avoid 271 * scanning the lines over and over. 272 */ 273unsigned score; 274}; 275 276/* 277 * Any merge of blames happens on lists of blames that arrived via 278 * different parents in a single suspect. In this case, we want to 279 * sort according to the suspect line numbers as opposed to the final 280 * image line numbers. The function body is somewhat longish because 281 * it avoids unnecessary writes. 282 */ 283 284static struct blame_entry *blame_merge(struct blame_entry *list1, 285struct blame_entry *list2) 286{ 287struct blame_entry *p1 = list1, *p2 = list2, 288**tail = &list1; 289 290if(!p1) 291return p2; 292if(!p2) 293return p1; 294 295if(p1->s_lno <= p2->s_lno) { 296do{ 297 tail = &p1->next; 298if((p1 = *tail) == NULL) { 299*tail = p2; 300return list1; 301} 302}while(p1->s_lno <= p2->s_lno); 303} 304for(;;) { 305*tail = p2; 306do{ 307 tail = &p2->next; 308if((p2 = *tail) == NULL) { 309*tail = p1; 310return list1; 311} 312}while(p1->s_lno > p2->s_lno); 313*tail = p1; 314do{ 315 tail = &p1->next; 316if((p1 = *tail) == NULL) { 317*tail = p2; 318return list1; 319} 320}while(p1->s_lno <= p2->s_lno); 321} 322} 323 324static void*get_next_blame(const void*p) 325{ 326return((struct blame_entry *)p)->next; 327} 328 329static voidset_next_blame(void*p1,void*p2) 330{ 331((struct blame_entry *)p1)->next = p2; 332} 333 334/* 335 * Final image line numbers are all different, so we don't need a 336 * three-way comparison here. 337 */ 338 339static intcompare_blame_final(const void*p1,const void*p2) 340{ 341return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 342?1: -1; 343} 344 345static intcompare_blame_suspect(const void*p1,const void*p2) 346{ 347const struct blame_entry *s1 = p1, *s2 = p2; 348/* 349 * to allow for collating suspects, we sort according to the 350 * respective pointer value as the primary sorting criterion. 351 * The actual relation is pretty unimportant as long as it 352 * establishes a total order. Comparing as integers gives us 353 * that. 354 */ 355if(s1->suspect != s2->suspect) 356return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 357if(s1->s_lno == s2->s_lno) 358return0; 359return s1->s_lno > s2->s_lno ?1: -1; 360} 361 362static struct blame_entry *blame_sort(struct blame_entry *head, 363int(*compare_fn)(const void*,const void*)) 364{ 365returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 366} 367 368static intcompare_commits_by_reverse_commit_date(const void*a, 369const void*b, 370void*c) 371{ 372return-compare_commits_by_commit_date(a, b, c); 373} 374 375/* 376 * The current state of the blame assignment. 377 */ 378struct scoreboard { 379/* the final commit (i.e. where we started digging from) */ 380struct commit *final; 381/* Priority queue for commits with unassigned blame records */ 382struct prio_queue commits; 383struct rev_info *revs; 384const char*path; 385 386/* 387 * The contents in the final image. 388 * Used by many functions to obtain contents of the nth line, 389 * indexed with scoreboard.lineno[blame_entry.lno]. 390 */ 391const char*final_buf; 392unsigned long final_buf_size; 393 394/* linked list of blames */ 395struct blame_entry *ent; 396 397/* look-up a line in the final buffer */ 398int num_lines; 399int*lineno; 400}; 401 402static voidsanity_check_refcnt(struct scoreboard *); 403 404/* 405 * If two blame entries that are next to each other came from 406 * contiguous lines in the same origin (i.e. <commit, path> pair), 407 * merge them together. 408 */ 409static voidcoalesce(struct scoreboard *sb) 410{ 411struct blame_entry *ent, *next; 412 413for(ent = sb->ent; ent && (next = ent->next); ent = next) { 414if(ent->suspect == next->suspect && 415 ent->s_lno + ent->num_lines == next->s_lno) { 416 ent->num_lines += next->num_lines; 417 ent->next = next->next; 418origin_decref(next->suspect); 419free(next); 420 ent->score =0; 421 next = ent;/* again */ 422} 423} 424 425if(DEBUG)/* sanity */ 426sanity_check_refcnt(sb); 427} 428 429/* 430 * Merge the given sorted list of blames into a preexisting origin. 431 * If there were no previous blames to that commit, it is entered into 432 * the commit priority queue of the score board. 433 */ 434 435static voidqueue_blames(struct scoreboard *sb,struct origin *porigin, 436struct blame_entry *sorted) 437{ 438if(porigin->suspects) 439 porigin->suspects =blame_merge(porigin->suspects, sorted); 440else{ 441struct origin *o; 442for(o = porigin->commit->util; o; o = o->next) { 443if(o->suspects) { 444 porigin->suspects = sorted; 445return; 446} 447} 448 porigin->suspects = sorted; 449prio_queue_put(&sb->commits, porigin->commit); 450} 451} 452 453/* 454 * Given a commit and a path in it, create a new origin structure. 455 * The callers that add blame to the scoreboard should use 456 * get_origin() to obtain shared, refcounted copy instead of calling 457 * this function directly. 458 */ 459static struct origin *make_origin(struct commit *commit,const char*path) 460{ 461struct origin *o; 462FLEX_ALLOC_STR(o, path, path); 463 o->commit = commit; 464 o->refcnt =1; 465 o->next = commit->util; 466 commit->util = o; 467return o; 468} 469 470/* 471 * Locate an existing origin or create a new one. 472 * This moves the origin to front position in the commit util list. 473 */ 474static struct origin *get_origin(struct scoreboard *sb, 475struct commit *commit, 476const char*path) 477{ 478struct origin *o, *l; 479 480for(o = commit->util, l = NULL; o; l = o, o = o->next) { 481if(!strcmp(o->path, path)) { 482/* bump to front */ 483if(l) { 484 l->next = o->next; 485 o->next = commit->util; 486 commit->util = o; 487} 488returnorigin_incref(o); 489} 490} 491returnmake_origin(commit, path); 492} 493 494/* 495 * Fill the blob_sha1 field of an origin if it hasn't, so that later 496 * call to fill_origin_blob() can use it to locate the data. blob_sha1 497 * for an origin is also used to pass the blame for the entire file to 498 * the parent to detect the case where a child's blob is identical to 499 * that of its parent's. 500 * 501 * This also fills origin->mode for corresponding tree path. 502 */ 503static intfill_blob_sha1_and_mode(struct origin *origin) 504{ 505if(!is_null_sha1(origin->blob_sha1)) 506return0; 507if(get_tree_entry(origin->commit->object.oid.hash, 508 origin->path, 509 origin->blob_sha1, &origin->mode)) 510goto error_out; 511if(sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB) 512goto error_out; 513return0; 514 error_out: 515hashclr(origin->blob_sha1); 516 origin->mode = S_IFINVALID; 517return-1; 518} 519 520/* 521 * We have an origin -- check if the same path exists in the 522 * parent and return an origin structure to represent it. 523 */ 524static struct origin *find_origin(struct scoreboard *sb, 525struct commit *parent, 526struct origin *origin) 527{ 528struct origin *porigin; 529struct diff_options diff_opts; 530const char*paths[2]; 531 532/* First check any existing origins */ 533for(porigin = parent->util; porigin; porigin = porigin->next) 534if(!strcmp(porigin->path, origin->path)) { 535/* 536 * The same path between origin and its parent 537 * without renaming -- the most common case. 538 */ 539returnorigin_incref(porigin); 540} 541 542/* See if the origin->path is different between parent 543 * and origin first. Most of the time they are the 544 * same and diff-tree is fairly efficient about this. 545 */ 546diff_setup(&diff_opts); 547DIFF_OPT_SET(&diff_opts, RECURSIVE); 548 diff_opts.detect_rename =0; 549 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 550 paths[0] = origin->path; 551 paths[1] = NULL; 552 553parse_pathspec(&diff_opts.pathspec, 554 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 555 PATHSPEC_LITERAL_PATH,"", paths); 556diff_setup_done(&diff_opts); 557 558if(is_null_oid(&origin->commit->object.oid)) 559do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 560else 561diff_tree_sha1(parent->tree->object.oid.hash, 562 origin->commit->tree->object.oid.hash, 563"", &diff_opts); 564diffcore_std(&diff_opts); 565 566if(!diff_queued_diff.nr) { 567/* The path is the same as parent */ 568 porigin =get_origin(sb, parent, origin->path); 569hashcpy(porigin->blob_sha1, origin->blob_sha1); 570 porigin->mode = origin->mode; 571}else{ 572/* 573 * Since origin->path is a pathspec, if the parent 574 * commit had it as a directory, we will see a whole 575 * bunch of deletion of files in the directory that we 576 * do not care about. 577 */ 578int i; 579struct diff_filepair *p = NULL; 580for(i =0; i < diff_queued_diff.nr; i++) { 581const char*name; 582 p = diff_queued_diff.queue[i]; 583 name = p->one->path ? p->one->path : p->two->path; 584if(!strcmp(name, origin->path)) 585break; 586} 587if(!p) 588die("internal error in blame::find_origin"); 589switch(p->status) { 590default: 591die("internal error in blame::find_origin (%c)", 592 p->status); 593case'M': 594 porigin =get_origin(sb, parent, origin->path); 595hashcpy(porigin->blob_sha1, p->one->sha1); 596 porigin->mode = p->one->mode; 597break; 598case'A': 599case'T': 600/* Did not exist in parent, or type changed */ 601break; 602} 603} 604diff_flush(&diff_opts); 605free_pathspec(&diff_opts.pathspec); 606return porigin; 607} 608 609/* 610 * We have an origin -- find the path that corresponds to it in its 611 * parent and return an origin structure to represent it. 612 */ 613static struct origin *find_rename(struct scoreboard *sb, 614struct commit *parent, 615struct origin *origin) 616{ 617struct origin *porigin = NULL; 618struct diff_options diff_opts; 619int i; 620 621diff_setup(&diff_opts); 622DIFF_OPT_SET(&diff_opts, RECURSIVE); 623 diff_opts.detect_rename = DIFF_DETECT_RENAME; 624 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 625 diff_opts.single_follow = origin->path; 626diff_setup_done(&diff_opts); 627 628if(is_null_oid(&origin->commit->object.oid)) 629do_diff_cache(parent->tree->object.oid.hash, &diff_opts); 630else 631diff_tree_sha1(parent->tree->object.oid.hash, 632 origin->commit->tree->object.oid.hash, 633"", &diff_opts); 634diffcore_std(&diff_opts); 635 636for(i =0; i < diff_queued_diff.nr; i++) { 637struct diff_filepair *p = diff_queued_diff.queue[i]; 638if((p->status =='R'|| p->status =='C') && 639!strcmp(p->two->path, origin->path)) { 640 porigin =get_origin(sb, parent, p->one->path); 641hashcpy(porigin->blob_sha1, p->one->sha1); 642 porigin->mode = p->one->mode; 643break; 644} 645} 646diff_flush(&diff_opts); 647free_pathspec(&diff_opts.pathspec); 648return porigin; 649} 650 651/* 652 * Append a new blame entry to a given output queue. 653 */ 654static voidadd_blame_entry(struct blame_entry ***queue,struct blame_entry *e) 655{ 656origin_incref(e->suspect); 657 658 e->next = **queue; 659**queue = e; 660*queue = &e->next; 661} 662 663/* 664 * src typically is on-stack; we want to copy the information in it to 665 * a malloced blame_entry that gets added to the given queue. The 666 * origin of dst loses a refcnt. 667 */ 668static voiddup_entry(struct blame_entry ***queue, 669struct blame_entry *dst,struct blame_entry *src) 670{ 671origin_incref(src->suspect); 672origin_decref(dst->suspect); 673memcpy(dst, src,sizeof(*src)); 674 dst->next = **queue; 675**queue = dst; 676*queue = &dst->next; 677} 678 679static const char*nth_line(struct scoreboard *sb,long lno) 680{ 681return sb->final_buf + sb->lineno[lno]; 682} 683 684static const char*nth_line_cb(void*data,long lno) 685{ 686returnnth_line((struct scoreboard *)data, lno); 687} 688 689/* 690 * It is known that lines between tlno to same came from parent, and e 691 * has an overlap with that range. it also is known that parent's 692 * line plno corresponds to e's line tlno. 693 * 694 * <---- e -----> 695 * <------> 696 * <------------> 697 * <------------> 698 * <------------------> 699 * 700 * Split e into potentially three parts; before this chunk, the chunk 701 * to be blamed for the parent, and after that portion. 702 */ 703static voidsplit_overlap(struct blame_entry *split, 704struct blame_entry *e, 705int tlno,int plno,int same, 706struct origin *parent) 707{ 708int chunk_end_lno; 709memset(split,0,sizeof(struct blame_entry [3])); 710 711if(e->s_lno < tlno) { 712/* there is a pre-chunk part not blamed on parent */ 713 split[0].suspect =origin_incref(e->suspect); 714 split[0].lno = e->lno; 715 split[0].s_lno = e->s_lno; 716 split[0].num_lines = tlno - e->s_lno; 717 split[1].lno = e->lno + tlno - e->s_lno; 718 split[1].s_lno = plno; 719} 720else{ 721 split[1].lno = e->lno; 722 split[1].s_lno = plno + (e->s_lno - tlno); 723} 724 725if(same < e->s_lno + e->num_lines) { 726/* there is a post-chunk part not blamed on parent */ 727 split[2].suspect =origin_incref(e->suspect); 728 split[2].lno = e->lno + (same - e->s_lno); 729 split[2].s_lno = e->s_lno + (same - e->s_lno); 730 split[2].num_lines = e->s_lno + e->num_lines - same; 731 chunk_end_lno = split[2].lno; 732} 733else 734 chunk_end_lno = e->lno + e->num_lines; 735 split[1].num_lines = chunk_end_lno - split[1].lno; 736 737/* 738 * if it turns out there is nothing to blame the parent for, 739 * forget about the splitting. !split[1].suspect signals this. 740 */ 741if(split[1].num_lines <1) 742return; 743 split[1].suspect =origin_incref(parent); 744} 745 746/* 747 * split_overlap() divided an existing blame e into up to three parts 748 * in split. Any assigned blame is moved to queue to 749 * reflect the split. 750 */ 751static voidsplit_blame(struct blame_entry ***blamed, 752struct blame_entry ***unblamed, 753struct blame_entry *split, 754struct blame_entry *e) 755{ 756struct blame_entry *new_entry; 757 758if(split[0].suspect && split[2].suspect) { 759/* The first part (reuse storage for the existing entry e) */ 760dup_entry(unblamed, e, &split[0]); 761 762/* The last part -- me */ 763 new_entry =xmalloc(sizeof(*new_entry)); 764memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 765add_blame_entry(unblamed, new_entry); 766 767/* ... and the middle part -- parent */ 768 new_entry =xmalloc(sizeof(*new_entry)); 769memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 770add_blame_entry(blamed, new_entry); 771} 772else if(!split[0].suspect && !split[2].suspect) 773/* 774 * The parent covers the entire area; reuse storage for 775 * e and replace it with the parent. 776 */ 777dup_entry(blamed, e, &split[1]); 778else if(split[0].suspect) { 779/* me and then parent */ 780dup_entry(unblamed, e, &split[0]); 781 782 new_entry =xmalloc(sizeof(*new_entry)); 783memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 784add_blame_entry(blamed, new_entry); 785} 786else{ 787/* parent and then me */ 788dup_entry(blamed, e, &split[1]); 789 790 new_entry =xmalloc(sizeof(*new_entry)); 791memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 792add_blame_entry(unblamed, new_entry); 793} 794} 795 796/* 797 * After splitting the blame, the origins used by the 798 * on-stack blame_entry should lose one refcnt each. 799 */ 800static voiddecref_split(struct blame_entry *split) 801{ 802int i; 803 804for(i =0; i <3; i++) 805origin_decref(split[i].suspect); 806} 807 808/* 809 * reverse_blame reverses the list given in head, appending tail. 810 * That allows us to build lists in reverse order, then reverse them 811 * afterwards. This can be faster than building the list in proper 812 * order right away. The reason is that building in proper order 813 * requires writing a link in the _previous_ element, while building 814 * in reverse order just requires placing the list head into the 815 * _current_ element. 816 */ 817 818static struct blame_entry *reverse_blame(struct blame_entry *head, 819struct blame_entry *tail) 820{ 821while(head) { 822struct blame_entry *next = head->next; 823 head->next = tail; 824 tail = head; 825 head = next; 826} 827return tail; 828} 829 830/* 831 * Process one hunk from the patch between the current suspect for 832 * blame_entry e and its parent. This first blames any unfinished 833 * entries before the chunk (which is where target and parent start 834 * differing) on the parent, and then splits blame entries at the 835 * start and at the end of the difference region. Since use of -M and 836 * -C options may lead to overlapping/duplicate source line number 837 * ranges, all we can rely on from sorting/merging is the order of the 838 * first suspect line number. 839 */ 840static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 841int tlno,int offset,int same, 842struct origin *parent) 843{ 844struct blame_entry *e = **srcq; 845struct blame_entry *samep = NULL, *diffp = NULL; 846 847while(e && e->s_lno < tlno) { 848struct blame_entry *next = e->next; 849/* 850 * current record starts before differing portion. If 851 * it reaches into it, we need to split it up and 852 * examine the second part separately. 853 */ 854if(e->s_lno + e->num_lines > tlno) { 855/* Move second half to a new record */ 856int len = tlno - e->s_lno; 857struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 858 n->suspect = e->suspect; 859 n->lno = e->lno + len; 860 n->s_lno = e->s_lno + len; 861 n->num_lines = e->num_lines - len; 862 e->num_lines = len; 863 e->score =0; 864/* Push new record to diffp */ 865 n->next = diffp; 866 diffp = n; 867}else 868origin_decref(e->suspect); 869/* Pass blame for everything before the differing 870 * chunk to the parent */ 871 e->suspect =origin_incref(parent); 872 e->s_lno += offset; 873 e->next = samep; 874 samep = e; 875 e = next; 876} 877/* 878 * As we don't know how much of a common stretch after this 879 * diff will occur, the currently blamed parts are all that we 880 * can assign to the parent for now. 881 */ 882 883if(samep) { 884**dstq =reverse_blame(samep, **dstq); 885*dstq = &samep->next; 886} 887/* 888 * Prepend the split off portions: everything after e starts 889 * after the blameable portion. 890 */ 891 e =reverse_blame(diffp, e); 892 893/* 894 * Now retain records on the target while parts are different 895 * from the parent. 896 */ 897 samep = NULL; 898 diffp = NULL; 899while(e && e->s_lno < same) { 900struct blame_entry *next = e->next; 901 902/* 903 * If current record extends into sameness, need to split. 904 */ 905if(e->s_lno + e->num_lines > same) { 906/* 907 * Move second half to a new record to be 908 * processed by later chunks 909 */ 910int len = same - e->s_lno; 911struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 912 n->suspect =origin_incref(e->suspect); 913 n->lno = e->lno + len; 914 n->s_lno = e->s_lno + len; 915 n->num_lines = e->num_lines - len; 916 e->num_lines = len; 917 e->score =0; 918/* Push new record to samep */ 919 n->next = samep; 920 samep = n; 921} 922 e->next = diffp; 923 diffp = e; 924 e = next; 925} 926**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 927/* Move across elements that are in the unblamable portion */ 928if(diffp) 929*srcq = &diffp->next; 930} 931 932struct blame_chunk_cb_data { 933struct origin *parent; 934long offset; 935struct blame_entry **dstq; 936struct blame_entry **srcq; 937}; 938 939/* diff chunks are from parent to target */ 940static intblame_chunk_cb(long start_a,long count_a, 941long start_b,long count_b,void*data) 942{ 943struct blame_chunk_cb_data *d = data; 944if(start_a - start_b != d->offset) 945die("internal error in blame::blame_chunk_cb"); 946blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 947 start_b + count_b, d->parent); 948 d->offset = start_a + count_a - (start_b + count_b); 949return0; 950} 951 952/* 953 * We are looking at the origin 'target' and aiming to pass blame 954 * for the lines it is suspected to its parent. Run diff to find 955 * which lines came from parent and pass blame for them. 956 */ 957static voidpass_blame_to_parent(struct scoreboard *sb, 958struct origin *target, 959struct origin *parent) 960{ 961 mmfile_t file_p, file_o; 962struct blame_chunk_cb_data d; 963struct blame_entry *newdest = NULL; 964 965if(!target->suspects) 966return;/* nothing remains for this target */ 967 968 d.parent = parent; 969 d.offset =0; 970 d.dstq = &newdest; d.srcq = &target->suspects; 971 972fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 973fill_origin_blob(&sb->revs->diffopt, target, &file_o); 974 num_get_patch++; 975 976if(diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d)) 977die("unable to generate diff (%s->%s)", 978oid_to_hex(&parent->commit->object.oid), 979oid_to_hex(&target->commit->object.oid)); 980/* The rest are the same as the parent */ 981blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 982*d.dstq = NULL; 983queue_blames(sb, parent, newdest); 984 985return; 986} 987 988/* 989 * The lines in blame_entry after splitting blames many times can become 990 * very small and trivial, and at some point it becomes pointless to 991 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 992 * ordinary C program, and it is not worth to say it was copied from 993 * totally unrelated file in the parent. 994 * 995 * Compute how trivial the lines in the blame_entry are. 996 */ 997static unsignedent_score(struct scoreboard *sb,struct blame_entry *e) 998{ 999unsigned score;1000const char*cp, *ep;10011002if(e->score)1003return e->score;10041005 score =1;1006 cp =nth_line(sb, e->lno);1007 ep =nth_line(sb, e->lno + e->num_lines);1008while(cp < ep) {1009unsigned ch = *((unsigned char*)cp);1010if(isalnum(ch))1011 score++;1012 cp++;1013}1014 e->score = score;1015return score;1016}10171018/*1019 * best_so_far[] and this[] are both a split of an existing blame_entry1020 * that passes blame to the parent. Maintain best_so_far the best split1021 * so far, by comparing this and best_so_far and copying this into1022 * bst_so_far as needed.1023 */1024static voidcopy_split_if_better(struct scoreboard *sb,1025struct blame_entry *best_so_far,1026struct blame_entry *this)1027{1028int i;10291030if(!this[1].suspect)1031return;1032if(best_so_far[1].suspect) {1033if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1034return;1035}10361037for(i =0; i <3; i++)1038origin_incref(this[i].suspect);1039decref_split(best_so_far);1040memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1041}10421043/*1044 * We are looking at a part of the final image represented by1045 * ent (tlno and same are offset by ent->s_lno).1046 * tlno is where we are looking at in the final image.1047 * up to (but not including) same match preimage.1048 * plno is where we are looking at in the preimage.1049 *1050 * <-------------- final image ---------------------->1051 * <------ent------>1052 * ^tlno ^same1053 * <---------preimage----->1054 * ^plno1055 *1056 * All line numbers are 0-based.1057 */1058static voidhandle_split(struct scoreboard *sb,1059struct blame_entry *ent,1060int tlno,int plno,int same,1061struct origin *parent,1062struct blame_entry *split)1063{1064if(ent->num_lines <= tlno)1065return;1066if(tlno < same) {1067struct blame_entry this[3];1068 tlno += ent->s_lno;1069 same += ent->s_lno;1070split_overlap(this, ent, tlno, plno, same, parent);1071copy_split_if_better(sb, split,this);1072decref_split(this);1073}1074}10751076struct handle_split_cb_data {1077struct scoreboard *sb;1078struct blame_entry *ent;1079struct origin *parent;1080struct blame_entry *split;1081long plno;1082long tlno;1083};10841085static inthandle_split_cb(long start_a,long count_a,1086long start_b,long count_b,void*data)1087{1088struct handle_split_cb_data *d = data;1089handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1090 d->split);1091 d->plno = start_a + count_a;1092 d->tlno = start_b + count_b;1093return0;1094}10951096/*1097 * Find the lines from parent that are the same as ent so that1098 * we can pass blames to it. file_p has the blob contents for1099 * the parent.1100 */1101static voidfind_copy_in_blob(struct scoreboard *sb,1102struct blame_entry *ent,1103struct origin *parent,1104struct blame_entry *split,1105 mmfile_t *file_p)1106{1107const char*cp;1108 mmfile_t file_o;1109struct handle_split_cb_data d;11101111memset(&d,0,sizeof(d));1112 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1113/*1114 * Prepare mmfile that contains only the lines in ent.1115 */1116 cp =nth_line(sb, ent->lno);1117 file_o.ptr = (char*) cp;1118 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11191120/*1121 * file_o is a part of final image we are annotating.1122 * file_p partially may match that image.1123 */1124memset(split,0,sizeof(struct blame_entry [3]));1125if(diff_hunks(file_p, &file_o,1, handle_split_cb, &d))1126die("unable to generate diff (%s)",1127oid_to_hex(&parent->commit->object.oid));1128/* remainder, if any, all match the preimage */1129handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1130}11311132/* Move all blame entries from list *source that have a score smaller1133 * than score_min to the front of list *small.1134 * Returns a pointer to the link pointing to the old head of the small list.1135 */11361137static struct blame_entry **filter_small(struct scoreboard *sb,1138struct blame_entry **small,1139struct blame_entry **source,1140unsigned score_min)1141{1142struct blame_entry *p = *source;1143struct blame_entry *oldsmall = *small;1144while(p) {1145if(ent_score(sb, p) <= score_min) {1146*small = p;1147 small = &p->next;1148 p = *small;1149}else{1150*source = p;1151 source = &p->next;1152 p = *source;1153}1154}1155*small = oldsmall;1156*source = NULL;1157return small;1158}11591160/*1161 * See if lines currently target is suspected for can be attributed to1162 * parent.1163 */1164static voidfind_move_in_parent(struct scoreboard *sb,1165struct blame_entry ***blamed,1166struct blame_entry **toosmall,1167struct origin *target,1168struct origin *parent)1169{1170struct blame_entry *e, split[3];1171struct blame_entry *unblamed = target->suspects;1172struct blame_entry *leftover = NULL;1173 mmfile_t file_p;11741175if(!unblamed)1176return;/* nothing remains for this target */11771178fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1179if(!file_p.ptr)1180return;11811182/* At each iteration, unblamed has a NULL-terminated list of1183 * entries that have not yet been tested for blame. leftover1184 * contains the reversed list of entries that have been tested1185 * without being assignable to the parent.1186 */1187do{1188struct blame_entry **unblamedtail = &unblamed;1189struct blame_entry *next;1190for(e = unblamed; e; e = next) {1191 next = e->next;1192find_copy_in_blob(sb, e, parent, split, &file_p);1193if(split[1].suspect &&1194 blame_move_score <ent_score(sb, &split[1])) {1195split_blame(blamed, &unblamedtail, split, e);1196}else{1197 e->next = leftover;1198 leftover = e;1199}1200decref_split(split);1201}1202*unblamedtail = NULL;1203 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1204}while(unblamed);1205 target->suspects =reverse_blame(leftover, NULL);1206}12071208struct blame_list {1209struct blame_entry *ent;1210struct blame_entry split[3];1211};12121213/*1214 * Count the number of entries the target is suspected for,1215 * and prepare a list of entry and the best split.1216 */1217static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1218int*num_ents_p)1219{1220struct blame_entry *e;1221int num_ents, i;1222struct blame_list *blame_list = NULL;12231224for(e = unblamed, num_ents =0; e; e = e->next)1225 num_ents++;1226if(num_ents) {1227 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1228for(e = unblamed, i =0; e; e = e->next)1229 blame_list[i++].ent = e;1230}1231*num_ents_p = num_ents;1232return blame_list;1233}12341235/*1236 * For lines target is suspected for, see if we can find code movement1237 * across file boundary from the parent commit. porigin is the path1238 * in the parent we already tried.1239 */1240static voidfind_copy_in_parent(struct scoreboard *sb,1241struct blame_entry ***blamed,1242struct blame_entry **toosmall,1243struct origin *target,1244struct commit *parent,1245struct origin *porigin,1246int opt)1247{1248struct diff_options diff_opts;1249int i, j;1250struct blame_list *blame_list;1251int num_ents;1252struct blame_entry *unblamed = target->suspects;1253struct blame_entry *leftover = NULL;12541255if(!unblamed)1256return;/* nothing remains for this target */12571258diff_setup(&diff_opts);1259DIFF_OPT_SET(&diff_opts, RECURSIVE);1260 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12611262diff_setup_done(&diff_opts);12631264/* Try "find copies harder" on new path if requested;1265 * we do not want to use diffcore_rename() actually to1266 * match things up; find_copies_harder is set only to1267 * force diff_tree_sha1() to feed all filepairs to diff_queue,1268 * and this code needs to be after diff_setup_done(), which1269 * usually makes find-copies-harder imply copy detection.1270 */1271if((opt & PICKAXE_BLAME_COPY_HARDEST)1272|| ((opt & PICKAXE_BLAME_COPY_HARDER)1273&& (!porigin ||strcmp(target->path, porigin->path))))1274DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12751276if(is_null_oid(&target->commit->object.oid))1277do_diff_cache(parent->tree->object.oid.hash, &diff_opts);1278else1279diff_tree_sha1(parent->tree->object.oid.hash,1280 target->commit->tree->object.oid.hash,1281"", &diff_opts);12821283if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1284diffcore_std(&diff_opts);12851286do{1287struct blame_entry **unblamedtail = &unblamed;1288 blame_list =setup_blame_list(unblamed, &num_ents);12891290for(i =0; i < diff_queued_diff.nr; i++) {1291struct diff_filepair *p = diff_queued_diff.queue[i];1292struct origin *norigin;1293 mmfile_t file_p;1294struct blame_entry this[3];12951296if(!DIFF_FILE_VALID(p->one))1297continue;/* does not exist in parent */1298if(S_ISGITLINK(p->one->mode))1299continue;/* ignore git links */1300if(porigin && !strcmp(p->one->path, porigin->path))1301/* find_move already dealt with this path */1302continue;13031304 norigin =get_origin(sb, parent, p->one->path);1305hashcpy(norigin->blob_sha1, p->one->sha1);1306 norigin->mode = p->one->mode;1307fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1308if(!file_p.ptr)1309continue;13101311for(j =0; j < num_ents; j++) {1312find_copy_in_blob(sb, blame_list[j].ent,1313 norigin,this, &file_p);1314copy_split_if_better(sb, blame_list[j].split,1315this);1316decref_split(this);1317}1318origin_decref(norigin);1319}13201321for(j =0; j < num_ents; j++) {1322struct blame_entry *split = blame_list[j].split;1323if(split[1].suspect &&1324 blame_copy_score <ent_score(sb, &split[1])) {1325split_blame(blamed, &unblamedtail, split,1326 blame_list[j].ent);1327}else{1328 blame_list[j].ent->next = leftover;1329 leftover = blame_list[j].ent;1330}1331decref_split(split);1332}1333free(blame_list);1334*unblamedtail = NULL;1335 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1336}while(unblamed);1337 target->suspects =reverse_blame(leftover, NULL);1338diff_flush(&diff_opts);1339free_pathspec(&diff_opts.pathspec);1340}13411342/*1343 * The blobs of origin and porigin exactly match, so everything1344 * origin is suspected for can be blamed on the parent.1345 */1346static voidpass_whole_blame(struct scoreboard *sb,1347struct origin *origin,struct origin *porigin)1348{1349struct blame_entry *e, *suspects;13501351if(!porigin->file.ptr && origin->file.ptr) {1352/* Steal its file */1353 porigin->file = origin->file;1354 origin->file.ptr = NULL;1355}1356 suspects = origin->suspects;1357 origin->suspects = NULL;1358for(e = suspects; e; e = e->next) {1359origin_incref(porigin);1360origin_decref(e->suspect);1361 e->suspect = porigin;1362}1363queue_blames(sb, porigin, suspects);1364}13651366/*1367 * We pass blame from the current commit to its parents. We keep saying1368 * "parent" (and "porigin"), but what we mean is to find scapegoat to1369 * exonerate ourselves.1370 */1371static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1372{1373if(!reverse) {1374if(revs->first_parent_only &&1375 commit->parents &&1376 commit->parents->next) {1377free_commit_list(commit->parents->next);1378 commit->parents->next = NULL;1379}1380return commit->parents;1381}1382returnlookup_decoration(&revs->children, &commit->object);1383}13841385static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1386{1387struct commit_list *l =first_scapegoat(revs, commit);1388returncommit_list_count(l);1389}13901391/* Distribute collected unsorted blames to the respected sorted lists1392 * in the various origins.1393 */1394static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1395{1396 blamed =blame_sort(blamed, compare_blame_suspect);1397while(blamed)1398{1399struct origin *porigin = blamed->suspect;1400struct blame_entry *suspects = NULL;1401do{1402struct blame_entry *next = blamed->next;1403 blamed->next = suspects;1404 suspects = blamed;1405 blamed = next;1406}while(blamed && blamed->suspect == porigin);1407 suspects =reverse_blame(suspects, NULL);1408queue_blames(sb, porigin, suspects);1409}1410}14111412#define MAXSG 1614131414static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1415{1416struct rev_info *revs = sb->revs;1417int i, pass, num_sg;1418struct commit *commit = origin->commit;1419struct commit_list *sg;1420struct origin *sg_buf[MAXSG];1421struct origin *porigin, **sg_origin = sg_buf;1422struct blame_entry *toosmall = NULL;1423struct blame_entry *blames, **blametail = &blames;14241425 num_sg =num_scapegoats(revs, commit);1426if(!num_sg)1427goto finish;1428else if(num_sg <ARRAY_SIZE(sg_buf))1429memset(sg_buf,0,sizeof(sg_buf));1430else1431 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14321433/*1434 * The first pass looks for unrenamed path to optimize for1435 * common cases, then we look for renames in the second pass.1436 */1437for(pass =0; pass <2- no_whole_file_rename; pass++) {1438struct origin *(*find)(struct scoreboard *,1439struct commit *,struct origin *);1440 find = pass ? find_rename : find_origin;14411442for(i =0, sg =first_scapegoat(revs, commit);1443 i < num_sg && sg;1444 sg = sg->next, i++) {1445struct commit *p = sg->item;1446int j, same;14471448if(sg_origin[i])1449continue;1450if(parse_commit(p))1451continue;1452 porigin =find(sb, p, origin);1453if(!porigin)1454continue;1455if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1456pass_whole_blame(sb, origin, porigin);1457origin_decref(porigin);1458goto finish;1459}1460for(j = same =0; j < i; j++)1461if(sg_origin[j] &&1462!hashcmp(sg_origin[j]->blob_sha1,1463 porigin->blob_sha1)) {1464 same =1;1465break;1466}1467if(!same)1468 sg_origin[i] = porigin;1469else1470origin_decref(porigin);1471}1472}14731474 num_commits++;1475for(i =0, sg =first_scapegoat(revs, commit);1476 i < num_sg && sg;1477 sg = sg->next, i++) {1478struct origin *porigin = sg_origin[i];1479if(!porigin)1480continue;1481if(!origin->previous) {1482origin_incref(porigin);1483 origin->previous = porigin;1484}1485pass_blame_to_parent(sb, origin, porigin);1486if(!origin->suspects)1487goto finish;1488}14891490/*1491 * Optionally find moves in parents' files.1492 */1493if(opt & PICKAXE_BLAME_MOVE) {1494filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1495if(origin->suspects) {1496for(i =0, sg =first_scapegoat(revs, commit);1497 i < num_sg && sg;1498 sg = sg->next, i++) {1499struct origin *porigin = sg_origin[i];1500if(!porigin)1501continue;1502find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1503if(!origin->suspects)1504break;1505}1506}1507}15081509/*1510 * Optionally find copies from parents' files.1511 */1512if(opt & PICKAXE_BLAME_COPY) {1513if(blame_copy_score > blame_move_score)1514filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1515else if(blame_copy_score < blame_move_score) {1516 origin->suspects =blame_merge(origin->suspects, toosmall);1517 toosmall = NULL;1518filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1519}1520if(!origin->suspects)1521goto finish;15221523for(i =0, sg =first_scapegoat(revs, commit);1524 i < num_sg && sg;1525 sg = sg->next, i++) {1526struct origin *porigin = sg_origin[i];1527find_copy_in_parent(sb, &blametail, &toosmall,1528 origin, sg->item, porigin, opt);1529if(!origin->suspects)1530goto finish;1531}1532}15331534finish:1535*blametail = NULL;1536distribute_blame(sb, blames);1537/*1538 * prepend toosmall to origin->suspects1539 *1540 * There is no point in sorting: this ends up on a big1541 * unsorted list in the caller anyway.1542 */1543if(toosmall) {1544struct blame_entry **tail = &toosmall;1545while(*tail)1546 tail = &(*tail)->next;1547*tail = origin->suspects;1548 origin->suspects = toosmall;1549}1550for(i =0; i < num_sg; i++) {1551if(sg_origin[i]) {1552drop_origin_blob(sg_origin[i]);1553origin_decref(sg_origin[i]);1554}1555}1556drop_origin_blob(origin);1557if(sg_buf != sg_origin)1558free(sg_origin);1559}15601561/*1562 * Information on commits, used for output.1563 */1564struct commit_info {1565struct strbuf author;1566struct strbuf author_mail;1567unsigned long author_time;1568struct strbuf author_tz;15691570/* filled only when asked for details */1571struct strbuf committer;1572struct strbuf committer_mail;1573unsigned long committer_time;1574struct strbuf committer_tz;15751576struct strbuf summary;1577};15781579/*1580 * Parse author/committer line in the commit object buffer1581 */1582static voidget_ac_line(const char*inbuf,const char*what,1583struct strbuf *name,struct strbuf *mail,1584unsigned long*time,struct strbuf *tz)1585{1586struct ident_split ident;1587size_t len, maillen, namelen;1588char*tmp, *endp;1589const char*namebuf, *mailbuf;15901591 tmp =strstr(inbuf, what);1592if(!tmp)1593goto error_out;1594 tmp +=strlen(what);1595 endp =strchr(tmp,'\n');1596if(!endp)1597 len =strlen(tmp);1598else1599 len = endp - tmp;16001601if(split_ident_line(&ident, tmp, len)) {1602 error_out:1603/* Ugh */1604 tmp ="(unknown)";1605strbuf_addstr(name, tmp);1606strbuf_addstr(mail, tmp);1607strbuf_addstr(tz, tmp);1608*time =0;1609return;1610}16111612 namelen = ident.name_end - ident.name_begin;1613 namebuf = ident.name_begin;16141615 maillen = ident.mail_end - ident.mail_begin;1616 mailbuf = ident.mail_begin;16171618if(ident.date_begin && ident.date_end)1619*time =strtoul(ident.date_begin, NULL,10);1620else1621*time =0;16221623if(ident.tz_begin && ident.tz_end)1624strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1625else1626strbuf_addstr(tz,"(unknown)");16271628/*1629 * Now, convert both name and e-mail using mailmap1630 */1631map_user(&mailmap, &mailbuf, &maillen,1632&namebuf, &namelen);16331634strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1635strbuf_add(name, namebuf, namelen);1636}16371638static voidcommit_info_init(struct commit_info *ci)1639{16401641strbuf_init(&ci->author,0);1642strbuf_init(&ci->author_mail,0);1643strbuf_init(&ci->author_tz,0);1644strbuf_init(&ci->committer,0);1645strbuf_init(&ci->committer_mail,0);1646strbuf_init(&ci->committer_tz,0);1647strbuf_init(&ci->summary,0);1648}16491650static voidcommit_info_destroy(struct commit_info *ci)1651{16521653strbuf_release(&ci->author);1654strbuf_release(&ci->author_mail);1655strbuf_release(&ci->author_tz);1656strbuf_release(&ci->committer);1657strbuf_release(&ci->committer_mail);1658strbuf_release(&ci->committer_tz);1659strbuf_release(&ci->summary);1660}16611662static voidget_commit_info(struct commit *commit,1663struct commit_info *ret,1664int detailed)1665{1666int len;1667const char*subject, *encoding;1668const char*message;16691670commit_info_init(ret);16711672 encoding =get_log_output_encoding();1673 message =logmsg_reencode(commit, NULL, encoding);1674get_ac_line(message,"\nauthor ",1675&ret->author, &ret->author_mail,1676&ret->author_time, &ret->author_tz);16771678if(!detailed) {1679unuse_commit_buffer(commit, message);1680return;1681}16821683get_ac_line(message,"\ncommitter ",1684&ret->committer, &ret->committer_mail,1685&ret->committer_time, &ret->committer_tz);16861687 len =find_commit_subject(message, &subject);1688if(len)1689strbuf_add(&ret->summary, subject, len);1690else1691strbuf_addf(&ret->summary,"(%s)",oid_to_hex(&commit->object.oid));16921693unuse_commit_buffer(commit, message);1694}16951696/*1697 * To allow LF and other nonportable characters in pathnames,1698 * they are c-style quoted as needed.1699 */1700static voidwrite_filename_info(const char*path)1701{1702printf("filename ");1703write_name_quoted(path, stdout,'\n');1704}17051706/*1707 * Porcelain/Incremental format wants to show a lot of details per1708 * commit. Instead of repeating this every line, emit it only once,1709 * the first time each commit appears in the output (unless the1710 * user has specifically asked for us to repeat).1711 */1712static intemit_one_suspect_detail(struct origin *suspect,int repeat)1713{1714struct commit_info ci;17151716if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1717return0;17181719 suspect->commit->object.flags |= METAINFO_SHOWN;1720get_commit_info(suspect->commit, &ci,1);1721printf("author%s\n", ci.author.buf);1722printf("author-mail%s\n", ci.author_mail.buf);1723printf("author-time%lu\n", ci.author_time);1724printf("author-tz%s\n", ci.author_tz.buf);1725printf("committer%s\n", ci.committer.buf);1726printf("committer-mail%s\n", ci.committer_mail.buf);1727printf("committer-time%lu\n", ci.committer_time);1728printf("committer-tz%s\n", ci.committer_tz.buf);1729printf("summary%s\n", ci.summary.buf);1730if(suspect->commit->object.flags & UNINTERESTING)1731printf("boundary\n");1732if(suspect->previous) {1733struct origin *prev = suspect->previous;1734printf("previous%s",oid_to_hex(&prev->commit->object.oid));1735write_name_quoted(prev->path, stdout,'\n');1736}17371738commit_info_destroy(&ci);17391740return1;1741}17421743/*1744 * The blame_entry is found to be guilty for the range.1745 * Show it in incremental output.1746 */1747static voidfound_guilty_entry(struct blame_entry *ent)1748{1749if(incremental) {1750struct origin *suspect = ent->suspect;17511752printf("%s %d %d %d\n",1753oid_to_hex(&suspect->commit->object.oid),1754 ent->s_lno +1, ent->lno +1, ent->num_lines);1755emit_one_suspect_detail(suspect,0);1756write_filename_info(suspect->path);1757maybe_flush_or_die(stdout,"stdout");1758}1759}17601761/*1762 * The main loop -- while we have blobs with lines whose true origin1763 * is still unknown, pick one blob, and allow its lines to pass blames1764 * to its parents. */1765static voidassign_blame(struct scoreboard *sb,int opt)1766{1767struct rev_info *revs = sb->revs;1768struct commit *commit =prio_queue_get(&sb->commits);17691770while(commit) {1771struct blame_entry *ent;1772struct origin *suspect = commit->util;17731774/* find one suspect to break down */1775while(suspect && !suspect->suspects)1776 suspect = suspect->next;17771778if(!suspect) {1779 commit =prio_queue_get(&sb->commits);1780continue;1781}17821783assert(commit == suspect->commit);17841785/*1786 * We will use this suspect later in the loop,1787 * so hold onto it in the meantime.1788 */1789origin_incref(suspect);1790parse_commit(commit);1791if(reverse ||1792(!(commit->object.flags & UNINTERESTING) &&1793!(revs->max_age != -1&& commit->date < revs->max_age)))1794pass_blame(sb, suspect, opt);1795else{1796 commit->object.flags |= UNINTERESTING;1797if(commit->object.parsed)1798mark_parents_uninteresting(commit);1799}1800/* treat root commit as boundary */1801if(!commit->parents && !show_root)1802 commit->object.flags |= UNINTERESTING;18031804/* Take responsibility for the remaining entries */1805 ent = suspect->suspects;1806if(ent) {1807 suspect->guilty =1;1808for(;;) {1809struct blame_entry *next = ent->next;1810found_guilty_entry(ent);1811if(next) {1812 ent = next;1813continue;1814}1815 ent->next = sb->ent;1816 sb->ent = suspect->suspects;1817 suspect->suspects = NULL;1818break;1819}1820}1821origin_decref(suspect);18221823if(DEBUG)/* sanity */1824sanity_check_refcnt(sb);1825}1826}18271828static const char*format_time(unsigned long time,const char*tz_str,1829int show_raw_time)1830{1831static struct strbuf time_buf = STRBUF_INIT;18321833strbuf_reset(&time_buf);1834if(show_raw_time) {1835strbuf_addf(&time_buf,"%lu%s", time, tz_str);1836}1837else{1838const char*time_str;1839size_t time_width;1840int tz;1841 tz =atoi(tz_str);1842 time_str =show_date(time, tz, &blame_date_mode);1843strbuf_addstr(&time_buf, time_str);1844/*1845 * Add space paddings to time_buf to display a fixed width1846 * string, and use time_width for display width calibration.1847 */1848for(time_width =utf8_strwidth(time_str);1849 time_width < blame_date_width;1850 time_width++)1851strbuf_addch(&time_buf,' ');1852}1853return time_buf.buf;1854}18551856#define OUTPUT_ANNOTATE_COMPAT 0011857#define OUTPUT_LONG_OBJECT_NAME 0021858#define OUTPUT_RAW_TIMESTAMP 0041859#define OUTPUT_PORCELAIN 0101860#define OUTPUT_SHOW_NAME 0201861#define OUTPUT_SHOW_NUMBER 0401862#define OUTPUT_SHOW_SCORE 01001863#define OUTPUT_NO_AUTHOR 02001864#define OUTPUT_SHOW_EMAIL 04001865#define OUTPUT_LINE_PORCELAIN 0100018661867static voidemit_porcelain_details(struct origin *suspect,int repeat)1868{1869if(emit_one_suspect_detail(suspect, repeat) ||1870(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1871write_filename_info(suspect->path);1872}18731874static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1875int opt)1876{1877int repeat = opt & OUTPUT_LINE_PORCELAIN;1878int cnt;1879const char*cp;1880struct origin *suspect = ent->suspect;1881char hex[GIT_SHA1_HEXSZ +1];18821883sha1_to_hex_r(hex, suspect->commit->object.oid.hash);1884printf("%s %d %d %d\n",1885 hex,1886 ent->s_lno +1,1887 ent->lno +1,1888 ent->num_lines);1889emit_porcelain_details(suspect, repeat);18901891 cp =nth_line(sb, ent->lno);1892for(cnt =0; cnt < ent->num_lines; cnt++) {1893char ch;1894if(cnt) {1895printf("%s %d %d\n", hex,1896 ent->s_lno +1+ cnt,1897 ent->lno +1+ cnt);1898if(repeat)1899emit_porcelain_details(suspect,1);1900}1901putchar('\t');1902do{1903 ch = *cp++;1904putchar(ch);1905}while(ch !='\n'&&1906 cp < sb->final_buf + sb->final_buf_size);1907}19081909if(sb->final_buf_size && cp[-1] !='\n')1910putchar('\n');1911}19121913static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1914{1915int cnt;1916const char*cp;1917struct origin *suspect = ent->suspect;1918struct commit_info ci;1919char hex[GIT_SHA1_HEXSZ +1];1920int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19211922get_commit_info(suspect->commit, &ci,1);1923sha1_to_hex_r(hex, suspect->commit->object.oid.hash);19241925 cp =nth_line(sb, ent->lno);1926for(cnt =0; cnt < ent->num_lines; cnt++) {1927char ch;1928int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19291930if(suspect->commit->object.flags & UNINTERESTING) {1931if(blank_boundary)1932memset(hex,' ', length);1933else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1934 length--;1935putchar('^');1936}1937}19381939printf("%.*s", length, hex);1940if(opt & OUTPUT_ANNOTATE_COMPAT) {1941const char*name;1942if(opt & OUTPUT_SHOW_EMAIL)1943 name = ci.author_mail.buf;1944else1945 name = ci.author.buf;1946printf("\t(%10s\t%10s\t%d)", name,1947format_time(ci.author_time, ci.author_tz.buf,1948 show_raw_time),1949 ent->lno +1+ cnt);1950}else{1951if(opt & OUTPUT_SHOW_SCORE)1952printf(" %*d%02d",1953 max_score_digits, ent->score,1954 ent->suspect->refcnt);1955if(opt & OUTPUT_SHOW_NAME)1956printf(" %-*.*s", longest_file, longest_file,1957 suspect->path);1958if(opt & OUTPUT_SHOW_NUMBER)1959printf(" %*d", max_orig_digits,1960 ent->s_lno +1+ cnt);19611962if(!(opt & OUTPUT_NO_AUTHOR)) {1963const char*name;1964int pad;1965if(opt & OUTPUT_SHOW_EMAIL)1966 name = ci.author_mail.buf;1967else1968 name = ci.author.buf;1969 pad = longest_author -utf8_strwidth(name);1970printf(" (%s%*s%10s",1971 name, pad,"",1972format_time(ci.author_time,1973 ci.author_tz.buf,1974 show_raw_time));1975}1976printf(" %*d) ",1977 max_digits, ent->lno +1+ cnt);1978}1979do{1980 ch = *cp++;1981putchar(ch);1982}while(ch !='\n'&&1983 cp < sb->final_buf + sb->final_buf_size);1984}19851986if(sb->final_buf_size && cp[-1] !='\n')1987putchar('\n');19881989commit_info_destroy(&ci);1990}19911992static voidoutput(struct scoreboard *sb,int option)1993{1994struct blame_entry *ent;19951996if(option & OUTPUT_PORCELAIN) {1997for(ent = sb->ent; ent; ent = ent->next) {1998int count =0;1999struct origin *suspect;2000struct commit *commit = ent->suspect->commit;2001if(commit->object.flags & MORE_THAN_ONE_PATH)2002continue;2003for(suspect = commit->util; suspect; suspect = suspect->next) {2004if(suspect->guilty && count++) {2005 commit->object.flags |= MORE_THAN_ONE_PATH;2006break;2007}2008}2009}2010}20112012for(ent = sb->ent; ent; ent = ent->next) {2013if(option & OUTPUT_PORCELAIN)2014emit_porcelain(sb, ent, option);2015else{2016emit_other(sb, ent, option);2017}2018}2019}20202021static const char*get_next_line(const char*start,const char*end)2022{2023const char*nl =memchr(start,'\n', end - start);2024return nl ? nl +1: end;2025}20262027/*2028 * To allow quick access to the contents of nth line in the2029 * final image, prepare an index in the scoreboard.2030 */2031static intprepare_lines(struct scoreboard *sb)2032{2033const char*buf = sb->final_buf;2034unsigned long len = sb->final_buf_size;2035const char*end = buf + len;2036const char*p;2037int*lineno;2038int num =0;20392040for(p = buf; p < end; p =get_next_line(p, end))2041 num++;20422043ALLOC_ARRAY(sb->lineno, num +1);2044 lineno = sb->lineno;20452046for(p = buf; p < end; p =get_next_line(p, end))2047*lineno++ = p - buf;20482049*lineno = len;20502051 sb->num_lines = num;2052return sb->num_lines;2053}20542055/*2056 * Add phony grafts for use with -S; this is primarily to2057 * support git's cvsserver that wants to give a linear history2058 * to its clients.2059 */2060static intread_ancestry(const char*graft_file)2061{2062FILE*fp =fopen(graft_file,"r");2063struct strbuf buf = STRBUF_INIT;2064if(!fp)2065return-1;2066while(!strbuf_getwholeline(&buf, fp,'\n')) {2067/* The format is just "Commit Parent1 Parent2 ...\n" */2068struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2069if(graft)2070register_commit_graft(graft,0);2071}2072fclose(fp);2073strbuf_release(&buf);2074return0;2075}20762077static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2078{2079const char*uniq =find_unique_abbrev(suspect->commit->object.oid.hash,2080 auto_abbrev);2081int len =strlen(uniq);2082if(auto_abbrev < len)2083return len;2084return auto_abbrev;2085}20862087/*2088 * How many columns do we need to show line numbers, authors,2089 * and filenames?2090 */2091static voidfind_alignment(struct scoreboard *sb,int*option)2092{2093int longest_src_lines =0;2094int longest_dst_lines =0;2095unsigned largest_score =0;2096struct blame_entry *e;2097int compute_auto_abbrev = (abbrev <0);2098int auto_abbrev = default_abbrev;20992100for(e = sb->ent; e; e = e->next) {2101struct origin *suspect = e->suspect;2102int num;21032104if(compute_auto_abbrev)2105 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2106if(strcmp(suspect->path, sb->path))2107*option |= OUTPUT_SHOW_NAME;2108 num =strlen(suspect->path);2109if(longest_file < num)2110 longest_file = num;2111if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2112struct commit_info ci;2113 suspect->commit->object.flags |= METAINFO_SHOWN;2114get_commit_info(suspect->commit, &ci,1);2115if(*option & OUTPUT_SHOW_EMAIL)2116 num =utf8_strwidth(ci.author_mail.buf);2117else2118 num =utf8_strwidth(ci.author.buf);2119if(longest_author < num)2120 longest_author = num;2121commit_info_destroy(&ci);2122}2123 num = e->s_lno + e->num_lines;2124if(longest_src_lines < num)2125 longest_src_lines = num;2126 num = e->lno + e->num_lines;2127if(longest_dst_lines < num)2128 longest_dst_lines = num;2129if(largest_score <ent_score(sb, e))2130 largest_score =ent_score(sb, e);2131}2132 max_orig_digits =decimal_width(longest_src_lines);2133 max_digits =decimal_width(longest_dst_lines);2134 max_score_digits =decimal_width(largest_score);21352136if(compute_auto_abbrev)2137/* one more abbrev length is needed for the boundary commit */2138 abbrev = auto_abbrev +1;2139}21402141/*2142 * For debugging -- origin is refcounted, and this asserts that2143 * we do not underflow.2144 */2145static voidsanity_check_refcnt(struct scoreboard *sb)2146{2147int baa =0;2148struct blame_entry *ent;21492150for(ent = sb->ent; ent; ent = ent->next) {2151/* Nobody should have zero or negative refcnt */2152if(ent->suspect->refcnt <=0) {2153fprintf(stderr,"%sin%shas negative refcnt%d\n",2154 ent->suspect->path,2155oid_to_hex(&ent->suspect->commit->object.oid),2156 ent->suspect->refcnt);2157 baa =1;2158}2159}2160if(baa) {2161int opt =0160;2162find_alignment(sb, &opt);2163output(sb, opt);2164die("Baa%d!", baa);2165}2166}21672168static unsignedparse_score(const char*arg)2169{2170char*end;2171unsigned long score =strtoul(arg, &end,10);2172if(*end)2173return0;2174return score;2175}21762177static const char*add_prefix(const char*prefix,const char*path)2178{2179returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2180}21812182static intgit_blame_config(const char*var,const char*value,void*cb)2183{2184if(!strcmp(var,"blame.showroot")) {2185 show_root =git_config_bool(var, value);2186return0;2187}2188if(!strcmp(var,"blame.blankboundary")) {2189 blank_boundary =git_config_bool(var, value);2190return0;2191}2192if(!strcmp(var,"blame.showemail")) {2193int*output_option = cb;2194if(git_config_bool(var, value))2195*output_option |= OUTPUT_SHOW_EMAIL;2196else2197*output_option &= ~OUTPUT_SHOW_EMAIL;2198return0;2199}2200if(!strcmp(var,"blame.date")) {2201if(!value)2202returnconfig_error_nonbool(var);2203parse_date_format(value, &blame_date_mode);2204return0;2205}22062207if(userdiff_config(var, value) <0)2208return-1;22092210returngit_default_config(var, value, cb);2211}22122213static voidverify_working_tree_path(struct commit *work_tree,const char*path)2214{2215struct commit_list *parents;22162217for(parents = work_tree->parents; parents; parents = parents->next) {2218const unsigned char*commit_sha1 = parents->item->object.oid.hash;2219unsigned char blob_sha1[20];2220unsigned mode;22212222if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2223sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2224return;2225}2226die("no such path '%s' in HEAD", path);2227}22282229static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2230{2231struct commit *parent;22322233 parent =lookup_commit_reference(sha1);2234if(!parent)2235die("no such commit%s",sha1_to_hex(sha1));2236return&commit_list_insert(parent, tail)->next;2237}22382239static voidappend_merge_parents(struct commit_list **tail)2240{2241int merge_head;2242struct strbuf line = STRBUF_INIT;22432244 merge_head =open(git_path_merge_head(), O_RDONLY);2245if(merge_head <0) {2246if(errno == ENOENT)2247return;2248die("cannot open '%s' for reading",git_path_merge_head());2249}22502251while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2252unsigned char sha1[20];2253if(line.len <40||get_sha1_hex(line.buf, sha1))2254die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2255 tail =append_parent(tail, sha1);2256}2257close(merge_head);2258strbuf_release(&line);2259}22602261/*2262 * This isn't as simple as passing sb->buf and sb->len, because we2263 * want to transfer ownership of the buffer to the commit (so we2264 * must use detach).2265 */2266static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2267{2268size_t len;2269void*buf =strbuf_detach(sb, &len);2270set_commit_buffer(c, buf, len);2271}22722273/*2274 * Prepare a dummy commit that represents the work tree (or staged) item.2275 * Note that annotating work tree item never works in the reverse.2276 */2277static struct commit *fake_working_tree_commit(struct diff_options *opt,2278const char*path,2279const char*contents_from)2280{2281struct commit *commit;2282struct origin *origin;2283struct commit_list **parent_tail, *parent;2284unsigned char head_sha1[20];2285struct strbuf buf = STRBUF_INIT;2286const char*ident;2287time_t now;2288int size, len;2289struct cache_entry *ce;2290unsigned mode;2291struct strbuf msg = STRBUF_INIT;22922293time(&now);2294 commit =alloc_commit_node();2295 commit->object.parsed =1;2296 commit->date = now;2297 parent_tail = &commit->parents;22982299if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2300die("no such ref: HEAD");23012302 parent_tail =append_parent(parent_tail, head_sha1);2303append_merge_parents(parent_tail);2304verify_working_tree_path(commit, path);23052306 origin =make_origin(commit, path);23072308 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2309strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2310for(parent = commit->parents; parent; parent = parent->next)2311strbuf_addf(&msg,"parent%s\n",2312oid_to_hex(&parent->item->object.oid));2313strbuf_addf(&msg,2314"author%s\n"2315"committer%s\n\n"2316"Version of%sfrom%s\n",2317 ident, ident, path,2318(!contents_from ? path :2319(!strcmp(contents_from,"-") ?"standard input": contents_from)));2320set_commit_buffer_from_strbuf(commit, &msg);23212322if(!contents_from ||strcmp("-", contents_from)) {2323struct stat st;2324const char*read_from;2325char*buf_ptr;2326unsigned long buf_len;23272328if(contents_from) {2329if(stat(contents_from, &st) <0)2330die_errno("Cannot stat '%s'", contents_from);2331 read_from = contents_from;2332}2333else{2334if(lstat(path, &st) <0)2335die_errno("Cannot lstat '%s'", path);2336 read_from = path;2337}2338 mode =canon_mode(st.st_mode);23392340switch(st.st_mode & S_IFMT) {2341case S_IFREG:2342if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2343textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2344strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2345else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2346die_errno("cannot open or read '%s'", read_from);2347break;2348case S_IFLNK:2349if(strbuf_readlink(&buf, read_from, st.st_size) <0)2350die_errno("cannot readlink '%s'", read_from);2351break;2352default:2353die("unsupported file type%s", read_from);2354}2355}2356else{2357/* Reading from stdin */2358 mode =0;2359if(strbuf_read(&buf,0,0) <0)2360die_errno("failed to read from stdin");2361}2362convert_to_git(path, buf.buf, buf.len, &buf,0);2363 origin->file.ptr = buf.buf;2364 origin->file.size = buf.len;2365pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23662367/*2368 * Read the current index, replace the path entry with2369 * origin->blob_sha1 without mucking with its mode or type2370 * bits; we are not going to write this index out -- we just2371 * want to run "diff-index --cached".2372 */2373discard_cache();2374read_cache();23752376 len =strlen(path);2377if(!mode) {2378int pos =cache_name_pos(path, len);2379if(0<= pos)2380 mode = active_cache[pos]->ce_mode;2381else2382/* Let's not bother reading from HEAD tree */2383 mode = S_IFREG |0644;2384}2385 size =cache_entry_size(len);2386 ce =xcalloc(1, size);2387hashcpy(ce->sha1, origin->blob_sha1);2388memcpy(ce->name, path, len);2389 ce->ce_flags =create_ce_flags(0);2390 ce->ce_namelen = len;2391 ce->ce_mode =create_ce_mode(mode);2392add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23932394cache_tree_invalidate_path(&the_index, path);23952396return commit;2397}23982399static struct commit *find_single_final(struct rev_info *revs,2400const char**name_p)2401{2402int i;2403struct commit *found = NULL;2404const char*name = NULL;24052406for(i =0; i < revs->pending.nr; i++) {2407struct object *obj = revs->pending.objects[i].item;2408if(obj->flags & UNINTERESTING)2409continue;2410while(obj->type == OBJ_TAG)2411 obj =deref_tag(obj, NULL,0);2412if(obj->type != OBJ_COMMIT)2413die("Non commit%s?", revs->pending.objects[i].name);2414if(found)2415die("More than one commit to dig from%sand%s?",2416 revs->pending.objects[i].name, name);2417 found = (struct commit *)obj;2418 name = revs->pending.objects[i].name;2419}2420if(name_p)2421*name_p = name;2422return found;2423}24242425static char*prepare_final(struct scoreboard *sb)2426{2427const char*name;2428 sb->final =find_single_final(sb->revs, &name);2429returnxstrdup_or_null(name);2430}24312432static char*prepare_initial(struct scoreboard *sb)2433{2434int i;2435const char*final_commit_name = NULL;2436struct rev_info *revs = sb->revs;24372438/*2439 * There must be one and only one negative commit, and it must be2440 * the boundary.2441 */2442for(i =0; i < revs->pending.nr; i++) {2443struct object *obj = revs->pending.objects[i].item;2444if(!(obj->flags & UNINTERESTING))2445continue;2446while(obj->type == OBJ_TAG)2447 obj =deref_tag(obj, NULL,0);2448if(obj->type != OBJ_COMMIT)2449die("Non commit%s?", revs->pending.objects[i].name);2450if(sb->final)2451die("More than one commit to dig down to%sand%s?",2452 revs->pending.objects[i].name,2453 final_commit_name);2454 sb->final = (struct commit *) obj;2455 final_commit_name = revs->pending.objects[i].name;2456}2457if(!final_commit_name)2458die("No commit to dig down to?");2459returnxstrdup(final_commit_name);2460}24612462static intblame_copy_callback(const struct option *option,const char*arg,int unset)2463{2464int*opt = option->value;24652466/*2467 * -C enables copy from removed files;2468 * -C -C enables copy from existing files, but only2469 * when blaming a new file;2470 * -C -C -C enables copy from existing files for2471 * everybody2472 */2473if(*opt & PICKAXE_BLAME_COPY_HARDER)2474*opt |= PICKAXE_BLAME_COPY_HARDEST;2475if(*opt & PICKAXE_BLAME_COPY)2476*opt |= PICKAXE_BLAME_COPY_HARDER;2477*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;24782479if(arg)2480 blame_copy_score =parse_score(arg);2481return0;2482}24832484static intblame_move_callback(const struct option *option,const char*arg,int unset)2485{2486int*opt = option->value;24872488*opt |= PICKAXE_BLAME_MOVE;24892490if(arg)2491 blame_move_score =parse_score(arg);2492return0;2493}24942495intcmd_blame(int argc,const char**argv,const char*prefix)2496{2497struct rev_info revs;2498const char*path;2499struct scoreboard sb;2500struct origin *o;2501struct blame_entry *ent = NULL;2502long dashdash_pos, lno;2503char*final_commit_name = NULL;2504enum object_type type;2505struct commit *final_commit = NULL;25062507static struct string_list range_list;2508static int output_option =0, opt =0;2509static int show_stats =0;2510static const char*revs_file = NULL;2511static const char*contents_from = NULL;2512static const struct option options[] = {2513OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2514OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2515OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2516OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2517OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2518OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2519OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2520OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2521OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2522OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2523OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2524OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2525OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2526OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2527OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2528OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2529OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2530OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2531{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2532{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2533OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2534OPT__ABBREV(&abbrev),2535OPT_END()2536};25372538struct parse_opt_ctx_t ctx;2539int cmd_is_annotate = !strcmp(argv[0],"annotate");2540struct range_set ranges;2541unsigned int range_i;2542long anchor;25432544git_config(git_blame_config, &output_option);2545init_revisions(&revs, NULL);2546 revs.date_mode = blame_date_mode;2547DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2548DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25492550 save_commit_buffer =0;2551 dashdash_pos =0;25522553parse_options_start(&ctx, argc, argv, prefix, options,2554 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2555for(;;) {2556switch(parse_options_step(&ctx, options, blame_opt_usage)) {2557case PARSE_OPT_HELP:2558exit(129);2559case PARSE_OPT_DONE:2560if(ctx.argv[0])2561 dashdash_pos = ctx.cpidx;2562goto parse_done;2563}25642565if(!strcmp(ctx.argv[0],"--reverse")) {2566 ctx.argv[0] ="--children";2567 reverse =1;2568}2569parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2570}2571parse_done:2572 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2573DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2574 argc =parse_options_end(&ctx);25752576if(0< abbrev)2577/* one more abbrev length is needed for the boundary commit */2578 abbrev++;25792580if(revs_file &&read_ancestry(revs_file))2581die_errno("reading graft file '%s' failed", revs_file);25822583if(cmd_is_annotate) {2584 output_option |= OUTPUT_ANNOTATE_COMPAT;2585 blame_date_mode.type = DATE_ISO8601;2586}else{2587 blame_date_mode = revs.date_mode;2588}25892590/* The maximum width used to show the dates */2591switch(blame_date_mode.type) {2592case DATE_RFC2822:2593 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2594break;2595case DATE_ISO8601_STRICT:2596 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2597break;2598case DATE_ISO8601:2599 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2600break;2601case DATE_RAW:2602 blame_date_width =sizeof("1161298804 -0700");2603break;2604case DATE_SHORT:2605 blame_date_width =sizeof("2006-10-19");2606break;2607case DATE_RELATIVE:2608/* TRANSLATORS: This string is used to tell us the maximum2609 display width for a relative timestamp in "git blame"2610 output. For C locale, "4 years, 11 months ago", which2611 takes 22 places, is the longest among various forms of2612 relative timestamps, but your language may need more or2613 fewer display columns. */2614 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2615break;2616case DATE_NORMAL:2617 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2618break;2619case DATE_STRFTIME:2620 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2621break;2622}2623 blame_date_width -=1;/* strip the null */26242625if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2626 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2627 PICKAXE_BLAME_COPY_HARDER);26282629if(!blame_move_score)2630 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2631if(!blame_copy_score)2632 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26332634/*2635 * We have collected options unknown to us in argv[1..unk]2636 * which are to be passed to revision machinery if we are2637 * going to do the "bottom" processing.2638 *2639 * The remaining are:2640 *2641 * (1) if dashdash_pos != 0, it is either2642 * "blame [revisions] -- <path>" or2643 * "blame -- <path> <rev>"2644 *2645 * (2) otherwise, it is one of the two:2646 * "blame [revisions] <path>"2647 * "blame <path> <rev>"2648 *2649 * Note that we must strip out <path> from the arguments: we do not2650 * want the path pruning but we may want "bottom" processing.2651 */2652if(dashdash_pos) {2653switch(argc - dashdash_pos -1) {2654case2:/* (1b) */2655if(argc !=4)2656usage_with_options(blame_opt_usage, options);2657/* reorder for the new way: <rev> -- <path> */2658 argv[1] = argv[3];2659 argv[3] = argv[2];2660 argv[2] ="--";2661/* FALLTHROUGH */2662case1:/* (1a) */2663 path =add_prefix(prefix, argv[--argc]);2664 argv[argc] = NULL;2665break;2666default:2667usage_with_options(blame_opt_usage, options);2668}2669}else{2670if(argc <2)2671usage_with_options(blame_opt_usage, options);2672 path =add_prefix(prefix, argv[argc -1]);2673if(argc ==3&& !file_exists(path)) {/* (2b) */2674 path =add_prefix(prefix, argv[1]);2675 argv[1] = argv[2];2676}2677 argv[argc -1] ="--";26782679setup_work_tree();2680if(!file_exists(path))2681die_errno("cannot stat path '%s'", path);2682}26832684 revs.disable_stdin =1;2685setup_revisions(argc, argv, &revs, NULL);2686memset(&sb,0,sizeof(sb));26872688 sb.revs = &revs;2689if(!reverse) {2690 final_commit_name =prepare_final(&sb);2691 sb.commits.compare = compare_commits_by_commit_date;2692}2693else if(contents_from)2694die("--contents and --reverse do not blend well.");2695else{2696 final_commit_name =prepare_initial(&sb);2697 sb.commits.compare = compare_commits_by_reverse_commit_date;2698if(revs.first_parent_only)2699 revs.children.name = NULL;2700}27012702if(!sb.final) {2703/*2704 * "--not A B -- path" without anything positive;2705 * do not default to HEAD, but use the working tree2706 * or "--contents".2707 */2708setup_work_tree();2709 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2710 path, contents_from);2711add_pending_object(&revs, &(sb.final->object),":");2712}2713else if(contents_from)2714die("Cannot use --contents with final commit object name");27152716if(reverse && revs.first_parent_only) {2717 final_commit =find_single_final(sb.revs, NULL);2718if(!final_commit)2719die("--reverse and --first-parent together require specified latest commit");2720}27212722/*2723 * If we have bottom, this will mark the ancestors of the2724 * bottom commits we would reach while traversing as2725 * uninteresting.2726 */2727if(prepare_revision_walk(&revs))2728die(_("revision walk setup failed"));27292730if(reverse && revs.first_parent_only) {2731struct commit *c = final_commit;27322733 sb.revs->children.name ="children";2734while(c->parents &&2735oidcmp(&c->object.oid, &sb.final->object.oid)) {2736struct commit_list *l =xcalloc(1,sizeof(*l));27372738 l->item = c;2739if(add_decoration(&sb.revs->children,2740&c->parents->item->object, l))2741die("BUG: not unique item in first-parent chain");2742 c = c->parents->item;2743}27442745if(oidcmp(&c->object.oid, &sb.final->object.oid))2746die("--reverse --first-parent together require range along first-parent chain");2747}27482749if(is_null_oid(&sb.final->object.oid)) {2750 o = sb.final->util;2751 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2752 sb.final_buf_size = o->file.size;2753}2754else{2755 o =get_origin(&sb, sb.final, path);2756if(fill_blob_sha1_and_mode(o))2757die("no such path%sin%s", path, final_commit_name);27582759if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2760textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2761&sb.final_buf_size))2762;2763else2764 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2765&sb.final_buf_size);27662767if(!sb.final_buf)2768die("Cannot read blob%sfor path%s",2769sha1_to_hex(o->blob_sha1),2770 path);2771}2772 num_read_blob++;2773 lno =prepare_lines(&sb);27742775if(lno && !range_list.nr)2776string_list_append(&range_list,xstrdup("1"));27772778 anchor =1;2779range_set_init(&ranges, range_list.nr);2780for(range_i =0; range_i < range_list.nr; ++range_i) {2781long bottom, top;2782if(parse_range_arg(range_list.items[range_i].string,2783 nth_line_cb, &sb, lno, anchor,2784&bottom, &top, sb.path))2785usage(blame_usage);2786if(lno < top || ((lno || bottom) && lno < bottom))2787die("file%shas only%lu lines", path, lno);2788if(bottom <1)2789 bottom =1;2790if(top <1)2791 top = lno;2792 bottom--;2793range_set_append_unsafe(&ranges, bottom, top);2794 anchor = top +1;2795}2796sort_and_merge_range_set(&ranges);27972798for(range_i = ranges.nr; range_i >0; --range_i) {2799const struct range *r = &ranges.ranges[range_i -1];2800long bottom = r->start;2801long top = r->end;2802struct blame_entry *next = ent;2803 ent =xcalloc(1,sizeof(*ent));2804 ent->lno = bottom;2805 ent->num_lines = top - bottom;2806 ent->suspect = o;2807 ent->s_lno = bottom;2808 ent->next = next;2809origin_incref(o);2810}28112812 o->suspects = ent;2813prio_queue_put(&sb.commits, o->commit);28142815origin_decref(o);28162817range_set_release(&ranges);2818string_list_clear(&range_list,0);28192820 sb.ent = NULL;2821 sb.path = path;28222823read_mailmap(&mailmap, NULL);28242825if(!incremental)2826setup_pager();28272828assign_blame(&sb, opt);28292830free(final_commit_name);28312832if(incremental)2833return0;28342835 sb.ent =blame_sort(sb.ent, compare_blame_final);28362837coalesce(&sb);28382839if(!(output_option & OUTPUT_PORCELAIN))2840find_alignment(&sb, &output_option);28412842output(&sb, output_option);2843free((void*)sb.final_buf);2844for(ent = sb.ent; ent; ) {2845struct blame_entry *e = ent->next;2846free(ent);2847 ent = e;2848}28492850if(show_stats) {2851printf("num read blob:%d\n", num_read_blob);2852printf("num get patch:%d\n", num_get_patch);2853printf("num commits:%d\n", num_commits);2854}2855return0;2856}