1/* 2 * Pickaxe 3 * 4 * Copyright (c) 2006, Junio C Hamano 5 */ 6 7#include"cache.h" 8#include"builtin.h" 9#include"blob.h" 10#include"commit.h" 11#include"tag.h" 12#include"tree-walk.h" 13#include"diff.h" 14#include"diffcore.h" 15#include"revision.h" 16#include"quote.h" 17#include"xdiff-interface.h" 18#include"cache-tree.h" 19#include"path-list.h" 20#include"mailmap.h" 21#include"parse-options.h" 22 23static char blame_usage[] ="git-blame [options] [rev-opts] [rev] [--] file"; 24 25static const char*blame_opt_usage[] = { 26 blame_usage, 27"", 28"[rev-opts] are documented in git-rev-parse(1)", 29 NULL 30}; 31 32static int longest_file; 33static int longest_author; 34static int max_orig_digits; 35static int max_digits; 36static int max_score_digits; 37static int show_root; 38static int reverse; 39static int blank_boundary; 40static int incremental; 41static int cmd_is_annotate; 42static int xdl_opts = XDF_NEED_MINIMAL; 43static struct path_list mailmap; 44 45#ifndef DEBUG 46#define DEBUG 0 47#endif 48 49/* stats */ 50static int num_read_blob; 51static int num_get_patch; 52static int num_commits; 53 54#define PICKAXE_BLAME_MOVE 01 55#define PICKAXE_BLAME_COPY 02 56#define PICKAXE_BLAME_COPY_HARDER 04 57#define PICKAXE_BLAME_COPY_HARDEST 010 58 59/* 60 * blame for a blame_entry with score lower than these thresholds 61 * is not passed to the parent using move/copy logic. 62 */ 63static unsigned blame_move_score; 64static unsigned blame_copy_score; 65#define BLAME_DEFAULT_MOVE_SCORE 20 66#define BLAME_DEFAULT_COPY_SCORE 40 67 68/* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */ 69#define METAINFO_SHOWN (1u<<12) 70#define MORE_THAN_ONE_PATH (1u<<13) 71 72/* 73 * One blob in a commit that is being suspected 74 */ 75struct origin { 76int refcnt; 77struct commit *commit; 78 mmfile_t file; 79unsigned char blob_sha1[20]; 80char path[FLEX_ARRAY]; 81}; 82 83/* 84 * Given an origin, prepare mmfile_t structure to be used by the 85 * diff machinery 86 */ 87static voidfill_origin_blob(struct origin *o, mmfile_t *file) 88{ 89if(!o->file.ptr) { 90enum object_type type; 91 num_read_blob++; 92 file->ptr =read_sha1_file(o->blob_sha1, &type, 93(unsigned long*)(&(file->size))); 94if(!file->ptr) 95die("Cannot read blob%sfor path%s", 96sha1_to_hex(o->blob_sha1), 97 o->path); 98 o->file = *file; 99} 100else 101*file = o->file; 102} 103 104/* 105 * Origin is refcounted and usually we keep the blob contents to be 106 * reused. 107 */ 108staticinlinestruct origin *origin_incref(struct origin *o) 109{ 110if(o) 111 o->refcnt++; 112return o; 113} 114 115static voidorigin_decref(struct origin *o) 116{ 117if(o && --o->refcnt <=0) { 118free(o->file.ptr); 119free(o); 120} 121} 122 123static voiddrop_origin_blob(struct origin *o) 124{ 125if(o->file.ptr) { 126free(o->file.ptr); 127 o->file.ptr = NULL; 128} 129} 130 131/* 132 * Each group of lines is described by a blame_entry; it can be split 133 * as we pass blame to the parents. They form a linked list in the 134 * scoreboard structure, sorted by the target line number. 135 */ 136struct blame_entry { 137struct blame_entry *prev; 138struct blame_entry *next; 139 140/* the first line of this group in the final image; 141 * internally all line numbers are 0 based. 142 */ 143int lno; 144 145/* how many lines this group has */ 146int num_lines; 147 148/* the commit that introduced this group into the final image */ 149struct origin *suspect; 150 151/* true if the suspect is truly guilty; false while we have not 152 * checked if the group came from one of its parents. 153 */ 154char guilty; 155 156/* the line number of the first line of this group in the 157 * suspect's file; internally all line numbers are 0 based. 158 */ 159int s_lno; 160 161/* how significant this entry is -- cached to avoid 162 * scanning the lines over and over. 163 */ 164unsigned score; 165}; 166 167/* 168 * The current state of the blame assignment. 169 */ 170struct scoreboard { 171/* the final commit (i.e. where we started digging from) */ 172struct commit *final; 173struct rev_info *revs; 174const char*path; 175 176/* 177 * The contents in the final image. 178 * Used by many functions to obtain contents of the nth line, 179 * indexed with scoreboard.lineno[blame_entry.lno]. 180 */ 181const char*final_buf; 182unsigned long final_buf_size; 183 184/* linked list of blames */ 185struct blame_entry *ent; 186 187/* look-up a line in the final buffer */ 188int num_lines; 189int*lineno; 190}; 191 192staticinlineintsame_suspect(struct origin *a,struct origin *b) 193{ 194if(a == b) 195return1; 196if(a->commit != b->commit) 197return0; 198return!strcmp(a->path, b->path); 199} 200 201static voidsanity_check_refcnt(struct scoreboard *); 202 203/* 204 * If two blame entries that are next to each other came from 205 * contiguous lines in the same origin (i.e. <commit, path> pair), 206 * merge them together. 207 */ 208static voidcoalesce(struct scoreboard *sb) 209{ 210struct blame_entry *ent, *next; 211 212for(ent = sb->ent; ent && (next = ent->next); ent = next) { 213if(same_suspect(ent->suspect, next->suspect) && 214 ent->guilty == next->guilty && 215 ent->s_lno + ent->num_lines == next->s_lno) { 216 ent->num_lines += next->num_lines; 217 ent->next = next->next; 218if(ent->next) 219 ent->next->prev = ent; 220origin_decref(next->suspect); 221free(next); 222 ent->score =0; 223 next = ent;/* again */ 224} 225} 226 227if(DEBUG)/* sanity */ 228sanity_check_refcnt(sb); 229} 230 231/* 232 * Given a commit and a path in it, create a new origin structure. 233 * The callers that add blame to the scoreboard should use 234 * get_origin() to obtain shared, refcounted copy instead of calling 235 * this function directly. 236 */ 237static struct origin *make_origin(struct commit *commit,const char*path) 238{ 239struct origin *o; 240 o =xcalloc(1,sizeof(*o) +strlen(path) +1); 241 o->commit = commit; 242 o->refcnt =1; 243strcpy(o->path, path); 244return o; 245} 246 247/* 248 * Locate an existing origin or create a new one. 249 */ 250static struct origin *get_origin(struct scoreboard *sb, 251struct commit *commit, 252const char*path) 253{ 254struct blame_entry *e; 255 256for(e = sb->ent; e; e = e->next) { 257if(e->suspect->commit == commit && 258!strcmp(e->suspect->path, path)) 259returnorigin_incref(e->suspect); 260} 261returnmake_origin(commit, path); 262} 263 264/* 265 * Fill the blob_sha1 field of an origin if it hasn't, so that later 266 * call to fill_origin_blob() can use it to locate the data. blob_sha1 267 * for an origin is also used to pass the blame for the entire file to 268 * the parent to detect the case where a child's blob is identical to 269 * that of its parent's. 270 */ 271static intfill_blob_sha1(struct origin *origin) 272{ 273unsigned mode; 274 275if(!is_null_sha1(origin->blob_sha1)) 276return0; 277if(get_tree_entry(origin->commit->object.sha1, 278 origin->path, 279 origin->blob_sha1, &mode)) 280goto error_out; 281if(sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB) 282goto error_out; 283return0; 284 error_out: 285hashclr(origin->blob_sha1); 286return-1; 287} 288 289/* 290 * We have an origin -- check if the same path exists in the 291 * parent and return an origin structure to represent it. 292 */ 293static struct origin *find_origin(struct scoreboard *sb, 294struct commit *parent, 295struct origin *origin) 296{ 297struct origin *porigin = NULL; 298struct diff_options diff_opts; 299const char*paths[2]; 300 301if(parent->util) { 302/* 303 * Each commit object can cache one origin in that 304 * commit. This is a freestanding copy of origin and 305 * not refcounted. 306 */ 307struct origin *cached = parent->util; 308if(!strcmp(cached->path, origin->path)) { 309/* 310 * The same path between origin and its parent 311 * without renaming -- the most common case. 312 */ 313 porigin =get_origin(sb, parent, cached->path); 314 315/* 316 * If the origin was newly created (i.e. get_origin 317 * would call make_origin if none is found in the 318 * scoreboard), it does not know the blob_sha1, 319 * so copy it. Otherwise porigin was in the 320 * scoreboard and already knows blob_sha1. 321 */ 322if(porigin->refcnt ==1) 323hashcpy(porigin->blob_sha1, cached->blob_sha1); 324return porigin; 325} 326/* otherwise it was not very useful; free it */ 327free(parent->util); 328 parent->util = NULL; 329} 330 331/* See if the origin->path is different between parent 332 * and origin first. Most of the time they are the 333 * same and diff-tree is fairly efficient about this. 334 */ 335diff_setup(&diff_opts); 336DIFF_OPT_SET(&diff_opts, RECURSIVE); 337 diff_opts.detect_rename =0; 338 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 339 paths[0] = origin->path; 340 paths[1] = NULL; 341 342diff_tree_setup_paths(paths, &diff_opts); 343if(diff_setup_done(&diff_opts) <0) 344die("diff-setup"); 345 346if(is_null_sha1(origin->commit->object.sha1)) 347do_diff_cache(parent->tree->object.sha1, &diff_opts); 348else 349diff_tree_sha1(parent->tree->object.sha1, 350 origin->commit->tree->object.sha1, 351"", &diff_opts); 352diffcore_std(&diff_opts); 353 354/* It is either one entry that says "modified", or "created", 355 * or nothing. 356 */ 357if(!diff_queued_diff.nr) { 358/* The path is the same as parent */ 359 porigin =get_origin(sb, parent, origin->path); 360hashcpy(porigin->blob_sha1, origin->blob_sha1); 361} 362else if(diff_queued_diff.nr !=1) 363die("internal error in blame::find_origin"); 364else{ 365struct diff_filepair *p = diff_queued_diff.queue[0]; 366switch(p->status) { 367default: 368die("internal error in blame::find_origin (%c)", 369 p->status); 370case'M': 371 porigin =get_origin(sb, parent, origin->path); 372hashcpy(porigin->blob_sha1, p->one->sha1); 373break; 374case'A': 375case'T': 376/* Did not exist in parent, or type changed */ 377break; 378} 379} 380diff_flush(&diff_opts); 381diff_tree_release_paths(&diff_opts); 382if(porigin) { 383/* 384 * Create a freestanding copy that is not part of 385 * the refcounted origin found in the scoreboard, and 386 * cache it in the commit. 387 */ 388struct origin *cached; 389 390 cached =make_origin(porigin->commit, porigin->path); 391hashcpy(cached->blob_sha1, porigin->blob_sha1); 392 parent->util = cached; 393} 394return porigin; 395} 396 397/* 398 * We have an origin -- find the path that corresponds to it in its 399 * parent and return an origin structure to represent it. 400 */ 401static struct origin *find_rename(struct scoreboard *sb, 402struct commit *parent, 403struct origin *origin) 404{ 405struct origin *porigin = NULL; 406struct diff_options diff_opts; 407int i; 408const char*paths[2]; 409 410diff_setup(&diff_opts); 411DIFF_OPT_SET(&diff_opts, RECURSIVE); 412 diff_opts.detect_rename = DIFF_DETECT_RENAME; 413 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT; 414 diff_opts.single_follow = origin->path; 415 paths[0] = NULL; 416diff_tree_setup_paths(paths, &diff_opts); 417if(diff_setup_done(&diff_opts) <0) 418die("diff-setup"); 419 420if(is_null_sha1(origin->commit->object.sha1)) 421do_diff_cache(parent->tree->object.sha1, &diff_opts); 422else 423diff_tree_sha1(parent->tree->object.sha1, 424 origin->commit->tree->object.sha1, 425"", &diff_opts); 426diffcore_std(&diff_opts); 427 428for(i =0; i < diff_queued_diff.nr; i++) { 429struct diff_filepair *p = diff_queued_diff.queue[i]; 430if((p->status =='R'|| p->status =='C') && 431!strcmp(p->two->path, origin->path)) { 432 porigin =get_origin(sb, parent, p->one->path); 433hashcpy(porigin->blob_sha1, p->one->sha1); 434break; 435} 436} 437diff_flush(&diff_opts); 438diff_tree_release_paths(&diff_opts); 439return porigin; 440} 441 442/* 443 * Parsing of patch chunks... 444 */ 445struct chunk { 446/* line number in postimage; up to but not including this 447 * line is the same as preimage 448 */ 449int same; 450 451/* preimage line number after this chunk */ 452int p_next; 453 454/* postimage line number after this chunk */ 455int t_next; 456}; 457 458struct patch { 459struct chunk *chunks; 460int num; 461}; 462 463struct blame_diff_state { 464struct xdiff_emit_state xm; 465struct patch *ret; 466unsigned hunk_post_context; 467unsigned hunk_in_pre_context :1; 468}; 469 470static voidprocess_u_diff(void*state_,char*line,unsigned long len) 471{ 472struct blame_diff_state *state = state_; 473struct chunk *chunk; 474int off1, off2, len1, len2, num; 475 476 num = state->ret->num; 477if(len <4|| line[0] !='@'|| line[1] !='@') { 478if(state->hunk_in_pre_context && line[0] ==' ') 479 state->ret->chunks[num -1].same++; 480else{ 481 state->hunk_in_pre_context =0; 482if(line[0] ==' ') 483 state->hunk_post_context++; 484else 485 state->hunk_post_context =0; 486} 487return; 488} 489 490if(num && state->hunk_post_context) { 491 chunk = &state->ret->chunks[num -1]; 492 chunk->p_next -= state->hunk_post_context; 493 chunk->t_next -= state->hunk_post_context; 494} 495 state->ret->num = ++num; 496 state->ret->chunks =xrealloc(state->ret->chunks, 497sizeof(struct chunk) * num); 498 chunk = &state->ret->chunks[num -1]; 499if(parse_hunk_header(line, len, &off1, &len1, &off2, &len2)) { 500 state->ret->num--; 501return; 502} 503 504/* Line numbers in patch output are one based. */ 505 off1--; 506 off2--; 507 508 chunk->same = len2 ? off2 : (off2 +1); 509 510 chunk->p_next = off1 + (len1 ? len1 :1); 511 chunk->t_next = chunk->same + len2; 512 state->hunk_in_pre_context =1; 513 state->hunk_post_context =0; 514} 515 516static struct patch *compare_buffer(mmfile_t *file_p, mmfile_t *file_o, 517int context) 518{ 519struct blame_diff_state state; 520 xpparam_t xpp; 521 xdemitconf_t xecfg; 522 xdemitcb_t ecb; 523 524 xpp.flags = xdl_opts; 525memset(&xecfg,0,sizeof(xecfg)); 526 xecfg.ctxlen = context; 527 ecb.outf = xdiff_outf; 528 ecb.priv = &state; 529memset(&state,0,sizeof(state)); 530 state.xm.consume = process_u_diff; 531 state.ret =xmalloc(sizeof(struct patch)); 532 state.ret->chunks = NULL; 533 state.ret->num =0; 534 535xdi_diff(file_p, file_o, &xpp, &xecfg, &ecb); 536 537if(state.ret->num) { 538struct chunk *chunk; 539 chunk = &state.ret->chunks[state.ret->num -1]; 540 chunk->p_next -= state.hunk_post_context; 541 chunk->t_next -= state.hunk_post_context; 542} 543return state.ret; 544} 545 546/* 547 * Run diff between two origins and grab the patch output, so that 548 * we can pass blame for lines origin is currently suspected for 549 * to its parent. 550 */ 551static struct patch *get_patch(struct origin *parent,struct origin *origin) 552{ 553 mmfile_t file_p, file_o; 554struct patch *patch; 555 556fill_origin_blob(parent, &file_p); 557fill_origin_blob(origin, &file_o); 558if(!file_p.ptr || !file_o.ptr) 559return NULL; 560 patch =compare_buffer(&file_p, &file_o,0); 561 num_get_patch++; 562return patch; 563} 564 565static voidfree_patch(struct patch *p) 566{ 567free(p->chunks); 568free(p); 569} 570 571/* 572 * Link in a new blame entry to the scoreboard. Entries that cover the 573 * same line range have been removed from the scoreboard previously. 574 */ 575static voidadd_blame_entry(struct scoreboard *sb,struct blame_entry *e) 576{ 577struct blame_entry *ent, *prev = NULL; 578 579origin_incref(e->suspect); 580 581for(ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next) 582 prev = ent; 583 584/* prev, if not NULL, is the last one that is below e */ 585 e->prev = prev; 586if(prev) { 587 e->next = prev->next; 588 prev->next = e; 589} 590else{ 591 e->next = sb->ent; 592 sb->ent = e; 593} 594if(e->next) 595 e->next->prev = e; 596} 597 598/* 599 * src typically is on-stack; we want to copy the information in it to 600 * a malloced blame_entry that is already on the linked list of the 601 * scoreboard. The origin of dst loses a refcnt while the origin of src 602 * gains one. 603 */ 604static voiddup_entry(struct blame_entry *dst,struct blame_entry *src) 605{ 606struct blame_entry *p, *n; 607 608 p = dst->prev; 609 n = dst->next; 610origin_incref(src->suspect); 611origin_decref(dst->suspect); 612memcpy(dst, src,sizeof(*src)); 613 dst->prev = p; 614 dst->next = n; 615 dst->score =0; 616} 617 618static const char*nth_line(struct scoreboard *sb,int lno) 619{ 620return sb->final_buf + sb->lineno[lno]; 621} 622 623/* 624 * It is known that lines between tlno to same came from parent, and e 625 * has an overlap with that range. it also is known that parent's 626 * line plno corresponds to e's line tlno. 627 * 628 * <---- e -----> 629 * <------> 630 * <------------> 631 * <------------> 632 * <------------------> 633 * 634 * Split e into potentially three parts; before this chunk, the chunk 635 * to be blamed for the parent, and after that portion. 636 */ 637static voidsplit_overlap(struct blame_entry *split, 638struct blame_entry *e, 639int tlno,int plno,int same, 640struct origin *parent) 641{ 642int chunk_end_lno; 643memset(split,0,sizeof(struct blame_entry [3])); 644 645if(e->s_lno < tlno) { 646/* there is a pre-chunk part not blamed on parent */ 647 split[0].suspect =origin_incref(e->suspect); 648 split[0].lno = e->lno; 649 split[0].s_lno = e->s_lno; 650 split[0].num_lines = tlno - e->s_lno; 651 split[1].lno = e->lno + tlno - e->s_lno; 652 split[1].s_lno = plno; 653} 654else{ 655 split[1].lno = e->lno; 656 split[1].s_lno = plno + (e->s_lno - tlno); 657} 658 659if(same < e->s_lno + e->num_lines) { 660/* there is a post-chunk part not blamed on parent */ 661 split[2].suspect =origin_incref(e->suspect); 662 split[2].lno = e->lno + (same - e->s_lno); 663 split[2].s_lno = e->s_lno + (same - e->s_lno); 664 split[2].num_lines = e->s_lno + e->num_lines - same; 665 chunk_end_lno = split[2].lno; 666} 667else 668 chunk_end_lno = e->lno + e->num_lines; 669 split[1].num_lines = chunk_end_lno - split[1].lno; 670 671/* 672 * if it turns out there is nothing to blame the parent for, 673 * forget about the splitting. !split[1].suspect signals this. 674 */ 675if(split[1].num_lines <1) 676return; 677 split[1].suspect =origin_incref(parent); 678} 679 680/* 681 * split_overlap() divided an existing blame e into up to three parts 682 * in split. Adjust the linked list of blames in the scoreboard to 683 * reflect the split. 684 */ 685static voidsplit_blame(struct scoreboard *sb, 686struct blame_entry *split, 687struct blame_entry *e) 688{ 689struct blame_entry *new_entry; 690 691if(split[0].suspect && split[2].suspect) { 692/* The first part (reuse storage for the existing entry e) */ 693dup_entry(e, &split[0]); 694 695/* The last part -- me */ 696 new_entry =xmalloc(sizeof(*new_entry)); 697memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 698add_blame_entry(sb, new_entry); 699 700/* ... and the middle part -- parent */ 701 new_entry =xmalloc(sizeof(*new_entry)); 702memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 703add_blame_entry(sb, new_entry); 704} 705else if(!split[0].suspect && !split[2].suspect) 706/* 707 * The parent covers the entire area; reuse storage for 708 * e and replace it with the parent. 709 */ 710dup_entry(e, &split[1]); 711else if(split[0].suspect) { 712/* me and then parent */ 713dup_entry(e, &split[0]); 714 715 new_entry =xmalloc(sizeof(*new_entry)); 716memcpy(new_entry, &(split[1]),sizeof(struct blame_entry)); 717add_blame_entry(sb, new_entry); 718} 719else{ 720/* parent and then me */ 721dup_entry(e, &split[1]); 722 723 new_entry =xmalloc(sizeof(*new_entry)); 724memcpy(new_entry, &(split[2]),sizeof(struct blame_entry)); 725add_blame_entry(sb, new_entry); 726} 727 728if(DEBUG) {/* sanity */ 729struct blame_entry *ent; 730int lno = sb->ent->lno, corrupt =0; 731 732for(ent = sb->ent; ent; ent = ent->next) { 733if(lno != ent->lno) 734 corrupt =1; 735if(ent->s_lno <0) 736 corrupt =1; 737 lno += ent->num_lines; 738} 739if(corrupt) { 740 lno = sb->ent->lno; 741for(ent = sb->ent; ent; ent = ent->next) { 742printf("L%8d l%8d n%8d\n", 743 lno, ent->lno, ent->num_lines); 744 lno = ent->lno + ent->num_lines; 745} 746die("oops"); 747} 748} 749} 750 751/* 752 * After splitting the blame, the origins used by the 753 * on-stack blame_entry should lose one refcnt each. 754 */ 755static voiddecref_split(struct blame_entry *split) 756{ 757int i; 758 759for(i =0; i <3; i++) 760origin_decref(split[i].suspect); 761} 762 763/* 764 * Helper for blame_chunk(). blame_entry e is known to overlap with 765 * the patch hunk; split it and pass blame to the parent. 766 */ 767static voidblame_overlap(struct scoreboard *sb,struct blame_entry *e, 768int tlno,int plno,int same, 769struct origin *parent) 770{ 771struct blame_entry split[3]; 772 773split_overlap(split, e, tlno, plno, same, parent); 774if(split[1].suspect) 775split_blame(sb, split, e); 776decref_split(split); 777} 778 779/* 780 * Find the line number of the last line the target is suspected for. 781 */ 782static intfind_last_in_target(struct scoreboard *sb,struct origin *target) 783{ 784struct blame_entry *e; 785int last_in_target = -1; 786 787for(e = sb->ent; e; e = e->next) { 788if(e->guilty || !same_suspect(e->suspect, target)) 789continue; 790if(last_in_target < e->s_lno + e->num_lines) 791 last_in_target = e->s_lno + e->num_lines; 792} 793return last_in_target; 794} 795 796/* 797 * Process one hunk from the patch between the current suspect for 798 * blame_entry e and its parent. Find and split the overlap, and 799 * pass blame to the overlapping part to the parent. 800 */ 801static voidblame_chunk(struct scoreboard *sb, 802int tlno,int plno,int same, 803struct origin *target,struct origin *parent) 804{ 805struct blame_entry *e; 806 807for(e = sb->ent; e; e = e->next) { 808if(e->guilty || !same_suspect(e->suspect, target)) 809continue; 810if(same <= e->s_lno) 811continue; 812if(tlno < e->s_lno + e->num_lines) 813blame_overlap(sb, e, tlno, plno, same, parent); 814} 815} 816 817/* 818 * We are looking at the origin 'target' and aiming to pass blame 819 * for the lines it is suspected to its parent. Run diff to find 820 * which lines came from parent and pass blame for them. 821 */ 822static intpass_blame_to_parent(struct scoreboard *sb, 823struct origin *target, 824struct origin *parent) 825{ 826int i, last_in_target, plno, tlno; 827struct patch *patch; 828 829 last_in_target =find_last_in_target(sb, target); 830if(last_in_target <0) 831return1;/* nothing remains for this target */ 832 833 patch =get_patch(parent, target); 834 plno = tlno =0; 835for(i =0; i < patch->num; i++) { 836struct chunk *chunk = &patch->chunks[i]; 837 838blame_chunk(sb, tlno, plno, chunk->same, target, parent); 839 plno = chunk->p_next; 840 tlno = chunk->t_next; 841} 842/* The rest (i.e. anything after tlno) are the same as the parent */ 843blame_chunk(sb, tlno, plno, last_in_target, target, parent); 844 845free_patch(patch); 846return0; 847} 848 849/* 850 * The lines in blame_entry after splitting blames many times can become 851 * very small and trivial, and at some point it becomes pointless to 852 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any 853 * ordinary C program, and it is not worth to say it was copied from 854 * totally unrelated file in the parent. 855 * 856 * Compute how trivial the lines in the blame_entry are. 857 */ 858static unsignedent_score(struct scoreboard *sb,struct blame_entry *e) 859{ 860unsigned score; 861const char*cp, *ep; 862 863if(e->score) 864return e->score; 865 866 score =1; 867 cp =nth_line(sb, e->lno); 868 ep =nth_line(sb, e->lno + e->num_lines); 869while(cp < ep) { 870unsigned ch = *((unsigned char*)cp); 871if(isalnum(ch)) 872 score++; 873 cp++; 874} 875 e->score = score; 876return score; 877} 878 879/* 880 * best_so_far[] and this[] are both a split of an existing blame_entry 881 * that passes blame to the parent. Maintain best_so_far the best split 882 * so far, by comparing this and best_so_far and copying this into 883 * bst_so_far as needed. 884 */ 885static voidcopy_split_if_better(struct scoreboard *sb, 886struct blame_entry *best_so_far, 887struct blame_entry *this) 888{ 889int i; 890 891if(!this[1].suspect) 892return; 893if(best_so_far[1].suspect) { 894if(ent_score(sb, &this[1]) <ent_score(sb, &best_so_far[1])) 895return; 896} 897 898for(i =0; i <3; i++) 899origin_incref(this[i].suspect); 900decref_split(best_so_far); 901memcpy(best_so_far,this,sizeof(struct blame_entry [3])); 902} 903 904/* 905 * We are looking at a part of the final image represented by 906 * ent (tlno and same are offset by ent->s_lno). 907 * tlno is where we are looking at in the final image. 908 * up to (but not including) same match preimage. 909 * plno is where we are looking at in the preimage. 910 * 911 * <-------------- final image ----------------------> 912 * <------ent------> 913 * ^tlno ^same 914 * <---------preimage-----> 915 * ^plno 916 * 917 * All line numbers are 0-based. 918 */ 919static voidhandle_split(struct scoreboard *sb, 920struct blame_entry *ent, 921int tlno,int plno,int same, 922struct origin *parent, 923struct blame_entry *split) 924{ 925if(ent->num_lines <= tlno) 926return; 927if(tlno < same) { 928struct blame_entry this[3]; 929 tlno += ent->s_lno; 930 same += ent->s_lno; 931split_overlap(this, ent, tlno, plno, same, parent); 932copy_split_if_better(sb, split,this); 933decref_split(this); 934} 935} 936 937/* 938 * Find the lines from parent that are the same as ent so that 939 * we can pass blames to it. file_p has the blob contents for 940 * the parent. 941 */ 942static voidfind_copy_in_blob(struct scoreboard *sb, 943struct blame_entry *ent, 944struct origin *parent, 945struct blame_entry *split, 946 mmfile_t *file_p) 947{ 948const char*cp; 949int cnt; 950 mmfile_t file_o; 951struct patch *patch; 952int i, plno, tlno; 953 954/* 955 * Prepare mmfile that contains only the lines in ent. 956 */ 957 cp =nth_line(sb, ent->lno); 958 file_o.ptr = (char*) cp; 959 cnt = ent->num_lines; 960 961while(cnt && cp < sb->final_buf + sb->final_buf_size) { 962if(*cp++ =='\n') 963 cnt--; 964} 965 file_o.size = cp - file_o.ptr; 966 967 patch =compare_buffer(file_p, &file_o,1); 968 969/* 970 * file_o is a part of final image we are annotating. 971 * file_p partially may match that image. 972 */ 973memset(split,0,sizeof(struct blame_entry [3])); 974 plno = tlno =0; 975for(i =0; i < patch->num; i++) { 976struct chunk *chunk = &patch->chunks[i]; 977 978handle_split(sb, ent, tlno, plno, chunk->same, parent, split); 979 plno = chunk->p_next; 980 tlno = chunk->t_next; 981} 982/* remainder, if any, all match the preimage */ 983handle_split(sb, ent, tlno, plno, ent->num_lines, parent, split); 984free_patch(patch); 985} 986 987/* 988 * See if lines currently target is suspected for can be attributed to 989 * parent. 990 */ 991static intfind_move_in_parent(struct scoreboard *sb, 992struct origin *target, 993struct origin *parent) 994{ 995int last_in_target, made_progress; 996struct blame_entry *e, split[3]; 997 mmfile_t file_p; 998 999 last_in_target =find_last_in_target(sb, target);1000if(last_in_target <0)1001return1;/* nothing remains for this target */10021003fill_origin_blob(parent, &file_p);1004if(!file_p.ptr)1005return0;10061007 made_progress =1;1008while(made_progress) {1009 made_progress =0;1010for(e = sb->ent; e; e = e->next) {1011if(e->guilty || !same_suspect(e->suspect, target))1012continue;1013find_copy_in_blob(sb, e, parent, split, &file_p);1014if(split[1].suspect &&1015 blame_move_score <ent_score(sb, &split[1])) {1016split_blame(sb, split, e);1017 made_progress =1;1018}1019decref_split(split);1020}1021}1022return0;1023}10241025struct blame_list {1026struct blame_entry *ent;1027struct blame_entry split[3];1028};10291030/*1031 * Count the number of entries the target is suspected for,1032 * and prepare a list of entry and the best split.1033 */1034static struct blame_list *setup_blame_list(struct scoreboard *sb,1035struct origin *target,1036int*num_ents_p)1037{1038struct blame_entry *e;1039int num_ents, i;1040struct blame_list *blame_list = NULL;10411042for(e = sb->ent, num_ents =0; e; e = e->next)1043if(!e->guilty &&same_suspect(e->suspect, target))1044 num_ents++;1045if(num_ents) {1046 blame_list =xcalloc(num_ents,sizeof(struct blame_list));1047for(e = sb->ent, i =0; e; e = e->next)1048if(!e->guilty &&same_suspect(e->suspect, target))1049 blame_list[i++].ent = e;1050}1051*num_ents_p = num_ents;1052return blame_list;1053}10541055/*1056 * For lines target is suspected for, see if we can find code movement1057 * across file boundary from the parent commit. porigin is the path1058 * in the parent we already tried.1059 */1060static intfind_copy_in_parent(struct scoreboard *sb,1061struct origin *target,1062struct commit *parent,1063struct origin *porigin,1064int opt)1065{1066struct diff_options diff_opts;1067const char*paths[1];1068int i, j;1069int retval;1070struct blame_list *blame_list;1071int num_ents;10721073 blame_list =setup_blame_list(sb, target, &num_ents);1074if(!blame_list)1075return1;/* nothing remains for this target */10761077diff_setup(&diff_opts);1078DIFF_OPT_SET(&diff_opts, RECURSIVE);1079 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;10801081 paths[0] = NULL;1082diff_tree_setup_paths(paths, &diff_opts);1083if(diff_setup_done(&diff_opts) <0)1084die("diff-setup");10851086/* Try "find copies harder" on new path if requested;1087 * we do not want to use diffcore_rename() actually to1088 * match things up; find_copies_harder is set only to1089 * force diff_tree_sha1() to feed all filepairs to diff_queue,1090 * and this code needs to be after diff_setup_done(), which1091 * usually makes find-copies-harder imply copy detection.1092 */1093if((opt & PICKAXE_BLAME_COPY_HARDEST)1094|| ((opt & PICKAXE_BLAME_COPY_HARDER)1095&& (!porigin ||strcmp(target->path, porigin->path))))1096DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);10971098if(is_null_sha1(target->commit->object.sha1))1099do_diff_cache(parent->tree->object.sha1, &diff_opts);1100else1101diff_tree_sha1(parent->tree->object.sha1,1102 target->commit->tree->object.sha1,1103"", &diff_opts);11041105if(!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))1106diffcore_std(&diff_opts);11071108 retval =0;1109while(1) {1110int made_progress =0;11111112for(i =0; i < diff_queued_diff.nr; i++) {1113struct diff_filepair *p = diff_queued_diff.queue[i];1114struct origin *norigin;1115 mmfile_t file_p;1116struct blame_entry this[3];11171118if(!DIFF_FILE_VALID(p->one))1119continue;/* does not exist in parent */1120if(porigin && !strcmp(p->one->path, porigin->path))1121/* find_move already dealt with this path */1122continue;11231124 norigin =get_origin(sb, parent, p->one->path);1125hashcpy(norigin->blob_sha1, p->one->sha1);1126fill_origin_blob(norigin, &file_p);1127if(!file_p.ptr)1128continue;11291130for(j =0; j < num_ents; j++) {1131find_copy_in_blob(sb, blame_list[j].ent,1132 norigin,this, &file_p);1133copy_split_if_better(sb, blame_list[j].split,1134this);1135decref_split(this);1136}1137origin_decref(norigin);1138}11391140for(j =0; j < num_ents; j++) {1141struct blame_entry *split = blame_list[j].split;1142if(split[1].suspect &&1143 blame_copy_score <ent_score(sb, &split[1])) {1144split_blame(sb, split, blame_list[j].ent);1145 made_progress =1;1146}1147decref_split(split);1148}1149free(blame_list);11501151if(!made_progress)1152break;1153 blame_list =setup_blame_list(sb, target, &num_ents);1154if(!blame_list) {1155 retval =1;1156break;1157}1158}1159diff_flush(&diff_opts);1160diff_tree_release_paths(&diff_opts);1161return retval;1162}11631164/*1165 * The blobs of origin and porigin exactly match, so everything1166 * origin is suspected for can be blamed on the parent.1167 */1168static voidpass_whole_blame(struct scoreboard *sb,1169struct origin *origin,struct origin *porigin)1170{1171struct blame_entry *e;11721173if(!porigin->file.ptr && origin->file.ptr) {1174/* Steal its file */1175 porigin->file = origin->file;1176 origin->file.ptr = NULL;1177}1178for(e = sb->ent; e; e = e->next) {1179if(!same_suspect(e->suspect, origin))1180continue;1181origin_incref(porigin);1182origin_decref(e->suspect);1183 e->suspect = porigin;1184}1185}11861187/*1188 * We pass blame from the current commit to its parents. We keep saying1189 * "parent" (and "porigin"), but what we mean is to find scapegoat to1190 * exonerate ourselves.1191 */1192static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit)1193{1194if(!reverse)1195return commit->parents;1196returnlookup_decoration(&revs->children, &commit->object);1197}11981199static intnum_scapegoats(struct rev_info *revs,struct commit *commit)1200{1201int cnt;1202struct commit_list *l =first_scapegoat(revs, commit);1203for(cnt =0; l; l = l->next)1204 cnt++;1205return cnt;1206}12071208#define MAXSG 1612091210static voidpass_blame(struct scoreboard *sb,struct origin *origin,int opt)1211{1212struct rev_info *revs = sb->revs;1213int i, pass, num_sg;1214struct commit *commit = origin->commit;1215struct commit_list *sg;1216struct origin *sg_buf[MAXSG];1217struct origin *porigin, **sg_origin = sg_buf;12181219 num_sg =num_scapegoats(revs, commit);1220if(!num_sg)1221goto finish;1222else if(num_sg <ARRAY_SIZE(sg_buf))1223memset(sg_buf,0,sizeof(sg_buf));1224else1225 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));12261227/*1228 * The first pass looks for unrenamed path to optimize for1229 * common cases, then we look for renames in the second pass.1230 */1231for(pass =0; pass <2; pass++) {1232struct origin *(*find)(struct scoreboard *,1233struct commit *,struct origin *);1234 find = pass ? find_rename : find_origin;12351236for(i =0, sg =first_scapegoat(revs, commit);1237 i < num_sg && sg;1238 sg = sg->next, i++) {1239struct commit *p = sg->item;1240int j, same;12411242if(sg_origin[i])1243continue;1244if(parse_commit(p))1245continue;1246 porigin =find(sb, p, origin);1247if(!porigin)1248continue;1249if(!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {1250pass_whole_blame(sb, origin, porigin);1251origin_decref(porigin);1252goto finish;1253}1254for(j = same =0; j < i; j++)1255if(sg_origin[j] &&1256!hashcmp(sg_origin[j]->blob_sha1,1257 porigin->blob_sha1)) {1258 same =1;1259break;1260}1261if(!same)1262 sg_origin[i] = porigin;1263else1264origin_decref(porigin);1265}1266}12671268 num_commits++;1269for(i =0, sg =first_scapegoat(revs, commit);1270 i < num_sg && sg;1271 sg = sg->next, i++) {1272struct origin *porigin = sg_origin[i];1273if(!porigin)1274continue;1275if(pass_blame_to_parent(sb, origin, porigin))1276goto finish;1277}12781279/*1280 * Optionally find moves in parents' files.1281 */1282if(opt & PICKAXE_BLAME_MOVE)1283for(i =0, sg =first_scapegoat(revs, commit);1284 i < num_sg && sg;1285 sg = sg->next, i++) {1286struct origin *porigin = sg_origin[i];1287if(!porigin)1288continue;1289if(find_move_in_parent(sb, origin, porigin))1290goto finish;1291}12921293/*1294 * Optionally find copies from parents' files.1295 */1296if(opt & PICKAXE_BLAME_COPY)1297for(i =0, sg =first_scapegoat(revs, commit);1298 i < num_sg && sg;1299 sg = sg->next, i++) {1300struct origin *porigin = sg_origin[i];1301if(find_copy_in_parent(sb, origin, sg->item,1302 porigin, opt))1303goto finish;1304}13051306 finish:1307for(i =0; i < num_sg; i++) {1308if(sg_origin[i]) {1309drop_origin_blob(sg_origin[i]);1310origin_decref(sg_origin[i]);1311}1312}1313drop_origin_blob(origin);1314if(sg_buf != sg_origin)1315free(sg_origin);1316}13171318/*1319 * Information on commits, used for output.1320 */1321struct commit_info1322{1323const char*author;1324const char*author_mail;1325unsigned long author_time;1326const char*author_tz;13271328/* filled only when asked for details */1329const char*committer;1330const char*committer_mail;1331unsigned long committer_time;1332const char*committer_tz;13331334const char*summary;1335};13361337/*1338 * Parse author/committer line in the commit object buffer1339 */1340static voidget_ac_line(const char*inbuf,const char*what,1341int bufsz,char*person,const char**mail,1342unsigned long*time,const char**tz)1343{1344int len, tzlen, maillen;1345char*tmp, *endp, *timepos;13461347 tmp =strstr(inbuf, what);1348if(!tmp)1349goto error_out;1350 tmp +=strlen(what);1351 endp =strchr(tmp,'\n');1352if(!endp)1353 len =strlen(tmp);1354else1355 len = endp - tmp;1356if(bufsz <= len) {1357 error_out:1358/* Ugh */1359*mail = *tz ="(unknown)";1360*time =0;1361return;1362}1363memcpy(person, tmp, len);13641365 tmp = person;1366 tmp += len;1367*tmp =0;1368while(*tmp !=' ')1369 tmp--;1370*tz = tmp+1;1371 tzlen = (person+len)-(tmp+1);13721373*tmp =0;1374while(*tmp !=' ')1375 tmp--;1376*time =strtoul(tmp, NULL,10);1377 timepos = tmp;13781379*tmp =0;1380while(*tmp !=' ')1381 tmp--;1382*mail = tmp +1;1383*tmp =0;1384 maillen = timepos - tmp;13851386if(!mailmap.nr)1387return;13881389/*1390 * mailmap expansion may make the name longer.1391 * make room by pushing stuff down.1392 */1393 tmp = person + bufsz - (tzlen +1);1394memmove(tmp, *tz, tzlen);1395 tmp[tzlen] =0;1396*tz = tmp;13971398 tmp = tmp - (maillen +1);1399memmove(tmp, *mail, maillen);1400 tmp[maillen] =0;1401*mail = tmp;14021403/*1404 * Now, convert e-mail using mailmap1405 */1406map_email(&mailmap, tmp +1, person, tmp-person-1);1407}14081409static voidget_commit_info(struct commit *commit,1410struct commit_info *ret,1411int detailed)1412{1413int len;1414char*tmp, *endp;1415static char author_buf[1024];1416static char committer_buf[1024];1417static char summary_buf[1024];14181419/*1420 * We've operated without save_commit_buffer, so1421 * we now need to populate them for output.1422 */1423if(!commit->buffer) {1424enum object_type type;1425unsigned long size;1426 commit->buffer =1427read_sha1_file(commit->object.sha1, &type, &size);1428if(!commit->buffer)1429die("Cannot read commit%s",1430sha1_to_hex(commit->object.sha1));1431}1432 ret->author = author_buf;1433get_ac_line(commit->buffer,"\nauthor ",1434sizeof(author_buf), author_buf, &ret->author_mail,1435&ret->author_time, &ret->author_tz);14361437if(!detailed)1438return;14391440 ret->committer = committer_buf;1441get_ac_line(commit->buffer,"\ncommitter ",1442sizeof(committer_buf), committer_buf, &ret->committer_mail,1443&ret->committer_time, &ret->committer_tz);14441445 ret->summary = summary_buf;1446 tmp =strstr(commit->buffer,"\n\n");1447if(!tmp) {1448 error_out:1449sprintf(summary_buf,"(%s)",sha1_to_hex(commit->object.sha1));1450return;1451}1452 tmp +=2;1453 endp =strchr(tmp,'\n');1454if(!endp)1455 endp = tmp +strlen(tmp);1456 len = endp - tmp;1457if(len >=sizeof(summary_buf) || len ==0)1458goto error_out;1459memcpy(summary_buf, tmp, len);1460 summary_buf[len] =0;1461}14621463/*1464 * To allow LF and other nonportable characters in pathnames,1465 * they are c-style quoted as needed.1466 */1467static voidwrite_filename_info(const char*path)1468{1469printf("filename ");1470write_name_quoted(path, stdout,'\n');1471}14721473/*1474 * The blame_entry is found to be guilty for the range. Mark it1475 * as such, and show it in incremental output.1476 */1477static voidfound_guilty_entry(struct blame_entry *ent)1478{1479if(ent->guilty)1480return;1481 ent->guilty =1;1482if(incremental) {1483struct origin *suspect = ent->suspect;14841485printf("%s %d %d %d\n",1486sha1_to_hex(suspect->commit->object.sha1),1487 ent->s_lno +1, ent->lno +1, ent->num_lines);1488if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {1489struct commit_info ci;1490 suspect->commit->object.flags |= METAINFO_SHOWN;1491get_commit_info(suspect->commit, &ci,1);1492printf("author%s\n", ci.author);1493printf("author-mail%s\n", ci.author_mail);1494printf("author-time%lu\n", ci.author_time);1495printf("author-tz%s\n", ci.author_tz);1496printf("committer%s\n", ci.committer);1497printf("committer-mail%s\n", ci.committer_mail);1498printf("committer-time%lu\n", ci.committer_time);1499printf("committer-tz%s\n", ci.committer_tz);1500printf("summary%s\n", ci.summary);1501if(suspect->commit->object.flags & UNINTERESTING)1502printf("boundary\n");1503}1504write_filename_info(suspect->path);1505maybe_flush_or_die(stdout,"stdout");1506}1507}15081509/*1510 * The main loop -- while the scoreboard has lines whose true origin1511 * is still unknown, pick one blame_entry, and allow its current1512 * suspect to pass blames to its parents.1513 */1514static voidassign_blame(struct scoreboard *sb,int opt)1515{1516struct rev_info *revs = sb->revs;15171518while(1) {1519struct blame_entry *ent;1520struct commit *commit;1521struct origin *suspect = NULL;15221523/* find one suspect to break down */1524for(ent = sb->ent; !suspect && ent; ent = ent->next)1525if(!ent->guilty)1526 suspect = ent->suspect;1527if(!suspect)1528return;/* all done */15291530/*1531 * We will use this suspect later in the loop,1532 * so hold onto it in the meantime.1533 */1534origin_incref(suspect);1535 commit = suspect->commit;1536if(!commit->object.parsed)1537parse_commit(commit);1538if(reverse ||1539(!(commit->object.flags & UNINTERESTING) &&1540!(revs->max_age != -1&& commit->date < revs->max_age)))1541pass_blame(sb, suspect, opt);1542else{1543 commit->object.flags |= UNINTERESTING;1544if(commit->object.parsed)1545mark_parents_uninteresting(commit);1546}1547/* treat root commit as boundary */1548if(!commit->parents && !show_root)1549 commit->object.flags |= UNINTERESTING;15501551/* Take responsibility for the remaining entries */1552for(ent = sb->ent; ent; ent = ent->next)1553if(same_suspect(ent->suspect, suspect))1554found_guilty_entry(ent);1555origin_decref(suspect);15561557if(DEBUG)/* sanity */1558sanity_check_refcnt(sb);1559}1560}15611562static const char*format_time(unsigned long time,const char*tz_str,1563int show_raw_time)1564{1565static char time_buf[128];1566time_t t = time;1567int minutes, tz;1568struct tm *tm;15691570if(show_raw_time) {1571sprintf(time_buf,"%lu%s", time, tz_str);1572return time_buf;1573}15741575 tz =atoi(tz_str);1576 minutes = tz <0? -tz : tz;1577 minutes = (minutes /100)*60+ (minutes %100);1578 minutes = tz <0? -minutes : minutes;1579 t = time + minutes *60;1580 tm =gmtime(&t);15811582strftime(time_buf,sizeof(time_buf),"%Y-%m-%d %H:%M:%S", tm);1583strcat(time_buf, tz_str);1584return time_buf;1585}15861587#define OUTPUT_ANNOTATE_COMPAT 0011588#define OUTPUT_LONG_OBJECT_NAME 0021589#define OUTPUT_RAW_TIMESTAMP 0041590#define OUTPUT_PORCELAIN 0101591#define OUTPUT_SHOW_NAME 0201592#define OUTPUT_SHOW_NUMBER 0401593#define OUTPUT_SHOW_SCORE 01001594#define OUTPUT_NO_AUTHOR 020015951596static voidemit_porcelain(struct scoreboard *sb,struct blame_entry *ent)1597{1598int cnt;1599const char*cp;1600struct origin *suspect = ent->suspect;1601char hex[41];16021603strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));1604printf("%s%c%d %d %d\n",1605 hex,1606 ent->guilty ?' ':'*',// purely for debugging1607 ent->s_lno +1,1608 ent->lno +1,1609 ent->num_lines);1610if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {1611struct commit_info ci;1612 suspect->commit->object.flags |= METAINFO_SHOWN;1613get_commit_info(suspect->commit, &ci,1);1614printf("author%s\n", ci.author);1615printf("author-mail%s\n", ci.author_mail);1616printf("author-time%lu\n", ci.author_time);1617printf("author-tz%s\n", ci.author_tz);1618printf("committer%s\n", ci.committer);1619printf("committer-mail%s\n", ci.committer_mail);1620printf("committer-time%lu\n", ci.committer_time);1621printf("committer-tz%s\n", ci.committer_tz);1622write_filename_info(suspect->path);1623printf("summary%s\n", ci.summary);1624if(suspect->commit->object.flags & UNINTERESTING)1625printf("boundary\n");1626}1627else if(suspect->commit->object.flags & MORE_THAN_ONE_PATH)1628write_filename_info(suspect->path);16291630 cp =nth_line(sb, ent->lno);1631for(cnt =0; cnt < ent->num_lines; cnt++) {1632char ch;1633if(cnt)1634printf("%s %d %d\n", hex,1635 ent->s_lno +1+ cnt,1636 ent->lno +1+ cnt);1637putchar('\t');1638do{1639 ch = *cp++;1640putchar(ch);1641}while(ch !='\n'&&1642 cp < sb->final_buf + sb->final_buf_size);1643}1644}16451646static voidemit_other(struct scoreboard *sb,struct blame_entry *ent,int opt)1647{1648int cnt;1649const char*cp;1650struct origin *suspect = ent->suspect;1651struct commit_info ci;1652char hex[41];1653int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);16541655get_commit_info(suspect->commit, &ci,1);1656strcpy(hex,sha1_to_hex(suspect->commit->object.sha1));16571658 cp =nth_line(sb, ent->lno);1659for(cnt =0; cnt < ent->num_lines; cnt++) {1660char ch;1661int length = (opt & OUTPUT_LONG_OBJECT_NAME) ?40:8;16621663if(suspect->commit->object.flags & UNINTERESTING) {1664if(blank_boundary)1665memset(hex,' ', length);1666else if(!cmd_is_annotate) {1667 length--;1668putchar('^');1669}1670}16711672printf("%.*s", length, hex);1673if(opt & OUTPUT_ANNOTATE_COMPAT)1674printf("\t(%10s\t%10s\t%d)", ci.author,1675format_time(ci.author_time, ci.author_tz,1676 show_raw_time),1677 ent->lno +1+ cnt);1678else{1679if(opt & OUTPUT_SHOW_SCORE)1680printf(" %*d%02d",1681 max_score_digits, ent->score,1682 ent->suspect->refcnt);1683if(opt & OUTPUT_SHOW_NAME)1684printf(" %-*.*s", longest_file, longest_file,1685 suspect->path);1686if(opt & OUTPUT_SHOW_NUMBER)1687printf(" %*d", max_orig_digits,1688 ent->s_lno +1+ cnt);16891690if(!(opt & OUTPUT_NO_AUTHOR))1691printf(" (%-*.*s%10s",1692 longest_author, longest_author,1693 ci.author,1694format_time(ci.author_time,1695 ci.author_tz,1696 show_raw_time));1697printf(" %*d) ",1698 max_digits, ent->lno +1+ cnt);1699}1700do{1701 ch = *cp++;1702putchar(ch);1703}while(ch !='\n'&&1704 cp < sb->final_buf + sb->final_buf_size);1705}1706}17071708static voidoutput(struct scoreboard *sb,int option)1709{1710struct blame_entry *ent;17111712if(option & OUTPUT_PORCELAIN) {1713for(ent = sb->ent; ent; ent = ent->next) {1714struct blame_entry *oth;1715struct origin *suspect = ent->suspect;1716struct commit *commit = suspect->commit;1717if(commit->object.flags & MORE_THAN_ONE_PATH)1718continue;1719for(oth = ent->next; oth; oth = oth->next) {1720if((oth->suspect->commit != commit) ||1721!strcmp(oth->suspect->path, suspect->path))1722continue;1723 commit->object.flags |= MORE_THAN_ONE_PATH;1724break;1725}1726}1727}17281729for(ent = sb->ent; ent; ent = ent->next) {1730if(option & OUTPUT_PORCELAIN)1731emit_porcelain(sb, ent);1732else{1733emit_other(sb, ent, option);1734}1735}1736}17371738/*1739 * To allow quick access to the contents of nth line in the1740 * final image, prepare an index in the scoreboard.1741 */1742static intprepare_lines(struct scoreboard *sb)1743{1744const char*buf = sb->final_buf;1745unsigned long len = sb->final_buf_size;1746int num =0, incomplete =0, bol =1;17471748if(len && buf[len-1] !='\n')1749 incomplete++;/* incomplete line at the end */1750while(len--) {1751if(bol) {1752 sb->lineno =xrealloc(sb->lineno,1753sizeof(int* ) * (num +1));1754 sb->lineno[num] = buf - sb->final_buf;1755 bol =0;1756}1757if(*buf++ =='\n') {1758 num++;1759 bol =1;1760}1761}1762 sb->lineno =xrealloc(sb->lineno,1763sizeof(int* ) * (num + incomplete +1));1764 sb->lineno[num + incomplete] = buf - sb->final_buf;1765 sb->num_lines = num + incomplete;1766return sb->num_lines;1767}17681769/*1770 * Add phony grafts for use with -S; this is primarily to1771 * support git-cvsserver that wants to give a linear history1772 * to its clients.1773 */1774static intread_ancestry(const char*graft_file)1775{1776FILE*fp =fopen(graft_file,"r");1777char buf[1024];1778if(!fp)1779return-1;1780while(fgets(buf,sizeof(buf), fp)) {1781/* The format is just "Commit Parent1 Parent2 ...\n" */1782int len =strlen(buf);1783struct commit_graft *graft =read_graft_line(buf, len);1784if(graft)1785register_commit_graft(graft,0);1786}1787fclose(fp);1788return0;1789}17901791/*1792 * How many columns do we need to show line numbers in decimal?1793 */1794static intlineno_width(int lines)1795{1796int i, width;17971798for(width =1, i =10; i <= lines +1; width++)1799 i *=10;1800return width;1801}18021803/*1804 * How many columns do we need to show line numbers, authors,1805 * and filenames?1806 */1807static voidfind_alignment(struct scoreboard *sb,int*option)1808{1809int longest_src_lines =0;1810int longest_dst_lines =0;1811unsigned largest_score =0;1812struct blame_entry *e;18131814for(e = sb->ent; e; e = e->next) {1815struct origin *suspect = e->suspect;1816struct commit_info ci;1817int num;18181819if(strcmp(suspect->path, sb->path))1820*option |= OUTPUT_SHOW_NAME;1821 num =strlen(suspect->path);1822if(longest_file < num)1823 longest_file = num;1824if(!(suspect->commit->object.flags & METAINFO_SHOWN)) {1825 suspect->commit->object.flags |= METAINFO_SHOWN;1826get_commit_info(suspect->commit, &ci,1);1827 num =strlen(ci.author);1828if(longest_author < num)1829 longest_author = num;1830}1831 num = e->s_lno + e->num_lines;1832if(longest_src_lines < num)1833 longest_src_lines = num;1834 num = e->lno + e->num_lines;1835if(longest_dst_lines < num)1836 longest_dst_lines = num;1837if(largest_score <ent_score(sb, e))1838 largest_score =ent_score(sb, e);1839}1840 max_orig_digits =lineno_width(longest_src_lines);1841 max_digits =lineno_width(longest_dst_lines);1842 max_score_digits =lineno_width(largest_score);1843}18441845/*1846 * For debugging -- origin is refcounted, and this asserts that1847 * we do not underflow.1848 */1849static voidsanity_check_refcnt(struct scoreboard *sb)1850{1851int baa =0;1852struct blame_entry *ent;18531854for(ent = sb->ent; ent; ent = ent->next) {1855/* Nobody should have zero or negative refcnt */1856if(ent->suspect->refcnt <=0) {1857fprintf(stderr,"%sin%shas negative refcnt%d\n",1858 ent->suspect->path,1859sha1_to_hex(ent->suspect->commit->object.sha1),1860 ent->suspect->refcnt);1861 baa =1;1862}1863}1864for(ent = sb->ent; ent; ent = ent->next) {1865/* Mark the ones that haven't been checked */1866if(0< ent->suspect->refcnt)1867 ent->suspect->refcnt = -ent->suspect->refcnt;1868}1869for(ent = sb->ent; ent; ent = ent->next) {1870/*1871 * ... then pick each and see if they have the the1872 * correct refcnt.1873 */1874int found;1875struct blame_entry *e;1876struct origin *suspect = ent->suspect;18771878if(0< suspect->refcnt)1879continue;1880 suspect->refcnt = -suspect->refcnt;/* Unmark */1881for(found =0, e = sb->ent; e; e = e->next) {1882if(e->suspect != suspect)1883continue;1884 found++;1885}1886if(suspect->refcnt != found) {1887fprintf(stderr,"%sin%shas refcnt%d, not%d\n",1888 ent->suspect->path,1889sha1_to_hex(ent->suspect->commit->object.sha1),1890 ent->suspect->refcnt, found);1891 baa =2;1892}1893}1894if(baa) {1895int opt =0160;1896find_alignment(sb, &opt);1897output(sb, opt);1898die("Baa%d!", baa);1899}1900}19011902/*1903 * Used for the command line parsing; check if the path exists1904 * in the working tree.1905 */1906static inthas_path_in_work_tree(const char*path)1907{1908struct stat st;1909return!lstat(path, &st);1910}19111912static unsignedparse_score(const char*arg)1913{1914char*end;1915unsigned long score =strtoul(arg, &end,10);1916if(*end)1917return0;1918return score;1919}19201921static const char*add_prefix(const char*prefix,const char*path)1922{1923returnprefix_path(prefix, prefix ?strlen(prefix) :0, path);1924}19251926/*1927 * Parsing of (comma separated) one item in the -L option1928 */1929static const char*parse_loc(const char*spec,1930struct scoreboard *sb,long lno,1931long begin,long*ret)1932{1933char*term;1934const char*line;1935long num;1936int reg_error;1937 regex_t regexp;1938 regmatch_t match[1];19391940/* Allow "-L <something>,+20" to mean starting at <something>1941 * for 20 lines, or "-L <something>,-5" for 5 lines ending at1942 * <something>.1943 */1944if(1< begin && (spec[0] =='+'|| spec[0] =='-')) {1945 num =strtol(spec +1, &term,10);1946if(term != spec +1) {1947if(spec[0] =='-')1948 num =0- num;1949if(0< num)1950*ret = begin + num -2;1951else if(!num)1952*ret = begin;1953else1954*ret = begin + num;1955return term;1956}1957return spec;1958}1959 num =strtol(spec, &term,10);1960if(term != spec) {1961*ret = num;1962return term;1963}1964if(spec[0] !='/')1965return spec;19661967/* it could be a regexp of form /.../ */1968for(term = (char*) spec +1; *term && *term !='/'; term++) {1969if(*term =='\\')1970 term++;1971}1972if(*term !='/')1973return spec;19741975/* try [spec+1 .. term-1] as regexp */1976*term =0;1977 begin--;/* input is in human terms */1978 line =nth_line(sb, begin);19791980if(!(reg_error =regcomp(®exp, spec +1, REG_NEWLINE)) &&1981!(reg_error =regexec(®exp, line,1, match,0))) {1982const char*cp = line + match[0].rm_so;1983const char*nline;19841985while(begin++ < lno) {1986 nline =nth_line(sb, begin);1987if(line <= cp && cp < nline)1988break;1989 line = nline;1990}1991*ret = begin;1992regfree(®exp);1993*term++ ='/';1994return term;1995}1996else{1997char errbuf[1024];1998regerror(reg_error, ®exp, errbuf,1024);1999die("-L parameter '%s':%s", spec +1, errbuf);2000}2001}20022003/*2004 * Parsing of -L option2005 */2006static voidprepare_blame_range(struct scoreboard *sb,2007const char*bottomtop,2008long lno,2009long*bottom,long*top)2010{2011const char*term;20122013 term =parse_loc(bottomtop, sb, lno,1, bottom);2014if(*term ==',') {2015 term =parse_loc(term +1, sb, lno, *bottom +1, top);2016if(*term)2017usage(blame_usage);2018}2019if(*term)2020usage(blame_usage);2021}20222023static intgit_blame_config(const char*var,const char*value,void*cb)2024{2025if(!strcmp(var,"blame.showroot")) {2026 show_root =git_config_bool(var, value);2027return0;2028}2029if(!strcmp(var,"blame.blankboundary")) {2030 blank_boundary =git_config_bool(var, value);2031return0;2032}2033returngit_default_config(var, value, cb);2034}20352036/*2037 * Prepare a dummy commit that represents the work tree (or staged) item.2038 * Note that annotating work tree item never works in the reverse.2039 */2040static struct commit *fake_working_tree_commit(const char*path,const char*contents_from)2041{2042struct commit *commit;2043struct origin *origin;2044unsigned char head_sha1[20];2045struct strbuf buf;2046const char*ident;2047time_t now;2048int size, len;2049struct cache_entry *ce;2050unsigned mode;20512052if(get_sha1("HEAD", head_sha1))2053die("No such ref: HEAD");20542055time(&now);2056 commit =xcalloc(1,sizeof(*commit));2057 commit->parents =xcalloc(1,sizeof(*commit->parents));2058 commit->parents->item =lookup_commit_reference(head_sha1);2059 commit->object.parsed =1;2060 commit->date = now;2061 commit->object.type = OBJ_COMMIT;20622063 origin =make_origin(commit, path);20642065strbuf_init(&buf,0);2066if(!contents_from ||strcmp("-", contents_from)) {2067struct stat st;2068const char*read_from;2069unsigned long fin_size;20702071if(contents_from) {2072if(stat(contents_from, &st) <0)2073die("Cannot stat%s", contents_from);2074 read_from = contents_from;2075}2076else{2077if(lstat(path, &st) <0)2078die("Cannot lstat%s", path);2079 read_from = path;2080}2081 fin_size =xsize_t(st.st_size);2082 mode =canon_mode(st.st_mode);2083switch(st.st_mode & S_IFMT) {2084case S_IFREG:2085if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)2086die("cannot open or read%s", read_from);2087break;2088case S_IFLNK:2089if(readlink(read_from, buf.buf, buf.alloc) != fin_size)2090die("cannot readlink%s", read_from);2091 buf.len = fin_size;2092break;2093default:2094die("unsupported file type%s", read_from);2095}2096}2097else{2098/* Reading from stdin */2099 contents_from ="standard input";2100 mode =0;2101if(strbuf_read(&buf,0,0) <0)2102die("read error%sfrom stdin",strerror(errno));2103}2104convert_to_git(path, buf.buf, buf.len, &buf,0);2105 origin->file.ptr = buf.buf;2106 origin->file.size = buf.len;2107pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);2108 commit->util = origin;21092110/*2111 * Read the current index, replace the path entry with2112 * origin->blob_sha1 without mucking with its mode or type2113 * bits; we are not going to write this index out -- we just2114 * want to run "diff-index --cached".2115 */2116discard_cache();2117read_cache();21182119 len =strlen(path);2120if(!mode) {2121int pos =cache_name_pos(path, len);2122if(0<= pos)2123 mode = active_cache[pos]->ce_mode;2124else2125/* Let's not bother reading from HEAD tree */2126 mode = S_IFREG |0644;2127}2128 size =cache_entry_size(len);2129 ce =xcalloc(1, size);2130hashcpy(ce->sha1, origin->blob_sha1);2131memcpy(ce->name, path, len);2132 ce->ce_flags =create_ce_flags(len,0);2133 ce->ce_mode =create_ce_mode(mode);2134add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);21352136/*2137 * We are not going to write this out, so this does not matter2138 * right now, but someday we might optimize diff-index --cached2139 * with cache-tree information.2140 */2141cache_tree_invalidate_path(active_cache_tree, path);21422143 commit->buffer =xmalloc(400);2144 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0);2145snprintf(commit->buffer,400,2146"tree 0000000000000000000000000000000000000000\n"2147"parent%s\n"2148"author%s\n"2149"committer%s\n\n"2150"Version of%sfrom%s\n",2151sha1_to_hex(head_sha1),2152 ident, ident, path, contents_from ? contents_from : path);2153return commit;2154}21552156static const char*prepare_final(struct scoreboard *sb)2157{2158int i;2159const char*final_commit_name = NULL;2160struct rev_info *revs = sb->revs;21612162/*2163 * There must be one and only one positive commit in the2164 * revs->pending array.2165 */2166for(i =0; i < revs->pending.nr; i++) {2167struct object *obj = revs->pending.objects[i].item;2168if(obj->flags & UNINTERESTING)2169continue;2170while(obj->type == OBJ_TAG)2171 obj =deref_tag(obj, NULL,0);2172if(obj->type != OBJ_COMMIT)2173die("Non commit%s?", revs->pending.objects[i].name);2174if(sb->final)2175die("More than one commit to dig from%sand%s?",2176 revs->pending.objects[i].name,2177 final_commit_name);2178 sb->final = (struct commit *) obj;2179 final_commit_name = revs->pending.objects[i].name;2180}2181return final_commit_name;2182}21832184static const char*prepare_initial(struct scoreboard *sb)2185{2186int i;2187const char*final_commit_name = NULL;2188struct rev_info *revs = sb->revs;21892190/*2191 * There must be one and only one negative commit, and it must be2192 * the boundary.2193 */2194for(i =0; i < revs->pending.nr; i++) {2195struct object *obj = revs->pending.objects[i].item;2196if(!(obj->flags & UNINTERESTING))2197continue;2198while(obj->type == OBJ_TAG)2199 obj =deref_tag(obj, NULL,0);2200if(obj->type != OBJ_COMMIT)2201die("Non commit%s?", revs->pending.objects[i].name);2202if(sb->final)2203die("More than one commit to dig down to%sand%s?",2204 revs->pending.objects[i].name,2205 final_commit_name);2206 sb->final = (struct commit *) obj;2207 final_commit_name = revs->pending.objects[i].name;2208}2209if(!final_commit_name)2210die("No commit to dig down to?");2211return final_commit_name;2212}22132214static intblame_copy_callback(const struct option *option,const char*arg,int unset)2215{2216int*opt = option->value;22172218/*2219 * -C enables copy from removed files;2220 * -C -C enables copy from existing files, but only2221 * when blaming a new file;2222 * -C -C -C enables copy from existing files for2223 * everybody2224 */2225if(*opt & PICKAXE_BLAME_COPY_HARDER)2226*opt |= PICKAXE_BLAME_COPY_HARDEST;2227if(*opt & PICKAXE_BLAME_COPY)2228*opt |= PICKAXE_BLAME_COPY_HARDER;2229*opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;22302231if(arg)2232 blame_copy_score =parse_score(arg);2233return0;2234}22352236static intblame_move_callback(const struct option *option,const char*arg,int unset)2237{2238int*opt = option->value;22392240*opt |= PICKAXE_BLAME_MOVE;22412242if(arg)2243 blame_move_score =parse_score(arg);2244return0;2245}22462247static intblame_bottomtop_callback(const struct option *option,const char*arg,int unset)2248{2249const char**bottomtop = option->value;2250if(!arg)2251return-1;2252if(*bottomtop)2253die("More than one '-L n,m' option given");2254*bottomtop = arg;2255return0;2256}22572258intcmd_blame(int argc,const char**argv,const char*prefix)2259{2260struct rev_info revs;2261const char*path;2262struct scoreboard sb;2263struct origin *o;2264struct blame_entry *ent;2265int i, seen_dashdash, unk;2266long bottom, top, lno;2267const char*final_commit_name = NULL;2268enum object_type type;22692270static const char*bottomtop = NULL;2271static int output_option =0, opt =0;2272static int show_stats =0;2273static const char*revs_file = NULL;2274static const char*contents_from = NULL;2275static const struct option options[] = {2276OPT_BOOLEAN(0,"incremental", &incremental,"Show blame entries as we find them, incrementally"),2277OPT_BOOLEAN('b', NULL, &blank_boundary,"Show blank SHA-1 for boundary commits (Default: off)"),2278OPT_BOOLEAN(0,"root", &show_root,"Do not treat root commits as boundaries (Default: off)"),2279OPT_BOOLEAN(0,"show-stats", &show_stats,"Show work cost statistics"),2280OPT_BIT(0,"score-debug", &output_option,"Show output score for blame entries", OUTPUT_SHOW_SCORE),2281OPT_BIT('f',"show-name", &output_option,"Show original filename (Default: auto)", OUTPUT_SHOW_NAME),2282OPT_BIT('n',"show-number", &output_option,"Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),2283OPT_BIT('p',"porcelain", &output_option,"Show in a format designed for machine consumption", OUTPUT_PORCELAIN),2284OPT_BIT('c', NULL, &output_option,"Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),2285OPT_BIT('t', NULL, &output_option,"Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),2286OPT_BIT('l', NULL, &output_option,"Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),2287OPT_BIT('s', NULL, &output_option,"Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),2288OPT_BIT('w', NULL, &xdl_opts,"Ignore whitespace differences", XDF_IGNORE_WHITESPACE),2289OPT_STRING('S', NULL, &revs_file,"file","Use revisions from <file> instead of calling git-rev-list"),2290OPT_STRING(0,"contents", &contents_from,"file","Use <file>'s contents as the final image"),2291{ OPTION_CALLBACK,'C', NULL, &opt,"score","Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },2292{ OPTION_CALLBACK,'M', NULL, &opt,"score","Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },2293OPT_CALLBACK('L', NULL, &bottomtop,"n,m","Process only line range n,m, counting from 1", blame_bottomtop_callback),2294OPT_END()2295};22962297struct parse_opt_ctx_t ctx;22982299 cmd_is_annotate = !strcmp(argv[0],"annotate");23002301git_config(git_blame_config, NULL);2302init_revisions(&revs, NULL);2303 save_commit_buffer =0;23042305parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |2306 PARSE_OPT_KEEP_ARGV0);2307for(;;) {2308int n;23092310switch(parse_options_step(&ctx, options, blame_opt_usage)) {2311case PARSE_OPT_HELP:2312exit(129);2313case PARSE_OPT_DONE:2314goto parse_done;2315}23162317if(!strcmp(ctx.argv[0],"--reverse")) {2318 ctx.argv[0] ="--children";2319 reverse =1;2320}2321 n =handle_revision_opt(&revs, ctx.argc, ctx.argv,2322&ctx.cpidx, ctx.out);2323if(n <=0) {2324error("unknown option `%s'", ctx.argv[0]);2325usage_with_options(blame_opt_usage, options);2326}2327 ctx.argv += n;2328 ctx.argc -= n;2329}2330parse_done:2331 argc =parse_options_end(&ctx);23322333 seen_dashdash =0;2334for(unk = i =1; i < argc; i++) {2335const char*arg = argv[i];2336if(*arg !='-')2337break;2338else if(!strcmp("--", arg)) {2339 seen_dashdash =1;2340 i++;2341break;2342}2343else2344 argv[unk++] = arg;2345}23462347if(!blame_move_score)2348 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;2349if(!blame_copy_score)2350 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;23512352/*2353 * We have collected options unknown to us in argv[1..unk]2354 * which are to be passed to revision machinery if we are2355 * going to do the "bottom" processing.2356 *2357 * The remaining are:2358 *2359 * (1) if seen_dashdash, its either2360 * "-options -- <path>" or2361 * "-options -- <path> <rev>".2362 * but the latter is allowed only if there is no2363 * options that we passed to revision machinery.2364 *2365 * (2) otherwise, we may have "--" somewhere later and2366 * might be looking at the first one of multiple 'rev'2367 * parameters (e.g. " master ^next ^maint -- path").2368 * See if there is a dashdash first, and give the2369 * arguments before that to revision machinery.2370 * After that there must be one 'path'.2371 *2372 * (3) otherwise, its one of the three:2373 * "-options <path> <rev>"2374 * "-options <rev> <path>"2375 * "-options <path>"2376 * but again the first one is allowed only if2377 * there is no options that we passed to revision2378 * machinery.2379 */23802381if(seen_dashdash) {2382/* (1) */2383if(argc <= i)2384usage_with_options(blame_opt_usage, options);2385 path =add_prefix(prefix, argv[i]);2386if(i +1== argc -1) {2387if(unk !=1)2388usage_with_options(blame_opt_usage, options);2389 argv[unk++] = argv[i +1];2390}2391else if(i +1!= argc)2392/* garbage at end */2393usage_with_options(blame_opt_usage, options);2394}2395else{2396int j;2397for(j = i; !seen_dashdash && j < argc; j++)2398if(!strcmp(argv[j],"--"))2399 seen_dashdash = j;2400if(seen_dashdash) {2401/* (2) */2402if(seen_dashdash +1!= argc -1)2403usage_with_options(blame_opt_usage, options);2404 path =add_prefix(prefix, argv[seen_dashdash +1]);2405for(j = i; j < seen_dashdash; j++)2406 argv[unk++] = argv[j];2407}2408else{2409/* (3) */2410if(argc <= i)2411usage_with_options(blame_opt_usage, options);2412 path =add_prefix(prefix, argv[i]);2413if(i +1== argc -1) {2414 final_commit_name = argv[i +1];24152416/* if (unk == 1) we could be getting2417 * old-style2418 */2419if(unk ==1&& !has_path_in_work_tree(path)) {2420 path =add_prefix(prefix, argv[i +1]);2421 final_commit_name = argv[i];2422}2423}2424else if(i != argc -1)2425usage_with_options(blame_opt_usage, options);24262427setup_work_tree();2428if(!has_path_in_work_tree(path))2429die("cannot stat path%s:%s",2430 path,strerror(errno));2431}2432}24332434if(final_commit_name)2435 argv[unk++] = final_commit_name;24362437/*2438 * Now we got rev and path. We do not want the path pruning2439 * but we may want "bottom" processing.2440 */2441 argv[unk++] ="--";/* terminate the rev name */2442 argv[unk] = NULL;24432444setup_revisions(unk, argv, &revs, NULL);2445memset(&sb,0,sizeof(sb));24462447 sb.revs = &revs;2448if(!reverse)2449 final_commit_name =prepare_final(&sb);2450else if(contents_from)2451die("--contents and --children do not blend well.");2452else2453 final_commit_name =prepare_initial(&sb);24542455if(!sb.final) {2456/*2457 * "--not A B -- path" without anything positive;2458 * do not default to HEAD, but use the working tree2459 * or "--contents".2460 */2461setup_work_tree();2462 sb.final =fake_working_tree_commit(path, contents_from);2463add_pending_object(&revs, &(sb.final->object),":");2464}2465else if(contents_from)2466die("Cannot use --contents with final commit object name");24672468/*2469 * If we have bottom, this will mark the ancestors of the2470 * bottom commits we would reach while traversing as2471 * uninteresting.2472 */2473if(prepare_revision_walk(&revs))2474die("revision walk setup failed");24752476if(is_null_sha1(sb.final->object.sha1)) {2477char*buf;2478 o = sb.final->util;2479 buf =xmalloc(o->file.size +1);2480memcpy(buf, o->file.ptr, o->file.size +1);2481 sb.final_buf = buf;2482 sb.final_buf_size = o->file.size;2483}2484else{2485 o =get_origin(&sb, sb.final, path);2486if(fill_blob_sha1(o))2487die("no such path%sin%s", path, final_commit_name);24882489 sb.final_buf =read_sha1_file(o->blob_sha1, &type,2490&sb.final_buf_size);2491if(!sb.final_buf)2492die("Cannot read blob%sfor path%s",2493sha1_to_hex(o->blob_sha1),2494 path);2495}2496 num_read_blob++;2497 lno =prepare_lines(&sb);24982499 bottom = top =0;2500if(bottomtop)2501prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);2502if(bottom && top && top < bottom) {2503long tmp;2504 tmp = top; top = bottom; bottom = tmp;2505}2506if(bottom <1)2507 bottom =1;2508if(top <1)2509 top = lno;2510 bottom--;2511if(lno < top)2512die("file%shas only%lu lines", path, lno);25132514 ent =xcalloc(1,sizeof(*ent));2515 ent->lno = bottom;2516 ent->num_lines = top - bottom;2517 ent->suspect = o;2518 ent->s_lno = bottom;25192520 sb.ent = ent;2521 sb.path = path;25222523if(revs_file &&read_ancestry(revs_file))2524die("reading graft file%sfailed:%s",2525 revs_file,strerror(errno));25262527read_mailmap(&mailmap,".mailmap", NULL);25282529if(!incremental)2530setup_pager();25312532assign_blame(&sb, opt);25332534if(incremental)2535return0;25362537coalesce(&sb);25382539if(!(output_option & OUTPUT_PORCELAIN))2540find_alignment(&sb, &output_option);25412542output(&sb, output_option);2543free((void*)sb.final_buf);2544for(ent = sb.ent; ent; ) {2545struct blame_entry *e = ent->next;2546free(ent);2547 ent = e;2548}25492550if(show_stats) {2551printf("num read blob:%d\n", num_read_blob);2552printf("num get patch:%d\n", num_get_patch);2553printf("num commits:%d\n", num_commits);2554}2555return0;2556}