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 976if(diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d)) 977die("unable to generate diff (%s->%s)", 978sha1_to_hex(parent->commit->object.sha1), 979sha1_to_hex(target->commit->object.sha1)); 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)",1127sha1_to_hex(parent->commit->object.sha1));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_sha1(target->commit->object.sha1))1277do_diff_cache(parent->tree->object.sha1, &diff_opts);1278else1279diff_tree_sha1(parent->tree->object.sha1,1280 target->commit->tree->object.sha1,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)1374return commit->parents;1375returnlookup_decoration(&revs->children, &commit->object);1376}13771378static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1379{1380struct commit_list *l =first_scapegoat(revs, commit);1381returncommit_list_count(l);1382}13831384/* Distribute collected unsorted blames to the respected sorted lists1385 * in the various origins.1386 */1387static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1388{1389 blamed =blame_sort(blamed, compare_blame_suspect);1390while(blamed)1391{1392struct origin *porigin = blamed->suspect;1393struct blame_entry *suspects = NULL;1394do{1395struct blame_entry *next = blamed->next;1396 blamed->next = suspects;1397 suspects = blamed;1398 blamed = next;1399}while(blamed && blamed->suspect == porigin);1400 suspects =reverse_blame(suspects, NULL);1401queue_blames(sb, porigin, suspects);1402}1403}14041405#define MAXSG 1614061407static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1408{1409struct rev_info *revs = sb->revs;1410int i, pass, num_sg;1411struct commit *commit = origin->commit;1412struct commit_list *sg;1413struct origin *sg_buf[MAXSG];1414struct origin *porigin, **sg_origin = sg_buf;1415struct blame_entry *toosmall = NULL;1416struct blame_entry *blames, **blametail = &blames;14171418 num_sg =num_scapegoats(revs, commit);1419if(!num_sg)1420goto finish;1421else if(num_sg <ARRAY_SIZE(sg_buf))1422memset(sg_buf,0,sizeof(sg_buf));1423else1424 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14251426/*1427 * The first pass looks for unrenamed path to optimize for1428 * common cases, then we look for renames in the second pass.1429 */1430for(pass =0; pass <2- no_whole_file_rename; pass++) {1431struct origin *(*find)(struct scoreboard *,1432struct commit *,struct origin *);1433 find = pass ? find_rename : find_origin;14341435for(i =0, sg =first_scapegoat(revs, commit);1436 i < num_sg && sg;1437 sg = sg->next, i++) {1438struct commit *p = sg->item;1439int j, same;14401441if(sg_origin[i])1442continue;1443if(parse_commit(p))1444continue;1445 porigin =find(sb, p, origin);1446if(!porigin)1447continue;1448if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1449pass_whole_blame(sb, origin, porigin);1450origin_decref(porigin);1451goto finish;1452}1453for(j = same =0; j < i; j++)1454if(sg_origin[j] &&1455!hashcmp(sg_origin[j]->blob_sha1,1456 porigin->blob_sha1)) {1457 same =1;1458break;1459}1460if(!same)1461 sg_origin[i] = porigin;1462else1463origin_decref(porigin);1464}1465}14661467 num_commits++;1468for(i =0, sg =first_scapegoat(revs, commit);1469 i < num_sg && sg;1470 sg = sg->next, i++) {1471struct origin *porigin = sg_origin[i];1472if(!porigin)1473continue;1474if(!origin->previous) {1475origin_incref(porigin);1476 origin->previous = porigin;1477}1478pass_blame_to_parent(sb, origin, porigin);1479if(!origin->suspects)1480goto finish;1481}14821483/*1484 * Optionally find moves in parents' files.1485 */1486if(opt & PICKAXE_BLAME_MOVE) {1487filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1488if(origin->suspects) {1489for(i =0, sg =first_scapegoat(revs, commit);1490 i < num_sg && sg;1491 sg = sg->next, i++) {1492struct origin *porigin = sg_origin[i];1493if(!porigin)1494continue;1495find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1496if(!origin->suspects)1497break;1498}1499}1500}15011502/*1503 * Optionally find copies from parents' files.1504 */1505if(opt & PICKAXE_BLAME_COPY) {1506if(blame_copy_score > blame_move_score)1507filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1508else if(blame_copy_score < blame_move_score) {1509 origin->suspects =blame_merge(origin->suspects, toosmall);1510 toosmall = NULL;1511filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1512}1513if(!origin->suspects)1514goto finish;15151516for(i =0, sg =first_scapegoat(revs, commit);1517 i < num_sg && sg;1518 sg = sg->next, i++) {1519struct origin *porigin = sg_origin[i];1520find_copy_in_parent(sb, &blametail, &toosmall,1521 origin, sg->item, porigin, opt);1522if(!origin->suspects)1523goto finish;1524}1525}15261527finish:1528*blametail = NULL;1529distribute_blame(sb, blames);1530/*1531 * prepend toosmall to origin->suspects1532 *1533 * There is no point in sorting: this ends up on a big1534 * unsorted list in the caller anyway.1535 */1536if(toosmall) {1537struct blame_entry **tail = &toosmall;1538while(*tail)1539 tail = &(*tail)->next;1540*tail = origin->suspects;1541 origin->suspects = toosmall;1542}1543for(i =0; i < num_sg; i++) {1544if(sg_origin[i]) {1545drop_origin_blob(sg_origin[i]);1546origin_decref(sg_origin[i]);1547}1548}1549drop_origin_blob(origin);1550if(sg_buf != sg_origin)1551free(sg_origin);1552}15531554/*1555 * Information on commits, used for output.1556 */1557struct commit_info {1558struct strbuf author;1559struct strbuf author_mail;1560unsigned long author_time;1561struct strbuf author_tz;15621563/* filled only when asked for details */1564struct strbuf committer;1565struct strbuf committer_mail;1566unsigned long committer_time;1567struct strbuf committer_tz;15681569struct strbuf summary;1570};15711572/*1573 * Parse author/committer line in the commit object buffer1574 */1575static voidget_ac_line(const char*inbuf,const char*what,1576struct strbuf *name,struct strbuf *mail,1577unsigned long*time,struct strbuf *tz)1578{1579struct ident_split ident;1580size_t len, maillen, namelen;1581char*tmp, *endp;1582const char*namebuf, *mailbuf;15831584 tmp =strstr(inbuf, what);1585if(!tmp)1586goto error_out;1587 tmp +=strlen(what);1588 endp =strchr(tmp,'\n');1589if(!endp)1590 len =strlen(tmp);1591else1592 len = endp - tmp;15931594if(split_ident_line(&ident, tmp, len)) {1595 error_out:1596/* Ugh */1597 tmp ="(unknown)";1598strbuf_addstr(name, tmp);1599strbuf_addstr(mail, tmp);1600strbuf_addstr(tz, tmp);1601*time =0;1602return;1603}16041605 namelen = ident.name_end - ident.name_begin;1606 namebuf = ident.name_begin;16071608 maillen = ident.mail_end - ident.mail_begin;1609 mailbuf = ident.mail_begin;16101611if(ident.date_begin && ident.date_end)1612*time =strtoul(ident.date_begin, NULL,10);1613else1614*time =0;16151616if(ident.tz_begin && ident.tz_end)1617strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1618else1619strbuf_addstr(tz,"(unknown)");16201621/*1622 * Now, convert both name and e-mail using mailmap1623 */1624map_user(&mailmap, &mailbuf, &maillen,1625&namebuf, &namelen);16261627strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1628strbuf_add(name, namebuf, namelen);1629}16301631static voidcommit_info_init(struct commit_info *ci)1632{16331634strbuf_init(&ci->author,0);1635strbuf_init(&ci->author_mail,0);1636strbuf_init(&ci->author_tz,0);1637strbuf_init(&ci->committer,0);1638strbuf_init(&ci->committer_mail,0);1639strbuf_init(&ci->committer_tz,0);1640strbuf_init(&ci->summary,0);1641}16421643static voidcommit_info_destroy(struct commit_info *ci)1644{16451646strbuf_release(&ci->author);1647strbuf_release(&ci->author_mail);1648strbuf_release(&ci->author_tz);1649strbuf_release(&ci->committer);1650strbuf_release(&ci->committer_mail);1651strbuf_release(&ci->committer_tz);1652strbuf_release(&ci->summary);1653}16541655static voidget_commit_info(struct commit *commit,1656struct commit_info *ret,1657int detailed)1658{1659int len;1660const char*subject, *encoding;1661const char*message;16621663commit_info_init(ret);16641665 encoding =get_log_output_encoding();1666 message =logmsg_reencode(commit, NULL, encoding);1667get_ac_line(message,"\nauthor ",1668&ret->author, &ret->author_mail,1669&ret->author_time, &ret->author_tz);16701671if(!detailed) {1672unuse_commit_buffer(commit, message);1673return;1674}16751676get_ac_line(message,"\ncommitter ",1677&ret->committer, &ret->committer_mail,1678&ret->committer_time, &ret->committer_tz);16791680 len =find_commit_subject(message, &subject);1681if(len)1682strbuf_add(&ret->summary, subject, len);1683else1684strbuf_addf(&ret->summary,"(%s)",sha1_to_hex(commit->object.sha1));16851686unuse_commit_buffer(commit, message);1687}16881689/*1690 * To allow LF and other nonportable characters in pathnames,1691 * they are c-style quoted as needed.1692 */1693static voidwrite_filename_info(const char*path)1694{1695printf("filename ");1696write_name_quoted(path, stdout,'\n');1697}16981699/*1700 * Porcelain/Incremental format wants to show a lot of details per1701 * commit. Instead of repeating this every line, emit it only once,1702 * the first time each commit appears in the output (unless the1703 * user has specifically asked for us to repeat).1704 */1705static intemit_one_suspect_detail(struct origin *suspect,int repeat)1706{1707struct commit_info ci;17081709if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1710return0;17111712 suspect->commit->object.flags |= METAINFO_SHOWN;1713get_commit_info(suspect->commit, &ci,1);1714printf("author%s\n", ci.author.buf);1715printf("author-mail%s\n", ci.author_mail.buf);1716printf("author-time%lu\n", ci.author_time);1717printf("author-tz%s\n", ci.author_tz.buf);1718printf("committer%s\n", ci.committer.buf);1719printf("committer-mail%s\n", ci.committer_mail.buf);1720printf("committer-time%lu\n", ci.committer_time);1721printf("committer-tz%s\n", ci.committer_tz.buf);1722printf("summary%s\n", ci.summary.buf);1723if(suspect->commit->object.flags & UNINTERESTING)1724printf("boundary\n");1725if(suspect->previous) {1726struct origin *prev = suspect->previous;1727printf("previous%s",sha1_to_hex(prev->commit->object.sha1));1728write_name_quoted(prev->path, stdout,'\n');1729}17301731commit_info_destroy(&ci);17321733return1;1734}17351736/*1737 * The blame_entry is found to be guilty for the range.1738 * Show it in incremental output.1739 */1740static voidfound_guilty_entry(struct blame_entry *ent)1741{1742if(incremental) {1743struct origin *suspect = ent->suspect;17441745printf("%s %d %d %d\n",1746sha1_to_hex(suspect->commit->object.sha1),1747 ent->s_lno +1, ent->lno +1, ent->num_lines);1748emit_one_suspect_detail(suspect,0);1749write_filename_info(suspect->path);1750maybe_flush_or_die(stdout,"stdout");1751}1752}17531754/*1755 * The main loop -- while we have blobs with lines whose true origin1756 * is still unknown, pick one blob, and allow its lines to pass blames1757 * to its parents. */1758static voidassign_blame(struct scoreboard *sb,int opt)1759{1760struct rev_info *revs = sb->revs;1761struct commit *commit =prio_queue_get(&sb->commits);17621763while(commit) {1764struct blame_entry *ent;1765struct origin *suspect = commit->util;17661767/* find one suspect to break down */1768while(suspect && !suspect->suspects)1769 suspect = suspect->next;17701771if(!suspect) {1772 commit =prio_queue_get(&sb->commits);1773continue;1774}17751776assert(commit == suspect->commit);17771778/*1779 * We will use this suspect later in the loop,1780 * so hold onto it in the meantime.1781 */1782origin_incref(suspect);1783parse_commit(commit);1784if(reverse ||1785(!(commit->object.flags & UNINTERESTING) &&1786!(revs->max_age != -1&& commit->date < revs->max_age)))1787pass_blame(sb, suspect, opt);1788else{1789 commit->object.flags |= UNINTERESTING;1790if(commit->object.parsed)1791mark_parents_uninteresting(commit);1792}1793/* treat root commit as boundary */1794if(!commit->parents && !show_root)1795 commit->object.flags |= UNINTERESTING;17961797/* Take responsibility for the remaining entries */1798 ent = suspect->suspects;1799if(ent) {1800 suspect->guilty =1;1801for(;;) {1802struct blame_entry *next = ent->next;1803found_guilty_entry(ent);1804if(next) {1805 ent = next;1806continue;1807}1808 ent->next = sb->ent;1809 sb->ent = suspect->suspects;1810 suspect->suspects = NULL;1811break;1812}1813}1814origin_decref(suspect);18151816if(DEBUG)/* sanity */1817sanity_check_refcnt(sb);1818}1819}18201821static const char*format_time(unsigned long time,const char*tz_str,1822int show_raw_time)1823{1824static struct strbuf time_buf = STRBUF_INIT;18251826strbuf_reset(&time_buf);1827if(show_raw_time) {1828strbuf_addf(&time_buf,"%lu%s", time, tz_str);1829}1830else{1831const char*time_str;1832size_t time_width;1833int tz;1834 tz =atoi(tz_str);1835 time_str =show_date(time, tz, blame_date_mode);1836strbuf_addstr(&time_buf, time_str);1837/*1838 * Add space paddings to time_buf to display a fixed width1839 * string, and use time_width for display width calibration.1840 */1841for(time_width =utf8_strwidth(time_str);1842 time_width < blame_date_width;1843 time_width++)1844strbuf_addch(&time_buf,' ');1845}1846return time_buf.buf;1847}18481849#define OUTPUT_ANNOTATE_COMPAT 0011850#define OUTPUT_LONG_OBJECT_NAME 0021851#define OUTPUT_RAW_TIMESTAMP 0041852#define OUTPUT_PORCELAIN 0101853#define OUTPUT_SHOW_NAME 0201854#define OUTPUT_SHOW_NUMBER 0401855#define OUTPUT_SHOW_SCORE 01001856#define OUTPUT_NO_AUTHOR 02001857#define OUTPUT_SHOW_EMAIL 04001858#define OUTPUT_LINE_PORCELAIN 0100018591860static voidemit_porcelain_details(struct origin *suspect,int repeat)1861{1862if(emit_one_suspect_detail(suspect, repeat) ||1863(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1864write_filename_info(suspect->path);1865}18661867static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1868int opt)1869{1870int repeat = opt & OUTPUT_LINE_PORCELAIN;1871int cnt;1872const char*cp;1873struct origin *suspect = ent->suspect;1874char hex[41];18751876strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));1877printf("%s %d %d %d\n",1878 hex,1879 ent->s_lno +1,1880 ent->lno +1,1881 ent->num_lines);1882emit_porcelain_details(suspect, repeat);18831884 cp =nth_line(sb, ent->lno);1885for(cnt =0; cnt < ent->num_lines; cnt++) {1886char ch;1887if(cnt) {1888printf("%s %d %d\n", hex,1889 ent->s_lno +1+ cnt,1890 ent->lno +1+ cnt);1891if(repeat)1892emit_porcelain_details(suspect,1);1893}1894putchar('\t');1895do{1896 ch = *cp++;1897putchar(ch);1898}while(ch !='\n'&&1899 cp < sb->final_buf + sb->final_buf_size);1900}19011902if(sb->final_buf_size && cp[-1] !='\n')1903putchar('\n');1904}19051906static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1907{1908int cnt;1909const char*cp;1910struct origin *suspect = ent->suspect;1911struct commit_info ci;1912char hex[41];1913int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19141915get_commit_info(suspect->commit, &ci,1);1916strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));19171918 cp =nth_line(sb, ent->lno);1919for(cnt =0; cnt < ent->num_lines; cnt++) {1920char ch;1921int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19221923if(suspect->commit->object.flags & UNINTERESTING) {1924if(blank_boundary)1925memset(hex,' ', length);1926else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1927 length--;1928putchar('^');1929}1930}19311932printf("%.*s", length, hex);1933if(opt & OUTPUT_ANNOTATE_COMPAT) {1934const char*name;1935if(opt & OUTPUT_SHOW_EMAIL)1936 name = ci.author_mail.buf;1937else1938 name = ci.author.buf;1939printf("\t(%10s\t%10s\t%d)", name,1940format_time(ci.author_time, ci.author_tz.buf,1941 show_raw_time),1942 ent->lno +1+ cnt);1943}else{1944if(opt & OUTPUT_SHOW_SCORE)1945printf(" %*d%02d",1946 max_score_digits, ent->score,1947 ent->suspect->refcnt);1948if(opt & OUTPUT_SHOW_NAME)1949printf(" %-*.*s", longest_file, longest_file,1950 suspect->path);1951if(opt & OUTPUT_SHOW_NUMBER)1952printf(" %*d", max_orig_digits,1953 ent->s_lno +1+ cnt);19541955if(!(opt & OUTPUT_NO_AUTHOR)) {1956const char*name;1957int pad;1958if(opt & OUTPUT_SHOW_EMAIL)1959 name = ci.author_mail.buf;1960else1961 name = ci.author.buf;1962 pad = longest_author -utf8_strwidth(name);1963printf(" (%s%*s%10s",1964 name, pad,"",1965format_time(ci.author_time,1966 ci.author_tz.buf,1967 show_raw_time));1968}1969printf(" %*d) ",1970 max_digits, ent->lno +1+ cnt);1971}1972do{1973 ch = *cp++;1974putchar(ch);1975}while(ch !='\n'&&1976 cp < sb->final_buf + sb->final_buf_size);1977}19781979if(sb->final_buf_size && cp[-1] !='\n')1980putchar('\n');19811982commit_info_destroy(&ci);1983}19841985static voidoutput(struct scoreboard *sb,int option)1986{1987struct blame_entry *ent;19881989if(option & OUTPUT_PORCELAIN) {1990for(ent = sb->ent; ent; ent = ent->next) {1991int count =0;1992struct origin *suspect;1993struct commit *commit = ent->suspect->commit;1994if(commit->object.flags & MORE_THAN_ONE_PATH)1995continue;1996for(suspect = commit->util; suspect; suspect = suspect->next) {1997if(suspect->guilty && count++) {1998 commit->object.flags |= MORE_THAN_ONE_PATH;1999break;2000}2001}2002}2003}20042005for(ent = sb->ent; ent; ent = ent->next) {2006if(option & OUTPUT_PORCELAIN)2007emit_porcelain(sb, ent, option);2008else{2009emit_other(sb, ent, option);2010}2011}2012}20132014static const char*get_next_line(const char*start,const char*end)2015{2016const char*nl =memchr(start,'\n', end - start);2017return nl ? nl +1: end;2018}20192020/*2021 * To allow quick access to the contents of nth line in the2022 * final image, prepare an index in the scoreboard.2023 */2024static intprepare_lines(struct scoreboard *sb)2025{2026const char*buf = sb->final_buf;2027unsigned long len = sb->final_buf_size;2028const char*end = buf + len;2029const char*p;2030int*lineno;2031int num =0;20322033for(p = buf; p < end; p =get_next_line(p, end))2034 num++;20352036 sb->lineno = lineno =xmalloc(sizeof(*sb->lineno) * (num +1));20372038for(p = buf; p < end; p =get_next_line(p, end))2039*lineno++ = p - buf;20402041*lineno = len;20422043 sb->num_lines = num;2044return sb->num_lines;2045}20462047/*2048 * Add phony grafts for use with -S; this is primarily to2049 * support git's cvsserver that wants to give a linear history2050 * to its clients.2051 */2052static intread_ancestry(const char*graft_file)2053{2054FILE*fp =fopen(graft_file,"r");2055struct strbuf buf = STRBUF_INIT;2056if(!fp)2057return-1;2058while(!strbuf_getwholeline(&buf, fp,'\n')) {2059/* The format is just "Commit Parent1 Parent2 ...\n" */2060struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2061if(graft)2062register_commit_graft(graft,0);2063}2064fclose(fp);2065strbuf_release(&buf);2066return0;2067}20682069static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2070{2071const char*uniq =find_unique_abbrev(suspect->commit->object.sha1,2072 auto_abbrev);2073int len =strlen(uniq);2074if(auto_abbrev < len)2075return len;2076return auto_abbrev;2077}20782079/*2080 * How many columns do we need to show line numbers, authors,2081 * and filenames?2082 */2083static voidfind_alignment(struct scoreboard *sb,int*option)2084{2085int longest_src_lines =0;2086int longest_dst_lines =0;2087unsigned largest_score =0;2088struct blame_entry *e;2089int compute_auto_abbrev = (abbrev <0);2090int auto_abbrev = default_abbrev;20912092for(e = sb->ent; e; e = e->next) {2093struct origin *suspect = e->suspect;2094int num;20952096if(compute_auto_abbrev)2097 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2098if(strcmp(suspect->path, sb->path))2099*option |= OUTPUT_SHOW_NAME;2100 num =strlen(suspect->path);2101if(longest_file < num)2102 longest_file = num;2103if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2104struct commit_info ci;2105 suspect->commit->object.flags |= METAINFO_SHOWN;2106get_commit_info(suspect->commit, &ci,1);2107if(*option & OUTPUT_SHOW_EMAIL)2108 num =utf8_strwidth(ci.author_mail.buf);2109else2110 num =utf8_strwidth(ci.author.buf);2111if(longest_author < num)2112 longest_author = num;2113commit_info_destroy(&ci);2114}2115 num = e->s_lno + e->num_lines;2116if(longest_src_lines < num)2117 longest_src_lines = num;2118 num = e->lno + e->num_lines;2119if(longest_dst_lines < num)2120 longest_dst_lines = num;2121if(largest_score <ent_score(sb, e))2122 largest_score =ent_score(sb, e);2123}2124 max_orig_digits =decimal_width(longest_src_lines);2125 max_digits =decimal_width(longest_dst_lines);2126 max_score_digits =decimal_width(largest_score);21272128if(compute_auto_abbrev)2129/* one more abbrev length is needed for the boundary commit */2130 abbrev = auto_abbrev +1;2131}21322133/*2134 * For debugging -- origin is refcounted, and this asserts that2135 * we do not underflow.2136 */2137static voidsanity_check_refcnt(struct scoreboard *sb)2138{2139int baa =0;2140struct blame_entry *ent;21412142for(ent = sb->ent; ent; ent = ent->next) {2143/* Nobody should have zero or negative refcnt */2144if(ent->suspect->refcnt <=0) {2145fprintf(stderr,"%sin%shas negative refcnt%d\n",2146 ent->suspect->path,2147sha1_to_hex(ent->suspect->commit->object.sha1),2148 ent->suspect->refcnt);2149 baa =1;2150}2151}2152if(baa) {2153int opt =0160;2154find_alignment(sb, &opt);2155output(sb, opt);2156die("Baa%d!", baa);2157}2158}21592160static unsignedparse_score(const char*arg)2161{2162char*end;2163unsigned long score =strtoul(arg, &end,10);2164if(*end)2165return0;2166return score;2167}21682169static const char*add_prefix(const char*prefix,const char*path)2170{2171returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2172}21732174static intgit_blame_config(const char*var,const char*value,void*cb)2175{2176if(!strcmp(var,"blame.showroot")) {2177 show_root =git_config_bool(var, value);2178return0;2179}2180if(!strcmp(var,"blame.blankboundary")) {2181 blank_boundary =git_config_bool(var, value);2182return0;2183}2184if(!strcmp(var,"blame.date")) {2185if(!value)2186returnconfig_error_nonbool(var);2187 blame_date_mode =parse_date_format(value);2188return0;2189}21902191if(userdiff_config(var, value) <0)2192return-1;21932194returngit_default_config(var, value, cb);2195}21962197static voidverify_working_tree_path(struct commit *work_tree,const char*path)2198{2199struct commit_list *parents;22002201for(parents = work_tree->parents; parents; parents = parents->next) {2202const unsigned char*commit_sha1 = parents->item->object.sha1;2203unsigned char blob_sha1[20];2204unsigned mode;22052206if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2207sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2208return;2209}2210die("no such path '%s' in HEAD", path);2211}22122213static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2214{2215struct commit *parent;22162217 parent =lookup_commit_reference(sha1);2218if(!parent)2219die("no such commit%s",sha1_to_hex(sha1));2220return&commit_list_insert(parent, tail)->next;2221}22222223static voidappend_merge_parents(struct commit_list **tail)2224{2225int merge_head;2226const char*merge_head_file =git_path("MERGE_HEAD");2227struct strbuf line = STRBUF_INIT;22282229 merge_head =open(merge_head_file, O_RDONLY);2230if(merge_head <0) {2231if(errno == ENOENT)2232return;2233die("cannot open '%s' for reading", merge_head_file);2234}22352236while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2237unsigned char sha1[20];2238if(line.len <40||get_sha1_hex(line.buf, sha1))2239die("unknown line in '%s':%s", merge_head_file, line.buf);2240 tail =append_parent(tail, sha1);2241}2242close(merge_head);2243strbuf_release(&line);2244}22452246/*2247 * This isn't as simple as passing sb->buf and sb->len, because we2248 * want to transfer ownership of the buffer to the commit (so we2249 * must use detach).2250 */2251static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2252{2253size_t len;2254void*buf =strbuf_detach(sb, &len);2255set_commit_buffer(c, buf, len);2256}22572258/*2259 * Prepare a dummy commit that represents the work tree (or staged) item.2260 * Note that annotating work tree item never works in the reverse.2261 */2262static struct commit *fake_working_tree_commit(struct diff_options *opt,2263const char*path,2264const char*contents_from)2265{2266struct commit *commit;2267struct origin *origin;2268struct commit_list **parent_tail, *parent;2269unsigned char head_sha1[20];2270struct strbuf buf = STRBUF_INIT;2271const char*ident;2272time_t now;2273int size, len;2274struct cache_entry *ce;2275unsigned mode;2276struct strbuf msg = STRBUF_INIT;22772278time(&now);2279 commit =alloc_commit_node();2280 commit->object.parsed =1;2281 commit->date = now;2282 parent_tail = &commit->parents;22832284if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2285die("no such ref: HEAD");22862287 parent_tail =append_parent(parent_tail, head_sha1);2288append_merge_parents(parent_tail);2289verify_working_tree_path(commit, path);22902291 origin =make_origin(commit, path);22922293 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2294strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2295for(parent = commit->parents; parent; parent = parent->next)2296strbuf_addf(&msg,"parent%s\n",2297sha1_to_hex(parent->item->object.sha1));2298strbuf_addf(&msg,2299"author%s\n"2300"committer%s\n\n"2301"Version of%sfrom%s\n",2302 ident, ident, path,2303(!contents_from ? path :2304(!strcmp(contents_from,"-") ?"standard input": contents_from)));2305set_commit_buffer_from_strbuf(commit, &msg);23062307if(!contents_from ||strcmp("-", contents_from)) {2308struct stat st;2309const char*read_from;2310char*buf_ptr;2311unsigned long buf_len;23122313if(contents_from) {2314if(stat(contents_from, &st) <0)2315die_errno("Cannot stat '%s'", contents_from);2316 read_from = contents_from;2317}2318else{2319if(lstat(path, &st) <0)2320die_errno("Cannot lstat '%s'", path);2321 read_from = path;2322}2323 mode =canon_mode(st.st_mode);23242325switch(st.st_mode & S_IFMT) {2326case S_IFREG:2327if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2328textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2329strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2330else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2331die_errno("cannot open or read '%s'", read_from);2332break;2333case S_IFLNK:2334if(strbuf_readlink(&buf, read_from, st.st_size) <0)2335die_errno("cannot readlink '%s'", read_from);2336break;2337default:2338die("unsupported file type%s", read_from);2339}2340}2341else{2342/* Reading from stdin */2343 mode =0;2344if(strbuf_read(&buf,0,0) <0)2345die_errno("failed to read from stdin");2346}2347convert_to_git(path, buf.buf, buf.len, &buf,0);2348 origin->file.ptr = buf.buf;2349 origin->file.size = buf.len;2350pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23512352/*2353 * Read the current index, replace the path entry with2354 * origin->blob_sha1 without mucking with its mode or type2355 * bits; we are not going to write this index out -- we just2356 * want to run "diff-index --cached".2357 */2358discard_cache();2359read_cache();23602361 len =strlen(path);2362if(!mode) {2363int pos =cache_name_pos(path, len);2364if(0<= pos)2365 mode = active_cache[pos]->ce_mode;2366else2367/* Let's not bother reading from HEAD tree */2368 mode = S_IFREG |0644;2369}2370 size =cache_entry_size(len);2371 ce =xcalloc(1, size);2372hashcpy(ce->sha1, origin->blob_sha1);2373memcpy(ce->name, path, len);2374 ce->ce_flags =create_ce_flags(0);2375 ce->ce_namelen = len;2376 ce->ce_mode =create_ce_mode(mode);2377add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23782379/*2380 * We are not going to write this out, so this does not matter2381 * right now, but someday we might optimize diff-index --cached2382 * with cache-tree information.2383 */2384cache_tree_invalidate_path(&the_index, path);23852386return commit;2387}23882389static char*prepare_final(struct scoreboard *sb)2390{2391int i;2392const char*final_commit_name = NULL;2393struct rev_info *revs = sb->revs;23942395/*2396 * There must be one and only one positive commit in the2397 * revs->pending array.2398 */2399for(i =0; i < revs->pending.nr; i++) {2400struct object *obj = revs->pending.objects[i].item;2401if(obj->flags & UNINTERESTING)2402continue;2403while(obj->type == OBJ_TAG)2404 obj =deref_tag(obj, NULL,0);2405if(obj->type != OBJ_COMMIT)2406die("Non commit%s?", revs->pending.objects[i].name);2407if(sb->final)2408die("More than one commit to dig from%sand%s?",2409 revs->pending.objects[i].name,2410 final_commit_name);2411 sb->final = (struct commit *) obj;2412 final_commit_name = revs->pending.objects[i].name;2413}2414returnxstrdup_or_null(final_commit_name);2415}24162417static char*prepare_initial(struct scoreboard *sb)2418{2419int i;2420const char*final_commit_name = NULL;2421struct rev_info *revs = sb->revs;24222423/*2424 * There must be one and only one negative commit, and it must be2425 * the boundary.2426 */2427for(i =0; i < revs->pending.nr; i++) {2428struct object *obj = revs->pending.objects[i].item;2429if(!(obj->flags & UNINTERESTING))2430continue;2431while(obj->type == OBJ_TAG)2432 obj =deref_tag(obj, NULL,0);2433if(obj->type != OBJ_COMMIT)2434die("Non commit%s?", revs->pending.objects[i].name);2435if(sb->final)2436die("More than one commit to dig down to%sand%s?",2437 revs->pending.objects[i].name,2438 final_commit_name);2439 sb->final = (struct commit *) obj;2440 final_commit_name = revs->pending.objects[i].name;2441}2442if(!final_commit_name)2443die("No commit to dig down to?");2444returnxstrdup(final_commit_name);2445}24462447static intblame_copy_callback(const struct option *option,const char*arg,int unset)2448{2449int*opt = option->value;24502451/*2452 * -C enables copy from removed files;2453 * -C -C enables copy from existing files, but only2454 * when blaming a new file;2455 * -C -C -C enables copy from existing files for2456 * everybody2457 */2458if(*opt & PICKAXE_BLAME_COPY_HARDER)2459*opt |= PICKAXE_BLAME_COPY_HARDEST;2460if(*opt & PICKAXE_BLAME_COPY)2461*opt |= PICKAXE_BLAME_COPY_HARDER;2462*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;24632464if(arg)2465 blame_copy_score =parse_score(arg);2466return0;2467}24682469static intblame_move_callback(const struct option *option,const char*arg,int unset)2470{2471int*opt = option->value;24722473*opt |= PICKAXE_BLAME_MOVE;24742475if(arg)2476 blame_move_score =parse_score(arg);2477return0;2478}24792480intcmd_blame(int argc,const char**argv,const char*prefix)2481{2482struct rev_info revs;2483const char*path;2484struct scoreboard sb;2485struct origin *o;2486struct blame_entry *ent = NULL;2487long dashdash_pos, lno;2488char*final_commit_name = NULL;2489enum object_type type;24902491static struct string_list range_list;2492static int output_option =0, opt =0;2493static int show_stats =0;2494static const char*revs_file = NULL;2495static const char*contents_from = NULL;2496static const struct option options[] = {2497OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2498OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2499OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2500OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2501OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2502OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2503OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2504OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2505OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2506OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2507OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2508OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2509OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2510OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2511OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2512OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2513OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2514OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2515{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2516{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2517OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2518OPT__ABBREV(&abbrev),2519OPT_END()2520};25212522struct parse_opt_ctx_t ctx;2523int cmd_is_annotate = !strcmp(argv[0],"annotate");2524struct range_set ranges;2525unsigned int range_i;2526long anchor;25272528git_config(git_blame_config, NULL);2529init_revisions(&revs, NULL);2530 revs.date_mode = blame_date_mode;2531DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2532DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25332534 save_commit_buffer =0;2535 dashdash_pos =0;25362537parse_options_start(&ctx, argc, argv, prefix, options,2538 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2539for(;;) {2540switch(parse_options_step(&ctx, options, blame_opt_usage)) {2541case PARSE_OPT_HELP:2542exit(129);2543case PARSE_OPT_DONE:2544if(ctx.argv[0])2545 dashdash_pos = ctx.cpidx;2546goto parse_done;2547}25482549if(!strcmp(ctx.argv[0],"--reverse")) {2550 ctx.argv[0] ="--children";2551 reverse =1;2552}2553parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2554}2555parse_done:2556 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2557DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2558 argc =parse_options_end(&ctx);25592560if(0< abbrev)2561/* one more abbrev length is needed for the boundary commit */2562 abbrev++;25632564if(revs_file &&read_ancestry(revs_file))2565die_errno("reading graft file '%s' failed", revs_file);25662567if(cmd_is_annotate) {2568 output_option |= OUTPUT_ANNOTATE_COMPAT;2569 blame_date_mode = DATE_ISO8601;2570}else{2571 blame_date_mode = revs.date_mode;2572}25732574/* The maximum width used to show the dates */2575switch(blame_date_mode) {2576case DATE_RFC2822:2577 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2578break;2579case DATE_ISO8601_STRICT:2580 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2581break;2582case DATE_ISO8601:2583 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2584break;2585case DATE_RAW:2586 blame_date_width =sizeof("1161298804 -0700");2587break;2588case DATE_SHORT:2589 blame_date_width =sizeof("2006-10-19");2590break;2591case DATE_RELATIVE:2592/* TRANSLATORS: This string is used to tell us the maximum2593 display width for a relative timestamp in "git blame"2594 output. For C locale, "4 years, 11 months ago", which2595 takes 22 places, is the longest among various forms of2596 relative timestamps, but your language may need more or2597 fewer display columns. */2598 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2599break;2600case DATE_LOCAL:2601case DATE_NORMAL:2602 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2603break;2604}2605 blame_date_width -=1;/* strip the null */26062607if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2608 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2609 PICKAXE_BLAME_COPY_HARDER);26102611if(!blame_move_score)2612 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2613if(!blame_copy_score)2614 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26152616/*2617 * We have collected options unknown to us in argv[1..unk]2618 * which are to be passed to revision machinery if we are2619 * going to do the "bottom" processing.2620 *2621 * The remaining are:2622 *2623 * (1) if dashdash_pos != 0, it is either2624 * "blame [revisions] -- <path>" or2625 * "blame -- <path> <rev>"2626 *2627 * (2) otherwise, it is one of the two:2628 * "blame [revisions] <path>"2629 * "blame <path> <rev>"2630 *2631 * Note that we must strip out <path> from the arguments: we do not2632 * want the path pruning but we may want "bottom" processing.2633 */2634if(dashdash_pos) {2635switch(argc - dashdash_pos -1) {2636case2:/* (1b) */2637if(argc !=4)2638usage_with_options(blame_opt_usage, options);2639/* reorder for the new way: <rev> -- <path> */2640 argv[1] = argv[3];2641 argv[3] = argv[2];2642 argv[2] ="--";2643/* FALLTHROUGH */2644case1:/* (1a) */2645 path =add_prefix(prefix, argv[--argc]);2646 argv[argc] = NULL;2647break;2648default:2649usage_with_options(blame_opt_usage, options);2650}2651}else{2652if(argc <2)2653usage_with_options(blame_opt_usage, options);2654 path =add_prefix(prefix, argv[argc -1]);2655if(argc ==3&& !file_exists(path)) {/* (2b) */2656 path =add_prefix(prefix, argv[1]);2657 argv[1] = argv[2];2658}2659 argv[argc -1] ="--";26602661setup_work_tree();2662if(!file_exists(path))2663die_errno("cannot stat path '%s'", path);2664}26652666 revs.disable_stdin =1;2667setup_revisions(argc, argv, &revs, NULL);2668memset(&sb,0,sizeof(sb));26692670 sb.revs = &revs;2671if(!reverse) {2672 final_commit_name =prepare_final(&sb);2673 sb.commits.compare = compare_commits_by_commit_date;2674}2675else if(contents_from)2676die("--contents and --children do not blend well.");2677else{2678 final_commit_name =prepare_initial(&sb);2679 sb.commits.compare = compare_commits_by_reverse_commit_date;2680}26812682if(!sb.final) {2683/*2684 * "--not A B -- path" without anything positive;2685 * do not default to HEAD, but use the working tree2686 * or "--contents".2687 */2688setup_work_tree();2689 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2690 path, contents_from);2691add_pending_object(&revs, &(sb.final->object),":");2692}2693else if(contents_from)2694die("Cannot use --contents with final commit object name");26952696/*2697 * If we have bottom, this will mark the ancestors of the2698 * bottom commits we would reach while traversing as2699 * uninteresting.2700 */2701if(prepare_revision_walk(&revs))2702die(_("revision walk setup failed"));27032704if(is_null_sha1(sb.final->object.sha1)) {2705 o = sb.final->util;2706 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2707 sb.final_buf_size = o->file.size;2708}2709else{2710 o =get_origin(&sb, sb.final, path);2711if(fill_blob_sha1_and_mode(o))2712die("no such path%sin%s", path, final_commit_name);27132714if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2715textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2716&sb.final_buf_size))2717;2718else2719 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2720&sb.final_buf_size);27212722if(!sb.final_buf)2723die("Cannot read blob%sfor path%s",2724sha1_to_hex(o->blob_sha1),2725 path);2726}2727 num_read_blob++;2728 lno =prepare_lines(&sb);27292730if(lno && !range_list.nr)2731string_list_append(&range_list,xstrdup("1"));27322733 anchor =1;2734range_set_init(&ranges, range_list.nr);2735for(range_i =0; range_i < range_list.nr; ++range_i) {2736long bottom, top;2737if(parse_range_arg(range_list.items[range_i].string,2738 nth_line_cb, &sb, lno, anchor,2739&bottom, &top, sb.path))2740usage(blame_usage);2741if(lno < top || ((lno || bottom) && lno < bottom))2742die("file%shas only%lu lines", path, lno);2743if(bottom <1)2744 bottom =1;2745if(top <1)2746 top = lno;2747 bottom--;2748range_set_append_unsafe(&ranges, bottom, top);2749 anchor = top +1;2750}2751sort_and_merge_range_set(&ranges);27522753for(range_i = ranges.nr; range_i >0; --range_i) {2754const struct range *r = &ranges.ranges[range_i -1];2755long bottom = r->start;2756long top = r->end;2757struct blame_entry *next = ent;2758 ent =xcalloc(1,sizeof(*ent));2759 ent->lno = bottom;2760 ent->num_lines = top - bottom;2761 ent->suspect = o;2762 ent->s_lno = bottom;2763 ent->next = next;2764origin_incref(o);2765}27662767 o->suspects = ent;2768prio_queue_put(&sb.commits, o->commit);27692770origin_decref(o);27712772range_set_release(&ranges);2773string_list_clear(&range_list,0);27742775 sb.ent = NULL;2776 sb.path = path;27772778read_mailmap(&mailmap, NULL);27792780if(!incremental)2781setup_pager();27822783assign_blame(&sb, opt);27842785free(final_commit_name);27862787if(incremental)2788return0;27892790 sb.ent =blame_sort(sb.ent, compare_blame_final);27912792coalesce(&sb);27932794if(!(output_option & OUTPUT_PORCELAIN))2795find_alignment(&sb, &output_option);27962797output(&sb, output_option);2798free((void*)sb.final_buf);2799for(ent = sb.ent; ent; ) {2800struct blame_entry *e = ent->next;2801free(ent);2802 ent = e;2803}28042805if(show_stats) {2806printf("num read blob:%d\n", num_read_blob);2807printf("num get patch:%d\n", num_get_patch);2808printf("num commits:%d\n", num_commits);2809}2810return0;2811}