1/* 2 * Blame 3 * 4 * Copyright (c) 2006, 2014 by its authors 5 * See COPYING for licensing conditions 6 */ 7 8#include"cache.h" 9#include"refs.h" 10#include"builtin.h" 11#include"blob.h" 12#include"commit.h" 13#include"tag.h" 14#include"tree-walk.h" 15#include"diff.h" 16#include"diffcore.h" 17#include"revision.h" 18#include"quote.h" 19#include"xdiff-interface.h" 20#include"cache-tree.h" 21#include"string-list.h" 22#include"mailmap.h" 23#include"mergesort.h" 24#include"parse-options.h" 25#include"prio-queue.h" 26#include"utf8.h" 27#include"userdiff.h" 28#include"line-range.h" 29#include"line-log.h" 30#include"dir.h" 31 32static char blame_usage[] =N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>"); 33 34static const char*blame_opt_usage[] = { 35 blame_usage, 36"", 37N_("<rev-opts> are documented in git-rev-list(1)"), 38 NULL 39}; 40 41static int longest_file; 42static int longest_author; 43static int max_orig_digits; 44static int max_digits; 45static int max_score_digits; 46static int show_root; 47static int reverse; 48static int blank_boundary; 49static int incremental; 50static int xdl_opts; 51static int abbrev = -1; 52static int no_whole_file_rename; 53 54static struct date_mode blame_date_mode = { DATE_ISO8601 }; 55static size_t blame_date_width; 56 57static struct string_list mailmap; 58 59#ifndef DEBUG 60#define DEBUG 0 61#endif 62 63/* stats */ 64static int num_read_blob; 65static int num_get_patch; 66static int num_commits; 67 68#define PICKAXE_BLAME_MOVE 01 69#define PICKAXE_BLAME_COPY 02 70#define PICKAXE_BLAME_COPY_HARDER 04 71#define PICKAXE_BLAME_COPY_HARDEST 010 72 73/* 74 * blame for a blame_entry with score lower than these thresholds 75 * is not passed to the parent using move/copy logic. 76 */ 77static unsigned blame_move_score; 78static unsigned blame_copy_score; 79#define BLAME_DEFAULT_MOVE_SCORE 20 80#define BLAME_DEFAULT_COPY_SCORE 40 81 82/* Remember to update object flag allocation in object.h */ 83#define METAINFO_SHOWN (1u<<12) 84#define MORE_THAN_ONE_PATH (1u<<13) 85 86/* 87 * One blob in a commit that is being suspected 88 */ 89struct origin { 90int refcnt; 91/* Record preceding blame record for this blob */ 92struct origin *previous; 93/* origins are put in a list linked via `next' hanging off the 94 * corresponding commit's util field in order to make finding 95 * them fast. The presence in this chain does not count 96 * towards the origin's reference count. It is tempting to 97 * let it count as long as the commit is pending examination, 98 * but even under circumstances where the commit will be 99 * present multiple times in the priority queue of unexamined 100 * commits, processing the first instance will not leave any 101 * work requiring the origin data for the second instance. An 102 * interspersed commit changing that would have to be 103 * preexisting with a different ancestry and with the same 104 * commit date in order to wedge itself between two instances 105 * of the same commit in the priority queue _and_ produce 106 * blame entries relevant for it. While we don't want to let 107 * us get tripped up by this case, it certainly does not seem 108 * worth optimizing for. 109 */ 110struct origin *next; 111struct commit *commit; 112/* `suspects' contains blame entries that may be attributed to 113 * this origin's commit or to parent commits. When a commit 114 * is being processed, all suspects will be moved, either by 115 * assigning them to an origin in a different commit, or by 116 * shipping them to the scoreboard's ent list because they 117 * cannot be attributed to a different commit. 118 */ 119struct blame_entry *suspects; 120 mmfile_t file; 121unsigned char blob_sha1[20]; 122unsigned mode; 123/* guilty gets set when shipping any suspects to the final 124 * blame list instead of other commits 125 */ 126char guilty; 127char path[FLEX_ARRAY]; 128}; 129 130static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b,long ctxlen, 131 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data) 132{ 133 xpparam_t xpp = {0}; 134 xdemitconf_t xecfg = {0}; 135 xdemitcb_t ecb = {NULL}; 136 137 xpp.flags = xdl_opts; 138 xecfg.ctxlen = ctxlen; 139 xecfg.hunk_func = hunk_func; 140 ecb.priv = cb_data; 141returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 142} 143 144/* 145 * Prepare diff_filespec and convert it using diff textconv API 146 * if the textconv driver exists. 147 * Return 1 if the conversion succeeds, 0 otherwise. 148 */ 149inttextconv_object(const char*path, 150unsigned mode, 151const unsigned char*sha1, 152int sha1_valid, 153char**buf, 154unsigned long*buf_size) 155{ 156struct diff_filespec *df; 157struct userdiff_driver *textconv; 158 159 df =alloc_filespec(path); 160fill_filespec(df, sha1, sha1_valid, mode); 161 textconv =get_textconv(df); 162if(!textconv) { 163free_filespec(df); 164return0; 165} 166 167*buf_size =fill_textconv(textconv, df, buf); 168free_filespec(df); 169return1; 170} 171 172/* 173 * Given an origin, prepare mmfile_t structure to be used by the 174 * diff machinery 175 */ 176static voidfill_origin_blob(struct diff_options *opt, 177struct origin *o, mmfile_t *file) 178{ 179if(!o->file.ptr) { 180enum object_type type; 181unsigned long file_size; 182 183 num_read_blob++; 184if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) && 185textconv_object(o->path, o->mode, o->blob_sha1,1, &file->ptr, &file_size)) 186; 187else 188 file->ptr =read_sha1_file(o->blob_sha1, &type, &file_size); 189 file->size = file_size; 190 191if(!file->ptr) 192die("Cannot read blob%sfor path%s", 193sha1_to_hex(o->blob_sha1), 194 o->path); 195 o->file = *file; 196} 197else 198*file = o->file; 199} 200 201/* 202 * Origin is refcounted and usually we keep the blob contents to be 203 * reused. 204 */ 205staticinlinestruct origin *origin_incref(struct origin *o) 206{ 207if(o) 208 o->refcnt++; 209return o; 210} 211 212static voidorigin_decref(struct origin *o) 213{ 214if(o && --o->refcnt <=0) { 215struct origin *p, *l = NULL; 216if(o->previous) 217origin_decref(o->previous); 218free(o->file.ptr); 219/* Should be present exactly once in commit chain */ 220for(p = o->commit->util; p; l = p, p = p->next) { 221if(p == o) { 222if(l) 223 l->next = p->next; 224else 225 o->commit->util = p->next; 226free(o); 227return; 228} 229} 230die("internal error in blame::origin_decref"); 231} 232} 233 234static voiddrop_origin_blob(struct origin *o) 235{ 236if(o->file.ptr) { 237free(o->file.ptr); 238 o->file.ptr = NULL; 239} 240} 241 242/* 243 * Each group of lines is described by a blame_entry; it can be split 244 * as we pass blame to the parents. They are arranged in linked lists 245 * kept as `suspects' of some unprocessed origin, or entered (when the 246 * blame origin has been finalized) into the scoreboard structure. 247 * While the scoreboard structure is only sorted at the end of 248 * processing (according to final image line number), the lists 249 * attached to an origin are sorted by the target line number. 250 */ 251struct blame_entry { 252struct blame_entry *next; 253 254/* the first line of this group in the final image; 255 * internally all line numbers are 0 based. 256 */ 257int lno; 258 259/* how many lines this group has */ 260int num_lines; 261 262/* the commit that introduced this group into the final image */ 263struct origin *suspect; 264 265/* the line number of the first line of this group in the 266 * suspect's file; internally all line numbers are 0 based. 267 */ 268int s_lno; 269 270/* how significant this entry is -- cached to avoid 271 * scanning the lines over and over. 272 */ 273unsigned score; 274}; 275 276/* 277 * Any merge of blames happens on lists of blames that arrived via 278 * different parents in a single suspect. In this case, we want to 279 * sort according to the suspect line numbers as opposed to the final 280 * image line numbers. The function body is somewhat longish because 281 * it avoids unnecessary writes. 282 */ 283 284static struct blame_entry *blame_merge(struct blame_entry *list1, 285struct blame_entry *list2) 286{ 287struct blame_entry *p1 = list1, *p2 = list2, 288**tail = &list1; 289 290if(!p1) 291return p2; 292if(!p2) 293return p1; 294 295if(p1->s_lno <= p2->s_lno) { 296do{ 297 tail = &p1->next; 298if((p1 = *tail) == NULL) { 299*tail = p2; 300return list1; 301} 302}while(p1->s_lno <= p2->s_lno); 303} 304for(;;) { 305*tail = p2; 306do{ 307 tail = &p2->next; 308if((p2 = *tail) == NULL) { 309*tail = p1; 310return list1; 311} 312}while(p1->s_lno > p2->s_lno); 313*tail = p1; 314do{ 315 tail = &p1->next; 316if((p1 = *tail) == NULL) { 317*tail = p2; 318return list1; 319} 320}while(p1->s_lno <= p2->s_lno); 321} 322} 323 324static void*get_next_blame(const void*p) 325{ 326return((struct blame_entry *)p)->next; 327} 328 329static voidset_next_blame(void*p1,void*p2) 330{ 331((struct blame_entry *)p1)->next = p2; 332} 333 334/* 335 * Final image line numbers are all different, so we don't need a 336 * three-way comparison here. 337 */ 338 339static intcompare_blame_final(const void*p1,const void*p2) 340{ 341return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno 342?1: -1; 343} 344 345static intcompare_blame_suspect(const void*p1,const void*p2) 346{ 347const struct blame_entry *s1 = p1, *s2 = p2; 348/* 349 * to allow for collating suspects, we sort according to the 350 * respective pointer value as the primary sorting criterion. 351 * The actual relation is pretty unimportant as long as it 352 * establishes a total order. Comparing as integers gives us 353 * that. 354 */ 355if(s1->suspect != s2->suspect) 356return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1; 357if(s1->s_lno == s2->s_lno) 358return0; 359return s1->s_lno > s2->s_lno ?1: -1; 360} 361 362static struct blame_entry *blame_sort(struct blame_entry *head, 363int(*compare_fn)(const void*,const void*)) 364{ 365returnllist_mergesort(head, get_next_blame, set_next_blame, compare_fn); 366} 367 368static intcompare_commits_by_reverse_commit_date(const void*a, 369const void*b, 370void*c) 371{ 372return-compare_commits_by_commit_date(a, b, c); 373} 374 375/* 376 * The current state of the blame assignment. 377 */ 378struct scoreboard { 379/* the final commit (i.e. where we started digging from) */ 380struct commit *final; 381/* Priority queue for commits with unassigned blame records */ 382struct prio_queue commits; 383struct rev_info *revs; 384const char*path; 385 386/* 387 * The contents in the final image. 388 * Used by many functions to obtain contents of the nth line, 389 * indexed with scoreboard.lineno[blame_entry.lno]. 390 */ 391const char*final_buf; 392unsigned long final_buf_size; 393 394/* linked list of blames */ 395struct blame_entry *ent; 396 397/* look-up a line in the final buffer */ 398int num_lines; 399int*lineno; 400}; 401 402static voidsanity_check_refcnt(struct scoreboard *); 403 404/* 405 * If two blame entries that are next to each other came from 406 * contiguous lines in the same origin (i.e. <commit, path> pair), 407 * merge them together. 408 */ 409static voidcoalesce(struct scoreboard *sb) 410{ 411struct blame_entry *ent, *next; 412 413for(ent = sb->ent; ent && (next = ent->next); ent = next) { 414if(ent->suspect == next->suspect && 415 ent->s_lno + ent->num_lines == next->s_lno) { 416 ent->num_lines += next->num_lines; 417 ent->next = next->next; 418origin_decref(next->suspect); 419free(next); 420 ent->score =0; 421 next = ent;/* again */ 422} 423} 424 425if(DEBUG)/* sanity */ 426sanity_check_refcnt(sb); 427} 428 429/* 430 * Merge the given sorted list of blames into a preexisting origin. 431 * If there were no previous blames to that commit, it is entered into 432 * the commit priority queue of the score board. 433 */ 434 435static voidqueue_blames(struct scoreboard *sb,struct origin *porigin, 436struct blame_entry *sorted) 437{ 438if(porigin->suspects) 439 porigin->suspects =blame_merge(porigin->suspects, sorted); 440else{ 441struct origin *o; 442for(o = porigin->commit->util; o; o = o->next) { 443if(o->suspects) { 444 porigin->suspects = sorted; 445return; 446} 447} 448 porigin->suspects = sorted; 449prio_queue_put(&sb->commits, porigin->commit); 450} 451} 452 453/* 454 * Given a commit and a path in it, create a new origin structure. 455 * The callers that add blame to the scoreboard should use 456 * get_origin() to obtain shared, refcounted copy instead of calling 457 * this function directly. 458 */ 459static struct origin *make_origin(struct commit *commit,const char*path) 460{ 461struct origin *o; 462size_t pathlen =strlen(path) +1; 463 o =xcalloc(1,sizeof(*o) + pathlen); 464 o->commit = commit; 465 o->refcnt =1; 466 o->next = commit->util; 467 commit->util = o; 468memcpy(o->path, path, pathlen);/* includes NUL */ 469return o; 470} 471 472/* 473 * Locate an existing origin or create a new one. 474 * This moves the origin to front position in the commit util list. 475 */ 476static struct origin *get_origin(struct scoreboard *sb, 477struct commit *commit, 478const char*path) 479{ 480struct origin *o, *l; 481 482for(o = commit->util, l = NULL; o; l = o, o = o->next) { 483if(!strcmp(o->path, path)) { 484/* bump to front */ 485if(l) { 486 l->next = o->next; 487 o->next = commit->util; 488 commit->util = o; 489} 490returnorigin_incref(o); 491} 492} 493returnmake_origin(commit, path); 494} 495 496/* 497 * Fill the blob_sha1 field of an origin if it hasn't, so that later 498 * call to fill_origin_blob() can use it to locate the data. blob_sha1 499 * for an origin is also used to pass the blame for the entire file to 500 * the parent to detect the case where a child's blob is identical to 501 * that of its parent's. 502 * 503 * This also fills origin->mode for corresponding tree path. 504 */ 505static intfill_blob_sha1_and_mode(struct origin *origin) 506{ 507if(!is_null_sha1(origin->blob_sha1)) 508return0; 509if(get_tree_entry(get_object_hash(origin->commit->object), 510 origin->path, 511 origin->blob_sha1, &origin->mode)) 512goto error_out; 513if(sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB) 514goto error_out; 515return0; 516 error_out: 517hashclr(origin->blob_sha1); 518 origin->mode = S_IFINVALID; 519return-1; 520} 521 522/* 523 * We have an origin -- check if the same path exists in the 524 * parent and return an origin structure to represent it. 525 */ 526static struct origin *find_origin(struct scoreboard *sb, 527struct commit *parent, 528struct origin *origin) 529{ 530struct origin *porigin; 531struct diff_options diff_opts; 532const char*paths[2]; 533 534/* First check any existing origins */ 535for(porigin = parent->util; porigin; porigin = porigin->next) 536if(!strcmp(porigin->path, origin->path)) { 537/* 538 * The same path between origin and its parent 539 * without renaming -- the most common case. 540 */ 541returnorigin_incref(porigin); 542} 543 544/* See if the origin->path is different between parent 545 * and origin first. Most of the time they are the 546 * same and diff-tree is fairly efficient about this. 547 */ 548diff_setup(&diff_opts); 549DIFF_OPT_SET(&diff_opts, RECURSIVE); 550 diff_opts.detect_rename =0; 551 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 552 paths[0] = origin->path; 553 paths[1] = NULL; 554 555parse_pathspec(&diff_opts.pathspec, 556 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL, 557 PATHSPEC_LITERAL_PATH,"", paths); 558diff_setup_done(&diff_opts); 559 560if(is_null_oid(&origin->commit->object.oid)) 561do_diff_cache(get_object_hash(parent->tree->object), &diff_opts); 562else 563diff_tree_sha1(get_object_hash(parent->tree->object), 564get_object_hash(origin->commit->tree->object), 565"", &diff_opts); 566diffcore_std(&diff_opts); 567 568if(!diff_queued_diff.nr) { 569/* The path is the same as parent */ 570 porigin =get_origin(sb, parent, origin->path); 571hashcpy(porigin->blob_sha1, origin->blob_sha1); 572 porigin->mode = origin->mode; 573}else{ 574/* 575 * Since origin->path is a pathspec, if the parent 576 * commit had it as a directory, we will see a whole 577 * bunch of deletion of files in the directory that we 578 * do not care about. 579 */ 580int i; 581struct diff_filepair *p = NULL; 582for(i =0; i < diff_queued_diff.nr; i++) { 583const char*name; 584 p = diff_queued_diff.queue[i]; 585 name = p->one->path ? p->one->path : p->two->path; 586if(!strcmp(name, origin->path)) 587break; 588} 589if(!p) 590die("internal error in blame::find_origin"); 591switch(p->status) { 592default: 593die("internal error in blame::find_origin (%c)", 594 p->status); 595case'M': 596 porigin =get_origin(sb, parent, origin->path); 597hashcpy(porigin->blob_sha1, p->one->sha1); 598 porigin->mode = p->one->mode; 599break; 600case'A': 601case'T': 602/* Did not exist in parent, or type changed */ 603break; 604} 605} 606diff_flush(&diff_opts); 607free_pathspec(&diff_opts.pathspec); 608return porigin; 609} 610 611/* 612 * We have an origin -- find the path that corresponds to it in its 613 * parent and return an origin structure to represent it. 614 */ 615static struct origin *find_rename(struct scoreboard *sb, 616struct commit *parent, 617struct origin *origin) 618{ 619struct origin *porigin = NULL; 620struct diff_options diff_opts; 621int i; 622 623diff_setup(&diff_opts); 624DIFF_OPT_SET(&diff_opts, RECURSIVE); 625 diff_opts.detect_rename = DIFF_DETECT_RENAME; 626 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 627 diff_opts.single_follow = origin->path; 628diff_setup_done(&diff_opts); 629 630if(is_null_oid(&origin->commit->object.oid)) 631do_diff_cache(get_object_hash(parent->tree->object), &diff_opts); 632else 633diff_tree_sha1(get_object_hash(parent->tree->object), 634get_object_hash(origin->commit->tree->object), 635"", &diff_opts); 636diffcore_std(&diff_opts); 637 638for(i =0; i < diff_queued_diff.nr; i++) { 639struct diff_filepair *p = diff_queued_diff.queue[i]; 640if((p->status =='R'|| p->status =='C') && 641!strcmp(p->two->path, origin->path)) { 642 porigin =get_origin(sb, parent, p->one->path); 643hashcpy(porigin->blob_sha1, p->one->sha1); 644 porigin->mode = p->one->mode; 645break; 646} 647} 648diff_flush(&diff_opts); 649free_pathspec(&diff_opts.pathspec); 650return porigin; 651} 652 653/* 654 * Append a new blame entry to a given output queue. 655 */ 656static voidadd_blame_entry(struct blame_entry ***queue,struct blame_entry *e) 657{ 658origin_incref(e->suspect); 659 660 e->next = **queue; 661**queue = e; 662*queue = &e->next; 663} 664 665/* 666 * src typically is on-stack; we want to copy the information in it to 667 * a malloced blame_entry that gets added to the given queue. The 668 * origin of dst loses a refcnt. 669 */ 670static voiddup_entry(struct blame_entry ***queue, 671struct blame_entry *dst,struct blame_entry *src) 672{ 673origin_incref(src->suspect); 674origin_decref(dst->suspect); 675memcpy(dst, src,sizeof(*src)); 676 dst->next = **queue; 677**queue = dst; 678*queue = &dst->next; 679} 680 681static const char*nth_line(struct scoreboard *sb,long lno) 682{ 683return sb->final_buf + sb->lineno[lno]; 684} 685 686static const char*nth_line_cb(void*data,long lno) 687{ 688returnnth_line((struct scoreboard *)data, lno); 689} 690 691/* 692 * It is known that lines between tlno to same came from parent, and e 693 * has an overlap with that range. it also is known that parent's 694 * line plno corresponds to e's line tlno. 695 * 696 * <---- e -----> 697 * <------> 698 * <------------> 699 * <------------> 700 * <------------------> 701 * 702 * Split e into potentially three parts; before this chunk, the chunk 703 * to be blamed for the parent, and after that portion. 704 */ 705static voidsplit_overlap(struct blame_entry *split, 706struct blame_entry *e, 707int tlno,int plno,int same, 708struct origin *parent) 709{ 710int chunk_end_lno; 711memset(split,0,sizeof(struct blame_entry [3])); 712 713if(e->s_lno < tlno) { 714/* there is a pre-chunk part not blamed on parent */ 715 split[0].suspect =origin_incref(e->suspect); 716 split[0].lno = e->lno; 717 split[0].s_lno = e->s_lno; 718 split[0].num_lines = tlno - e->s_lno; 719 split[1].lno = e->lno + tlno - e->s_lno; 720 split[1].s_lno = plno; 721} 722else{ 723 split[1].lno = e->lno; 724 split[1].s_lno = plno + (e->s_lno - tlno); 725} 726 727if(same < e->s_lno + e->num_lines) { 728/* there is a post-chunk part not blamed on parent */ 729 split[2].suspect =origin_incref(e->suspect); 730 split[2].lno = e->lno + (same - e->s_lno); 731 split[2].s_lno = e->s_lno + (same - e->s_lno); 732 split[2].num_lines = e->s_lno + e->num_lines - same; 733 chunk_end_lno = split[2].lno; 734} 735else 736 chunk_end_lno = e->lno + e->num_lines; 737 split[1].num_lines = chunk_end_lno - split[1].lno; 738 739/* 740 * if it turns out there is nothing to blame the parent for, 741 * forget about the splitting. !split[1].suspect signals this. 742 */ 743if(split[1].num_lines <1) 744return; 745 split[1].suspect =origin_incref(parent); 746} 747 748/* 749 * split_overlap() divided an existing blame e into up to three parts 750 * in split. Any assigned blame is moved to queue to 751 * reflect the split. 752 */ 753static voidsplit_blame(struct blame_entry ***blamed, 754struct blame_entry ***unblamed, 755struct blame_entry *split, 756struct blame_entry *e) 757{ 758struct blame_entry *new_entry; 759 760if(split[0].suspect && split[2].suspect) { 761/* The first part (reuse storage for the existing entry e) */ 762dup_entry(unblamed, e, &split[0]); 763 764/* The last part -- me */ 765 new_entry =xmalloc(sizeof(*new_entry)); 766memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 767add_blame_entry(unblamed, new_entry); 768 769/* ... and the middle part -- parent */ 770 new_entry =xmalloc(sizeof(*new_entry)); 771memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 772add_blame_entry(blamed, new_entry); 773} 774else if(!split[0].suspect && !split[2].suspect) 775/* 776 * The parent covers the entire area; reuse storage for 777 * e and replace it with the parent. 778 */ 779dup_entry(blamed, e, &split[1]); 780else if(split[0].suspect) { 781/* me and then parent */ 782dup_entry(unblamed, e, &split[0]); 783 784 new_entry =xmalloc(sizeof(*new_entry)); 785memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 786add_blame_entry(blamed, new_entry); 787} 788else{ 789/* parent and then me */ 790dup_entry(blamed, e, &split[1]); 791 792 new_entry =xmalloc(sizeof(*new_entry)); 793memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 794add_blame_entry(unblamed, new_entry); 795} 796} 797 798/* 799 * After splitting the blame, the origins used by the 800 * on-stack blame_entry should lose one refcnt each. 801 */ 802static voiddecref_split(struct blame_entry *split) 803{ 804int i; 805 806for(i =0; i <3; i++) 807origin_decref(split[i].suspect); 808} 809 810/* 811 * reverse_blame reverses the list given in head, appending tail. 812 * That allows us to build lists in reverse order, then reverse them 813 * afterwards. This can be faster than building the list in proper 814 * order right away. The reason is that building in proper order 815 * requires writing a link in the _previous_ element, while building 816 * in reverse order just requires placing the list head into the 817 * _current_ element. 818 */ 819 820static struct blame_entry *reverse_blame(struct blame_entry *head, 821struct blame_entry *tail) 822{ 823while(head) { 824struct blame_entry *next = head->next; 825 head->next = tail; 826 tail = head; 827 head = next; 828} 829return tail; 830} 831 832/* 833 * Process one hunk from the patch between the current suspect for 834 * blame_entry e and its parent. This first blames any unfinished 835 * entries before the chunk (which is where target and parent start 836 * differing) on the parent, and then splits blame entries at the 837 * start and at the end of the difference region. Since use of -M and 838 * -C options may lead to overlapping/duplicate source line number 839 * ranges, all we can rely on from sorting/merging is the order of the 840 * first suspect line number. 841 */ 842static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq, 843int tlno,int offset,int same, 844struct origin *parent) 845{ 846struct blame_entry *e = **srcq; 847struct blame_entry *samep = NULL, *diffp = NULL; 848 849while(e && e->s_lno < tlno) { 850struct blame_entry *next = e->next; 851/* 852 * current record starts before differing portion. If 853 * it reaches into it, we need to split it up and 854 * examine the second part separately. 855 */ 856if(e->s_lno + e->num_lines > tlno) { 857/* Move second half to a new record */ 858int len = tlno - e->s_lno; 859struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 860 n->suspect = e->suspect; 861 n->lno = e->lno + len; 862 n->s_lno = e->s_lno + len; 863 n->num_lines = e->num_lines - len; 864 e->num_lines = len; 865 e->score =0; 866/* Push new record to diffp */ 867 n->next = diffp; 868 diffp = n; 869}else 870origin_decref(e->suspect); 871/* Pass blame for everything before the differing 872 * chunk to the parent */ 873 e->suspect =origin_incref(parent); 874 e->s_lno += offset; 875 e->next = samep; 876 samep = e; 877 e = next; 878} 879/* 880 * As we don't know how much of a common stretch after this 881 * diff will occur, the currently blamed parts are all that we 882 * can assign to the parent for now. 883 */ 884 885if(samep) { 886**dstq =reverse_blame(samep, **dstq); 887*dstq = &samep->next; 888} 889/* 890 * Prepend the split off portions: everything after e starts 891 * after the blameable portion. 892 */ 893 e =reverse_blame(diffp, e); 894 895/* 896 * Now retain records on the target while parts are different 897 * from the parent. 898 */ 899 samep = NULL; 900 diffp = NULL; 901while(e && e->s_lno < same) { 902struct blame_entry *next = e->next; 903 904/* 905 * If current record extends into sameness, need to split. 906 */ 907if(e->s_lno + e->num_lines > same) { 908/* 909 * Move second half to a new record to be 910 * processed by later chunks 911 */ 912int len = same - e->s_lno; 913struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry)); 914 n->suspect =origin_incref(e->suspect); 915 n->lno = e->lno + len; 916 n->s_lno = e->s_lno + len; 917 n->num_lines = e->num_lines - len; 918 e->num_lines = len; 919 e->score =0; 920/* Push new record to samep */ 921 n->next = samep; 922 samep = n; 923} 924 e->next = diffp; 925 diffp = e; 926 e = next; 927} 928**srcq =reverse_blame(diffp,reverse_blame(samep, e)); 929/* Move across elements that are in the unblamable portion */ 930if(diffp) 931*srcq = &diffp->next; 932} 933 934struct blame_chunk_cb_data { 935struct origin *parent; 936long offset; 937struct blame_entry **dstq; 938struct blame_entry **srcq; 939}; 940 941/* diff chunks are from parent to target */ 942static intblame_chunk_cb(long start_a,long count_a, 943long start_b,long count_b,void*data) 944{ 945struct blame_chunk_cb_data *d = data; 946if(start_a - start_b != d->offset) 947die("internal error in blame::blame_chunk_cb"); 948blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b, 949 start_b + count_b, d->parent); 950 d->offset = start_a + count_a - (start_b + count_b); 951return0; 952} 953 954/* 955 * We are looking at the origin 'target' and aiming to pass blame 956 * for the lines it is suspected to its parent. Run diff to find 957 * which lines came from parent and pass blame for them. 958 */ 959static voidpass_blame_to_parent(struct scoreboard *sb, 960struct origin *target, 961struct origin *parent) 962{ 963 mmfile_t file_p, file_o; 964struct blame_chunk_cb_data d; 965struct blame_entry *newdest = NULL; 966 967if(!target->suspects) 968return;/* nothing remains for this target */ 969 970 d.parent = parent; 971 d.offset =0; 972 d.dstq = &newdest; d.srcq = &target->suspects; 973 974fill_origin_blob(&sb->revs->diffopt, parent, &file_p); 975fill_origin_blob(&sb->revs->diffopt, target, &file_o); 976 num_get_patch++; 977 978if(diff_hunks(&file_p, &file_o,0, blame_chunk_cb, &d)) 979die("unable to generate diff (%s->%s)", 980oid_to_hex(&parent->commit->object.oid), 981oid_to_hex(&target->commit->object.oid)); 982/* The rest are the same as the parent */ 983blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent); 984*d.dstq = NULL; 985queue_blames(sb, parent, newdest); 986 987return; 988} 989 990/* 991 * The lines in blame_entry after splitting blames many times can become 992 * very small and trivial, and at some point it becomes pointless to 993 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 994 * ordinary C program, and it is not worth to say it was copied from 995 * totally unrelated file in the parent. 996 * 997 * Compute how trivial the lines in the blame_entry are. 998 */ 999static unsignedent_score(struct scoreboard *sb,struct blame_entry *e)1000{1001unsigned score;1002const char*cp, *ep;10031004if(e->score)1005return e->score;10061007 score =1;1008 cp =nth_line(sb, e->lno);1009 ep =nth_line(sb, e->lno + e->num_lines);1010while(cp < ep) {1011unsigned ch = *((unsigned char*)cp);1012if(isalnum(ch))1013 score++;1014 cp++;1015}1016 e->score = score;1017return score;1018}10191020/*1021 * best_so_far[] and this[] are both a split of an existing blame_entry1022 * that passes blame to the parent. Maintain best_so_far the best split1023 * so far, by comparing this and best_so_far and copying this into1024 * bst_so_far as needed.1025 */1026static voidcopy_split_if_better(struct scoreboard *sb,1027struct blame_entry *best_so_far,1028struct blame_entry *this)1029{1030int i;10311032if(!this[1].suspect)1033return;1034if(best_so_far[1].suspect) {1035if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1]))1036return;1037}10381039for(i =0; i <3; i++)1040origin_incref(this[i].suspect);1041decref_split(best_so_far);1042memcpy(best_so_far,this,sizeof(struct blame_entry [3]));1043}10441045/*1046 * We are looking at a part of the final image represented by1047 * ent (tlno and same are offset by ent->s_lno).1048 * tlno is where we are looking at in the final image.1049 * up to (but not including) same match preimage.1050 * plno is where we are looking at in the preimage.1051 *1052 * <-------------- final image ---------------------->1053 * <------ent------>1054 * ^tlno ^same1055 * <---------preimage----->1056 * ^plno1057 *1058 * All line numbers are 0-based.1059 */1060static voidhandle_split(struct scoreboard *sb,1061struct blame_entry *ent,1062int tlno,int plno,int same,1063struct origin *parent,1064struct blame_entry *split)1065{1066if(ent->num_lines <= tlno)1067return;1068if(tlno < same) {1069struct blame_entry this[3];1070 tlno += ent->s_lno;1071 same += ent->s_lno;1072split_overlap(this, ent, tlno, plno, same, parent);1073copy_split_if_better(sb, split,this);1074decref_split(this);1075}1076}10771078struct handle_split_cb_data {1079struct scoreboard *sb;1080struct blame_entry *ent;1081struct origin *parent;1082struct blame_entry *split;1083long plno;1084long tlno;1085};10861087static inthandle_split_cb(long start_a,long count_a,1088long start_b,long count_b,void*data)1089{1090struct handle_split_cb_data *d = data;1091handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1092 d->split);1093 d->plno = start_a + count_a;1094 d->tlno = start_b + count_b;1095return0;1096}10971098/*1099 * Find the lines from parent that are the same as ent so that1100 * we can pass blames to it. file_p has the blob contents for1101 * the parent.1102 */1103static voidfind_copy_in_blob(struct scoreboard *sb,1104struct blame_entry *ent,1105struct origin *parent,1106struct blame_entry *split,1107 mmfile_t *file_p)1108{1109const char*cp;1110 mmfile_t file_o;1111struct handle_split_cb_data d;11121113memset(&d,0,sizeof(d));1114 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1115/*1116 * Prepare mmfile that contains only the lines in ent.1117 */1118 cp =nth_line(sb, ent->lno);1119 file_o.ptr = (char*) cp;1120 file_o.size =nth_line(sb, ent->lno + ent->num_lines) - cp;11211122/*1123 * file_o is a part of final image we are annotating.1124 * file_p partially may match that image.1125 */1126memset(split,0,sizeof(struct blame_entry [3]));1127if(diff_hunks(file_p, &file_o,1, handle_split_cb, &d))1128die("unable to generate diff (%s)",1129oid_to_hex(&parent->commit->object.oid));1130/* remainder, if any, all match the preimage */1131handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);1132}11331134/* Move all blame entries from list *source that have a score smaller1135 * than score_min to the front of list *small.1136 * Returns a pointer to the link pointing to the old head of the small list.1137 */11381139static struct blame_entry **filter_small(struct scoreboard *sb,1140struct blame_entry **small,1141struct blame_entry **source,1142unsigned score_min)1143{1144struct blame_entry *p = *source;1145struct blame_entry *oldsmall = *small;1146while(p) {1147if(ent_score(sb, p) <= score_min) {1148*small = p;1149 small = &p->next;1150 p = *small;1151}else{1152*source = p;1153 source = &p->next;1154 p = *source;1155}1156}1157*small = oldsmall;1158*source = NULL;1159return small;1160}11611162/*1163 * See if lines currently target is suspected for can be attributed to1164 * parent.1165 */1166static voidfind_move_in_parent(struct scoreboard *sb,1167struct blame_entry ***blamed,1168struct blame_entry **toosmall,1169struct origin *target,1170struct origin *parent)1171{1172struct blame_entry *e, split[3];1173struct blame_entry *unblamed = target->suspects;1174struct blame_entry *leftover = NULL;1175 mmfile_t file_p;11761177if(!unblamed)1178return;/* nothing remains for this target */11791180fill_origin_blob(&sb->revs->diffopt, parent, &file_p);1181if(!file_p.ptr)1182return;11831184/* At each iteration, unblamed has a NULL-terminated list of1185 * entries that have not yet been tested for blame. leftover1186 * contains the reversed list of entries that have been tested1187 * without being assignable to the parent.1188 */1189do{1190struct blame_entry **unblamedtail = &unblamed;1191struct blame_entry *next;1192for(e = unblamed; e; e = next) {1193 next = e->next;1194find_copy_in_blob(sb, e, parent, split, &file_p);1195if(split[1].suspect &&1196 blame_move_score <ent_score(sb, &split[1])) {1197split_blame(blamed, &unblamedtail, split, e);1198}else{1199 e->next = leftover;1200 leftover = e;1201}1202decref_split(split);1203}1204*unblamedtail = NULL;1205 toosmall =filter_small(sb, toosmall, &unblamed, blame_move_score);1206}while(unblamed);1207 target->suspects =reverse_blame(leftover, NULL);1208}12091210struct blame_list {1211struct blame_entry *ent;1212struct blame_entry split[3];1213};12141215/*1216 * Count the number of entries the target is suspected for,1217 * and prepare a list of entry and the best split.1218 */1219static struct blame_list *setup_blame_list(struct blame_entry *unblamed,1220int*num_ents_p)1221{1222struct blame_entry *e;1223int num_ents, i;1224struct blame_list *blame_list = NULL;12251226for(e = unblamed, num_ents =0; e; e = e->next)1227 num_ents++;1228if(num_ents) {1229 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1230for(e = unblamed, i =0; e; e = e->next)1231 blame_list[i++].ent = e;1232}1233*num_ents_p = num_ents;1234return blame_list;1235}12361237/*1238 * For lines target is suspected for, see if we can find code movement1239 * across file boundary from the parent commit. porigin is the path1240 * in the parent we already tried.1241 */1242static voidfind_copy_in_parent(struct scoreboard *sb,1243struct blame_entry ***blamed,1244struct blame_entry **toosmall,1245struct origin *target,1246struct commit *parent,1247struct origin *porigin,1248int opt)1249{1250struct diff_options diff_opts;1251int i, j;1252struct blame_list *blame_list;1253int num_ents;1254struct blame_entry *unblamed = target->suspects;1255struct blame_entry *leftover = NULL;12561257if(!unblamed)1258return;/* nothing remains for this target */12591260diff_setup(&diff_opts);1261DIFF_OPT_SET(&diff_opts, RECURSIVE);1262 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;12631264diff_setup_done(&diff_opts);12651266/* Try "find copies harder" on new path if requested;1267 * we do not want to use diffcore_rename() actually to1268 * match things up; find_copies_harder is set only to1269 * force diff_tree_sha1() to feed all filepairs to diff_queue,1270 * and this code needs to be after diff_setup_done(), which1271 * usually makes find-copies-harder imply copy detection.1272 */1273if((opt & PICKAXE_BLAME_COPY_HARDEST)1274|| ((opt & PICKAXE_BLAME_COPY_HARDER)1275&& (!porigin ||strcmp(target->path, porigin->path))))1276DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);12771278if(is_null_oid(&target->commit->object.oid))1279do_diff_cache(get_object_hash(parent->tree->object), &diff_opts);1280else1281diff_tree_sha1(get_object_hash(parent->tree->object),1282get_object_hash(target->commit->tree->object),1283"", &diff_opts);12841285if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1286diffcore_std(&diff_opts);12871288do{1289struct blame_entry **unblamedtail = &unblamed;1290 blame_list =setup_blame_list(unblamed, &num_ents);12911292for(i =0; i < diff_queued_diff.nr; i++) {1293struct diff_filepair *p = diff_queued_diff.queue[i];1294struct origin *norigin;1295 mmfile_t file_p;1296struct blame_entry this[3];12971298if(!DIFF_FILE_VALID(p->one))1299continue;/* does not exist in parent */1300if(S_ISGITLINK(p->one->mode))1301continue;/* ignore git links */1302if(porigin && !strcmp(p->one->path, porigin->path))1303/* find_move already dealt with this path */1304continue;13051306 norigin =get_origin(sb, parent, p->one->path);1307hashcpy(norigin->blob_sha1, p->one->sha1);1308 norigin->mode = p->one->mode;1309fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);1310if(!file_p.ptr)1311continue;13121313for(j =0; j < num_ents; j++) {1314find_copy_in_blob(sb, blame_list[j].ent,1315 norigin,this, &file_p);1316copy_split_if_better(sb, blame_list[j].split,1317this);1318decref_split(this);1319}1320origin_decref(norigin);1321}13221323for(j =0; j < num_ents; j++) {1324struct blame_entry *split = blame_list[j].split;1325if(split[1].suspect &&1326 blame_copy_score <ent_score(sb, &split[1])) {1327split_blame(blamed, &unblamedtail, split,1328 blame_list[j].ent);1329}else{1330 blame_list[j].ent->next = leftover;1331 leftover = blame_list[j].ent;1332}1333decref_split(split);1334}1335free(blame_list);1336*unblamedtail = NULL;1337 toosmall =filter_small(sb, toosmall, &unblamed, blame_copy_score);1338}while(unblamed);1339 target->suspects =reverse_blame(leftover, NULL);1340diff_flush(&diff_opts);1341free_pathspec(&diff_opts.pathspec);1342}13431344/*1345 * The blobs of origin and porigin exactly match, so everything1346 * origin is suspected for can be blamed on the parent.1347 */1348static voidpass_whole_blame(struct scoreboard *sb,1349struct origin *origin,struct origin *porigin)1350{1351struct blame_entry *e, *suspects;13521353if(!porigin->file.ptr && origin->file.ptr) {1354/* Steal its file */1355 porigin->file = origin->file;1356 origin->file.ptr = NULL;1357}1358 suspects = origin->suspects;1359 origin->suspects = NULL;1360for(e = suspects; e; e = e->next) {1361origin_incref(porigin);1362origin_decref(e->suspect);1363 e->suspect = porigin;1364}1365queue_blames(sb, porigin, suspects);1366}13671368/*1369 * We pass blame from the current commit to its parents. We keep saying1370 * "parent" (and "porigin"), but what we mean is to find scapegoat to1371 * exonerate ourselves.1372 */1373static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1374{1375if(!reverse) {1376if(revs->first_parent_only &&1377 commit->parents &&1378 commit->parents->next) {1379free_commit_list(commit->parents->next);1380 commit->parents->next = NULL;1381}1382return commit->parents;1383}1384returnlookup_decoration(&revs->children, &commit->object);1385}13861387static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1388{1389struct commit_list *l =first_scapegoat(revs, commit);1390returncommit_list_count(l);1391}13921393/* Distribute collected unsorted blames to the respected sorted lists1394 * in the various origins.1395 */1396static voiddistribute_blame(struct scoreboard *sb,struct blame_entry *blamed)1397{1398 blamed =blame_sort(blamed, compare_blame_suspect);1399while(blamed)1400{1401struct origin *porigin = blamed->suspect;1402struct blame_entry *suspects = NULL;1403do{1404struct blame_entry *next = blamed->next;1405 blamed->next = suspects;1406 suspects = blamed;1407 blamed = next;1408}while(blamed && blamed->suspect == porigin);1409 suspects =reverse_blame(suspects, NULL);1410queue_blames(sb, porigin, suspects);1411}1412}14131414#define MAXSG 1614151416static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1417{1418struct rev_info *revs = sb->revs;1419int i, pass, num_sg;1420struct commit *commit = origin->commit;1421struct commit_list *sg;1422struct origin *sg_buf[MAXSG];1423struct origin *porigin, **sg_origin = sg_buf;1424struct blame_entry *toosmall = NULL;1425struct blame_entry *blames, **blametail = &blames;14261427 num_sg =num_scapegoats(revs, commit);1428if(!num_sg)1429goto finish;1430else if(num_sg <ARRAY_SIZE(sg_buf))1431memset(sg_buf,0,sizeof(sg_buf));1432else1433 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));14341435/*1436 * The first pass looks for unrenamed path to optimize for1437 * common cases, then we look for renames in the second pass.1438 */1439for(pass =0; pass <2- no_whole_file_rename; pass++) {1440struct origin *(*find)(struct scoreboard *,1441struct commit *,struct origin *);1442 find = pass ? find_rename : find_origin;14431444for(i =0, sg =first_scapegoat(revs, commit);1445 i < num_sg && sg;1446 sg = sg->next, i++) {1447struct commit *p = sg->item;1448int j, same;14491450if(sg_origin[i])1451continue;1452if(parse_commit(p))1453continue;1454 porigin =find(sb, p, origin);1455if(!porigin)1456continue;1457if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1458pass_whole_blame(sb, origin, porigin);1459origin_decref(porigin);1460goto finish;1461}1462for(j = same =0; j < i; j++)1463if(sg_origin[j] &&1464!hashcmp(sg_origin[j]->blob_sha1,1465 porigin->blob_sha1)) {1466 same =1;1467break;1468}1469if(!same)1470 sg_origin[i] = porigin;1471else1472origin_decref(porigin);1473}1474}14751476 num_commits++;1477for(i =0, sg =first_scapegoat(revs, commit);1478 i < num_sg && sg;1479 sg = sg->next, i++) {1480struct origin *porigin = sg_origin[i];1481if(!porigin)1482continue;1483if(!origin->previous) {1484origin_incref(porigin);1485 origin->previous = porigin;1486}1487pass_blame_to_parent(sb, origin, porigin);1488if(!origin->suspects)1489goto finish;1490}14911492/*1493 * Optionally find moves in parents' files.1494 */1495if(opt & PICKAXE_BLAME_MOVE) {1496filter_small(sb, &toosmall, &origin->suspects, blame_move_score);1497if(origin->suspects) {1498for(i =0, sg =first_scapegoat(revs, commit);1499 i < num_sg && sg;1500 sg = sg->next, i++) {1501struct origin *porigin = sg_origin[i];1502if(!porigin)1503continue;1504find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);1505if(!origin->suspects)1506break;1507}1508}1509}15101511/*1512 * Optionally find copies from parents' files.1513 */1514if(opt & PICKAXE_BLAME_COPY) {1515if(blame_copy_score > blame_move_score)1516filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1517else if(blame_copy_score < blame_move_score) {1518 origin->suspects =blame_merge(origin->suspects, toosmall);1519 toosmall = NULL;1520filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);1521}1522if(!origin->suspects)1523goto finish;15241525for(i =0, sg =first_scapegoat(revs, commit);1526 i < num_sg && sg;1527 sg = sg->next, i++) {1528struct origin *porigin = sg_origin[i];1529find_copy_in_parent(sb, &blametail, &toosmall,1530 origin, sg->item, porigin, opt);1531if(!origin->suspects)1532goto finish;1533}1534}15351536finish:1537*blametail = NULL;1538distribute_blame(sb, blames);1539/*1540 * prepend toosmall to origin->suspects1541 *1542 * There is no point in sorting: this ends up on a big1543 * unsorted list in the caller anyway.1544 */1545if(toosmall) {1546struct blame_entry **tail = &toosmall;1547while(*tail)1548 tail = &(*tail)->next;1549*tail = origin->suspects;1550 origin->suspects = toosmall;1551}1552for(i =0; i < num_sg; i++) {1553if(sg_origin[i]) {1554drop_origin_blob(sg_origin[i]);1555origin_decref(sg_origin[i]);1556}1557}1558drop_origin_blob(origin);1559if(sg_buf != sg_origin)1560free(sg_origin);1561}15621563/*1564 * Information on commits, used for output.1565 */1566struct commit_info {1567struct strbuf author;1568struct strbuf author_mail;1569unsigned long author_time;1570struct strbuf author_tz;15711572/* filled only when asked for details */1573struct strbuf committer;1574struct strbuf committer_mail;1575unsigned long committer_time;1576struct strbuf committer_tz;15771578struct strbuf summary;1579};15801581/*1582 * Parse author/committer line in the commit object buffer1583 */1584static voidget_ac_line(const char*inbuf,const char*what,1585struct strbuf *name,struct strbuf *mail,1586unsigned long*time,struct strbuf *tz)1587{1588struct ident_split ident;1589size_t len, maillen, namelen;1590char*tmp, *endp;1591const char*namebuf, *mailbuf;15921593 tmp =strstr(inbuf, what);1594if(!tmp)1595goto error_out;1596 tmp +=strlen(what);1597 endp =strchr(tmp,'\n');1598if(!endp)1599 len =strlen(tmp);1600else1601 len = endp - tmp;16021603if(split_ident_line(&ident, tmp, len)) {1604 error_out:1605/* Ugh */1606 tmp ="(unknown)";1607strbuf_addstr(name, tmp);1608strbuf_addstr(mail, tmp);1609strbuf_addstr(tz, tmp);1610*time =0;1611return;1612}16131614 namelen = ident.name_end - ident.name_begin;1615 namebuf = ident.name_begin;16161617 maillen = ident.mail_end - ident.mail_begin;1618 mailbuf = ident.mail_begin;16191620if(ident.date_begin && ident.date_end)1621*time =strtoul(ident.date_begin, NULL,10);1622else1623*time =0;16241625if(ident.tz_begin && ident.tz_end)1626strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);1627else1628strbuf_addstr(tz,"(unknown)");16291630/*1631 * Now, convert both name and e-mail using mailmap1632 */1633map_user(&mailmap, &mailbuf, &maillen,1634&namebuf, &namelen);16351636strbuf_addf(mail,"<%.*s>", (int)maillen, mailbuf);1637strbuf_add(name, namebuf, namelen);1638}16391640static voidcommit_info_init(struct commit_info *ci)1641{16421643strbuf_init(&ci->author,0);1644strbuf_init(&ci->author_mail,0);1645strbuf_init(&ci->author_tz,0);1646strbuf_init(&ci->committer,0);1647strbuf_init(&ci->committer_mail,0);1648strbuf_init(&ci->committer_tz,0);1649strbuf_init(&ci->summary,0);1650}16511652static voidcommit_info_destroy(struct commit_info *ci)1653{16541655strbuf_release(&ci->author);1656strbuf_release(&ci->author_mail);1657strbuf_release(&ci->author_tz);1658strbuf_release(&ci->committer);1659strbuf_release(&ci->committer_mail);1660strbuf_release(&ci->committer_tz);1661strbuf_release(&ci->summary);1662}16631664static voidget_commit_info(struct commit *commit,1665struct commit_info *ret,1666int detailed)1667{1668int len;1669const char*subject, *encoding;1670const char*message;16711672commit_info_init(ret);16731674 encoding =get_log_output_encoding();1675 message =logmsg_reencode(commit, NULL, encoding);1676get_ac_line(message,"\nauthor ",1677&ret->author, &ret->author_mail,1678&ret->author_time, &ret->author_tz);16791680if(!detailed) {1681unuse_commit_buffer(commit, message);1682return;1683}16841685get_ac_line(message,"\ncommitter ",1686&ret->committer, &ret->committer_mail,1687&ret->committer_time, &ret->committer_tz);16881689 len =find_commit_subject(message, &subject);1690if(len)1691strbuf_add(&ret->summary, subject, len);1692else1693strbuf_addf(&ret->summary,"(%s)",oid_to_hex(&commit->object.oid));16941695unuse_commit_buffer(commit, message);1696}16971698/*1699 * To allow LF and other nonportable characters in pathnames,1700 * they are c-style quoted as needed.1701 */1702static voidwrite_filename_info(const char*path)1703{1704printf("filename ");1705write_name_quoted(path, stdout,'\n');1706}17071708/*1709 * Porcelain/Incremental format wants to show a lot of details per1710 * commit. Instead of repeating this every line, emit it only once,1711 * the first time each commit appears in the output (unless the1712 * user has specifically asked for us to repeat).1713 */1714static intemit_one_suspect_detail(struct origin *suspect,int repeat)1715{1716struct commit_info ci;17171718if(!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))1719return0;17201721 suspect->commit->object.flags |= METAINFO_SHOWN;1722get_commit_info(suspect->commit, &ci,1);1723printf("author%s\n", ci.author.buf);1724printf("author-mail%s\n", ci.author_mail.buf);1725printf("author-time%lu\n", ci.author_time);1726printf("author-tz%s\n", ci.author_tz.buf);1727printf("committer%s\n", ci.committer.buf);1728printf("committer-mail%s\n", ci.committer_mail.buf);1729printf("committer-time%lu\n", ci.committer_time);1730printf("committer-tz%s\n", ci.committer_tz.buf);1731printf("summary%s\n", ci.summary.buf);1732if(suspect->commit->object.flags & UNINTERESTING)1733printf("boundary\n");1734if(suspect->previous) {1735struct origin *prev = suspect->previous;1736printf("previous%s",oid_to_hex(&prev->commit->object.oid));1737write_name_quoted(prev->path, stdout,'\n');1738}17391740commit_info_destroy(&ci);17411742return1;1743}17441745/*1746 * The blame_entry is found to be guilty for the range.1747 * Show it in incremental output.1748 */1749static voidfound_guilty_entry(struct blame_entry *ent)1750{1751if(incremental) {1752struct origin *suspect = ent->suspect;17531754printf("%s %d %d %d\n",1755oid_to_hex(&suspect->commit->object.oid),1756 ent->s_lno +1, ent->lno +1, ent->num_lines);1757emit_one_suspect_detail(suspect,0);1758write_filename_info(suspect->path);1759maybe_flush_or_die(stdout,"stdout");1760}1761}17621763/*1764 * The main loop -- while we have blobs with lines whose true origin1765 * is still unknown, pick one blob, and allow its lines to pass blames1766 * to its parents. */1767static voidassign_blame(struct scoreboard *sb,int opt)1768{1769struct rev_info *revs = sb->revs;1770struct commit *commit =prio_queue_get(&sb->commits);17711772while(commit) {1773struct blame_entry *ent;1774struct origin *suspect = commit->util;17751776/* find one suspect to break down */1777while(suspect && !suspect->suspects)1778 suspect = suspect->next;17791780if(!suspect) {1781 commit =prio_queue_get(&sb->commits);1782continue;1783}17841785assert(commit == suspect->commit);17861787/*1788 * We will use this suspect later in the loop,1789 * so hold onto it in the meantime.1790 */1791origin_incref(suspect);1792parse_commit(commit);1793if(reverse ||1794(!(commit->object.flags & UNINTERESTING) &&1795!(revs->max_age != -1&& commit->date < revs->max_age)))1796pass_blame(sb, suspect, opt);1797else{1798 commit->object.flags |= UNINTERESTING;1799if(commit->object.parsed)1800mark_parents_uninteresting(commit);1801}1802/* treat root commit as boundary */1803if(!commit->parents && !show_root)1804 commit->object.flags |= UNINTERESTING;18051806/* Take responsibility for the remaining entries */1807 ent = suspect->suspects;1808if(ent) {1809 suspect->guilty =1;1810for(;;) {1811struct blame_entry *next = ent->next;1812found_guilty_entry(ent);1813if(next) {1814 ent = next;1815continue;1816}1817 ent->next = sb->ent;1818 sb->ent = suspect->suspects;1819 suspect->suspects = NULL;1820break;1821}1822}1823origin_decref(suspect);18241825if(DEBUG)/* sanity */1826sanity_check_refcnt(sb);1827}1828}18291830static const char*format_time(unsigned long time,const char*tz_str,1831int show_raw_time)1832{1833static struct strbuf time_buf = STRBUF_INIT;18341835strbuf_reset(&time_buf);1836if(show_raw_time) {1837strbuf_addf(&time_buf,"%lu%s", time, tz_str);1838}1839else{1840const char*time_str;1841size_t time_width;1842int tz;1843 tz =atoi(tz_str);1844 time_str =show_date(time, tz, &blame_date_mode);1845strbuf_addstr(&time_buf, time_str);1846/*1847 * Add space paddings to time_buf to display a fixed width1848 * string, and use time_width for display width calibration.1849 */1850for(time_width =utf8_strwidth(time_str);1851 time_width < blame_date_width;1852 time_width++)1853strbuf_addch(&time_buf,' ');1854}1855return time_buf.buf;1856}18571858#define OUTPUT_ANNOTATE_COMPAT 0011859#define OUTPUT_LONG_OBJECT_NAME 0021860#define OUTPUT_RAW_TIMESTAMP 0041861#define OUTPUT_PORCELAIN 0101862#define OUTPUT_SHOW_NAME 0201863#define OUTPUT_SHOW_NUMBER 0401864#define OUTPUT_SHOW_SCORE 01001865#define OUTPUT_NO_AUTHOR 02001866#define OUTPUT_SHOW_EMAIL 04001867#define OUTPUT_LINE_PORCELAIN 0100018681869static voidemit_porcelain_details(struct origin *suspect,int repeat)1870{1871if(emit_one_suspect_detail(suspect, repeat) ||1872(suspect->commit->object.flags & MORE_THAN_ONE_PATH))1873write_filename_info(suspect->path);1874}18751876static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent,1877int opt)1878{1879int repeat = opt & OUTPUT_LINE_PORCELAIN;1880int cnt;1881const char*cp;1882struct origin *suspect = ent->suspect;1883char hex[GIT_SHA1_HEXSZ +1];18841885sha1_to_hex_r(hex, suspect->commit->object.oid.hash);1886printf("%s %d %d %d\n",1887 hex,1888 ent->s_lno +1,1889 ent->lno +1,1890 ent->num_lines);1891emit_porcelain_details(suspect, repeat);18921893 cp =nth_line(sb, ent->lno);1894for(cnt =0; cnt < ent->num_lines; cnt++) {1895char ch;1896if(cnt) {1897printf("%s %d %d\n", hex,1898 ent->s_lno +1+ cnt,1899 ent->lno +1+ cnt);1900if(repeat)1901emit_porcelain_details(suspect,1);1902}1903putchar('\t');1904do{1905 ch = *cp++;1906putchar(ch);1907}while(ch !='\n'&&1908 cp < sb->final_buf + sb->final_buf_size);1909}19101911if(sb->final_buf_size && cp[-1] !='\n')1912putchar('\n');1913}19141915static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1916{1917int cnt;1918const char*cp;1919struct origin *suspect = ent->suspect;1920struct commit_info ci;1921char hex[GIT_SHA1_HEXSZ +1];1922int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);19231924get_commit_info(suspect->commit, &ci,1);1925sha1_to_hex_r(hex, suspect->commit->object.oid.hash);19261927 cp =nth_line(sb, ent->lno);1928for(cnt =0; cnt < ent->num_lines; cnt++) {1929char ch;1930int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40: abbrev;19311932if(suspect->commit->object.flags & UNINTERESTING) {1933if(blank_boundary)1934memset(hex,' ', length);1935else if(!(opt & OUTPUT_ANNOTATE_COMPAT)) {1936 length--;1937putchar('^');1938}1939}19401941printf("%.*s", length, hex);1942if(opt & OUTPUT_ANNOTATE_COMPAT) {1943const char*name;1944if(opt & OUTPUT_SHOW_EMAIL)1945 name = ci.author_mail.buf;1946else1947 name = ci.author.buf;1948printf("\t(%10s\t%10s\t%d)", name,1949format_time(ci.author_time, ci.author_tz.buf,1950 show_raw_time),1951 ent->lno +1+ cnt);1952}else{1953if(opt & OUTPUT_SHOW_SCORE)1954printf(" %*d%02d",1955 max_score_digits, ent->score,1956 ent->suspect->refcnt);1957if(opt & OUTPUT_SHOW_NAME)1958printf(" %-*.*s", longest_file, longest_file,1959 suspect->path);1960if(opt & OUTPUT_SHOW_NUMBER)1961printf(" %*d", max_orig_digits,1962 ent->s_lno +1+ cnt);19631964if(!(opt & OUTPUT_NO_AUTHOR)) {1965const char*name;1966int pad;1967if(opt & OUTPUT_SHOW_EMAIL)1968 name = ci.author_mail.buf;1969else1970 name = ci.author.buf;1971 pad = longest_author -utf8_strwidth(name);1972printf(" (%s%*s%10s",1973 name, pad,"",1974format_time(ci.author_time,1975 ci.author_tz.buf,1976 show_raw_time));1977}1978printf(" %*d) ",1979 max_digits, ent->lno +1+ cnt);1980}1981do{1982 ch = *cp++;1983putchar(ch);1984}while(ch !='\n'&&1985 cp < sb->final_buf + sb->final_buf_size);1986}19871988if(sb->final_buf_size && cp[-1] !='\n')1989putchar('\n');19901991commit_info_destroy(&ci);1992}19931994static voidoutput(struct scoreboard *sb,int option)1995{1996struct blame_entry *ent;19971998if(option & OUTPUT_PORCELAIN) {1999for(ent = sb->ent; ent; ent = ent->next) {2000int count =0;2001struct origin *suspect;2002struct commit *commit = ent->suspect->commit;2003if(commit->object.flags & MORE_THAN_ONE_PATH)2004continue;2005for(suspect = commit->util; suspect; suspect = suspect->next) {2006if(suspect->guilty && count++) {2007 commit->object.flags |= MORE_THAN_ONE_PATH;2008break;2009}2010}2011}2012}20132014for(ent = sb->ent; ent; ent = ent->next) {2015if(option & OUTPUT_PORCELAIN)2016emit_porcelain(sb, ent, option);2017else{2018emit_other(sb, ent, option);2019}2020}2021}20222023static const char*get_next_line(const char*start,const char*end)2024{2025const char*nl =memchr(start,'\n', end - start);2026return nl ? nl +1: end;2027}20282029/*2030 * To allow quick access to the contents of nth line in the2031 * final image, prepare an index in the scoreboard.2032 */2033static intprepare_lines(struct scoreboard *sb)2034{2035const char*buf = sb->final_buf;2036unsigned long len = sb->final_buf_size;2037const char*end = buf + len;2038const char*p;2039int*lineno;2040int num =0;20412042for(p = buf; p < end; p =get_next_line(p, end))2043 num++;20442045 sb->lineno = lineno =xmalloc(sizeof(*sb->lineno) * (num +1));20462047for(p = buf; p < end; p =get_next_line(p, end))2048*lineno++ = p - buf;20492050*lineno = len;20512052 sb->num_lines = num;2053return sb->num_lines;2054}20552056/*2057 * Add phony grafts for use with -S; this is primarily to2058 * support git's cvsserver that wants to give a linear history2059 * to its clients.2060 */2061static intread_ancestry(const char*graft_file)2062{2063FILE*fp =fopen(graft_file,"r");2064struct strbuf buf = STRBUF_INIT;2065if(!fp)2066return-1;2067while(!strbuf_getwholeline(&buf, fp,'\n')) {2068/* The format is just "Commit Parent1 Parent2 ...\n" */2069struct commit_graft *graft =read_graft_line(buf.buf, buf.len);2070if(graft)2071register_commit_graft(graft,0);2072}2073fclose(fp);2074strbuf_release(&buf);2075return0;2076}20772078static intupdate_auto_abbrev(int auto_abbrev,struct origin *suspect)2079{2080const char*uniq =find_unique_abbrev(get_object_hash(suspect->commit->object),2081 auto_abbrev);2082int len =strlen(uniq);2083if(auto_abbrev < len)2084return len;2085return auto_abbrev;2086}20872088/*2089 * How many columns do we need to show line numbers, authors,2090 * and filenames?2091 */2092static voidfind_alignment(struct scoreboard *sb,int*option)2093{2094int longest_src_lines =0;2095int longest_dst_lines =0;2096unsigned largest_score =0;2097struct blame_entry *e;2098int compute_auto_abbrev = (abbrev <0);2099int auto_abbrev = default_abbrev;21002101for(e = sb->ent; e; e = e->next) {2102struct origin *suspect = e->suspect;2103int num;21042105if(compute_auto_abbrev)2106 auto_abbrev =update_auto_abbrev(auto_abbrev, suspect);2107if(strcmp(suspect->path, sb->path))2108*option |= OUTPUT_SHOW_NAME;2109 num =strlen(suspect->path);2110if(longest_file < num)2111 longest_file = num;2112if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {2113struct commit_info ci;2114 suspect->commit->object.flags |= METAINFO_SHOWN;2115get_commit_info(suspect->commit, &ci,1);2116if(*option & OUTPUT_SHOW_EMAIL)2117 num =utf8_strwidth(ci.author_mail.buf);2118else2119 num =utf8_strwidth(ci.author.buf);2120if(longest_author < num)2121 longest_author = num;2122commit_info_destroy(&ci);2123}2124 num = e->s_lno + e->num_lines;2125if(longest_src_lines < num)2126 longest_src_lines = num;2127 num = e->lno + e->num_lines;2128if(longest_dst_lines < num)2129 longest_dst_lines = num;2130if(largest_score <ent_score(sb, e))2131 largest_score =ent_score(sb, e);2132}2133 max_orig_digits =decimal_width(longest_src_lines);2134 max_digits =decimal_width(longest_dst_lines);2135 max_score_digits =decimal_width(largest_score);21362137if(compute_auto_abbrev)2138/* one more abbrev length is needed for the boundary commit */2139 abbrev = auto_abbrev +1;2140}21412142/*2143 * For debugging -- origin is refcounted, and this asserts that2144 * we do not underflow.2145 */2146static voidsanity_check_refcnt(struct scoreboard *sb)2147{2148int baa =0;2149struct blame_entry *ent;21502151for(ent = sb->ent; ent; ent = ent->next) {2152/* Nobody should have zero or negative refcnt */2153if(ent->suspect->refcnt <=0) {2154fprintf(stderr,"%sin%shas negative refcnt%d\n",2155 ent->suspect->path,2156oid_to_hex(&ent->suspect->commit->object.oid),2157 ent->suspect->refcnt);2158 baa =1;2159}2160}2161if(baa) {2162int opt =0160;2163find_alignment(sb, &opt);2164output(sb, opt);2165die("Baa%d!", baa);2166}2167}21682169static unsignedparse_score(const char*arg)2170{2171char*end;2172unsigned long score =strtoul(arg, &end,10);2173if(*end)2174return0;2175return score;2176}21772178static const char*add_prefix(const char*prefix,const char*path)2179{2180returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);2181}21822183static intgit_blame_config(const char*var,const char*value,void*cb)2184{2185if(!strcmp(var,"blame.showroot")) {2186 show_root =git_config_bool(var, value);2187return0;2188}2189if(!strcmp(var,"blame.blankboundary")) {2190 blank_boundary =git_config_bool(var, value);2191return0;2192}2193if(!strcmp(var,"blame.showemail")) {2194int*output_option = cb;2195if(git_config_bool(var, value))2196*output_option |= OUTPUT_SHOW_EMAIL;2197else2198*output_option &= ~OUTPUT_SHOW_EMAIL;2199return0;2200}2201if(!strcmp(var,"blame.date")) {2202if(!value)2203returnconfig_error_nonbool(var);2204parse_date_format(value, &blame_date_mode);2205return0;2206}22072208if(userdiff_config(var, value) <0)2209return-1;22102211returngit_default_config(var, value, cb);2212}22132214static voidverify_working_tree_path(struct commit *work_tree,const char*path)2215{2216struct commit_list *parents;22172218for(parents = work_tree->parents; parents; parents = parents->next) {2219const unsigned char*commit_sha1 =get_object_hash(parents->item->object);2220unsigned char blob_sha1[20];2221unsigned mode;22222223if(!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&2224sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)2225return;2226}2227die("no such path '%s' in HEAD", path);2228}22292230static struct commit_list **append_parent(struct commit_list **tail,const unsigned char*sha1)2231{2232struct commit *parent;22332234 parent =lookup_commit_reference(sha1);2235if(!parent)2236die("no such commit%s",sha1_to_hex(sha1));2237return&commit_list_insert(parent, tail)->next;2238}22392240static voidappend_merge_parents(struct commit_list **tail)2241{2242int merge_head;2243struct strbuf line = STRBUF_INIT;22442245 merge_head =open(git_path_merge_head(), O_RDONLY);2246if(merge_head <0) {2247if(errno == ENOENT)2248return;2249die("cannot open '%s' for reading",git_path_merge_head());2250}22512252while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) {2253unsigned char sha1[20];2254if(line.len <40||get_sha1_hex(line.buf, sha1))2255die("unknown line in '%s':%s",git_path_merge_head(), line.buf);2256 tail =append_parent(tail, sha1);2257}2258close(merge_head);2259strbuf_release(&line);2260}22612262/*2263 * This isn't as simple as passing sb->buf and sb->len, because we2264 * want to transfer ownership of the buffer to the commit (so we2265 * must use detach).2266 */2267static voidset_commit_buffer_from_strbuf(struct commit *c,struct strbuf *sb)2268{2269size_t len;2270void*buf =strbuf_detach(sb, &len);2271set_commit_buffer(c, buf, len);2272}22732274/*2275 * Prepare a dummy commit that represents the work tree (or staged) item.2276 * Note that annotating work tree item never works in the reverse.2277 */2278static struct commit *fake_working_tree_commit(struct diff_options *opt,2279const char*path,2280const char*contents_from)2281{2282struct commit *commit;2283struct origin *origin;2284struct commit_list **parent_tail, *parent;2285unsigned char head_sha1[20];2286struct strbuf buf = STRBUF_INIT;2287const char*ident;2288time_t now;2289int size, len;2290struct cache_entry *ce;2291unsigned mode;2292struct strbuf msg = STRBUF_INIT;22932294time(&now);2295 commit =alloc_commit_node();2296 commit->object.parsed =1;2297 commit->date = now;2298 parent_tail = &commit->parents;22992300if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))2301die("no such ref: HEAD");23022303 parent_tail =append_parent(parent_tail, head_sha1);2304append_merge_parents(parent_tail);2305verify_working_tree_path(commit, path);23062307 origin =make_origin(commit, path);23082309 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2310strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n");2311for(parent = commit->parents; parent; parent = parent->next)2312strbuf_addf(&msg,"parent%s\n",2313oid_to_hex(&parent->item->object.oid));2314strbuf_addf(&msg,2315"author%s\n"2316"committer%s\n\n"2317"Version of%sfrom%s\n",2318 ident, ident, path,2319(!contents_from ? path :2320(!strcmp(contents_from,"-") ?"standard input": contents_from)));2321set_commit_buffer_from_strbuf(commit, &msg);23222323if(!contents_from ||strcmp("-", contents_from)) {2324struct stat st;2325const char*read_from;2326char*buf_ptr;2327unsigned long buf_len;23282329if(contents_from) {2330if(stat(contents_from, &st) <0)2331die_errno("Cannot stat '%s'", contents_from);2332 read_from = contents_from;2333}2334else{2335if(lstat(path, &st) <0)2336die_errno("Cannot lstat '%s'", path);2337 read_from = path;2338}2339 mode =canon_mode(st.st_mode);23402341switch(st.st_mode & S_IFMT) {2342case S_IFREG:2343if(DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&2344textconv_object(read_from, mode, null_sha1,0, &buf_ptr, &buf_len))2345strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1);2346else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2347die_errno("cannot open or read '%s'", read_from);2348break;2349case S_IFLNK:2350if(strbuf_readlink(&buf, read_from, st.st_size) <0)2351die_errno("cannot readlink '%s'", read_from);2352break;2353default:2354die("unsupported file type%s", read_from);2355}2356}2357else{2358/* Reading from stdin */2359 mode =0;2360if(strbuf_read(&buf,0,0) <0)2361die_errno("failed to read from stdin");2362}2363convert_to_git(path, buf.buf, buf.len, &buf,0);2364 origin->file.ptr = buf.buf;2365 origin->file.size = buf.len;2366pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);23672368/*2369 * Read the current index, replace the path entry with2370 * origin->blob_sha1 without mucking with its mode or type2371 * bits; we are not going to write this index out -- we just2372 * want to run "diff-index --cached".2373 */2374discard_cache();2375read_cache();23762377 len =strlen(path);2378if(!mode) {2379int pos =cache_name_pos(path, len);2380if(0<= pos)2381 mode = active_cache[pos]->ce_mode;2382else2383/* Let's not bother reading from HEAD tree */2384 mode = S_IFREG |0644;2385}2386 size =cache_entry_size(len);2387 ce =xcalloc(1, size);2388hashcpy(ce->sha1, origin->blob_sha1);2389memcpy(ce->name, path, len);2390 ce->ce_flags =create_ce_flags(0);2391 ce->ce_namelen = len;2392 ce->ce_mode =create_ce_mode(mode);2393add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);23942395/*2396 * We are not going to write this out, so this does not matter2397 * right now, but someday we might optimize diff-index --cached2398 * with cache-tree information.2399 */2400cache_tree_invalidate_path(&the_index, path);24012402return commit;2403}24042405static struct object_array_entry *find_single_final(struct rev_info *revs)2406{2407int i;2408struct object_array_entry *found = NULL;24092410for(i =0; i < revs->pending.nr; i++) {2411struct object *obj = revs->pending.objects[i].item;2412if(obj->flags & UNINTERESTING)2413continue;2414while(obj->type == OBJ_TAG)2415 obj =deref_tag(obj, NULL,0);2416if(obj->type != OBJ_COMMIT)2417die("Non commit%s?", revs->pending.objects[i].name);2418if(found)2419die("More than one commit to dig from%sand%s?",2420 revs->pending.objects[i].name,2421 found->name);2422 found = &(revs->pending.objects[i]);2423}2424return found;2425}24262427static char*prepare_final(struct scoreboard *sb)2428{2429struct object_array_entry *found =find_single_final(sb->revs);2430if(found) {2431 sb->final = (struct commit *) found->item;2432returnxstrdup(found->name);2433}else{2434return NULL;2435}2436}24372438static char*prepare_initial(struct scoreboard *sb)2439{2440int i;2441const char*final_commit_name = NULL;2442struct rev_info *revs = sb->revs;24432444/*2445 * There must be one and only one negative commit, and it must be2446 * the boundary.2447 */2448for(i =0; i < revs->pending.nr; i++) {2449struct object *obj = revs->pending.objects[i].item;2450if(!(obj->flags & UNINTERESTING))2451continue;2452while(obj->type == OBJ_TAG)2453 obj =deref_tag(obj, NULL,0);2454if(obj->type != OBJ_COMMIT)2455die("Non commit%s?", revs->pending.objects[i].name);2456if(sb->final)2457die("More than one commit to dig down to%sand%s?",2458 revs->pending.objects[i].name,2459 final_commit_name);2460 sb->final = (struct commit *) obj;2461 final_commit_name = revs->pending.objects[i].name;2462}2463if(!final_commit_name)2464die("No commit to dig down to?");2465returnxstrdup(final_commit_name);2466}24672468static intblame_copy_callback(const struct option *option,const char*arg,int unset)2469{2470int*opt = option->value;24712472/*2473 * -C enables copy from removed files;2474 * -C -C enables copy from existing files, but only2475 * when blaming a new file;2476 * -C -C -C enables copy from existing files for2477 * everybody2478 */2479if(*opt & PICKAXE_BLAME_COPY_HARDER)2480*opt |= PICKAXE_BLAME_COPY_HARDEST;2481if(*opt & PICKAXE_BLAME_COPY)2482*opt |= PICKAXE_BLAME_COPY_HARDER;2483*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;24842485if(arg)2486 blame_copy_score =parse_score(arg);2487return0;2488}24892490static intblame_move_callback(const struct option *option,const char*arg,int unset)2491{2492int*opt = option->value;24932494*opt |= PICKAXE_BLAME_MOVE;24952496if(arg)2497 blame_move_score =parse_score(arg);2498return0;2499}25002501intcmd_blame(int argc,const char**argv,const char*prefix)2502{2503struct rev_info revs;2504const char*path;2505struct scoreboard sb;2506struct origin *o;2507struct blame_entry *ent = NULL;2508long dashdash_pos, lno;2509char*final_commit_name = NULL;2510enum object_type type;2511struct commit *final_commit = NULL;25122513static struct string_list range_list;2514static int output_option =0, opt =0;2515static int show_stats =0;2516static const char*revs_file = NULL;2517static const char*contents_from = NULL;2518static const struct option options[] = {2519OPT_BOOL(0,"incremental", &incremental,N_("Show blame entries as we find them, incrementally")),2520OPT_BOOL('b', NULL, &blank_boundary,N_("Show blank SHA-1 for boundary commits (Default: off)")),2521OPT_BOOL(0,"root", &show_root,N_("Do not treat root commits as boundaries (Default: off)")),2522OPT_BOOL(0,"show-stats", &show_stats,N_("Show work cost statistics")),2523OPT_BIT(0,"score-debug", &output_option,N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),2524OPT_BIT('f',"show-name", &output_option,N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),2525OPT_BIT('n',"show-number", &output_option,N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),2526OPT_BIT('p',"porcelain", &output_option,N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),2527OPT_BIT(0,"line-porcelain", &output_option,N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),2528OPT_BIT('c', NULL, &output_option,N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),2529OPT_BIT('t', NULL, &output_option,N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),2530OPT_BIT('l', NULL, &output_option,N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),2531OPT_BIT('s', NULL, &output_option,N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),2532OPT_BIT('e',"show-email", &output_option,N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),2533OPT_BIT('w', NULL, &xdl_opts,N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),2534OPT_BIT(0,"minimal", &xdl_opts,N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),2535OPT_STRING('S', NULL, &revs_file,N_("file"),N_("Use revisions from <file> instead of calling git-rev-list")),2536OPT_STRING(0,"contents", &contents_from,N_("file"),N_("Use <file>'s contents as the final image")),2537{ OPTION_CALLBACK,'C', NULL, &opt,N_("score"),N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },2538{ OPTION_CALLBACK,'M', NULL, &opt,N_("score"),N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },2539OPT_STRING_LIST('L', NULL, &range_list,N_("n,m"),N_("Process only line range n,m, counting from 1")),2540OPT__ABBREV(&abbrev),2541OPT_END()2542};25432544struct parse_opt_ctx_t ctx;2545int cmd_is_annotate = !strcmp(argv[0],"annotate");2546struct range_set ranges;2547unsigned int range_i;2548long anchor;25492550git_config(git_blame_config, &output_option);2551init_revisions(&revs, NULL);2552 revs.date_mode = blame_date_mode;2553DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);2554DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);25552556 save_commit_buffer =0;2557 dashdash_pos =0;25582559parse_options_start(&ctx, argc, argv, prefix, options,2560 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);2561for(;;) {2562switch(parse_options_step(&ctx, options, blame_opt_usage)) {2563case PARSE_OPT_HELP:2564exit(129);2565case PARSE_OPT_DONE:2566if(ctx.argv[0])2567 dashdash_pos = ctx.cpidx;2568goto parse_done;2569}25702571if(!strcmp(ctx.argv[0],"--reverse")) {2572 ctx.argv[0] ="--children";2573 reverse =1;2574}2575parse_revision_opt(&revs, &ctx, options, blame_opt_usage);2576}2577parse_done:2578 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);2579DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);2580 argc =parse_options_end(&ctx);25812582if(0< abbrev)2583/* one more abbrev length is needed for the boundary commit */2584 abbrev++;25852586if(revs_file &&read_ancestry(revs_file))2587die_errno("reading graft file '%s' failed", revs_file);25882589if(cmd_is_annotate) {2590 output_option |= OUTPUT_ANNOTATE_COMPAT;2591 blame_date_mode.type = DATE_ISO8601;2592}else{2593 blame_date_mode = revs.date_mode;2594}25952596/* The maximum width used to show the dates */2597switch(blame_date_mode.type) {2598case DATE_RFC2822:2599 blame_date_width =sizeof("Thu, 19 Oct 2006 16:00:04 -0700");2600break;2601case DATE_ISO8601_STRICT:2602 blame_date_width =sizeof("2006-10-19T16:00:04-07:00");2603break;2604case DATE_ISO8601:2605 blame_date_width =sizeof("2006-10-19 16:00:04 -0700");2606break;2607case DATE_RAW:2608 blame_date_width =sizeof("1161298804 -0700");2609break;2610case DATE_SHORT:2611 blame_date_width =sizeof("2006-10-19");2612break;2613case DATE_RELATIVE:2614/* TRANSLATORS: This string is used to tell us the maximum2615 display width for a relative timestamp in "git blame"2616 output. For C locale, "4 years, 11 months ago", which2617 takes 22 places, is the longest among various forms of2618 relative timestamps, but your language may need more or2619 fewer display columns. */2620 blame_date_width =utf8_strwidth(_("4 years, 11 months ago")) +1;/* add the null */2621break;2622case DATE_NORMAL:2623 blame_date_width =sizeof("Thu Oct 19 16:00:04 2006 -0700");2624break;2625case DATE_STRFTIME:2626 blame_date_width =strlen(show_date(0,0, &blame_date_mode)) +1;/* add the null */2627break;2628}2629 blame_date_width -=1;/* strip the null */26302631if(DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))2632 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |2633 PICKAXE_BLAME_COPY_HARDER);26342635if(!blame_move_score)2636 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2637if(!blame_copy_score)2638 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;26392640/*2641 * We have collected options unknown to us in argv[1..unk]2642 * which are to be passed to revision machinery if we are2643 * going to do the "bottom" processing.2644 *2645 * The remaining are:2646 *2647 * (1) if dashdash_pos != 0, it is either2648 * "blame [revisions] -- <path>" or2649 * "blame -- <path> <rev>"2650 *2651 * (2) otherwise, it is one of the two:2652 * "blame [revisions] <path>"2653 * "blame <path> <rev>"2654 *2655 * Note that we must strip out <path> from the arguments: we do not2656 * want the path pruning but we may want "bottom" processing.2657 */2658if(dashdash_pos) {2659switch(argc - dashdash_pos -1) {2660case2:/* (1b) */2661if(argc !=4)2662usage_with_options(blame_opt_usage, options);2663/* reorder for the new way: <rev> -- <path> */2664 argv[1] = argv[3];2665 argv[3] = argv[2];2666 argv[2] ="--";2667/* FALLTHROUGH */2668case1:/* (1a) */2669 path =add_prefix(prefix, argv[--argc]);2670 argv[argc] = NULL;2671break;2672default:2673usage_with_options(blame_opt_usage, options);2674}2675}else{2676if(argc <2)2677usage_with_options(blame_opt_usage, options);2678 path =add_prefix(prefix, argv[argc -1]);2679if(argc ==3&& !file_exists(path)) {/* (2b) */2680 path =add_prefix(prefix, argv[1]);2681 argv[1] = argv[2];2682}2683 argv[argc -1] ="--";26842685setup_work_tree();2686if(!file_exists(path))2687die_errno("cannot stat path '%s'", path);2688}26892690 revs.disable_stdin =1;2691setup_revisions(argc, argv, &revs, NULL);2692memset(&sb,0,sizeof(sb));26932694 sb.revs = &revs;2695if(!reverse) {2696 final_commit_name =prepare_final(&sb);2697 sb.commits.compare = compare_commits_by_commit_date;2698}2699else if(contents_from)2700die("--contents and --reverse do not blend well.");2701else{2702 final_commit_name =prepare_initial(&sb);2703 sb.commits.compare = compare_commits_by_reverse_commit_date;2704if(revs.first_parent_only)2705 revs.children.name = NULL;2706}27072708if(!sb.final) {2709/*2710 * "--not A B -- path" without anything positive;2711 * do not default to HEAD, but use the working tree2712 * or "--contents".2713 */2714setup_work_tree();2715 sb.final =fake_working_tree_commit(&sb.revs->diffopt,2716 path, contents_from);2717add_pending_object(&revs, &(sb.final->object),":");2718}2719else if(contents_from)2720die("Cannot use --contents with final commit object name");27212722if(reverse && revs.first_parent_only) {2723struct object_array_entry *entry =find_single_final(sb.revs);2724if(!entry)2725die("--reverse and --first-parent together require specified latest commit");2726else2727 final_commit = (struct commit*) entry->item;2728}27292730/*2731 * If we have bottom, this will mark the ancestors of the2732 * bottom commits we would reach while traversing as2733 * uninteresting.2734 */2735if(prepare_revision_walk(&revs))2736die(_("revision walk setup failed"));27372738if(reverse && revs.first_parent_only) {2739struct commit *c = final_commit;27402741 sb.revs->children.name ="children";2742while(c->parents &&2743oidcmp(&c->object.oid, &sb.final->object.oid)) {2744struct commit_list *l =xcalloc(1,sizeof(*l));27452746 l->item = c;2747if(add_decoration(&sb.revs->children,2748&c->parents->item->object, l))2749die("BUG: not unique item in first-parent chain");2750 c = c->parents->item;2751}27522753if(oidcmp(&c->object.oid, &sb.final->object.oid))2754die("--reverse --first-parent together require range along first-parent chain");2755}27562757if(is_null_oid(&sb.final->object.oid)) {2758 o = sb.final->util;2759 sb.final_buf =xmemdupz(o->file.ptr, o->file.size);2760 sb.final_buf_size = o->file.size;2761}2762else{2763 o =get_origin(&sb, sb.final, path);2764if(fill_blob_sha1_and_mode(o))2765die("no such path%sin%s", path, final_commit_name);27662767if(DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&2768textconv_object(path, o->mode, o->blob_sha1,1, (char**) &sb.final_buf,2769&sb.final_buf_size))2770;2771else2772 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2773&sb.final_buf_size);27742775if(!sb.final_buf)2776die("Cannot read blob%sfor path%s",2777sha1_to_hex(o->blob_sha1),2778 path);2779}2780 num_read_blob++;2781 lno =prepare_lines(&sb);27822783if(lno && !range_list.nr)2784string_list_append(&range_list,xstrdup("1"));27852786 anchor =1;2787range_set_init(&ranges, range_list.nr);2788for(range_i =0; range_i < range_list.nr; ++range_i) {2789long bottom, top;2790if(parse_range_arg(range_list.items[range_i].string,2791 nth_line_cb, &sb, lno, anchor,2792&bottom, &top, sb.path))2793usage(blame_usage);2794if(lno < top || ((lno || bottom) && lno < bottom))2795die("file%shas only%lu lines", path, lno);2796if(bottom <1)2797 bottom =1;2798if(top <1)2799 top = lno;2800 bottom--;2801range_set_append_unsafe(&ranges, bottom, top);2802 anchor = top +1;2803}2804sort_and_merge_range_set(&ranges);28052806for(range_i = ranges.nr; range_i >0; --range_i) {2807const struct range *r = &ranges.ranges[range_i -1];2808long bottom = r->start;2809long top = r->end;2810struct blame_entry *next = ent;2811 ent =xcalloc(1,sizeof(*ent));2812 ent->lno = bottom;2813 ent->num_lines = top - bottom;2814 ent->suspect = o;2815 ent->s_lno = bottom;2816 ent->next = next;2817origin_incref(o);2818}28192820 o->suspects = ent;2821prio_queue_put(&sb.commits, o->commit);28222823origin_decref(o);28242825range_set_release(&ranges);2826string_list_clear(&range_list,0);28272828 sb.ent = NULL;2829 sb.path = path;28302831read_mailmap(&mailmap, NULL);28322833if(!incremental)2834setup_pager();28352836assign_blame(&sb, opt);28372838free(final_commit_name);28392840if(incremental)2841return0;28422843 sb.ent =blame_sort(sb.ent, compare_blame_final);28442845coalesce(&sb);28462847if(!(output_option & OUTPUT_PORCELAIN))2848find_alignment(&sb, &output_option);28492850output(&sb, output_option);2851free((void*)sb.final_buf);2852for(ent = sb.ent; ent; ) {2853struct blame_entry *e = ent->next;2854free(ent);2855 ent = e;2856}28572858if(show_stats) {2859printf("num read blob:%d\n", num_read_blob);2860printf("num get patch:%d\n", num_get_patch);2861printf("num commits:%d\n", num_commits);2862}2863return0;2864}