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"builtin.h" 10#include"blob.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 31static char blame_usage[] =N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>"); 32 33static const char*blame_opt_usage[] = { 34 blame_usage, 35"", 36N_("<rev-opts> are documented in git-rev-list(1)"), 37 NULL 38}; 39 40static int longest_file; 41static int longest_author; 42static int max_orig_digits; 43static int max_digits; 44static int max_score_digits; 45static int show_root; 46static int reverse; 47static int blank_boundary; 48static int incremental; 49static int xdl_opts; 50static int abbrev = -1; 51static int no_whole_file_rename; 52 53static enum date_mode blame_date_mode = DATE_ISO8601; 54static size_t blame_date_width; 55 56static struct string_list mailmap; 57 58#ifndef DEBUG 59#define DEBUG 0 60#endif 61 62/* stats */ 63static int num_read_blob; 64static int num_get_patch; 65static int num_commits; 66 67#define PICKAXE_BLAME_MOVE 01 68#define PICKAXE_BLAME_COPY 02 69#define PICKAXE_BLAME_COPY_HARDER 04 70#define PICKAXE_BLAME_COPY_HARDEST 010 71 72/* 73 * blame for a blame_entry with score lower than these thresholds 74 * is not passed to the parent using move/copy logic. 75 */ 76static unsigned blame_move_score; 77static unsigned blame_copy_score; 78#define BLAME_DEFAULT_MOVE_SCORE 20 79#define BLAME_DEFAULT_COPY_SCORE 40 80 81/* Remember to update object flag allocation in object.h */ 82#define METAINFO_SHOWN (1u<<12) 83#define MORE_THAN_ONE_PATH (1u<<13) 84 85/* 86 * One blob in a commit that is being suspected 87 */ 88struct origin { 89int refcnt; 90/* Record preceding blame record for this blob */ 91struct origin *previous; 92/* origins are put in a list linked via `next' hanging off the 93 * corresponding commit's util field in order to make finding 94 * them fast. The presence in this chain does not count 95 * towards the origin's reference count. It is tempting to 96 * let it count as long as the commit is pending examination, 97 * but even under circumstances where the commit will be 98 * present multiple times in the priority queue of unexamined 99 * commits, processing the first instance will not leave any 100 * work requiring the origin data for the second instance. An 101 * interspersed commit changing that would have to be 102 * preexisting with a different ancestry and with the same 103 * commit date in order to wedge itself between two instances 104 * of the same commit in the priority queue _and_ produce 105 * blame entries relevant for it. While we don't want to let 106 * us get tripped up by this case, it certainly does not seem 107 * worth optimizing for. 108 */ 109struct origin *next; 110struct commit *commit; 111/* `suspects' contains blame entries that may be attributed to 112 * this origin's commit or to parent commits. When a commit 113 * is being processed, all suspects will be moved, either by 114 * assigning them to an origin in a different commit, or by 115 * shipping them to the scoreboard's ent list because they 116 * cannot be attributed to a different commit. 117 */ 118struct blame_entry *suspects; 119 mmfile_t file; 120unsigned char blob_sha1[20]; 121unsigned mode; 122/* guilty gets set when shipping any suspects to the final 123 * blame list instead of other commits 124 */ 125char guilty; 126char path[FLEX_ARRAY]; 127}; 128 129static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b,long ctxlen, 130 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data) 131{ 132 xpparam_t xpp = {0}; 133 xdemitconf_t xecfg = {0}; 134 xdemitcb_t ecb = {NULL}; 135 136 xpp.flags = xdl_opts; 137 xecfg.ctxlen = ctxlen; 138 xecfg.hunk_func = hunk_func; 139 ecb.priv = cb_data; 140returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 141} 142 143/* 144 * Prepare diff_filespec and convert it using diff textconv API 145 * if the textconv driver exists. 146 * Return 1 if the conversion succeeds, 0 otherwise. 147 */ 148inttextconv_object(const char*path, 149unsigned mode, 150const unsigned char*sha1, 151int sha1_valid, 152char**buf, 153unsigned long*buf_size) 154{ 155struct diff_filespec *df; 156struct userdiff_driver *textconv; 157 158 df =alloc_filespec(path); 159fill_filespec(df, sha1, sha1_valid, mode); 160 textconv =get_textconv(df); 161if(!textconv) { 162free_filespec(df); 163return0; 164} 165 166*buf_size =fill_textconv(textconv, df, buf); 167free_filespec(df); 168return1; 169} 170 171/* 172 * Given an origin, prepare mmfile_t structure to be used by the 173 * diff machinery 174 */ 175static voidfill_origin_blob(struct diff_options *opt, 176struct origin *o, mmfile_t *file) 177{ 178if(!o->file.ptr) { 179enum object_type type; 180unsigned long file_size; 181 182 num_read_blob++; 183if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 184textconv_object(o->path, o->mode, o->blob_sha1,1, &file->ptr, &file_size)) 185; 186else 187 file->ptr =read_sha1_file(o->blob_sha1, &type, &file_size); 188 file->size = file_size; 189 190if(!file->ptr) 191die("Cannot read blob%sfor path%s", 192sha1_to_hex(o->blob_sha1), 193 o->path); 194 o->file = *file; 195} 196else 197*file = o->file; 198} 199 200/* 201 * Origin is refcounted and usually we keep the blob contents to be 202 * reused. 203 */ 204staticinlinestruct origin *origin_incref(struct origin *o) 205{ 206if(o) 207 o->refcnt++; 208return o; 209} 210 211static voidorigin_decref(struct origin *o) 212{ 213if(o && --o->refcnt <=0) { 214struct origin *p, *l = NULL; 215if(o->previous) 216origin_decref(o->previous); 217free(o->file.ptr); 218/* Should be present exactly once in commit chain */ 219for(p = o->commit->util; p; l = p, p = p->next) { 220if(p == o) { 221if(l) 222 l->next = p->next; 223else 224 o->commit->util = p->next; 225free(o); 226return; 227} 228} 229die("internal error in blame::origin_decref"); 230} 231} 232 233static voiddrop_origin_blob(struct origin *o) 234{ 235if(o->file.ptr) { 236free(o->file.ptr); 237 o->file.ptr = NULL; 238} 239} 240 241/* 242 * Each group of lines is described by a blame_entry; it can be split 243 * as we pass blame to the parents. They are arranged in linked lists 244 * kept as `suspects' of some unprocessed origin, or entered (when the 245 * blame origin has been finalized) into the scoreboard structure. 246 * While the scoreboard structure is only sorted at the end of 247 * processing (according to final image line number), the lists 248 * attached to an origin are sorted by the target line number. 249 */ 250struct blame_entry { 251struct blame_entry *next; 252 253/* the first line of this group in the final image; 254 * internally all line numbers are 0 based. 255 */ 256int lno; 257 258/* how many lines this group has */ 259int num_lines; 260 261/* the commit that introduced this group into the final image */ 262struct origin *suspect; 263 264/* the line number of the first line of this group in the 265 * suspect's file; internally all line numbers are 0 based. 266 */ 267int s_lno; 268 269/* how significant this entry is -- cached to avoid 270 * scanning the lines over and over. 271 */ 272unsigned score; 273}; 274 275/* 276 * Any merge of blames happens on lists of blames that arrived via 277 * different parents in a single suspect. In this case, we want to 278 * sort according to the suspect line numbers as opposed to the final 279 * image line numbers. The function body is somewhat longish because 280 * it avoids unnecessary writes. 281 */ 282 283static struct blame_entry *blame_merge(struct blame_entry *list1, 284struct blame_entry *list2) 285{ 286struct blame_entry *p1 = list1, *p2 = list2, 287**tail = &list1; 288 289if(!p1) 290return p2; 291if(!p2) 292return p1; 293 294if(p1->s_lno <= p2->s_lno) { 295do{ 296 tail = &p1->next; 297if((p1 = *tail) == NULL) { 298*tail = p2; 299return list1; 300} 301}while(p1->s_lno <= p2->s_lno); 302} 303for(;;) { 304*tail = p2; 305do{ 306 tail = &p2->next; 307if((p2 = *tail) == NULL) { 308*tail = p1; 309return list1; 310} 311}while(p1->s_lno > p2->s_lno); 312*tail = p1; 313do{ 314 tail = &p1->next; 315if((p1 = *tail) == NULL) { 316*tail = p2; 317return list1; 318} 319}while(p1->s_lno <= p2->s_lno); 320} 321} 322 323static void*get_next_blame(const void*p) 324{ 325return((struct blame_entry *)p)->next; 326} 327 328static voidset_next_blame(void*p1,void*p2) 329{ 330((struct blame_entry *)p1)->next = p2; 331} 332 333/* 334 * Final image line numbers are all different, so we don't need a 335 * three-way comparison here. 336 */ 337 338static intcompare_blame_final(const void*p1,const void*p2) 339{ 340return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 341?1: -1; 342} 343 344static intcompare_blame_suspect(const void*p1,const void*p2) 345{ 346const struct blame_entry *s1 = p1, *s2 = p2; 347/* 348 * to allow for collating suspects, we sort according to the 349 * respective pointer value as the primary sorting criterion. 350 * The actual relation is pretty unimportant as long as it 351 * establishes a total order. Comparing as integers gives us 352 * that. 353 */ 354if(s1->suspect != s2->suspect) 355return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 356if(s1->s_lno == s2->s_lno) 357return0; 358return s1->s_lno > s2->s_lno ?1: -1; 359} 360 361static struct blame_entry *blame_sort(struct blame_entry *head, 362int(*compare_fn)(const void*,const void*)) 363{ 364returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 365} 366 367static intcompare_commits_by_reverse_commit_date(const void*a, 368const void*b, 369void*c) 370{ 371return-compare_commits_by_commit_date(a, b, c); 372} 373 374/* 375 * The current state of the blame assignment. 376 */ 377struct scoreboard { 378/* the final commit (i.e. where we started digging from) */ 379struct commit *final; 380/* Priority queue for commits with unassigned blame records */ 381struct prio_queue commits; 382struct rev_info *revs; 383const char*path; 384 385/* 386 * The contents in the final image. 387 * Used by many functions to obtain contents of the nth line, 388 * indexed with scoreboard.lineno[blame_entry.lno]. 389 */ 390const char*final_buf; 391unsigned long final_buf_size; 392 393/* linked list of blames */ 394struct blame_entry *ent; 395 396/* look-up a line in the final buffer */ 397int num_lines; 398int*lineno; 399}; 400 401static voidsanity_check_refcnt(struct scoreboard *); 402 403/* 404 * If two blame entries that are next to each other came from 405 * contiguous lines in the same origin (i.e. <commit, path> pair), 406 * merge them together. 407 */ 408static voidcoalesce(struct scoreboard *sb) 409{ 410struct blame_entry *ent, *next; 411 412for(ent = sb->ent; ent && (next = ent->next); ent = next) { 413if(ent->suspect == next->suspect && 414 ent->s_lno + ent->num_lines == next->s_lno) { 415 ent->num_lines += next->num_lines; 416 ent->next = next->next; 417origin_decref(next->suspect); 418free(next); 419 ent->score =0; 420 next = ent;/* again */ 421} 422} 423 424if(DEBUG)/* sanity */ 425sanity_check_refcnt(sb); 426} 427 428/* 429 * Merge the given sorted list of blames into a preexisting origin. 430 * If there were no previous blames to that commit, it is entered into 431 * the commit priority queue of the score board. 432 */ 433 434static voidqueue_blames(struct scoreboard *sb,struct origin *porigin, 435struct blame_entry *sorted) 436{ 437if(porigin->suspects) 438 porigin->suspects =blame_merge(porigin->suspects, sorted); 439else{ 440struct origin *o; 441for(o = porigin->commit->util; o; o = o->next) { 442if(o->suspects) { 443 porigin->suspects = sorted; 444return; 445} 446} 447 porigin->suspects = sorted; 448prio_queue_put(&sb->commits, porigin->commit); 449} 450} 451 452/* 453 * Given a commit and a path in it, create a new origin structure. 454 * The callers that add blame to the scoreboard should use 455 * get_origin() to obtain shared, refcounted copy instead of calling 456 * this function directly. 457 */ 458static struct origin *make_origin(struct commit *commit,const char*path) 459{ 460struct origin *o; 461 o =xcalloc(1,sizeof(*o) +strlen(path) +1); 462 o->commit = commit; 463 o->refcnt =1; 464 o->next = commit->util; 465 commit->util = o; 466strcpy(o->path, path); 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.sha1, 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_sha1(origin->commit->object.sha1)) 559do_diff_cache(parent->tree->object.sha1, &diff_opts); 560else 561diff_tree_sha1(parent->tree->object.sha1, 562 origin->commit->tree->object.sha1, 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_sha1(origin->commit->object.sha1)) 629do_diff_cache(parent->tree->object.sha1, &diff_opts); 630else 631diff_tree_sha1(parent->tree->object.sha1, 632 origin->commit->tree->object.sha1, 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 976diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d); 977/* The rest are the same as the parent */ 978blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 979*d.dstq = NULL; 980queue_blames(sb, parent, newdest); 981 982return; 983} 984 985/* 986 * The lines in blame_entry after splitting blames many times can become 987 * very small and trivial, and at some point it becomes pointless to 988 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 989 * ordinary C program, and it is not worth to say it was copied from 990 * totally unrelated file in the parent. 991 * 992 * Compute how trivial the lines in the blame_entry are. 993 */ 994static unsignedent_score(struct scoreboard *sb,struct blame_entry *e) 995{ 996unsigned score; 997const char*cp, *ep; 998 999if(e->score)1000return e->score;10011002 score =1;1003 cp =nth_line(sb, e->lno);1004 ep =nth_line(sb, e->lno + e->num_lines);1005while(cp < ep) {1006unsigned ch = *((unsigned char*)cp);1007if(isalnum(ch))1008 score++;1009 cp++;1010}1011 e->score = score;1012return score;1013}10141015/*1016 * best_so_far[] and this[] are both a split of an existing blame_entry1017 * that passes blame to the parent. Maintain best_so_far the best split1018 * so far, by comparing this and best_so_far and copying this into1019 * bst_so_far as needed.1020 */1021static voidcopy_split_if_better(struct scoreboard *sb,1022struct blame_entry *best_so_far,1023struct blame_entry *this)1024{1025int i;10261027if(!this[1].suspect)1028return;1029if(best_so_far[1].suspect) {1030if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1031return;1032}10331034for(i =0; i <3; i++)1035origin_incref(this[i].suspect);1036decref_split(best_so_far);1037memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1038}10391040/*1041 * We are looking at a part of the final image represented by1042 * ent (tlno and same are offset by ent->s_lno).1043 * tlno is where we are looking at in the final image.1044 * up to (but not including) same match preimage.1045 * plno is where we are looking at in the preimage.1046 *1047 * <-------------- final image ---------------------->1048 * <------ent------>1049 * ^tlno ^same1050 * <---------preimage----->1051 * ^plno1052 *1053 * All line numbers are 0-based.1054 */1055static voidhandle_split(struct scoreboard *sb,1056struct blame_entry *ent,1057int tlno,int plno,int same,1058struct origin *parent,1059struct blame_entry *split)1060{1061if(ent->num_lines <= tlno)1062return;1063if(tlno < same) {1064struct blame_entry this[3];1065 tlno += ent->s_lno;1066 same += ent->s_lno;1067split_overlap(this, ent, tlno, plno, same, parent);1068copy_split_if_better(sb, split,this);1069decref_split(this);1070}1071}10721073struct handle_split_cb_data {1074struct scoreboard *sb;1075struct blame_entry *ent;1076struct origin *parent;1077struct blame_entry *split;1078long plno;1079long tlno;1080};10811082static inthandle_split_cb(long start_a,long count_a,1083long start_b,long count_b,void*data)1084{1085struct handle_split_cb_data *d = data;1086handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1087 d->split);1088 d->plno = start_a + count_a;1089 d->tlno = start_b + count_b;1090return0;1091}10921093/*1094 * Find the lines from parent that are the same as ent so that1095 * we can pass blames to it. file_p has the blob contents for1096 * the parent.1097 */1098static voidfind_copy_in_blob(struct scoreboard *sb,1099struct blame_entry *ent,1100struct origin *parent,1101struct blame_entry *split,1102 mmfile_t *file_p)1103{1104const char*cp;1105 mmfile_t file_o;1106struct handle_split_cb_data d;11071108memset(&d,0,sizeof(d));1109 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1110/*1111 * Prepare mmfile that contains only the lines in ent.1112 */1113 cp =nth_line(sb, ent->lno);1114 file_o.ptr = (char*) cp;1115 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11161117/*1118 * file_o is a part of final image we are annotating.1119 * file_p partially may match that image.1120 */1121memset(split,0,sizeof(struct blame_entry [3]));1122diff_hunks(file_p, &file_o,1, handle_split_cb, &d);1123/* remainder, if any, all match the preimage */1124handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1125}11261127/* Move all blame entries from list *source that have a score smaller1128 * than score_min to the front of list *small.1129 * Returns a pointer to the link pointing to the old head of the small list.1130 */11311132static struct blame_entry **filter_small(struct scoreboard *sb,1133struct blame_entry **small,1134struct blame_entry **source,1135unsigned score_min)1136{1137struct blame_entry *p = *source;1138struct blame_entry *oldsmall = *small;1139while(p) {1140if(ent_score(sb, p) <= score_min) {1141*small = p;1142 small = &p->next;1143 p = *small;1144}else{1145*source = p;1146 source = &p->next;1147 p = *source;1148}1149}1150*small = oldsmall;1151*source = NULL;1152return small;1153}11541155/*1156 * See if lines currently target is suspected for can be attributed to1157 * parent.1158 */1159static voidfind_move_in_parent(struct scoreboard *sb,1160struct blame_entry ***blamed,1161struct blame_entry **toosmall,1162struct origin *target,1163struct origin *parent)1164{1165struct blame_entry *e, split[3];1166struct blame_entry *unblamed = target->suspects;1167struct blame_entry *leftover = NULL;1168 mmfile_t file_p;11691170if(!unblamed)1171return;/* nothing remains for this target */11721173fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1174if(!file_p.ptr)1175return;11761177/* At each iteration, unblamed has a NULL-terminated list of1178 * entries that have not yet been tested for blame. leftover1179 * contains the reversed list of entries that have been tested1180 * without being assignable to the parent.1181 */1182do{1183struct blame_entry **unblamedtail = &unblamed;1184struct blame_entry *next;1185for(e = unblamed; e; e = next) {1186 next = e->next;1187find_copy_in_blob(sb, e, parent, split, &file_p);1188if(split[1].suspect &&1189 blame_move_score <ent_score(sb, &split[1])) {1190split_blame(blamed, &unblamedtail, split, e);1191}else{1192 e->next = leftover;1193 leftover = e;1194}1195decref_split(split);1196}1197*unblamedtail = NULL;1198 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1199}while(unblamed);1200 target->suspects =reverse_blame(leftover, NULL);1201}12021203struct blame_list {1204struct blame_entry *ent;1205struct blame_entry split[3];1206};12071208/*1209 * Count the number of entries the target is suspected for,1210 * and prepare a list of entry and the best split.1211 */1212static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1213int*num_ents_p)1214{1215struct blame_entry *e;1216int num_ents, i;1217struct blame_list *blame_list = NULL;12181219for(e = unblamed, num_ents =0; e; e = e->next)1220 num_ents++;1221if(num_ents) {1222 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1223for(e = unblamed, i =0; e; e = e->next)1224 blame_list[i++].ent = e;1225}1226*num_ents_p = num_ents;1227return blame_list;1228}12291230/*1231 * For lines target is suspected for, see if we can find code movement1232 * across file boundary from the parent commit. porigin is the path1233 * in the parent we already tried.1234 */1235static voidfind_copy_in_parent(struct scoreboard *sb,1236struct blame_entry ***blamed,1237struct blame_entry **toosmall,1238struct origin *target,1239struct commit *parent,1240struct origin *porigin,1241int opt)1242{1243struct diff_options diff_opts;1244int i, j;1245struct blame_list *blame_list;1246int num_ents;1247struct blame_entry *unblamed = target->suspects;1248struct blame_entry *leftover = NULL;12491250if(!unblamed)1251return;/* nothing remains for this target */12521253diff_setup(&diff_opts);1254DIFF_OPT_SET(&diff_opts, RECURSIVE);1255 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12561257diff_setup_done(&diff_opts);12581259/* Try "find copies harder" on new path if requested;1260 * we do not want to use diffcore_rename() actually to1261 * match things up; find_copies_harder is set only to1262 * force diff_tree_sha1() to feed all filepairs to diff_queue,1263 * and this code needs to be after diff_setup_done(), which1264 * usually makes find-copies-harder imply copy detection.1265 */1266if((opt & PICKAXE_BLAME_COPY_HARDEST)1267|| ((opt & PICKAXE_BLAME_COPY_HARDER)1268&& (!porigin ||strcmp(target->path, porigin->path))))1269DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12701271if(is_null_sha1(target->commit->object.sha1))1272do_diff_cache(parent->tree->object.sha1, &diff_opts);1273else1274diff_tree_sha1(parent->tree->object.sha1,1275 target->commit->tree->object.sha1,1276"", &diff_opts);12771278if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1279diffcore_std(&diff_opts);12801281do{1282struct blame_entry **unblamedtail = &unblamed;1283 blame_list =setup_blame_list(unblamed, &num_ents);12841285for(i =0; i < diff_queued_diff.nr; i++) {1286struct diff_filepair *p = diff_queued_diff.queue[i];1287struct origin *norigin;1288 mmfile_t file_p;1289struct blame_entry this[3];12901291if(!DIFF_FILE_VALID(p->one))1292continue;/* does not exist in parent */1293if(S_ISGITLINK(p->one->mode))1294continue;/* ignore git links */1295if(porigin && !strcmp(p->one->path, porigin->path))1296/* find_move already dealt with this path */1297continue;12981299 norigin =get_origin(sb, parent, p->one->path);1300hashcpy(norigin->blob_sha1, p->one->sha1);1301 norigin->mode = p->one->mode;1302fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1303if(!file_p.ptr)1304continue;13051306for(j =0; j < num_ents; j++) {1307find_copy_in_blob(sb, blame_list[j].ent,1308 norigin,this, &file_p);1309copy_split_if_better(sb, blame_list[j].split,1310this);1311decref_split(this);1312}1313origin_decref(norigin);1314}13151316for(j =0; j < num_ents; j++) {1317struct blame_entry *split = blame_list[j].split;1318if(split[1].suspect &&1319 blame_copy_score <ent_score(sb, &split[1])) {1320split_blame(blamed, &unblamedtail, split,1321 blame_list[j].ent);1322}else{1323 blame_list[j].ent->next = leftover;1324 leftover = blame_list[j].ent;1325}1326decref_split(split);1327}1328free(blame_list);1329*unblamedtail = NULL;1330 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1331}while(unblamed);1332 target->suspects =reverse_blame(leftover, NULL);1333diff_flush(&diff_opts);1334free_pathspec(&diff_opts.pathspec);1335}13361337/*1338 * The blobs of origin and porigin exactly match, so everything1339 * origin is suspected for can be blamed on the parent.1340 */1341static voidpass_whole_blame(struct scoreboard *sb,1342struct origin *origin,struct origin *porigin)1343{1344struct blame_entry *e, *suspects;13451346if(!porigin->file.ptr && origin->file.ptr) {1347/* Steal its file */1348 porigin->file = origin->file;1349 origin->file.ptr = NULL;1350}1351 suspects = origin->suspects;1352 origin->suspects = NULL;1353for(e = suspects; e; e = e->next) {1354origin_incref(porigin);1355origin_decref(e->suspect);1356 e->suspect = porigin;1357}1358queue_blames(sb, porigin, suspects);1359}13601361/*1362 * We pass blame from the current commit to its parents. We keep saying1363 * "parent" (and "porigin"), but what we mean is to find scapegoat to1364 * exonerate ourselves.1365 */1366static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1367{1368if(!reverse)1369return commit->parents;1370returnlookup_decoration(&revs->children, &commit->object);1371}13721373static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1374{1375struct commit_list *l =first_scapegoat(revs, commit);1376returncommit_list_count(l);1377}13781379/* Distribute collected unsorted blames to the respected sorted lists1380 * in the various origins.1381 */1382static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1383{1384 blamed =blame_sort(blamed, compare_blame_suspect);1385while(blamed)1386{1387struct origin *porigin = blamed->suspect;1388struct blame_entry *suspects = NULL;1389do{1390struct blame_entry *next = blamed->next;1391 blamed->next = suspects;1392 suspects = blamed;1393 blamed = next;1394}while(blamed && blamed->suspect == porigin);1395 suspects =reverse_blame(suspects, NULL);1396queue_blames(sb, porigin, suspects);1397}1398}13991400#define MAXSG 1614011402static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1403{1404struct rev_info *revs = sb->revs;1405int i, pass, num_sg;1406struct commit *commit = origin->commit;1407struct commit_list *sg;1408struct origin *sg_buf[MAXSG];1409struct origin *porigin, **sg_origin = sg_buf;1410struct blame_entry *toosmall = NULL;1411struct blame_entry *blames, **blametail = &blames;14121413 num_sg =num_scapegoats(revs, commit);1414if(!num_sg)1415goto finish;1416else if(num_sg <ARRAY_SIZE(sg_buf))1417memset(sg_buf,0,sizeof(sg_buf));1418else1419 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14201421/*1422 * The first pass looks for unrenamed path to optimize for1423 * common cases, then we look for renames in the second pass.1424 */1425for(pass =0; pass <2- no_whole_file_rename; pass++) {1426struct origin *(*find)(struct scoreboard *,1427struct commit *,struct origin *);1428 find = pass ? find_rename : find_origin;14291430for(i =0, sg =first_scapegoat(revs, commit);1431 i < num_sg && sg;1432 sg = sg->next, i++) {1433struct commit *p = sg->item;1434int j, same;14351436if(sg_origin[i])1437continue;1438if(parse_commit(p))1439continue;1440 porigin =find(sb, p, origin);1441if(!porigin)1442continue;1443if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1444pass_whole_blame(sb, origin, porigin);1445origin_decref(porigin);1446goto finish;1447}1448for(j = same =0; j < i; j++)1449if(sg_origin[j] &&1450!hashcmp(sg_origin[j]->blob_sha1,1451 porigin->blob_sha1)) {1452 same =1;1453break;1454}1455if(!same)1456 sg_origin[i] = porigin;1457else1458origin_decref(porigin);1459}1460}14611462 num_commits++;1463for(i =0, sg =first_scapegoat(revs, commit);1464 i < num_sg && sg;1465 sg = sg->next, i++) {1466struct origin *porigin = sg_origin[i];1467if(!porigin)1468continue;1469if(!origin->previous) {1470origin_incref(porigin);1471 origin->previous = porigin;1472}1473pass_blame_to_parent(sb, origin, porigin);1474if(!origin->suspects)1475goto finish;1476}14771478/*1479 * Optionally find moves in parents' files.1480 */1481if(opt & PICKAXE_BLAME_MOVE) {1482filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1483if(origin->suspects) {1484for(i =0, sg =first_scapegoat(revs, commit);1485 i < num_sg && sg;1486 sg = sg->next, i++) {1487struct origin *porigin = sg_origin[i];1488if(!porigin)1489continue;1490find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1491if(!origin->suspects)1492break;1493}1494}1495}14961497/*1498 * Optionally find copies from parents' files.1499 */1500if(opt & PICKAXE_BLAME_COPY) {1501if(blame_copy_score > blame_move_score)1502filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1503else if(blame_copy_score < blame_move_score) {1504 origin->suspects =blame_merge(origin->suspects, toosmall);1505 toosmall = NULL;1506filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1507}1508if(!origin->suspects)1509goto finish;15101511for(i =0, sg =first_scapegoat(revs, commit);1512 i < num_sg && sg;1513 sg = sg->next, i++) {1514struct origin *porigin = sg_origin[i];1515find_copy_in_parent(sb, &blametail, &toosmall,1516 origin, sg->item, porigin, opt);1517if(!origin->suspects)1518goto finish;1519}1520}15211522finish:1523*blametail = NULL;1524distribute_blame(sb, blames);1525/*1526 * prepend toosmall to origin->suspects1527 *1528 * There is no point in sorting: this ends up on a big1529 * unsorted list in the caller anyway.1530 */1531if(toosmall) {1532struct blame_entry **tail = &toosmall;1533while(*tail)1534 tail = &(*tail)->next;1535*tail = origin->suspects;1536 origin->suspects = toosmall;1537}1538for(i =0; i < num_sg; i++) {1539if(sg_origin[i]) {1540drop_origin_blob(sg_origin[i]);1541origin_decref(sg_origin[i]);1542}1543}1544drop_origin_blob(origin);1545if(sg_buf != sg_origin)1546free(sg_origin);1547}15481549/*1550 * Information on commits, used for output.1551 */1552struct commit_info {1553struct strbuf author;1554struct strbuf author_mail;1555unsigned long author_time;1556struct strbuf author_tz;15571558/* filled only when asked for details */1559struct strbuf committer;1560struct strbuf committer_mail;1561unsigned long committer_time;1562struct strbuf committer_tz;15631564struct strbuf summary;1565};15661567/*1568 * Parse author/committer line in the commit object buffer1569 */1570static voidget_ac_line(const char*inbuf,const char*what,1571struct strbuf *name,struct strbuf *mail,1572unsigned long*time,struct strbuf *tz)1573{1574struct ident_split ident;1575size_t len, maillen, namelen;1576char*tmp, *endp;1577const char*namebuf, *mailbuf;15781579 tmp =strstr(inbuf, what);1580if(!tmp)1581goto error_out;1582 tmp +=strlen(what);1583 endp =strchr(tmp,'\n');1584if(!endp)1585 len =strlen(tmp);1586else1587 len = endp - tmp;15881589if(split_ident_line(&ident, tmp, len)) {1590 error_out:1591/* Ugh */1592 tmp ="(unknown)";1593strbuf_addstr(name, tmp);1594strbuf_addstr(mail, tmp);1595strbuf_addstr(tz, tmp);1596*time =0;1597return;1598}15991600 namelen = ident.name_end - ident.name_begin;1601 namebuf = ident.name_begin;16021603 maillen = ident.mail_end - ident.mail_begin;1604 mailbuf = ident.mail_begin;16051606if(ident.date_begin && ident.date_end)1607*time =strtoul(ident.date_begin, NULL,10);1608else1609*time =0;16101611if(ident.tz_begin && ident.tz_end)1612strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1613else1614strbuf_addstr(tz,"(unknown)");16151616/*1617 * Now, convert both name and e-mail using mailmap1618 */1619map_user(&mailmap, &mailbuf, &maillen,1620&namebuf, &namelen);16211622strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1623strbuf_add(name, namebuf, namelen);1624}16251626static voidcommit_info_init(struct commit_info *ci)1627{16281629strbuf_init(&ci->author,0);1630strbuf_init(&ci->author_mail,0);1631strbuf_init(&ci->author_tz,0);1632strbuf_init(&ci->committer,0);1633strbuf_init(&ci->committer_mail,0);1634strbuf_init(&ci->committer_tz,0);1635strbuf_init(&ci->summary,0);1636}16371638static voidcommit_info_destroy(struct commit_info *ci)1639{16401641strbuf_release(&ci->author);1642strbuf_release(&ci->author_mail);1643strbuf_release(&ci->author_tz);1644strbuf_release(&ci->committer);1645strbuf_release(&ci->committer_mail);1646strbuf_release(&ci->committer_tz);1647strbuf_release(&ci->summary);1648}16491650static voidget_commit_info(struct commit *commit,1651struct commit_info *ret,1652int detailed)1653{1654int len;1655const char*subject, *encoding;1656const char*message;16571658commit_info_init(ret);16591660 encoding =get_log_output_encoding();1661 message =logmsg_reencode(commit, NULL, encoding);1662get_ac_line(message,"\nauthor ",1663&ret->author, &ret->author_mail,1664&ret->author_time, &ret->author_tz);16651666if(!detailed) {1667unuse_commit_buffer(commit, message);1668return;1669}16701671get_ac_line(message,"\ncommitter ",1672&ret->committer, &ret->committer_mail,1673&ret->committer_time, &ret->committer_tz);16741675 len =find_commit_subject(message, &subject);1676if(len)1677strbuf_add(&ret->summary, subject, len);1678else1679strbuf_addf(&ret->summary,"(%s)",sha1_to_hex(commit->object.sha1));16801681unuse_commit_buffer(commit, message);1682}16831684/*1685 * To allow LF and other nonportable characters in pathnames,1686 * they are c-style quoted as needed.1687 */1688static voidwrite_filename_info(const char*path)1689{1690printf("filename ");1691write_name_quoted(path, stdout,'\n');1692}16931694/*1695 * Porcelain/Incremental format wants to show a lot of details per1696 * commit. Instead of repeating this every line, emit it only once,1697 * the first time each commit appears in the output (unless the1698 * user has specifically asked for us to repeat).1699 */1700static intemit_one_suspect_detail(struct origin *suspect,int repeat)1701{1702struct commit_info ci;17031704if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1705return0;17061707 suspect->commit->object.flags |= METAINFO_SHOWN;1708get_commit_info(suspect->commit, &ci,1);1709printf("author%s\n", ci.author.buf);1710printf("author-mail%s\n", ci.author_mail.buf);1711printf("author-time%lu\n", ci.author_time);1712printf("author-tz%s\n", ci.author_tz.buf);1713printf("committer%s\n", ci.committer.buf);1714printf("committer-mail%s\n", ci.committer_mail.buf);1715printf("committer-time%lu\n", ci.committer_time);1716printf("committer-tz%s\n", ci.committer_tz.buf);1717printf("summary%s\n", ci.summary.buf);1718if(suspect->commit->object.flags & UNINTERESTING)1719printf("boundary\n");1720if(suspect->previous) {1721struct origin *prev = suspect->previous;1722printf("previous%s",sha1_to_hex(prev->commit->object.sha1));1723write_name_quoted(prev->path, stdout,'\n');1724}17251726commit_info_destroy(&ci);17271728return1;1729}17301731/*1732 * The blame_entry is found to be guilty for the range.1733 * Show it in incremental output.1734 */1735static voidfound_guilty_entry(struct blame_entry *ent)1736{1737if(incremental) {1738struct origin *suspect = ent->suspect;17391740printf("%s %d %d %d\n",1741sha1_to_hex(suspect->commit->object.sha1),1742 ent->s_lno +1, ent->lno +1, ent->num_lines);1743emit_one_suspect_detail(suspect,0);1744write_filename_info(suspect->path);1745maybe_flush_or_die(stdout,"stdout");1746}1747}17481749/*1750 * The main loop -- while we have blobs with lines whose true origin1751 * is still unknown, pick one blob, and allow its lines to pass blames1752 * to its parents. */1753static voidassign_blame(struct scoreboard *sb,int opt)1754{1755struct rev_info *revs = sb->revs;1756struct commit *commit =prio_queue_get(&sb->commits);17571758while(commit) {1759struct blame_entry *ent;1760struct origin *suspect = commit->util;17611762/* find one suspect to break down */1763while(suspect && !suspect->suspects)1764 suspect = suspect->next;17651766if(!suspect) {1767 commit =prio_queue_get(&sb->commits);1768continue;1769}17701771assert(commit == suspect->commit);17721773/*1774 * We will use this suspect later in the loop,1775 * so hold onto it in the meantime.1776 */1777origin_incref(suspect);1778parse_commit(commit);1779if(reverse ||1780(!(commit->object.flags & UNINTERESTING) &&1781!(revs->max_age != -1&& commit->date < revs->max_age)))1782pass_blame(sb, suspect, opt);1783else{1784 commit->object.flags |= UNINTERESTING;1785if(commit->object.parsed)1786mark_parents_uninteresting(commit);1787}1788/* treat root commit as boundary */1789if(!commit->parents && !show_root)1790 commit->object.flags |= UNINTERESTING;17911792/* Take responsibility for the remaining entries */1793 ent = suspect->suspects;1794if(ent) {1795 suspect->guilty =1;1796for(;;) {1797struct blame_entry *next = ent->next;1798found_guilty_entry(ent);1799if(next) {1800 ent = next;1801continue;1802}1803 ent->next = sb->ent;1804 sb->ent = suspect->suspects;1805 suspect->suspects = NULL;1806break;1807}1808}1809origin_decref(suspect);18101811if(DEBUG)/* sanity */1812sanity_check_refcnt(sb);1813}1814}18151816static const char*format_time(unsigned long time,const char*tz_str,1817int show_raw_time)1818{1819static struct strbuf time_buf = STRBUF_INIT;18201821strbuf_reset(&time_buf);1822if(show_raw_time) {1823strbuf_addf(&time_buf,"%lu%s", time, tz_str);1824}1825else{1826const char*time_str;1827size_t time_width;1828int tz;1829 tz =atoi(tz_str);1830 time_str =show_date(time, tz, blame_date_mode);1831strbuf_addstr(&time_buf, time_str);1832/*1833 * Add space paddings to time_buf to display a fixed width1834 * string, and use time_width for display width calibration.1835 */1836for(time_width =utf8_strwidth(time_str);1837 time_width < blame_date_width;1838 time_width++)1839strbuf_addch(&time_buf,' ');1840}1841return time_buf.buf;1842}18431844#define OUTPUT_ANNOTATE_COMPAT 0011845#define OUTPUT_LONG_OBJECT_NAME 0021846#define OUTPUT_RAW_TIMESTAMP 0041847#define OUTPUT_PORCELAIN 0101848#define OUTPUT_SHOW_NAME 0201849#define OUTPUT_SHOW_NUMBER 0401850#define OUTPUT_SHOW_SCORE 01001851#define OUTPUT_NO_AUTHOR 02001852#define OUTPUT_SHOW_EMAIL 04001853#define OUTPUT_LINE_PORCELAIN 0100018541855static voidemit_porcelain_details(struct origin *suspect,int repeat)1856{1857if(emit_one_suspect_detail(suspect, repeat) ||1858(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1859write_filename_info(suspect->path);1860}18611862static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1863int opt)1864{1865int repeat = opt & OUTPUT_LINE_PORCELAIN;1866int cnt;1867const char*cp;1868struct origin *suspect = ent->suspect;1869char hex[41];18701871strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));1872printf("%s %d %d %d\n",1873 hex,1874 ent->s_lno +1,1875 ent->lno +1,1876 ent->num_lines);1877emit_porcelain_details(suspect, repeat);18781879 cp =nth_line(sb, ent->lno);1880for(cnt =0; cnt < ent->num_lines; cnt++) {1881char ch;1882if(cnt) {1883printf("%s %d %d\n", hex,1884 ent->s_lno +1+ cnt,1885 ent->lno +1+ cnt);1886if(repeat)1887emit_porcelain_details(suspect,1);1888}1889putchar('\t');1890do{1891 ch = *cp++;1892putchar(ch);1893}while(ch !='\n'&&1894 cp < sb->final_buf + sb->final_buf_size);1895}18961897if(sb->final_buf_size && cp[-1] !='\n')1898putchar('\n');1899}19001901static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1902{1903int cnt;1904const char*cp;1905struct origin *suspect = ent->suspect;1906struct commit_info ci;1907char hex[41];1908int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19091910get_commit_info(suspect->commit, &ci,1);1911strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));19121913 cp =nth_line(sb, ent->lno);1914for(cnt =0; cnt < ent->num_lines; cnt++) {1915char ch;1916int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19171918if(suspect->commit->object.flags & UNINTERESTING) {1919if(blank_boundary)1920memset(hex,' ', length);1921else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1922 length--;1923putchar('^');1924}1925}19261927printf("%.*s", length, hex);1928if(opt & OUTPUT_ANNOTATE_COMPAT) {1929const char*name;1930if(opt & OUTPUT_SHOW_EMAIL)1931 name = ci.author_mail.buf;1932else1933 name = ci.author.buf;1934printf("\t(%10s\t%10s\t%d)", name,1935format_time(ci.author_time, ci.author_tz.buf,1936 show_raw_time),1937 ent->lno +1+ cnt);1938}else{1939if(opt & OUTPUT_SHOW_SCORE)1940printf(" %*d%02d",1941 max_score_digits, ent->score,1942 ent->suspect->refcnt);1943if(opt & OUTPUT_SHOW_NAME)1944printf(" %-*.*s", longest_file, longest_file,1945 suspect->path);1946if(opt & OUTPUT_SHOW_NUMBER)1947printf(" %*d", max_orig_digits,1948 ent->s_lno +1+ cnt);19491950if(!(opt & OUTPUT_NO_AUTHOR)) {1951const char*name;1952int pad;1953if(opt & OUTPUT_SHOW_EMAIL)1954 name = ci.author_mail.buf;1955else1956 name = ci.author.buf;1957 pad = longest_author -utf8_strwidth(name);1958printf(" (%s%*s%10s",1959 name, pad,"",1960format_time(ci.author_time,1961 ci.author_tz.buf,1962 show_raw_time));1963}1964printf(" %*d) ",1965 max_digits, ent->lno +1+ cnt);1966}1967do{1968 ch = *cp++;1969putchar(ch);1970}while(ch !='\n'&&1971 cp < sb->final_buf + sb->final_buf_size);1972}19731974if(sb->final_buf_size && cp[-1] !='\n')1975putchar('\n');19761977commit_info_destroy(&ci);1978}19791980static voidoutput(struct scoreboard *sb,int option)1981{1982struct blame_entry *ent;19831984if(option & OUTPUT_PORCELAIN) {1985for(ent = sb->ent; ent; ent = ent->next) {1986int count =0;1987struct origin *suspect;1988struct commit *commit = ent->suspect->commit;1989if(commit->object.flags & MORE_THAN_ONE_PATH)1990continue;1991for(suspect = commit->util; suspect; suspect = suspect->next) {1992if(suspect->guilty && count++) {1993 commit->object.flags |= MORE_THAN_ONE_PATH;1994break;1995}1996}1997}1998}19992000for(ent = sb->ent; ent; ent = ent->next) {2001if(option & OUTPUT_PORCELAIN)2002emit_porcelain(sb, ent, option);2003else{2004emit_other(sb, ent, option);2005}2006}2007}20082009static const char*get_next_line(const char*start,const char*end)2010{2011const char*nl =memchr(start,'\n', end - start);2012return nl ? nl +1: end;2013}20142015/*2016 * To allow quick access to the contents of nth line in the2017 * final image, prepare an index in the scoreboard.2018 */2019static intprepare_lines(struct scoreboard *sb)2020{2021const char*buf = sb->final_buf;2022unsigned long len = sb->final_buf_size;2023const char*end = buf + len;2024const char*p;2025int*lineno;2026int num =0;20272028for(p = buf; p < end; p =get_next_line(p, end))2029 num++;20302031 sb->lineno = lineno =xmalloc(sizeof(*sb->lineno) * (num +1));20322033for(p = buf; p < end; p =get_next_line(p, end))2034*lineno++ = p - buf;20352036*lineno = len;20372038 sb->num_lines = num;2039return sb->num_lines;2040}20412042/*2043 * Add phony grafts for use with -S; this is primarily to2044 * support git's cvsserver that wants to give a linear history2045 * to its clients.2046 */2047static intread_ancestry(const char*graft_file)2048{2049FILE*fp =fopen(graft_file,"r");2050struct strbuf buf = STRBUF_INIT;2051if(!fp)2052return-1;2053while(!strbuf_getwholeline(&buf, fp,'\n')) {2054/* The format is just "Commit Parent1 Parent2 ...\n" */2055struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2056if(graft)2057register_commit_graft(graft,0);2058}2059fclose(fp);2060strbuf_release(&buf);2061return0;2062}20632064static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2065{2066const char*uniq =find_unique_abbrev(suspect->commit->object.sha1,2067 auto_abbrev);2068int len =strlen(uniq);2069if(auto_abbrev < len)2070return len;2071return auto_abbrev;2072}20732074/*2075 * How many columns do we need to show line numbers, authors,2076 * and filenames?2077 */2078static voidfind_alignment(struct scoreboard *sb,int*option)2079{2080int longest_src_lines =0;2081int longest_dst_lines =0;2082unsigned largest_score =0;2083struct blame_entry *e;2084int compute_auto_abbrev = (abbrev <0);2085int auto_abbrev = default_abbrev;20862087for(e = sb->ent; e; e = e->next) {2088struct origin *suspect = e->suspect;2089int num;20902091if(compute_auto_abbrev)2092 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2093if(strcmp(suspect->path, sb->path))2094*option |= OUTPUT_SHOW_NAME;2095 num =strlen(suspect->path);2096if(longest_file < num)2097 longest_file = num;2098if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2099struct commit_info ci;2100 suspect->commit->object.flags |= METAINFO_SHOWN;2101get_commit_info(suspect->commit, &ci,1);2102if(*option & OUTPUT_SHOW_EMAIL)2103 num =utf8_strwidth(ci.author_mail.buf);2104else2105 num =utf8_strwidth(ci.author.buf);2106if(longest_author < num)2107 longest_author = num;2108commit_info_destroy(&ci);2109}2110 num = e->s_lno + e->num_lines;2111if(longest_src_lines < num)2112 longest_src_lines = num;2113 num = e->lno + e->num_lines;2114if(longest_dst_lines < num)2115 longest_dst_lines = num;2116if(largest_score <ent_score(sb, e))2117 largest_score =ent_score(sb, e);2118}2119 max_orig_digits =decimal_width(longest_src_lines);2120 max_digits =decimal_width(longest_dst_lines);2121 max_score_digits =decimal_width(largest_score);21222123if(compute_auto_abbrev)2124/* one more abbrev length is needed for the boundary commit */2125 abbrev = auto_abbrev +1;2126}21272128/*2129 * For debugging -- origin is refcounted, and this asserts that2130 * we do not underflow.2131 */2132static voidsanity_check_refcnt(struct scoreboard *sb)2133{2134int baa =0;2135struct blame_entry *ent;21362137for(ent = sb->ent; ent; ent = ent->next) {2138/* Nobody should have zero or negative refcnt */2139if(ent->suspect->refcnt <=0) {2140fprintf(stderr,"%sin%shas negative refcnt%d\n",2141 ent->suspect->path,2142sha1_to_hex(ent->suspect->commit->object.sha1),2143 ent->suspect->refcnt);2144 baa =1;2145}2146}2147if(baa) {2148int opt =0160;2149find_alignment(sb, &opt);2150output(sb, opt);2151die("Baa%d!", baa);2152}2153}21542155static unsignedparse_score(const char*arg)2156{2157char*end;2158unsigned long score =strtoul(arg, &end,10);2159if(*end)2160return0;2161return score;2162}21632164static const char*add_prefix(const char*prefix,const char*path)2165{2166returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2167}21682169static intgit_blame_config(const char*var,const char*value,void*cb)2170{2171if(!strcmp(var,"blame.showroot")) {2172 show_root =git_config_bool(var, value);2173return0;2174}2175if(!strcmp(var,"blame.blankboundary")) {2176 blank_boundary =git_config_bool(var, value);2177return0;2178}2179if(!strcmp(var,"blame.showemail")) {2180int*output_option = cb;2181if(git_config_bool(var, value))2182*output_option |= OUTPUT_SHOW_EMAIL;2183else2184*output_option &= ~OUTPUT_SHOW_EMAIL;2185return0;2186}2187if(!strcmp(var,"blame.date")) {2188if(!value)2189returnconfig_error_nonbool(var);2190 blame_date_mode =parse_date_format(value);2191return0;2192}21932194if(userdiff_config(var, value) <0)2195return-1;21962197returngit_default_config(var, value, cb);2198}21992200static voidverify_working_tree_path(struct commit *work_tree,const char*path)2201{2202struct commit_list *parents;22032204for(parents = work_tree->parents; parents; parents = parents->next) {2205const unsigned char*commit_sha1 = parents->item->object.sha1;2206unsigned char blob_sha1[20];2207unsigned mode;22082209if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2210sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2211return;2212}2213die("no such path '%s' in HEAD", path);2214}22152216static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2217{2218struct commit *parent;22192220 parent =lookup_commit_reference(sha1);2221if(!parent)2222die("no such commit%s",sha1_to_hex(sha1));2223return&commit_list_insert(parent, tail)->next;2224}22252226static voidappend_merge_parents(struct commit_list **tail)2227{2228int merge_head;2229const char*merge_head_file =git_path("MERGE_HEAD");2230struct strbuf line = STRBUF_INIT;22312232 merge_head =open(merge_head_file, O_RDONLY);2233if(merge_head <0) {2234if(errno == ENOENT)2235return;2236die("cannot open '%s' for reading", merge_head_file);2237}22382239while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2240unsigned char sha1[20];2241if(line.len <40||get_sha1_hex(line.buf, sha1))2242die("unknown line in '%s':%s", merge_head_file, line.buf);2243 tail =append_parent(tail, sha1);2244}2245close(merge_head);2246strbuf_release(&line);2247}22482249/*2250 * This isn't as simple as passing sb->buf and sb->len, because we2251 * want to transfer ownership of the buffer to the commit (so we2252 * must use detach).2253 */2254static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2255{2256size_t len;2257void*buf =strbuf_detach(sb, &len);2258set_commit_buffer(c, buf, len);2259}22602261/*2262 * Prepare a dummy commit that represents the work tree (or staged) item.2263 * Note that annotating work tree item never works in the reverse.2264 */2265static struct commit *fake_working_tree_commit(struct diff_options *opt,2266const char*path,2267const char*contents_from)2268{2269struct commit *commit;2270struct origin *origin;2271struct commit_list **parent_tail, *parent;2272unsigned char head_sha1[20];2273struct strbuf buf = STRBUF_INIT;2274const char*ident;2275time_t now;2276int size, len;2277struct cache_entry *ce;2278unsigned mode;2279struct strbuf msg = STRBUF_INIT;22802281time(&now);2282 commit =alloc_commit_node();2283 commit->object.parsed =1;2284 commit->date = now;2285 parent_tail = &commit->parents;22862287if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2288die("no such ref: HEAD");22892290 parent_tail =append_parent(parent_tail, head_sha1);2291append_merge_parents(parent_tail);2292verify_working_tree_path(commit, path);22932294 origin =make_origin(commit, path);22952296 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2297strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2298for(parent = commit->parents; parent; parent = parent->next)2299strbuf_addf(&msg,"parent%s\n",2300sha1_to_hex(parent->item->object.sha1));2301strbuf_addf(&msg,2302"author%s\n"2303"committer%s\n\n"2304"Version of%sfrom%s\n",2305 ident, ident, path,2306(!contents_from ? path :2307(!strcmp(contents_from,"-") ?"standard input": contents_from)));2308set_commit_buffer_from_strbuf(commit, &msg);23092310if(!contents_from ||strcmp("-", contents_from)) {2311struct stat st;2312const char*read_from;2313char*buf_ptr;2314unsigned long buf_len;23152316if(contents_from) {2317if(stat(contents_from, &st) <0)2318die_errno("Cannot stat '%s'", contents_from);2319 read_from = contents_from;2320}2321else{2322if(lstat(path, &st) <0)2323die_errno("Cannot lstat '%s'", path);2324 read_from = path;2325}2326 mode =canon_mode(st.st_mode);23272328switch(st.st_mode & S_IFMT) {2329case S_IFREG:2330if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2331textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2332strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2333else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2334die_errno("cannot open or read '%s'", read_from);2335break;2336case S_IFLNK:2337if(strbuf_readlink(&buf, read_from, st.st_size) <0)2338die_errno("cannot readlink '%s'", read_from);2339break;2340default:2341die("unsupported file type%s", read_from);2342}2343}2344else{2345/* Reading from stdin */2346 mode =0;2347if(strbuf_read(&buf,0,0) <0)2348die_errno("failed to read from stdin");2349}2350convert_to_git(path, buf.buf, buf.len, &buf,0);2351 origin->file.ptr = buf.buf;2352 origin->file.size = buf.len;2353pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23542355/*2356 * Read the current index, replace the path entry with2357 * origin->blob_sha1 without mucking with its mode or type2358 * bits; we are not going to write this index out -- we just2359 * want to run "diff-index --cached".2360 */2361discard_cache();2362read_cache();23632364 len =strlen(path);2365if(!mode) {2366int pos =cache_name_pos(path, len);2367if(0<= pos)2368 mode = active_cache[pos]->ce_mode;2369else2370/* Let's not bother reading from HEAD tree */2371 mode = S_IFREG |0644;2372}2373 size =cache_entry_size(len);2374 ce =xcalloc(1, size);2375hashcpy(ce->sha1, origin->blob_sha1);2376memcpy(ce->name, path, len);2377 ce->ce_flags =create_ce_flags(0);2378 ce->ce_namelen = len;2379 ce->ce_mode =create_ce_mode(mode);2380add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23812382/*2383 * We are not going to write this out, so this does not matter2384 * right now, but someday we might optimize diff-index --cached2385 * with cache-tree information.2386 */2387cache_tree_invalidate_path(&the_index, path);23882389return commit;2390}23912392static char*prepare_final(struct scoreboard *sb)2393{2394int i;2395const char*final_commit_name = NULL;2396struct rev_info *revs = sb->revs;23972398/*2399 * There must be one and only one positive commit in the2400 * revs->pending array.2401 */2402for(i =0; i < revs->pending.nr; i++) {2403struct object *obj = revs->pending.objects[i].item;2404if(obj->flags & UNINTERESTING)2405continue;2406while(obj->type == OBJ_TAG)2407 obj =deref_tag(obj, NULL,0);2408if(obj->type != OBJ_COMMIT)2409die("Non commit%s?", revs->pending.objects[i].name);2410if(sb->final)2411die("More than one commit to dig from%sand%s?",2412 revs->pending.objects[i].name,2413 final_commit_name);2414 sb->final = (struct commit *) obj;2415 final_commit_name = revs->pending.objects[i].name;2416}2417returnxstrdup_or_null(final_commit_name);2418}24192420static char*prepare_initial(struct scoreboard *sb)2421{2422int i;2423const char*final_commit_name = NULL;2424struct rev_info *revs = sb->revs;24252426/*2427 * There must be one and only one negative commit, and it must be2428 * the boundary.2429 */2430for(i =0; i < revs->pending.nr; i++) {2431struct object *obj = revs->pending.objects[i].item;2432if(!(obj->flags & UNINTERESTING))2433continue;2434while(obj->type == OBJ_TAG)2435 obj =deref_tag(obj, NULL,0);2436if(obj->type != OBJ_COMMIT)2437die("Non commit%s?", revs->pending.objects[i].name);2438if(sb->final)2439die("More than one commit to dig down to%sand%s?",2440 revs->pending.objects[i].name,2441 final_commit_name);2442 sb->final = (struct commit *) obj;2443 final_commit_name = revs->pending.objects[i].name;2444}2445if(!final_commit_name)2446die("No commit to dig down to?");2447returnxstrdup(final_commit_name);2448}24492450static intblame_copy_callback(const struct option *option,const char*arg,int unset)2451{2452int*opt = option->value;24532454/*2455 * -C enables copy from removed files;2456 * -C -C enables copy from existing files, but only2457 * when blaming a new file;2458 * -C -C -C enables copy from existing files for2459 * everybody2460 */2461if(*opt & PICKAXE_BLAME_COPY_HARDER)2462*opt |= PICKAXE_BLAME_COPY_HARDEST;2463if(*opt & PICKAXE_BLAME_COPY)2464*opt |= PICKAXE_BLAME_COPY_HARDER;2465*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;24662467if(arg)2468 blame_copy_score =parse_score(arg);2469return0;2470}24712472static intblame_move_callback(const struct option *option,const char*arg,int unset)2473{2474int*opt = option->value;24752476*opt |= PICKAXE_BLAME_MOVE;24772478if(arg)2479 blame_move_score =parse_score(arg);2480return0;2481}24822483intcmd_blame(int argc,const char**argv,const char*prefix)2484{2485struct rev_info revs;2486const char*path;2487struct scoreboard sb;2488struct origin *o;2489struct blame_entry *ent = NULL;2490long dashdash_pos, lno;2491char*final_commit_name = NULL;2492enum object_type type;24932494static struct string_list range_list;2495static int output_option =0, opt =0;2496static int show_stats =0;2497static const char*revs_file = NULL;2498static const char*contents_from = NULL;2499static const struct option options[] = {2500OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2501OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2502OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2503OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2504OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2505OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2506OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2507OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2508OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2509OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2510OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2511OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2512OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2513OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2514OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2515OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2516OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2517OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2518{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2519{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2520OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2521OPT__ABBREV(&abbrev),2522OPT_END()2523};25242525struct parse_opt_ctx_t ctx;2526int cmd_is_annotate = !strcmp(argv[0],"annotate");2527struct range_set ranges;2528unsigned int range_i;2529long anchor;25302531git_config(git_blame_config, &output_option);2532init_revisions(&revs, NULL);2533 revs.date_mode = blame_date_mode;2534DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2535DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25362537 save_commit_buffer =0;2538 dashdash_pos =0;25392540parse_options_start(&ctx, argc, argv, prefix, options,2541 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2542for(;;) {2543switch(parse_options_step(&ctx, options, blame_opt_usage)) {2544case PARSE_OPT_HELP:2545exit(129);2546case PARSE_OPT_DONE:2547if(ctx.argv[0])2548 dashdash_pos = ctx.cpidx;2549goto parse_done;2550}25512552if(!strcmp(ctx.argv[0],"--reverse")) {2553 ctx.argv[0] ="--children";2554 reverse =1;2555}2556parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2557}2558parse_done:2559 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2560DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2561 argc =parse_options_end(&ctx);25622563if(0< abbrev)2564/* one more abbrev length is needed for the boundary commit */2565 abbrev++;25662567if(revs_file &&read_ancestry(revs_file))2568die_errno("reading graft file '%s' failed", revs_file);25692570if(cmd_is_annotate) {2571 output_option |= OUTPUT_ANNOTATE_COMPAT;2572 blame_date_mode = DATE_ISO8601;2573}else{2574 blame_date_mode = revs.date_mode;2575}25762577/* The maximum width used to show the dates */2578switch(blame_date_mode) {2579case DATE_RFC2822:2580 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2581break;2582case DATE_ISO8601_STRICT:2583 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2584break;2585case DATE_ISO8601:2586 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2587break;2588case DATE_RAW:2589 blame_date_width =sizeof("1161298804 -0700");2590break;2591case DATE_SHORT:2592 blame_date_width =sizeof("2006-10-19");2593break;2594case DATE_RELATIVE:2595/* TRANSLATORS: This string is used to tell us the maximum2596 display width for a relative timestamp in "git blame"2597 output. For C locale, "4 years, 11 months ago", which2598 takes 22 places, is the longest among various forms of2599 relative timestamps, but your language may need more or2600 fewer display columns. */2601 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2602break;2603case DATE_LOCAL:2604case DATE_NORMAL:2605 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2606break;2607}2608 blame_date_width -=1;/* strip the null */26092610if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2611 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2612 PICKAXE_BLAME_COPY_HARDER);26132614if(!blame_move_score)2615 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2616if(!blame_copy_score)2617 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26182619/*2620 * We have collected options unknown to us in argv[1..unk]2621 * which are to be passed to revision machinery if we are2622 * going to do the "bottom" processing.2623 *2624 * The remaining are:2625 *2626 * (1) if dashdash_pos != 0, it is either2627 * "blame [revisions] -- <path>" or2628 * "blame -- <path> <rev>"2629 *2630 * (2) otherwise, it is one of the two:2631 * "blame [revisions] <path>"2632 * "blame <path> <rev>"2633 *2634 * Note that we must strip out <path> from the arguments: we do not2635 * want the path pruning but we may want "bottom" processing.2636 */2637if(dashdash_pos) {2638switch(argc - dashdash_pos -1) {2639case2:/* (1b) */2640if(argc !=4)2641usage_with_options(blame_opt_usage, options);2642/* reorder for the new way: <rev> -- <path> */2643 argv[1] = argv[3];2644 argv[3] = argv[2];2645 argv[2] ="--";2646/* FALLTHROUGH */2647case1:/* (1a) */2648 path =add_prefix(prefix, argv[--argc]);2649 argv[argc] = NULL;2650break;2651default:2652usage_with_options(blame_opt_usage, options);2653}2654}else{2655if(argc <2)2656usage_with_options(blame_opt_usage, options);2657 path =add_prefix(prefix, argv[argc -1]);2658if(argc ==3&& !file_exists(path)) {/* (2b) */2659 path =add_prefix(prefix, argv[1]);2660 argv[1] = argv[2];2661}2662 argv[argc -1] ="--";26632664setup_work_tree();2665if(!file_exists(path))2666die_errno("cannot stat path '%s'", path);2667}26682669 revs.disable_stdin =1;2670setup_revisions(argc, argv, &revs, NULL);2671memset(&sb,0,sizeof(sb));26722673 sb.revs = &revs;2674if(!reverse) {2675 final_commit_name =prepare_final(&sb);2676 sb.commits.compare = compare_commits_by_commit_date;2677}2678else if(contents_from)2679die("--contents and --children do not blend well.");2680else{2681 final_commit_name =prepare_initial(&sb);2682 sb.commits.compare = compare_commits_by_reverse_commit_date;2683}26842685if(!sb.final) {2686/*2687 * "--not A B -- path" without anything positive;2688 * do not default to HEAD, but use the working tree2689 * or "--contents".2690 */2691setup_work_tree();2692 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2693 path, contents_from);2694add_pending_object(&revs, &(sb.final->object),":");2695}2696else if(contents_from)2697die("Cannot use --contents with final commit object name");26982699/*2700 * If we have bottom, this will mark the ancestors of the2701 * bottom commits we would reach while traversing as2702 * uninteresting.2703 */2704if(prepare_revision_walk(&revs))2705die(_("revision walk setup failed"));27062707if(is_null_sha1(sb.final->object.sha1)) {2708 o = sb.final->util;2709 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2710 sb.final_buf_size = o->file.size;2711}2712else{2713 o =get_origin(&sb, sb.final, path);2714if(fill_blob_sha1_and_mode(o))2715die("no such path%sin%s", path, final_commit_name);27162717if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2718textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2719&sb.final_buf_size))2720;2721else2722 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2723&sb.final_buf_size);27242725if(!sb.final_buf)2726die("Cannot read blob%sfor path%s",2727sha1_to_hex(o->blob_sha1),2728 path);2729}2730 num_read_blob++;2731 lno =prepare_lines(&sb);27322733if(lno && !range_list.nr)2734string_list_append(&range_list,xstrdup("1"));27352736 anchor =1;2737range_set_init(&ranges, range_list.nr);2738for(range_i =0; range_i < range_list.nr; ++range_i) {2739long bottom, top;2740if(parse_range_arg(range_list.items[range_i].string,2741 nth_line_cb, &sb, lno, anchor,2742&bottom, &top, sb.path))2743usage(blame_usage);2744if(lno < top || ((lno || bottom) && lno < bottom))2745die("file%shas only%lu lines", path, lno);2746if(bottom <1)2747 bottom =1;2748if(top <1)2749 top = lno;2750 bottom--;2751range_set_append_unsafe(&ranges, bottom, top);2752 anchor = top +1;2753}2754sort_and_merge_range_set(&ranges);27552756for(range_i = ranges.nr; range_i >0; --range_i) {2757const struct range *r = &ranges.ranges[range_i -1];2758long bottom = r->start;2759long top = r->end;2760struct blame_entry *next = ent;2761 ent =xcalloc(1,sizeof(*ent));2762 ent->lno = bottom;2763 ent->num_lines = top - bottom;2764 ent->suspect = o;2765 ent->s_lno = bottom;2766 ent->next = next;2767origin_incref(o);2768}27692770 o->suspects = ent;2771prio_queue_put(&sb.commits, o->commit);27722773origin_decref(o);27742775range_set_release(&ranges);2776string_list_clear(&range_list,0);27772778 sb.ent = NULL;2779 sb.path = path;27802781read_mailmap(&mailmap, NULL);27822783if(!incremental)2784setup_pager();27852786assign_blame(&sb, opt);27872788free(final_commit_name);27892790if(incremental)2791return0;27922793 sb.ent =blame_sort(sb.ent, compare_blame_final);27942795coalesce(&sb);27962797if(!(output_option & OUTPUT_PORCELAIN))2798find_alignment(&sb, &output_option);27992800output(&sb, output_option);2801free((void*)sb.final_buf);2802for(ent = sb.ent; ent; ) {2803struct blame_entry *e = ent->next;2804free(ent);2805 ent = e;2806}28072808if(show_stats) {2809printf("num read blob:%d\n", num_read_blob);2810printf("num get patch:%d\n", num_get_patch);2811printf("num commits:%d\n", num_commits);2812}2813return0;2814}