1#include"cache.h" 2#include"refs.h" 3#include"object-store.h" 4#include"cache-tree.h" 5#include"mergesort.h" 6#include"diff.h" 7#include"diffcore.h" 8#include"tag.h" 9#include"blame.h" 10#include"alloc.h" 11#include"commit-slab.h" 12 13define_commit_slab(blame_suspects,struct blame_origin *); 14static struct blame_suspects blame_suspects; 15 16struct blame_origin *get_blame_suspects(struct commit *commit) 17{ 18struct blame_origin **result; 19 20 result =blame_suspects_peek(&blame_suspects, commit); 21 22return result ? *result : NULL; 23} 24 25static voidset_blame_suspects(struct commit *commit,struct blame_origin *origin) 26{ 27*blame_suspects_at(&blame_suspects, commit) = origin; 28} 29 30voidblame_origin_decref(struct blame_origin *o) 31{ 32if(o && --o->refcnt <=0) { 33struct blame_origin *p, *l = NULL; 34if(o->previous) 35blame_origin_decref(o->previous); 36free(o->file.ptr); 37/* Should be present exactly once in commit chain */ 38for(p =get_blame_suspects(o->commit); p; l = p, p = p->next) { 39if(p == o) { 40if(l) 41 l->next = p->next; 42else 43set_blame_suspects(o->commit, p->next); 44free(o); 45return; 46} 47} 48die("internal error in blame_origin_decref"); 49} 50} 51 52/* 53 * Given a commit and a path in it, create a new origin structure. 54 * The callers that add blame to the scoreboard should use 55 * get_origin() to obtain shared, refcounted copy instead of calling 56 * this function directly. 57 */ 58static struct blame_origin *make_origin(struct commit *commit,const char*path) 59{ 60struct blame_origin *o; 61FLEX_ALLOC_STR(o, path, path); 62 o->commit = commit; 63 o->refcnt =1; 64 o->next =get_blame_suspects(commit); 65set_blame_suspects(commit, o); 66return o; 67} 68 69/* 70 * Locate an existing origin or create a new one. 71 * This moves the origin to front position in the commit util list. 72 */ 73static struct blame_origin *get_origin(struct commit *commit,const char*path) 74{ 75struct blame_origin *o, *l; 76 77for(o =get_blame_suspects(commit), l = NULL; o; l = o, o = o->next) { 78if(!strcmp(o->path, path)) { 79/* bump to front */ 80if(l) { 81 l->next = o->next; 82 o->next =get_blame_suspects(commit); 83set_blame_suspects(commit, o); 84} 85returnblame_origin_incref(o); 86} 87} 88returnmake_origin(commit, path); 89} 90 91 92 93static voidverify_working_tree_path(struct repository *r, 94struct commit *work_tree,const char*path) 95{ 96struct commit_list *parents; 97int pos; 98 99for(parents = work_tree->parents; parents; parents = parents->next) { 100const struct object_id *commit_oid = &parents->item->object.oid; 101struct object_id blob_oid; 102unsigned mode; 103 104if(!get_tree_entry(commit_oid, path, &blob_oid, &mode) && 105oid_object_info(r, &blob_oid, NULL) == OBJ_BLOB) 106return; 107} 108 109 pos =index_name_pos(r->index, path,strlen(path)); 110if(pos >=0) 111;/* path is in the index */ 112else if(-1- pos < r->index->cache_nr && 113!strcmp(r->index->cache[-1- pos]->name, path)) 114;/* path is in the index, unmerged */ 115else 116die("no such path '%s' in HEAD", path); 117} 118 119static struct commit_list **append_parent(struct repository *r, 120struct commit_list **tail, 121const struct object_id *oid) 122{ 123struct commit *parent; 124 125 parent =lookup_commit_reference(r, oid); 126if(!parent) 127die("no such commit%s",oid_to_hex(oid)); 128return&commit_list_insert(parent, tail)->next; 129} 130 131static voidappend_merge_parents(struct repository *r, 132struct commit_list **tail) 133{ 134int merge_head; 135struct strbuf line = STRBUF_INIT; 136 137 merge_head =open(git_path_merge_head(r), O_RDONLY); 138if(merge_head <0) { 139if(errno == ENOENT) 140return; 141die("cannot open '%s' for reading", 142git_path_merge_head(r)); 143} 144 145while(!strbuf_getwholeline_fd(&line, merge_head,'\n')) { 146struct object_id oid; 147if(line.len < GIT_SHA1_HEXSZ ||get_oid_hex(line.buf, &oid)) 148die("unknown line in '%s':%s", 149git_path_merge_head(r), line.buf); 150 tail =append_parent(r, tail, &oid); 151} 152close(merge_head); 153strbuf_release(&line); 154} 155 156/* 157 * This isn't as simple as passing sb->buf and sb->len, because we 158 * want to transfer ownership of the buffer to the commit (so we 159 * must use detach). 160 */ 161static voidset_commit_buffer_from_strbuf(struct repository *r, 162struct commit *c, 163struct strbuf *sb) 164{ 165size_t len; 166void*buf =strbuf_detach(sb, &len); 167set_commit_buffer(r, c, buf, len); 168} 169 170/* 171 * Prepare a dummy commit that represents the work tree (or staged) item. 172 * Note that annotating work tree item never works in the reverse. 173 */ 174static struct commit *fake_working_tree_commit(struct repository *r, 175struct diff_options *opt, 176const char*path, 177const char*contents_from) 178{ 179struct commit *commit; 180struct blame_origin *origin; 181struct commit_list **parent_tail, *parent; 182struct object_id head_oid; 183struct strbuf buf = STRBUF_INIT; 184const char*ident; 185time_t now; 186int len; 187struct cache_entry *ce; 188unsigned mode; 189struct strbuf msg = STRBUF_INIT; 190 191read_index(r->index); 192time(&now); 193 commit =alloc_commit_node(r); 194 commit->object.parsed =1; 195 commit->date = now; 196 parent_tail = &commit->parents; 197 198if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL)) 199die("no such ref: HEAD"); 200 201 parent_tail =append_parent(r, parent_tail, &head_oid); 202append_merge_parents(r, parent_tail); 203verify_working_tree_path(r, commit, path); 204 205 origin =make_origin(commit, path); 206 207 ident =fmt_ident("Not Committed Yet","not.committed.yet", NULL,0); 208strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n"); 209for(parent = commit->parents; parent; parent = parent->next) 210strbuf_addf(&msg,"parent%s\n", 211oid_to_hex(&parent->item->object.oid)); 212strbuf_addf(&msg, 213"author%s\n" 214"committer%s\n\n" 215"Version of%sfrom%s\n", 216 ident, ident, path, 217(!contents_from ? path : 218(!strcmp(contents_from,"-") ?"standard input": contents_from))); 219set_commit_buffer_from_strbuf(r, commit, &msg); 220 221if(!contents_from ||strcmp("-", contents_from)) { 222struct stat st; 223const char*read_from; 224char*buf_ptr; 225unsigned long buf_len; 226 227if(contents_from) { 228if(stat(contents_from, &st) <0) 229die_errno("Cannot stat '%s'", contents_from); 230 read_from = contents_from; 231} 232else{ 233if(lstat(path, &st) <0) 234die_errno("Cannot lstat '%s'", path); 235 read_from = path; 236} 237 mode =canon_mode(st.st_mode); 238 239switch(st.st_mode & S_IFMT) { 240case S_IFREG: 241if(opt->flags.allow_textconv && 242textconv_object(r, read_from, mode, &null_oid,0, &buf_ptr, &buf_len)) 243strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1); 244else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size) 245die_errno("cannot open or read '%s'", read_from); 246break; 247case S_IFLNK: 248if(strbuf_readlink(&buf, read_from, st.st_size) <0) 249die_errno("cannot readlink '%s'", read_from); 250break; 251default: 252die("unsupported file type%s", read_from); 253} 254} 255else{ 256/* Reading from stdin */ 257 mode =0; 258if(strbuf_read(&buf,0,0) <0) 259die_errno("failed to read from stdin"); 260} 261convert_to_git(r->index, path, buf.buf, buf.len, &buf,0); 262 origin->file.ptr = buf.buf; 263 origin->file.size = buf.len; 264pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid); 265 266/* 267 * Read the current index, replace the path entry with 268 * origin->blob_sha1 without mucking with its mode or type 269 * bits; we are not going to write this index out -- we just 270 * want to run "diff-index --cached". 271 */ 272discard_index(r->index); 273read_index(r->index); 274 275 len =strlen(path); 276if(!mode) { 277int pos =index_name_pos(r->index, path, len); 278if(0<= pos) 279 mode = r->index->cache[pos]->ce_mode; 280else 281/* Let's not bother reading from HEAD tree */ 282 mode = S_IFREG |0644; 283} 284 ce =make_empty_cache_entry(r->index, len); 285oidcpy(&ce->oid, &origin->blob_oid); 286memcpy(ce->name, path, len); 287 ce->ce_flags =create_ce_flags(0); 288 ce->ce_namelen = len; 289 ce->ce_mode =create_ce_mode(mode); 290add_index_entry(r->index, ce, 291 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 292 293cache_tree_invalidate_path(r->index, path); 294 295return commit; 296} 297 298 299 300static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b, 301 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data,int xdl_opts) 302{ 303 xpparam_t xpp = {0}; 304 xdemitconf_t xecfg = {0}; 305 xdemitcb_t ecb = {NULL}; 306 307 xpp.flags = xdl_opts; 308 xecfg.hunk_func = hunk_func; 309 ecb.priv = cb_data; 310returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 311} 312 313static const char*get_next_line(const char*start,const char*end) 314{ 315const char*nl =memchr(start,'\n', end - start); 316 317return nl ? nl +1: end; 318} 319 320static intfind_line_starts(int**line_starts,const char*buf, 321unsigned long len) 322{ 323const char*end = buf + len; 324const char*p; 325int*lineno; 326int num =0; 327 328for(p = buf; p < end; p =get_next_line(p, end)) 329 num++; 330 331ALLOC_ARRAY(*line_starts, num +1); 332 lineno = *line_starts; 333 334for(p = buf; p < end; p =get_next_line(p, end)) 335*lineno++ = p - buf; 336 337*lineno = len; 338 339return num; 340} 341 342struct fingerprint_entry; 343 344/* A fingerprint is intended to loosely represent a string, such that two 345 * fingerprints can be quickly compared to give an indication of the similarity 346 * of the strings that they represent. 347 * 348 * A fingerprint is represented as a multiset of the lower-cased byte pairs in 349 * the string that it represents. Whitespace is added at each end of the 350 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'. 351 * For example, the string "Darth Radar" will be converted to the following 352 * fingerprint: 353 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"} 354 * 355 * The similarity between two fingerprints is the size of the intersection of 356 * their multisets, including repeated elements. See fingerprint_similarity for 357 * examples. 358 * 359 * For ease of implementation, the fingerprint is implemented as a map 360 * of byte pairs to the count of that byte pair in the string, instead of 361 * allowing repeated elements in a set. 362 */ 363struct fingerprint { 364struct hashmap map; 365/* As we know the maximum number of entries in advance, it's 366 * convenient to store the entries in a single array instead of having 367 * the hashmap manage the memory. 368 */ 369struct fingerprint_entry *entries; 370}; 371 372/* A byte pair in a fingerprint. Stores the number of times the byte pair 373 * occurs in the string that the fingerprint represents. 374 */ 375struct fingerprint_entry { 376/* The hashmap entry - the hash represents the byte pair in its 377 * entirety so we don't need to store the byte pair separately. 378 */ 379struct hashmap_entry entry; 380/* The number of times the byte pair occurs in the string that the 381 * fingerprint represents. 382 */ 383int count; 384}; 385 386/* See `struct fingerprint` for an explanation of what a fingerprint is. 387 * \param result the fingerprint of the string is stored here. This must be 388 * freed later using free_fingerprint. 389 * \param line_begin the start of the string 390 * \param line_end the end of the string 391 */ 392static voidget_fingerprint(struct fingerprint *result, 393const char*line_begin, 394const char*line_end) 395{ 396unsigned int hash, c0 =0, c1; 397const char*p; 398int max_map_entry_count =1+ line_end - line_begin; 399struct fingerprint_entry *entry =xcalloc(max_map_entry_count, 400sizeof(struct fingerprint_entry)); 401struct fingerprint_entry *found_entry; 402 403hashmap_init(&result->map, NULL, NULL, max_map_entry_count); 404 result->entries = entry; 405for(p = line_begin; p <= line_end; ++p, c0 = c1) { 406/* Always terminate the string with whitespace. 407 * Normalise whitespace to 0, and normalise letters to 408 * lower case. This won't work for multibyte characters but at 409 * worst will match some unrelated characters. 410 */ 411if((p == line_end) ||isspace(*p)) 412 c1 =0; 413else 414 c1 =tolower(*p); 415 hash = c0 | (c1 <<8); 416/* Ignore whitespace pairs */ 417if(hash ==0) 418continue; 419hashmap_entry_init(entry, hash); 420 421 found_entry =hashmap_get(&result->map, entry, NULL); 422if(found_entry) { 423 found_entry->count +=1; 424}else{ 425 entry->count =1; 426hashmap_add(&result->map, entry); 427++entry; 428} 429} 430} 431 432static voidfree_fingerprint(struct fingerprint *f) 433{ 434hashmap_free(&f->map,0); 435free(f->entries); 436} 437 438/* Calculates the similarity between two fingerprints as the size of the 439 * intersection of their multisets, including repeated elements. See 440 * `struct fingerprint` for an explanation of the fingerprint representation. 441 * The similarity between "cat mat" and "father rather" is 2 because "at" is 442 * present twice in both strings while the similarity between "tim" and "mit" 443 * is 0. 444 */ 445static intfingerprint_similarity(struct fingerprint *a,struct fingerprint *b) 446{ 447int intersection =0; 448struct hashmap_iter iter; 449const struct fingerprint_entry *entry_a, *entry_b; 450 451hashmap_iter_init(&b->map, &iter); 452 453while((entry_b =hashmap_iter_next(&iter))) { 454if((entry_a =hashmap_get(&a->map, entry_b, NULL))) { 455 intersection += entry_a->count < entry_b->count ? 456 entry_a->count : entry_b->count; 457} 458} 459return intersection; 460} 461 462/* Subtracts byte-pair elements in B from A, modifying A in place. 463 */ 464static voidfingerprint_subtract(struct fingerprint *a,struct fingerprint *b) 465{ 466struct hashmap_iter iter; 467struct fingerprint_entry *entry_a; 468const struct fingerprint_entry *entry_b; 469 470hashmap_iter_init(&b->map, &iter); 471 472while((entry_b =hashmap_iter_next(&iter))) { 473if((entry_a =hashmap_get(&a->map, entry_b, NULL))) { 474if(entry_a->count <= entry_b->count) 475hashmap_remove(&a->map, entry_b, NULL); 476else 477 entry_a->count -= entry_b->count; 478} 479} 480} 481 482/* Calculate fingerprints for a series of lines. 483 * Puts the fingerprints in the fingerprints array, which must have been 484 * preallocated to allow storing line_count elements. 485 */ 486static voidget_line_fingerprints(struct fingerprint *fingerprints, 487const char*content,const int*line_starts, 488long first_line,long line_count) 489{ 490int i; 491const char*linestart, *lineend; 492 493 line_starts += first_line; 494for(i =0; i < line_count; ++i) { 495 linestart = content + line_starts[i]; 496 lineend = content + line_starts[i +1]; 497get_fingerprint(fingerprints + i, linestart, lineend); 498} 499} 500 501static voidfree_line_fingerprints(struct fingerprint *fingerprints, 502int nr_fingerprints) 503{ 504int i; 505 506for(i =0; i < nr_fingerprints; i++) 507free_fingerprint(&fingerprints[i]); 508} 509 510/* This contains the data necessary to linearly map a line number in one half 511 * of a diff chunk to the line in the other half of the diff chunk that is 512 * closest in terms of its position as a fraction of the length of the chunk. 513 */ 514struct line_number_mapping { 515int destination_start, destination_length, 516 source_start, source_length; 517}; 518 519/* Given a line number in one range, offset and scale it to map it onto the 520 * other range. 521 * Essentially this mapping is a simple linear equation but the calculation is 522 * more complicated to allow performing it with integer operations. 523 * Another complication is that if a line could map onto many lines in the 524 * destination range then we want to choose the line at the center of those 525 * possibilities. 526 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the 527 * first 5 lines in B will map onto the first line in the A chunk, while the 528 * last 5 lines will all map onto the second line in the A chunk. 529 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line 530 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A. 531 */ 532static intmap_line_number(int line_number, 533const struct line_number_mapping *mapping) 534{ 535return((line_number - mapping->source_start) *2+1) * 536 mapping->destination_length / 537(mapping->source_length *2) + 538 mapping->destination_start; 539} 540 541/* Get a pointer to the element storing the similarity between a line in A 542 * and a line in B. 543 * 544 * The similarities are stored in a 2-dimensional array. Each "row" in the 545 * array contains the similarities for a line in B. The similarities stored in 546 * a row are the similarities between the line in B and the nearby lines in A. 547 * To keep the length of each row the same, it is padded out with values of -1 548 * where the search range extends beyond the lines in A. 549 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk 550 * look like this: 551 * a | m 552 * b | n 553 * c | o 554 * d | p 555 * e | q 556 * Then the similarity array will contain: 557 * [-1, -1, am, bm, cm, 558 * -1, an, bn, cn, dn, 559 * ao, bo, co, do, eo, 560 * bp, cp, dp, ep, -1, 561 * cq, dq, eq, -1, -1] 562 * Where similarities are denoted either by -1 for invalid, or the 563 * concatenation of the two lines in the diff being compared. 564 * 565 * \param similarities array of similarities between lines in A and B 566 * \param line_a the index of the line in A, in the same frame of reference as 567 * closest_line_a. 568 * \param local_line_b the index of the line in B, relative to the first line 569 * in B that similarities represents. 570 * \param closest_line_a the index of the line in A that is deemed to be 571 * closest to local_line_b. This must be in the same 572 * frame of reference as line_a. This value defines 573 * where similarities is centered for the line in B. 574 * \param max_search_distance_a maximum distance in lines from the closest line 575 * in A for other lines in A for which 576 * similarities may be calculated. 577 */ 578static int*get_similarity(int*similarities, 579int line_a,int local_line_b, 580int closest_line_a,int max_search_distance_a) 581{ 582assert(abs(line_a - closest_line_a) <= 583 max_search_distance_a); 584return similarities + line_a - closest_line_a + 585 max_search_distance_a + 586 local_line_b * (max_search_distance_a *2+1); 587} 588 589#define CERTAIN_NOTHING_MATCHES -2 590#define CERTAINTY_NOT_CALCULATED -1 591 592/* Given a line in B, first calculate its similarities with nearby lines in A 593 * if not already calculated, then identify the most similar and second most 594 * similar lines. The "certainty" is calculated based on those two 595 * similarities. 596 * 597 * \param start_a the index of the first line of the chunk in A 598 * \param length_a the length in lines of the chunk in A 599 * \param local_line_b the index of the line in B, relative to the first line 600 * in the chunk. 601 * \param fingerprints_a array of fingerprints for the chunk in A 602 * \param fingerprints_b array of fingerprints for the chunk in B 603 * \param similarities 2-dimensional array of similarities between lines in A 604 * and B. See get_similarity() for more details. 605 * \param certainties array of values indicating how strongly a line in B is 606 * matched with some line in A. 607 * \param second_best_result array of absolute indices in A for the second 608 * closest match of a line in B. 609 * \param result array of absolute indices in A for the closest match of a line 610 * in B. 611 * \param max_search_distance_a maximum distance in lines from the closest line 612 * in A for other lines in A for which 613 * similarities may be calculated. 614 * \param map_line_number_in_b_to_a parameter to map_line_number(). 615 */ 616static voidfind_best_line_matches( 617int start_a, 618int length_a, 619int start_b, 620int local_line_b, 621struct fingerprint *fingerprints_a, 622struct fingerprint *fingerprints_b, 623int*similarities, 624int*certainties, 625int*second_best_result, 626int*result, 627const int max_search_distance_a, 628const struct line_number_mapping *map_line_number_in_b_to_a) 629{ 630 631int i, search_start, search_end, closest_local_line_a, *similarity, 632 best_similarity =0, second_best_similarity =0, 633 best_similarity_index =0, second_best_similarity_index =0; 634 635/* certainty has already been calculated so no need to redo the work */ 636if(certainties[local_line_b] != CERTAINTY_NOT_CALCULATED) 637return; 638 639 closest_local_line_a =map_line_number( 640 local_line_b + start_b, map_line_number_in_b_to_a) - start_a; 641 642 search_start = closest_local_line_a - max_search_distance_a; 643if(search_start <0) 644 search_start =0; 645 646 search_end = closest_local_line_a + max_search_distance_a +1; 647if(search_end > length_a) 648 search_end = length_a; 649 650for(i = search_start; i < search_end; ++i) { 651 similarity =get_similarity(similarities, 652 i, local_line_b, 653 closest_local_line_a, 654 max_search_distance_a); 655if(*similarity == -1) { 656/* This value will never exceed 10 but assert just in 657 * case 658 */ 659assert(abs(i - closest_local_line_a) <1000); 660/* scale the similarity by (1000 - distance from 661 * closest line) to act as a tie break between lines 662 * that otherwise are equally similar. 663 */ 664*similarity =fingerprint_similarity( 665 fingerprints_b + local_line_b, 666 fingerprints_a + i) * 667(1000-abs(i - closest_local_line_a)); 668} 669if(*similarity > best_similarity) { 670 second_best_similarity = best_similarity; 671 second_best_similarity_index = best_similarity_index; 672 best_similarity = *similarity; 673 best_similarity_index = i; 674}else if(*similarity > second_best_similarity) { 675 second_best_similarity = *similarity; 676 second_best_similarity_index = i; 677} 678} 679 680if(best_similarity ==0) { 681/* this line definitely doesn't match with anything. Mark it 682 * with this special value so it doesn't get invalidated and 683 * won't be recalculated. 684 */ 685 certainties[local_line_b] = CERTAIN_NOTHING_MATCHES; 686 result[local_line_b] = -1; 687}else{ 688/* Calculate the certainty with which this line matches. 689 * If the line matches well with two lines then that reduces 690 * the certainty. However we still want to prioritise matching 691 * a line that matches very well with two lines over matching a 692 * line that matches poorly with one line, hence doubling 693 * best_similarity. 694 * This means that if we have 695 * line X that matches only one line with a score of 3, 696 * line Y that matches two lines equally with a score of 5, 697 * and line Z that matches only one line with a score or 2, 698 * then the lines in order of certainty are X, Y, Z. 699 */ 700 certainties[local_line_b] = best_similarity *2- 701 second_best_similarity; 702 703/* We keep both the best and second best results to allow us to 704 * check at a later stage of the matching process whether the 705 * result needs to be invalidated. 706 */ 707 result[local_line_b] = start_a + best_similarity_index; 708 second_best_result[local_line_b] = 709 start_a + second_best_similarity_index; 710} 711} 712 713/* 714 * This finds the line that we can match with the most confidence, and 715 * uses it as a partition. It then calls itself on the lines on either side of 716 * that partition. In this way we avoid lines appearing out of order, and 717 * retain a sensible line ordering. 718 * \param start_a index of the first line in A with which lines in B may be 719 * compared. 720 * \param start_b index of the first line in B for which matching should be 721 * done. 722 * \param length_a number of lines in A with which lines in B may be compared. 723 * \param length_b number of lines in B for which matching should be done. 724 * \param fingerprints_a mutable array of fingerprints in A. The first element 725 * corresponds to the line at start_a. 726 * \param fingerprints_b array of fingerprints in B. The first element 727 * corresponds to the line at start_b. 728 * \param similarities 2-dimensional array of similarities between lines in A 729 * and B. See get_similarity() for more details. 730 * \param certainties array of values indicating how strongly a line in B is 731 * matched with some line in A. 732 * \param second_best_result array of absolute indices in A for the second 733 * closest match of a line in B. 734 * \param result array of absolute indices in A for the closest match of a line 735 * in B. 736 * \param max_search_distance_a maximum distance in lines from the closest line 737 * in A for other lines in A for which 738 * similarities may be calculated. 739 * \param max_search_distance_b an upper bound on the greatest possible 740 * distance between lines in B such that they will 741 * both be compared with the same line in A 742 * according to max_search_distance_a. 743 * \param map_line_number_in_b_to_a parameter to map_line_number(). 744 */ 745static voidfuzzy_find_matching_lines_recurse( 746int start_a,int start_b, 747int length_a,int length_b, 748struct fingerprint *fingerprints_a, 749struct fingerprint *fingerprints_b, 750int*similarities, 751int*certainties, 752int*second_best_result, 753int*result, 754int max_search_distance_a, 755int max_search_distance_b, 756const struct line_number_mapping *map_line_number_in_b_to_a) 757{ 758int i, invalidate_min, invalidate_max, offset_b, 759 second_half_start_a, second_half_start_b, 760 second_half_length_a, second_half_length_b, 761 most_certain_line_a, most_certain_local_line_b = -1, 762 most_certain_line_certainty = -1, 763 closest_local_line_a; 764 765for(i =0; i < length_b; ++i) { 766find_best_line_matches(start_a, 767 length_a, 768 start_b, 769 i, 770 fingerprints_a, 771 fingerprints_b, 772 similarities, 773 certainties, 774 second_best_result, 775 result, 776 max_search_distance_a, 777 map_line_number_in_b_to_a); 778 779if(certainties[i] > most_certain_line_certainty) { 780 most_certain_line_certainty = certainties[i]; 781 most_certain_local_line_b = i; 782} 783} 784 785/* No matches. */ 786if(most_certain_local_line_b == -1) 787return; 788 789 most_certain_line_a = result[most_certain_local_line_b]; 790 791/* 792 * Subtract the most certain line's fingerprint in B from the matched 793 * fingerprint in A. This means that other lines in B can't also match 794 * the same parts of the line in A. 795 */ 796fingerprint_subtract(fingerprints_a + most_certain_line_a - start_a, 797 fingerprints_b + most_certain_local_line_b); 798 799/* Invalidate results that may be affected by the choice of most 800 * certain line. 801 */ 802 invalidate_min = most_certain_local_line_b - max_search_distance_b; 803 invalidate_max = most_certain_local_line_b + max_search_distance_b +1; 804if(invalidate_min <0) 805 invalidate_min =0; 806if(invalidate_max > length_b) 807 invalidate_max = length_b; 808 809/* As the fingerprint in A has changed, discard previously calculated 810 * similarity values with that fingerprint. 811 */ 812for(i = invalidate_min; i < invalidate_max; ++i) { 813 closest_local_line_a =map_line_number( 814 i + start_b, map_line_number_in_b_to_a) - start_a; 815 816/* Check that the lines in A and B are close enough that there 817 * is a similarity value for them. 818 */ 819if(abs(most_certain_line_a - start_a - closest_local_line_a) > 820 max_search_distance_a) { 821continue; 822} 823 824*get_similarity(similarities, most_certain_line_a - start_a, 825 i, closest_local_line_a, 826 max_search_distance_a) = -1; 827} 828 829/* More invalidating of results that may be affected by the choice of 830 * most certain line. 831 * Discard the matches for lines in B that are currently matched with a 832 * line in A such that their ordering contradicts the ordering imposed 833 * by the choice of most certain line. 834 */ 835for(i = most_certain_local_line_b -1; i >= invalidate_min; --i) { 836/* In this loop we discard results for lines in B that are 837 * before most-certain-line-B but are matched with a line in A 838 * that is after most-certain-line-A. 839 */ 840if(certainties[i] >=0&& 841(result[i] >= most_certain_line_a || 842 second_best_result[i] >= most_certain_line_a)) { 843 certainties[i] = CERTAINTY_NOT_CALCULATED; 844} 845} 846for(i = most_certain_local_line_b +1; i < invalidate_max; ++i) { 847/* In this loop we discard results for lines in B that are 848 * after most-certain-line-B but are matched with a line in A 849 * that is before most-certain-line-A. 850 */ 851if(certainties[i] >=0&& 852(result[i] <= most_certain_line_a || 853 second_best_result[i] <= most_certain_line_a)) { 854 certainties[i] = CERTAINTY_NOT_CALCULATED; 855} 856} 857 858/* Repeat the matching process for lines before the most certain line. 859 */ 860if(most_certain_local_line_b >0) { 861fuzzy_find_matching_lines_recurse( 862 start_a, start_b, 863 most_certain_line_a +1- start_a, 864 most_certain_local_line_b, 865 fingerprints_a, fingerprints_b, similarities, 866 certainties, second_best_result, result, 867 max_search_distance_a, 868 max_search_distance_b, 869 map_line_number_in_b_to_a); 870} 871/* Repeat the matching process for lines after the most certain line. 872 */ 873if(most_certain_local_line_b +1< length_b) { 874 second_half_start_a = most_certain_line_a; 875 offset_b = most_certain_local_line_b +1; 876 second_half_start_b = start_b + offset_b; 877 second_half_length_a = 878 length_a + start_a - second_half_start_a; 879 second_half_length_b = 880 length_b + start_b - second_half_start_b; 881fuzzy_find_matching_lines_recurse( 882 second_half_start_a, second_half_start_b, 883 second_half_length_a, second_half_length_b, 884 fingerprints_a + second_half_start_a - start_a, 885 fingerprints_b + offset_b, 886 similarities + 887 offset_b * (max_search_distance_a *2+1), 888 certainties + offset_b, 889 second_best_result + offset_b, result + offset_b, 890 max_search_distance_a, 891 max_search_distance_b, 892 map_line_number_in_b_to_a); 893} 894} 895 896/* Find the lines in the parent line range that most closely match the lines in 897 * the target line range. This is accomplished by matching fingerprints in each 898 * blame_origin, and choosing the best matches that preserve the line ordering. 899 * See struct fingerprint for details of fingerprint matching, and 900 * fuzzy_find_matching_lines_recurse for details of preserving line ordering. 901 * 902 * The performance is believed to be O(n log n) in the typical case and O(n^2) 903 * in a pathological case, where n is the number of lines in the target range. 904 */ 905static int*fuzzy_find_matching_lines(struct blame_origin *parent, 906struct blame_origin *target, 907int tlno,int parent_slno,int same, 908int parent_len) 909{ 910/* We use the terminology "A" for the left hand side of the diff AKA 911 * parent, and "B" for the right hand side of the diff AKA target. */ 912int start_a = parent_slno; 913int length_a = parent_len; 914int start_b = tlno; 915int length_b = same - tlno; 916 917struct line_number_mapping map_line_number_in_b_to_a = { 918 start_a, length_a, start_b, length_b 919}; 920 921struct fingerprint *fingerprints_a = parent->fingerprints; 922struct fingerprint *fingerprints_b = target->fingerprints; 923 924int i, *result, *second_best_result, 925*certainties, *similarities, similarity_count; 926 927/* 928 * max_search_distance_a means that given a line in B, compare it to 929 * the line in A that is closest to its position, and the lines in A 930 * that are no greater than max_search_distance_a lines away from the 931 * closest line in A. 932 * 933 * max_search_distance_b is an upper bound on the greatest possible 934 * distance between lines in B such that they will both be compared 935 * with the same line in A according to max_search_distance_a. 936 */ 937int max_search_distance_a =10, max_search_distance_b; 938 939if(length_a <=0) 940return NULL; 941 942if(max_search_distance_a >= length_a) 943 max_search_distance_a = length_a ? length_a -1:0; 944 945 max_search_distance_b = ((2* max_search_distance_a +1) * length_b 946-1) / length_a; 947 948 result =xcalloc(sizeof(int), length_b); 949 second_best_result =xcalloc(sizeof(int), length_b); 950 certainties =xcalloc(sizeof(int), length_b); 951 952/* See get_similarity() for details of similarities. */ 953 similarity_count = length_b * (max_search_distance_a *2+1); 954 similarities =xcalloc(sizeof(int), similarity_count); 955 956for(i =0; i < length_b; ++i) { 957 result[i] = -1; 958 second_best_result[i] = -1; 959 certainties[i] = CERTAINTY_NOT_CALCULATED; 960} 961 962for(i =0; i < similarity_count; ++i) 963 similarities[i] = -1; 964 965fuzzy_find_matching_lines_recurse(start_a, start_b, 966 length_a, length_b, 967 fingerprints_a + start_a, 968 fingerprints_b + start_b, 969 similarities, 970 certainties, 971 second_best_result, 972 result, 973 max_search_distance_a, 974 max_search_distance_b, 975&map_line_number_in_b_to_a); 976 977free(similarities); 978free(certainties); 979free(second_best_result); 980 981return result; 982} 983 984static voidfill_origin_fingerprints(struct blame_origin *o, mmfile_t *file) 985{ 986int*line_starts; 987 988if(o->fingerprints) 989return; 990 o->num_lines =find_line_starts(&line_starts, o->file.ptr, 991 o->file.size); 992/* TODO: Will fill in fingerprints in a future commit */ 993free(line_starts); 994} 995 996static voiddrop_origin_fingerprints(struct blame_origin *o) 997{ 998} 9991000/*1001 * Given an origin, prepare mmfile_t structure to be used by the1002 * diff machinery1003 */1004static voidfill_origin_blob(struct diff_options *opt,1005struct blame_origin *o, mmfile_t *file,1006int*num_read_blob,int fill_fingerprints)1007{1008if(!o->file.ptr) {1009enum object_type type;1010unsigned long file_size;10111012(*num_read_blob)++;1013if(opt->flags.allow_textconv &&1014textconv_object(opt->repo, o->path, o->mode,1015&o->blob_oid,1, &file->ptr, &file_size))1016;1017else1018 file->ptr =read_object_file(&o->blob_oid, &type,1019&file_size);1020 file->size = file_size;10211022if(!file->ptr)1023die("Cannot read blob%sfor path%s",1024oid_to_hex(&o->blob_oid),1025 o->path);1026 o->file = *file;1027}1028else1029*file = o->file;1030if(fill_fingerprints)1031fill_origin_fingerprints(o, file);1032}10331034static voiddrop_origin_blob(struct blame_origin *o)1035{1036FREE_AND_NULL(o->file.ptr);1037drop_origin_fingerprints(o);1038}10391040/*1041 * Any merge of blames happens on lists of blames that arrived via1042 * different parents in a single suspect. In this case, we want to1043 * sort according to the suspect line numbers as opposed to the final1044 * image line numbers. The function body is somewhat longish because1045 * it avoids unnecessary writes.1046 */10471048static struct blame_entry *blame_merge(struct blame_entry *list1,1049struct blame_entry *list2)1050{1051struct blame_entry *p1 = list1, *p2 = list2,1052**tail = &list1;10531054if(!p1)1055return p2;1056if(!p2)1057return p1;10581059if(p1->s_lno <= p2->s_lno) {1060do{1061 tail = &p1->next;1062if((p1 = *tail) == NULL) {1063*tail = p2;1064return list1;1065}1066}while(p1->s_lno <= p2->s_lno);1067}1068for(;;) {1069*tail = p2;1070do{1071 tail = &p2->next;1072if((p2 = *tail) == NULL) {1073*tail = p1;1074return list1;1075}1076}while(p1->s_lno > p2->s_lno);1077*tail = p1;1078do{1079 tail = &p1->next;1080if((p1 = *tail) == NULL) {1081*tail = p2;1082return list1;1083}1084}while(p1->s_lno <= p2->s_lno);1085}1086}10871088static void*get_next_blame(const void*p)1089{1090return((struct blame_entry *)p)->next;1091}10921093static voidset_next_blame(void*p1,void*p2)1094{1095((struct blame_entry *)p1)->next = p2;1096}10971098/*1099 * Final image line numbers are all different, so we don't need a1100 * three-way comparison here.1101 */11021103static intcompare_blame_final(const void*p1,const void*p2)1104{1105return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno1106?1: -1;1107}11081109static intcompare_blame_suspect(const void*p1,const void*p2)1110{1111const struct blame_entry *s1 = p1, *s2 = p2;1112/*1113 * to allow for collating suspects, we sort according to the1114 * respective pointer value as the primary sorting criterion.1115 * The actual relation is pretty unimportant as long as it1116 * establishes a total order. Comparing as integers gives us1117 * that.1118 */1119if(s1->suspect != s2->suspect)1120return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1;1121if(s1->s_lno == s2->s_lno)1122return0;1123return s1->s_lno > s2->s_lno ?1: -1;1124}11251126voidblame_sort_final(struct blame_scoreboard *sb)1127{1128 sb->ent =llist_mergesort(sb->ent, get_next_blame, set_next_blame,1129 compare_blame_final);1130}11311132static intcompare_commits_by_reverse_commit_date(const void*a,1133const void*b,1134void*c)1135{1136return-compare_commits_by_commit_date(a, b, c);1137}11381139/*1140 * For debugging -- origin is refcounted, and this asserts that1141 * we do not underflow.1142 */1143static voidsanity_check_refcnt(struct blame_scoreboard *sb)1144{1145int baa =0;1146struct blame_entry *ent;11471148for(ent = sb->ent; ent; ent = ent->next) {1149/* Nobody should have zero or negative refcnt */1150if(ent->suspect->refcnt <=0) {1151fprintf(stderr,"%sin%shas negative refcnt%d\n",1152 ent->suspect->path,1153oid_to_hex(&ent->suspect->commit->object.oid),1154 ent->suspect->refcnt);1155 baa =1;1156}1157}1158if(baa)1159 sb->on_sanity_fail(sb, baa);1160}11611162/*1163 * If two blame entries that are next to each other came from1164 * contiguous lines in the same origin (i.e. <commit, path> pair),1165 * merge them together.1166 */1167voidblame_coalesce(struct blame_scoreboard *sb)1168{1169struct blame_entry *ent, *next;11701171for(ent = sb->ent; ent && (next = ent->next); ent = next) {1172if(ent->suspect == next->suspect &&1173 ent->s_lno + ent->num_lines == next->s_lno &&1174 ent->ignored == next->ignored &&1175 ent->unblamable == next->unblamable) {1176 ent->num_lines += next->num_lines;1177 ent->next = next->next;1178blame_origin_decref(next->suspect);1179free(next);1180 ent->score =0;1181 next = ent;/* again */1182}1183}11841185if(sb->debug)/* sanity */1186sanity_check_refcnt(sb);1187}11881189/*1190 * Merge the given sorted list of blames into a preexisting origin.1191 * If there were no previous blames to that commit, it is entered into1192 * the commit priority queue of the score board.1193 */11941195static voidqueue_blames(struct blame_scoreboard *sb,struct blame_origin *porigin,1196struct blame_entry *sorted)1197{1198if(porigin->suspects)1199 porigin->suspects =blame_merge(porigin->suspects, sorted);1200else{1201struct blame_origin *o;1202for(o =get_blame_suspects(porigin->commit); o; o = o->next) {1203if(o->suspects) {1204 porigin->suspects = sorted;1205return;1206}1207}1208 porigin->suspects = sorted;1209prio_queue_put(&sb->commits, porigin->commit);1210}1211}12121213/*1214 * Fill the blob_sha1 field of an origin if it hasn't, so that later1215 * call to fill_origin_blob() can use it to locate the data. blob_sha11216 * for an origin is also used to pass the blame for the entire file to1217 * the parent to detect the case where a child's blob is identical to1218 * that of its parent's.1219 *1220 * This also fills origin->mode for corresponding tree path.1221 */1222static intfill_blob_sha1_and_mode(struct repository *r,1223struct blame_origin *origin)1224{1225if(!is_null_oid(&origin->blob_oid))1226return0;1227if(get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))1228goto error_out;1229if(oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)1230goto error_out;1231return0;1232 error_out:1233oidclr(&origin->blob_oid);1234 origin->mode = S_IFINVALID;1235return-1;1236}12371238/*1239 * We have an origin -- check if the same path exists in the1240 * parent and return an origin structure to represent it.1241 */1242static struct blame_origin *find_origin(struct repository *r,1243struct commit *parent,1244struct blame_origin *origin)1245{1246struct blame_origin *porigin;1247struct diff_options diff_opts;1248const char*paths[2];12491250/* First check any existing origins */1251for(porigin =get_blame_suspects(parent); porigin; porigin = porigin->next)1252if(!strcmp(porigin->path, origin->path)) {1253/*1254 * The same path between origin and its parent1255 * without renaming -- the most common case.1256 */1257returnblame_origin_incref(porigin);1258}12591260/* See if the origin->path is different between parent1261 * and origin first. Most of the time they are the1262 * same and diff-tree is fairly efficient about this.1263 */1264repo_diff_setup(r, &diff_opts);1265 diff_opts.flags.recursive =1;1266 diff_opts.detect_rename =0;1267 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;1268 paths[0] = origin->path;1269 paths[1] = NULL;12701271parse_pathspec(&diff_opts.pathspec,1272 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,1273 PATHSPEC_LITERAL_PATH,"", paths);1274diff_setup_done(&diff_opts);12751276if(is_null_oid(&origin->commit->object.oid))1277do_diff_cache(get_commit_tree_oid(parent), &diff_opts);1278else1279diff_tree_oid(get_commit_tree_oid(parent),1280get_commit_tree_oid(origin->commit),1281"", &diff_opts);1282diffcore_std(&diff_opts);12831284if(!diff_queued_diff.nr) {1285/* The path is the same as parent */1286 porigin =get_origin(parent, origin->path);1287oidcpy(&porigin->blob_oid, &origin->blob_oid);1288 porigin->mode = origin->mode;1289}else{1290/*1291 * Since origin->path is a pathspec, if the parent1292 * commit had it as a directory, we will see a whole1293 * bunch of deletion of files in the directory that we1294 * do not care about.1295 */1296int i;1297struct diff_filepair *p = NULL;1298for(i =0; i < diff_queued_diff.nr; i++) {1299const char*name;1300 p = diff_queued_diff.queue[i];1301 name = p->one->path ? p->one->path : p->two->path;1302if(!strcmp(name, origin->path))1303break;1304}1305if(!p)1306die("internal error in blame::find_origin");1307switch(p->status) {1308default:1309die("internal error in blame::find_origin (%c)",1310 p->status);1311case'M':1312 porigin =get_origin(parent, origin->path);1313oidcpy(&porigin->blob_oid, &p->one->oid);1314 porigin->mode = p->one->mode;1315break;1316case'A':1317case'T':1318/* Did not exist in parent, or type changed */1319break;1320}1321}1322diff_flush(&diff_opts);1323clear_pathspec(&diff_opts.pathspec);1324return porigin;1325}13261327/*1328 * We have an origin -- find the path that corresponds to it in its1329 * parent and return an origin structure to represent it.1330 */1331static struct blame_origin *find_rename(struct repository *r,1332struct commit *parent,1333struct blame_origin *origin)1334{1335struct blame_origin *porigin = NULL;1336struct diff_options diff_opts;1337int i;13381339repo_diff_setup(r, &diff_opts);1340 diff_opts.flags.recursive =1;1341 diff_opts.detect_rename = DIFF_DETECT_RENAME;1342 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;1343 diff_opts.single_follow = origin->path;1344diff_setup_done(&diff_opts);13451346if(is_null_oid(&origin->commit->object.oid))1347do_diff_cache(get_commit_tree_oid(parent), &diff_opts);1348else1349diff_tree_oid(get_commit_tree_oid(parent),1350get_commit_tree_oid(origin->commit),1351"", &diff_opts);1352diffcore_std(&diff_opts);13531354for(i =0; i < diff_queued_diff.nr; i++) {1355struct diff_filepair *p = diff_queued_diff.queue[i];1356if((p->status =='R'|| p->status =='C') &&1357!strcmp(p->two->path, origin->path)) {1358 porigin =get_origin(parent, p->one->path);1359oidcpy(&porigin->blob_oid, &p->one->oid);1360 porigin->mode = p->one->mode;1361break;1362}1363}1364diff_flush(&diff_opts);1365clear_pathspec(&diff_opts.pathspec);1366return porigin;1367}13681369/*1370 * Append a new blame entry to a given output queue.1371 */1372static voidadd_blame_entry(struct blame_entry ***queue,1373const struct blame_entry *src)1374{1375struct blame_entry *e =xmalloc(sizeof(*e));1376memcpy(e, src,sizeof(*e));1377blame_origin_incref(e->suspect);13781379 e->next = **queue;1380**queue = e;1381*queue = &e->next;1382}13831384/*1385 * src typically is on-stack; we want to copy the information in it to1386 * a malloced blame_entry that gets added to the given queue. The1387 * origin of dst loses a refcnt.1388 */1389static voiddup_entry(struct blame_entry ***queue,1390struct blame_entry *dst,struct blame_entry *src)1391{1392blame_origin_incref(src->suspect);1393blame_origin_decref(dst->suspect);1394memcpy(dst, src,sizeof(*src));1395 dst->next = **queue;1396**queue = dst;1397*queue = &dst->next;1398}13991400const char*blame_nth_line(struct blame_scoreboard *sb,long lno)1401{1402return sb->final_buf + sb->lineno[lno];1403}14041405/*1406 * It is known that lines between tlno to same came from parent, and e1407 * has an overlap with that range. it also is known that parent's1408 * line plno corresponds to e's line tlno.1409 *1410 * <---- e ----->1411 * <------>1412 * <------------>1413 * <------------>1414 * <------------------>1415 *1416 * Split e into potentially three parts; before this chunk, the chunk1417 * to be blamed for the parent, and after that portion.1418 */1419static voidsplit_overlap(struct blame_entry *split,1420struct blame_entry *e,1421int tlno,int plno,int same,1422struct blame_origin *parent)1423{1424int chunk_end_lno;1425int i;1426memset(split,0,sizeof(struct blame_entry [3]));14271428for(i =0; i <3; i++) {1429 split[i].ignored = e->ignored;1430 split[i].unblamable = e->unblamable;1431}14321433if(e->s_lno < tlno) {1434/* there is a pre-chunk part not blamed on parent */1435 split[0].suspect =blame_origin_incref(e->suspect);1436 split[0].lno = e->lno;1437 split[0].s_lno = e->s_lno;1438 split[0].num_lines = tlno - e->s_lno;1439 split[1].lno = e->lno + tlno - e->s_lno;1440 split[1].s_lno = plno;1441}1442else{1443 split[1].lno = e->lno;1444 split[1].s_lno = plno + (e->s_lno - tlno);1445}14461447if(same < e->s_lno + e->num_lines) {1448/* there is a post-chunk part not blamed on parent */1449 split[2].suspect =blame_origin_incref(e->suspect);1450 split[2].lno = e->lno + (same - e->s_lno);1451 split[2].s_lno = e->s_lno + (same - e->s_lno);1452 split[2].num_lines = e->s_lno + e->num_lines - same;1453 chunk_end_lno = split[2].lno;1454}1455else1456 chunk_end_lno = e->lno + e->num_lines;1457 split[1].num_lines = chunk_end_lno - split[1].lno;14581459/*1460 * if it turns out there is nothing to blame the parent for,1461 * forget about the splitting. !split[1].suspect signals this.1462 */1463if(split[1].num_lines <1)1464return;1465 split[1].suspect =blame_origin_incref(parent);1466}14671468/*1469 * split_overlap() divided an existing blame e into up to three parts1470 * in split. Any assigned blame is moved to queue to1471 * reflect the split.1472 */1473static voidsplit_blame(struct blame_entry ***blamed,1474struct blame_entry ***unblamed,1475struct blame_entry *split,1476struct blame_entry *e)1477{1478if(split[0].suspect && split[2].suspect) {1479/* The first part (reuse storage for the existing entry e) */1480dup_entry(unblamed, e, &split[0]);14811482/* The last part -- me */1483add_blame_entry(unblamed, &split[2]);14841485/* ... and the middle part -- parent */1486add_blame_entry(blamed, &split[1]);1487}1488else if(!split[0].suspect && !split[2].suspect)1489/*1490 * The parent covers the entire area; reuse storage for1491 * e and replace it with the parent.1492 */1493dup_entry(blamed, e, &split[1]);1494else if(split[0].suspect) {1495/* me and then parent */1496dup_entry(unblamed, e, &split[0]);1497add_blame_entry(blamed, &split[1]);1498}1499else{1500/* parent and then me */1501dup_entry(blamed, e, &split[1]);1502add_blame_entry(unblamed, &split[2]);1503}1504}15051506/*1507 * After splitting the blame, the origins used by the1508 * on-stack blame_entry should lose one refcnt each.1509 */1510static voiddecref_split(struct blame_entry *split)1511{1512int i;15131514for(i =0; i <3; i++)1515blame_origin_decref(split[i].suspect);1516}15171518/*1519 * reverse_blame reverses the list given in head, appending tail.1520 * That allows us to build lists in reverse order, then reverse them1521 * afterwards. This can be faster than building the list in proper1522 * order right away. The reason is that building in proper order1523 * requires writing a link in the _previous_ element, while building1524 * in reverse order just requires placing the list head into the1525 * _current_ element.1526 */15271528static struct blame_entry *reverse_blame(struct blame_entry *head,1529struct blame_entry *tail)1530{1531while(head) {1532struct blame_entry *next = head->next;1533 head->next = tail;1534 tail = head;1535 head = next;1536}1537return tail;1538}15391540/*1541 * Splits a blame entry into two entries at 'len' lines. The original 'e'1542 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,1543 * which is returned, consists of the remainder: [e->lno + len, e->lno +1544 * e->num_lines). The caller needs to sort out the reference counting for the1545 * new entry's suspect.1546 */1547static struct blame_entry *split_blame_at(struct blame_entry *e,int len,1548struct blame_origin *new_suspect)1549{1550struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry));15511552 n->suspect = new_suspect;1553 n->ignored = e->ignored;1554 n->unblamable = e->unblamable;1555 n->lno = e->lno + len;1556 n->s_lno = e->s_lno + len;1557 n->num_lines = e->num_lines - len;1558 e->num_lines = len;1559 e->score =0;1560return n;1561}15621563struct blame_line_tracker {1564int is_parent;1565int s_lno;1566};15671568static intare_lines_adjacent(struct blame_line_tracker *first,1569struct blame_line_tracker *second)1570{1571return first->is_parent == second->is_parent &&1572 first->s_lno +1== second->s_lno;1573}15741575/*1576 * This cheap heuristic assigns lines in the chunk to their relative location in1577 * the parent's chunk. Any additional lines are left with the target.1578 */1579static voidguess_line_blames(struct blame_origin *parent,1580struct blame_origin *target,1581int tlno,int offset,int same,int parent_len,1582struct blame_line_tracker *line_blames)1583{1584int i, best_idx, target_idx;1585int parent_slno = tlno + offset;15861587for(i =0; i < same - tlno; i++) {1588 target_idx = tlno + i;1589 best_idx = target_idx + offset;1590if(best_idx < parent_slno + parent_len) {1591 line_blames[i].is_parent =1;1592 line_blames[i].s_lno = best_idx;1593}else{1594 line_blames[i].is_parent =0;1595 line_blames[i].s_lno = target_idx;1596}1597}1598}15991600/*1601 * This decides which parts of a blame entry go to the parent (added to the1602 * ignoredp list) and which stay with the target (added to the diffp list). The1603 * actual decision was made in a separate heuristic function, and those answers1604 * for the lines in 'e' are in line_blames. This consumes e, essentially1605 * putting it on a list.1606 *1607 * Note that the blame entries on the ignoredp list are not necessarily sorted1608 * with respect to the parent's line numbers yet.1609 */1610static voidignore_blame_entry(struct blame_entry *e,1611struct blame_origin *parent,1612struct blame_origin *target,1613struct blame_entry **diffp,1614struct blame_entry **ignoredp,1615struct blame_line_tracker *line_blames)1616{1617int entry_len, nr_lines, i;16181619/*1620 * We carve new entries off the front of e. Each entry comes from a1621 * contiguous chunk of lines: adjacent lines from the same origin1622 * (either the parent or the target).1623 */1624 entry_len =1;1625 nr_lines = e->num_lines;/* e changes in the loop */1626for(i =0; i < nr_lines; i++) {1627struct blame_entry *next = NULL;16281629/*1630 * We are often adjacent to the next line - only split the blame1631 * entry when we have to.1632 */1633if(i +1< nr_lines) {1634if(are_lines_adjacent(&line_blames[i],1635&line_blames[i +1])) {1636 entry_len++;1637continue;1638}1639 next =split_blame_at(e, entry_len,1640blame_origin_incref(e->suspect));1641}1642if(line_blames[i].is_parent) {1643 e->ignored =1;1644blame_origin_decref(e->suspect);1645 e->suspect =blame_origin_incref(parent);1646 e->s_lno = line_blames[i - entry_len +1].s_lno;1647 e->next = *ignoredp;1648*ignoredp = e;1649}else{1650 e->unblamable =1;1651/* e->s_lno is already in the target's address space. */1652 e->next = *diffp;1653*diffp = e;1654}1655assert(e->num_lines == entry_len);1656 e = next;1657 entry_len =1;1658}1659assert(!e);1660}16611662/*1663 * Process one hunk from the patch between the current suspect for1664 * blame_entry e and its parent. This first blames any unfinished1665 * entries before the chunk (which is where target and parent start1666 * differing) on the parent, and then splits blame entries at the1667 * start and at the end of the difference region. Since use of -M and1668 * -C options may lead to overlapping/duplicate source line number1669 * ranges, all we can rely on from sorting/merging is the order of the1670 * first suspect line number.1671 *1672 * tlno: line number in the target where this chunk begins1673 * same: line number in the target where this chunk ends1674 * offset: add to tlno to get the chunk starting point in the parent1675 * parent_len: number of lines in the parent chunk1676 */1677static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq,1678int tlno,int offset,int same,int parent_len,1679struct blame_origin *parent,1680struct blame_origin *target,int ignore_diffs)1681{1682struct blame_entry *e = **srcq;1683struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;1684struct blame_line_tracker *line_blames = NULL;16851686while(e && e->s_lno < tlno) {1687struct blame_entry *next = e->next;1688/*1689 * current record starts before differing portion. If1690 * it reaches into it, we need to split it up and1691 * examine the second part separately.1692 */1693if(e->s_lno + e->num_lines > tlno) {1694/* Move second half to a new record */1695struct blame_entry *n;16961697 n =split_blame_at(e, tlno - e->s_lno, e->suspect);1698/* Push new record to diffp */1699 n->next = diffp;1700 diffp = n;1701}else1702blame_origin_decref(e->suspect);1703/* Pass blame for everything before the differing1704 * chunk to the parent */1705 e->suspect =blame_origin_incref(parent);1706 e->s_lno += offset;1707 e->next = samep;1708 samep = e;1709 e = next;1710}1711/*1712 * As we don't know how much of a common stretch after this1713 * diff will occur, the currently blamed parts are all that we1714 * can assign to the parent for now.1715 */17161717if(samep) {1718**dstq =reverse_blame(samep, **dstq);1719*dstq = &samep->next;1720}1721/*1722 * Prepend the split off portions: everything after e starts1723 * after the blameable portion.1724 */1725 e =reverse_blame(diffp, e);17261727/*1728 * Now retain records on the target while parts are different1729 * from the parent.1730 */1731 samep = NULL;1732 diffp = NULL;17331734if(ignore_diffs && same - tlno >0) {1735 line_blames =xcalloc(sizeof(struct blame_line_tracker),1736 same - tlno);1737guess_line_blames(parent, target, tlno, offset, same,1738 parent_len, line_blames);1739}17401741while(e && e->s_lno < same) {1742struct blame_entry *next = e->next;17431744/*1745 * If current record extends into sameness, need to split.1746 */1747if(e->s_lno + e->num_lines > same) {1748/*1749 * Move second half to a new record to be1750 * processed by later chunks1751 */1752struct blame_entry *n;17531754 n =split_blame_at(e, same - e->s_lno,1755blame_origin_incref(e->suspect));1756/* Push new record to samep */1757 n->next = samep;1758 samep = n;1759}1760if(ignore_diffs) {1761ignore_blame_entry(e, parent, target, &diffp, &ignoredp,1762 line_blames + e->s_lno - tlno);1763}else{1764 e->next = diffp;1765 diffp = e;1766}1767 e = next;1768}1769free(line_blames);1770if(ignoredp) {1771/*1772 * Note ignoredp is not sorted yet, and thus neither is dstq.1773 * That list must be sorted before we queue_blames(). We defer1774 * sorting until after all diff hunks are processed, so that1775 * guess_line_blames() can pick *any* line in the parent. The1776 * slight drawback is that we end up sorting all blame entries1777 * passed to the parent, including those that are unrelated to1778 * changes made by the ignored commit.1779 */1780**dstq =reverse_blame(ignoredp, **dstq);1781*dstq = &ignoredp->next;1782}1783**srcq =reverse_blame(diffp,reverse_blame(samep, e));1784/* Move across elements that are in the unblamable portion */1785if(diffp)1786*srcq = &diffp->next;1787}17881789struct blame_chunk_cb_data {1790struct blame_origin *parent;1791struct blame_origin *target;1792long offset;1793int ignore_diffs;1794struct blame_entry **dstq;1795struct blame_entry **srcq;1796};17971798/* diff chunks are from parent to target */1799static intblame_chunk_cb(long start_a,long count_a,1800long start_b,long count_b,void*data)1801{1802struct blame_chunk_cb_data *d = data;1803if(start_a - start_b != d->offset)1804die("internal error in blame::blame_chunk_cb");1805blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,1806 start_b + count_b, count_a, d->parent, d->target,1807 d->ignore_diffs);1808 d->offset = start_a + count_a - (start_b + count_b);1809return0;1810}18111812/*1813 * We are looking at the origin 'target' and aiming to pass blame1814 * for the lines it is suspected to its parent. Run diff to find1815 * which lines came from parent and pass blame for them.1816 */1817static voidpass_blame_to_parent(struct blame_scoreboard *sb,1818struct blame_origin *target,1819struct blame_origin *parent,int ignore_diffs)1820{1821 mmfile_t file_p, file_o;1822struct blame_chunk_cb_data d;1823struct blame_entry *newdest = NULL;18241825if(!target->suspects)1826return;/* nothing remains for this target */18271828 d.parent = parent;1829 d.target = target;1830 d.offset =0;1831 d.ignore_diffs = ignore_diffs;1832 d.dstq = &newdest; d.srcq = &target->suspects;18331834fill_origin_blob(&sb->revs->diffopt, parent, &file_p,1835&sb->num_read_blob, ignore_diffs);1836fill_origin_blob(&sb->revs->diffopt, target, &file_o,1837&sb->num_read_blob, ignore_diffs);1838 sb->num_get_patch++;18391840if(diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))1841die("unable to generate diff (%s->%s)",1842oid_to_hex(&parent->commit->object.oid),1843oid_to_hex(&target->commit->object.oid));1844/* The rest are the same as the parent */1845blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX,0,1846 parent, target,0);1847*d.dstq = NULL;1848if(ignore_diffs)1849 newdest =llist_mergesort(newdest, get_next_blame,1850 set_next_blame,1851 compare_blame_suspect);1852queue_blames(sb, parent, newdest);18531854return;1855}18561857/*1858 * The lines in blame_entry after splitting blames many times can become1859 * very small and trivial, and at some point it becomes pointless to1860 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any1861 * ordinary C program, and it is not worth to say it was copied from1862 * totally unrelated file in the parent.1863 *1864 * Compute how trivial the lines in the blame_entry are.1865 */1866unsignedblame_entry_score(struct blame_scoreboard *sb,struct blame_entry *e)1867{1868unsigned score;1869const char*cp, *ep;18701871if(e->score)1872return e->score;18731874 score =1;1875 cp =blame_nth_line(sb, e->lno);1876 ep =blame_nth_line(sb, e->lno + e->num_lines);1877while(cp < ep) {1878unsigned ch = *((unsigned char*)cp);1879if(isalnum(ch))1880 score++;1881 cp++;1882}1883 e->score = score;1884return score;1885}18861887/*1888 * best_so_far[] and potential[] are both a split of an existing blame_entry1889 * that passes blame to the parent. Maintain best_so_far the best split so1890 * far, by comparing potential and best_so_far and copying potential into1891 * bst_so_far as needed.1892 */1893static voidcopy_split_if_better(struct blame_scoreboard *sb,1894struct blame_entry *best_so_far,1895struct blame_entry *potential)1896{1897int i;18981899if(!potential[1].suspect)1900return;1901if(best_so_far[1].suspect) {1902if(blame_entry_score(sb, &potential[1]) <1903blame_entry_score(sb, &best_so_far[1]))1904return;1905}19061907for(i =0; i <3; i++)1908blame_origin_incref(potential[i].suspect);1909decref_split(best_so_far);1910memcpy(best_so_far, potential,sizeof(struct blame_entry[3]));1911}19121913/*1914 * We are looking at a part of the final image represented by1915 * ent (tlno and same are offset by ent->s_lno).1916 * tlno is where we are looking at in the final image.1917 * up to (but not including) same match preimage.1918 * plno is where we are looking at in the preimage.1919 *1920 * <-------------- final image ---------------------->1921 * <------ent------>1922 * ^tlno ^same1923 * <---------preimage----->1924 * ^plno1925 *1926 * All line numbers are 0-based.1927 */1928static voidhandle_split(struct blame_scoreboard *sb,1929struct blame_entry *ent,1930int tlno,int plno,int same,1931struct blame_origin *parent,1932struct blame_entry *split)1933{1934if(ent->num_lines <= tlno)1935return;1936if(tlno < same) {1937struct blame_entry potential[3];1938 tlno += ent->s_lno;1939 same += ent->s_lno;1940split_overlap(potential, ent, tlno, plno, same, parent);1941copy_split_if_better(sb, split, potential);1942decref_split(potential);1943}1944}19451946struct handle_split_cb_data {1947struct blame_scoreboard *sb;1948struct blame_entry *ent;1949struct blame_origin *parent;1950struct blame_entry *split;1951long plno;1952long tlno;1953};19541955static inthandle_split_cb(long start_a,long count_a,1956long start_b,long count_b,void*data)1957{1958struct handle_split_cb_data *d = data;1959handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1960 d->split);1961 d->plno = start_a + count_a;1962 d->tlno = start_b + count_b;1963return0;1964}19651966/*1967 * Find the lines from parent that are the same as ent so that1968 * we can pass blames to it. file_p has the blob contents for1969 * the parent.1970 */1971static voidfind_copy_in_blob(struct blame_scoreboard *sb,1972struct blame_entry *ent,1973struct blame_origin *parent,1974struct blame_entry *split,1975 mmfile_t *file_p)1976{1977const char*cp;1978 mmfile_t file_o;1979struct handle_split_cb_data d;19801981memset(&d,0,sizeof(d));1982 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1983/*1984 * Prepare mmfile that contains only the lines in ent.1985 */1986 cp =blame_nth_line(sb, ent->lno);1987 file_o.ptr = (char*) cp;1988 file_o.size =blame_nth_line(sb, ent->lno + ent->num_lines) - cp;19891990/*1991 * file_o is a part of final image we are annotating.1992 * file_p partially may match that image.1993 */1994memset(split,0,sizeof(struct blame_entry [3]));1995if(diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))1996die("unable to generate diff (%s)",1997oid_to_hex(&parent->commit->object.oid));1998/* remainder, if any, all match the preimage */1999handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);2000}20012002/* Move all blame entries from list *source that have a score smaller2003 * than score_min to the front of list *small.2004 * Returns a pointer to the link pointing to the old head of the small list.2005 */20062007static struct blame_entry **filter_small(struct blame_scoreboard *sb,2008struct blame_entry **small,2009struct blame_entry **source,2010unsigned score_min)2011{2012struct blame_entry *p = *source;2013struct blame_entry *oldsmall = *small;2014while(p) {2015if(blame_entry_score(sb, p) <= score_min) {2016*small = p;2017 small = &p->next;2018 p = *small;2019}else{2020*source = p;2021 source = &p->next;2022 p = *source;2023}2024}2025*small = oldsmall;2026*source = NULL;2027return small;2028}20292030/*2031 * See if lines currently target is suspected for can be attributed to2032 * parent.2033 */2034static voidfind_move_in_parent(struct blame_scoreboard *sb,2035struct blame_entry ***blamed,2036struct blame_entry **toosmall,2037struct blame_origin *target,2038struct blame_origin *parent)2039{2040struct blame_entry *e, split[3];2041struct blame_entry *unblamed = target->suspects;2042struct blame_entry *leftover = NULL;2043 mmfile_t file_p;20442045if(!unblamed)2046return;/* nothing remains for this target */20472048fill_origin_blob(&sb->revs->diffopt, parent, &file_p,2049&sb->num_read_blob,0);2050if(!file_p.ptr)2051return;20522053/* At each iteration, unblamed has a NULL-terminated list of2054 * entries that have not yet been tested for blame. leftover2055 * contains the reversed list of entries that have been tested2056 * without being assignable to the parent.2057 */2058do{2059struct blame_entry **unblamedtail = &unblamed;2060struct blame_entry *next;2061for(e = unblamed; e; e = next) {2062 next = e->next;2063find_copy_in_blob(sb, e, parent, split, &file_p);2064if(split[1].suspect &&2065 sb->move_score <blame_entry_score(sb, &split[1])) {2066split_blame(blamed, &unblamedtail, split, e);2067}else{2068 e->next = leftover;2069 leftover = e;2070}2071decref_split(split);2072}2073*unblamedtail = NULL;2074 toosmall =filter_small(sb, toosmall, &unblamed, sb->move_score);2075}while(unblamed);2076 target->suspects =reverse_blame(leftover, NULL);2077}20782079struct blame_list {2080struct blame_entry *ent;2081struct blame_entry split[3];2082};20832084/*2085 * Count the number of entries the target is suspected for,2086 * and prepare a list of entry and the best split.2087 */2088static struct blame_list *setup_blame_list(struct blame_entry *unblamed,2089int*num_ents_p)2090{2091struct blame_entry *e;2092int num_ents, i;2093struct blame_list *blame_list = NULL;20942095for(e = unblamed, num_ents =0; e; e = e->next)2096 num_ents++;2097if(num_ents) {2098 blame_list =xcalloc(num_ents,sizeof(struct blame_list));2099for(e = unblamed, i =0; e; e = e->next)2100 blame_list[i++].ent = e;2101}2102*num_ents_p = num_ents;2103return blame_list;2104}21052106/*2107 * For lines target is suspected for, see if we can find code movement2108 * across file boundary from the parent commit. porigin is the path2109 * in the parent we already tried.2110 */2111static voidfind_copy_in_parent(struct blame_scoreboard *sb,2112struct blame_entry ***blamed,2113struct blame_entry **toosmall,2114struct blame_origin *target,2115struct commit *parent,2116struct blame_origin *porigin,2117int opt)2118{2119struct diff_options diff_opts;2120int i, j;2121struct blame_list *blame_list;2122int num_ents;2123struct blame_entry *unblamed = target->suspects;2124struct blame_entry *leftover = NULL;21252126if(!unblamed)2127return;/* nothing remains for this target */21282129repo_diff_setup(sb->repo, &diff_opts);2130 diff_opts.flags.recursive =1;2131 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;21322133diff_setup_done(&diff_opts);21342135/* Try "find copies harder" on new path if requested;2136 * we do not want to use diffcore_rename() actually to2137 * match things up; find_copies_harder is set only to2138 * force diff_tree_oid() to feed all filepairs to diff_queue,2139 * and this code needs to be after diff_setup_done(), which2140 * usually makes find-copies-harder imply copy detection.2141 */2142if((opt & PICKAXE_BLAME_COPY_HARDEST)2143|| ((opt & PICKAXE_BLAME_COPY_HARDER)2144&& (!porigin ||strcmp(target->path, porigin->path))))2145 diff_opts.flags.find_copies_harder =1;21462147if(is_null_oid(&target->commit->object.oid))2148do_diff_cache(get_commit_tree_oid(parent), &diff_opts);2149else2150diff_tree_oid(get_commit_tree_oid(parent),2151get_commit_tree_oid(target->commit),2152"", &diff_opts);21532154if(!diff_opts.flags.find_copies_harder)2155diffcore_std(&diff_opts);21562157do{2158struct blame_entry **unblamedtail = &unblamed;2159 blame_list =setup_blame_list(unblamed, &num_ents);21602161for(i =0; i < diff_queued_diff.nr; i++) {2162struct diff_filepair *p = diff_queued_diff.queue[i];2163struct blame_origin *norigin;2164 mmfile_t file_p;2165struct blame_entry potential[3];21662167if(!DIFF_FILE_VALID(p->one))2168continue;/* does not exist in parent */2169if(S_ISGITLINK(p->one->mode))2170continue;/* ignore git links */2171if(porigin && !strcmp(p->one->path, porigin->path))2172/* find_move already dealt with this path */2173continue;21742175 norigin =get_origin(parent, p->one->path);2176oidcpy(&norigin->blob_oid, &p->one->oid);2177 norigin->mode = p->one->mode;2178fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,2179&sb->num_read_blob,0);2180if(!file_p.ptr)2181continue;21822183for(j =0; j < num_ents; j++) {2184find_copy_in_blob(sb, blame_list[j].ent,2185 norigin, potential, &file_p);2186copy_split_if_better(sb, blame_list[j].split,2187 potential);2188decref_split(potential);2189}2190blame_origin_decref(norigin);2191}21922193for(j =0; j < num_ents; j++) {2194struct blame_entry *split = blame_list[j].split;2195if(split[1].suspect &&2196 sb->copy_score <blame_entry_score(sb, &split[1])) {2197split_blame(blamed, &unblamedtail, split,2198 blame_list[j].ent);2199}else{2200 blame_list[j].ent->next = leftover;2201 leftover = blame_list[j].ent;2202}2203decref_split(split);2204}2205free(blame_list);2206*unblamedtail = NULL;2207 toosmall =filter_small(sb, toosmall, &unblamed, sb->copy_score);2208}while(unblamed);2209 target->suspects =reverse_blame(leftover, NULL);2210diff_flush(&diff_opts);2211clear_pathspec(&diff_opts.pathspec);2212}22132214/*2215 * The blobs of origin and porigin exactly match, so everything2216 * origin is suspected for can be blamed on the parent.2217 */2218static voidpass_whole_blame(struct blame_scoreboard *sb,2219struct blame_origin *origin,struct blame_origin *porigin)2220{2221struct blame_entry *e, *suspects;22222223if(!porigin->file.ptr && origin->file.ptr) {2224/* Steal its file */2225 porigin->file = origin->file;2226 origin->file.ptr = NULL;2227}2228 suspects = origin->suspects;2229 origin->suspects = NULL;2230for(e = suspects; e; e = e->next) {2231blame_origin_incref(porigin);2232blame_origin_decref(e->suspect);2233 e->suspect = porigin;2234}2235queue_blames(sb, porigin, suspects);2236}22372238/*2239 * We pass blame from the current commit to its parents. We keep saying2240 * "parent" (and "porigin"), but what we mean is to find scapegoat to2241 * exonerate ourselves.2242 */2243static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit,2244int reverse)2245{2246if(!reverse) {2247if(revs->first_parent_only &&2248 commit->parents &&2249 commit->parents->next) {2250free_commit_list(commit->parents->next);2251 commit->parents->next = NULL;2252}2253return commit->parents;2254}2255returnlookup_decoration(&revs->children, &commit->object);2256}22572258static intnum_scapegoats(struct rev_info *revs,struct commit *commit,int reverse)2259{2260struct commit_list *l =first_scapegoat(revs, commit, reverse);2261returncommit_list_count(l);2262}22632264/* Distribute collected unsorted blames to the respected sorted lists2265 * in the various origins.2266 */2267static voiddistribute_blame(struct blame_scoreboard *sb,struct blame_entry *blamed)2268{2269 blamed =llist_mergesort(blamed, get_next_blame, set_next_blame,2270 compare_blame_suspect);2271while(blamed)2272{2273struct blame_origin *porigin = blamed->suspect;2274struct blame_entry *suspects = NULL;2275do{2276struct blame_entry *next = blamed->next;2277 blamed->next = suspects;2278 suspects = blamed;2279 blamed = next;2280}while(blamed && blamed->suspect == porigin);2281 suspects =reverse_blame(suspects, NULL);2282queue_blames(sb, porigin, suspects);2283}2284}22852286#define MAXSG 1622872288static voidpass_blame(struct blame_scoreboard *sb,struct blame_origin *origin,int opt)2289{2290struct rev_info *revs = sb->revs;2291int i, pass, num_sg;2292struct commit *commit = origin->commit;2293struct commit_list *sg;2294struct blame_origin *sg_buf[MAXSG];2295struct blame_origin *porigin, **sg_origin = sg_buf;2296struct blame_entry *toosmall = NULL;2297struct blame_entry *blames, **blametail = &blames;22982299 num_sg =num_scapegoats(revs, commit, sb->reverse);2300if(!num_sg)2301goto finish;2302else if(num_sg <ARRAY_SIZE(sg_buf))2303memset(sg_buf,0,sizeof(sg_buf));2304else2305 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));23062307/*2308 * The first pass looks for unrenamed path to optimize for2309 * common cases, then we look for renames in the second pass.2310 */2311for(pass =0; pass <2- sb->no_whole_file_rename; pass++) {2312struct blame_origin *(*find)(struct repository *,struct commit *,struct blame_origin *);2313 find = pass ? find_rename : find_origin;23142315for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2316 i < num_sg && sg;2317 sg = sg->next, i++) {2318struct commit *p = sg->item;2319int j, same;23202321if(sg_origin[i])2322continue;2323if(parse_commit(p))2324continue;2325 porigin =find(sb->repo, p, origin);2326if(!porigin)2327continue;2328if(oideq(&porigin->blob_oid, &origin->blob_oid)) {2329pass_whole_blame(sb, origin, porigin);2330blame_origin_decref(porigin);2331goto finish;2332}2333for(j = same =0; j < i; j++)2334if(sg_origin[j] &&2335oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {2336 same =1;2337break;2338}2339if(!same)2340 sg_origin[i] = porigin;2341else2342blame_origin_decref(porigin);2343}2344}23452346 sb->num_commits++;2347for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2348 i < num_sg && sg;2349 sg = sg->next, i++) {2350struct blame_origin *porigin = sg_origin[i];2351if(!porigin)2352continue;2353if(!origin->previous) {2354blame_origin_incref(porigin);2355 origin->previous = porigin;2356}2357pass_blame_to_parent(sb, origin, porigin,0);2358if(!origin->suspects)2359goto finish;2360}23612362/*2363 * Pass remaining suspects for ignored commits to their parents.2364 */2365if(oidset_contains(&sb->ignore_list, &commit->object.oid)) {2366for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2367 i < num_sg && sg;2368 sg = sg->next, i++) {2369struct blame_origin *porigin = sg_origin[i];23702371if(!porigin)2372continue;2373pass_blame_to_parent(sb, origin, porigin,1);2374if(!origin->suspects)2375goto finish;2376}2377}23782379/*2380 * Optionally find moves in parents' files.2381 */2382if(opt & PICKAXE_BLAME_MOVE) {2383filter_small(sb, &toosmall, &origin->suspects, sb->move_score);2384if(origin->suspects) {2385for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2386 i < num_sg && sg;2387 sg = sg->next, i++) {2388struct blame_origin *porigin = sg_origin[i];2389if(!porigin)2390continue;2391find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);2392if(!origin->suspects)2393break;2394}2395}2396}23972398/*2399 * Optionally find copies from parents' files.2400 */2401if(opt & PICKAXE_BLAME_COPY) {2402if(sb->copy_score > sb->move_score)2403filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);2404else if(sb->copy_score < sb->move_score) {2405 origin->suspects =blame_merge(origin->suspects, toosmall);2406 toosmall = NULL;2407filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);2408}2409if(!origin->suspects)2410goto finish;24112412for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2413 i < num_sg && sg;2414 sg = sg->next, i++) {2415struct blame_origin *porigin = sg_origin[i];2416find_copy_in_parent(sb, &blametail, &toosmall,2417 origin, sg->item, porigin, opt);2418if(!origin->suspects)2419goto finish;2420}2421}24222423finish:2424*blametail = NULL;2425distribute_blame(sb, blames);2426/*2427 * prepend toosmall to origin->suspects2428 *2429 * There is no point in sorting: this ends up on a big2430 * unsorted list in the caller anyway.2431 */2432if(toosmall) {2433struct blame_entry **tail = &toosmall;2434while(*tail)2435 tail = &(*tail)->next;2436*tail = origin->suspects;2437 origin->suspects = toosmall;2438}2439for(i =0; i < num_sg; i++) {2440if(sg_origin[i]) {2441drop_origin_blob(sg_origin[i]);2442blame_origin_decref(sg_origin[i]);2443}2444}2445drop_origin_blob(origin);2446if(sg_buf != sg_origin)2447free(sg_origin);2448}24492450/*2451 * The main loop -- while we have blobs with lines whose true origin2452 * is still unknown, pick one blob, and allow its lines to pass blames2453 * to its parents. */2454voidassign_blame(struct blame_scoreboard *sb,int opt)2455{2456struct rev_info *revs = sb->revs;2457struct commit *commit =prio_queue_get(&sb->commits);24582459while(commit) {2460struct blame_entry *ent;2461struct blame_origin *suspect =get_blame_suspects(commit);24622463/* find one suspect to break down */2464while(suspect && !suspect->suspects)2465 suspect = suspect->next;24662467if(!suspect) {2468 commit =prio_queue_get(&sb->commits);2469continue;2470}24712472assert(commit == suspect->commit);24732474/*2475 * We will use this suspect later in the loop,2476 * so hold onto it in the meantime.2477 */2478blame_origin_incref(suspect);2479parse_commit(commit);2480if(sb->reverse ||2481(!(commit->object.flags & UNINTERESTING) &&2482!(revs->max_age != -1&& commit->date < revs->max_age)))2483pass_blame(sb, suspect, opt);2484else{2485 commit->object.flags |= UNINTERESTING;2486if(commit->object.parsed)2487mark_parents_uninteresting(commit);2488}2489/* treat root commit as boundary */2490if(!commit->parents && !sb->show_root)2491 commit->object.flags |= UNINTERESTING;24922493/* Take responsibility for the remaining entries */2494 ent = suspect->suspects;2495if(ent) {2496 suspect->guilty =1;2497for(;;) {2498struct blame_entry *next = ent->next;2499if(sb->found_guilty_entry)2500 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);2501if(next) {2502 ent = next;2503continue;2504}2505 ent->next = sb->ent;2506 sb->ent = suspect->suspects;2507 suspect->suspects = NULL;2508break;2509}2510}2511blame_origin_decref(suspect);25122513if(sb->debug)/* sanity */2514sanity_check_refcnt(sb);2515}2516}25172518/*2519 * To allow quick access to the contents of nth line in the2520 * final image, prepare an index in the scoreboard.2521 */2522static intprepare_lines(struct blame_scoreboard *sb)2523{2524 sb->num_lines =find_line_starts(&sb->lineno, sb->final_buf,2525 sb->final_buf_size);2526return sb->num_lines;2527}25282529static struct commit *find_single_final(struct rev_info *revs,2530const char**name_p)2531{2532int i;2533struct commit *found = NULL;2534const char*name = NULL;25352536for(i =0; i < revs->pending.nr; i++) {2537struct object *obj = revs->pending.objects[i].item;2538if(obj->flags & UNINTERESTING)2539continue;2540 obj =deref_tag(revs->repo, obj, NULL,0);2541if(obj->type != OBJ_COMMIT)2542die("Non commit%s?", revs->pending.objects[i].name);2543if(found)2544die("More than one commit to dig from%sand%s?",2545 revs->pending.objects[i].name, name);2546 found = (struct commit *)obj;2547 name = revs->pending.objects[i].name;2548}2549if(name_p)2550*name_p =xstrdup_or_null(name);2551return found;2552}25532554static struct commit *dwim_reverse_initial(struct rev_info *revs,2555const char**name_p)2556{2557/*2558 * DWIM "git blame --reverse ONE -- PATH" as2559 * "git blame --reverse ONE..HEAD -- PATH" but only do so2560 * when it makes sense.2561 */2562struct object *obj;2563struct commit *head_commit;2564struct object_id head_oid;25652566if(revs->pending.nr !=1)2567return NULL;25682569/* Is that sole rev a committish? */2570 obj = revs->pending.objects[0].item;2571 obj =deref_tag(revs->repo, obj, NULL,0);2572if(obj->type != OBJ_COMMIT)2573return NULL;25742575/* Do we have HEAD? */2576if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))2577return NULL;2578 head_commit =lookup_commit_reference_gently(revs->repo,2579&head_oid,1);2580if(!head_commit)2581return NULL;25822583/* Turn "ONE" into "ONE..HEAD" then */2584 obj->flags |= UNINTERESTING;2585add_pending_object(revs, &head_commit->object,"HEAD");25862587if(name_p)2588*name_p = revs->pending.objects[0].name;2589return(struct commit *)obj;2590}25912592static struct commit *find_single_initial(struct rev_info *revs,2593const char**name_p)2594{2595int i;2596struct commit *found = NULL;2597const char*name = NULL;25982599/*2600 * There must be one and only one negative commit, and it must be2601 * the boundary.2602 */2603for(i =0; i < revs->pending.nr; i++) {2604struct object *obj = revs->pending.objects[i].item;2605if(!(obj->flags & UNINTERESTING))2606continue;2607 obj =deref_tag(revs->repo, obj, NULL,0);2608if(obj->type != OBJ_COMMIT)2609die("Non commit%s?", revs->pending.objects[i].name);2610if(found)2611die("More than one commit to dig up from,%sand%s?",2612 revs->pending.objects[i].name, name);2613 found = (struct commit *) obj;2614 name = revs->pending.objects[i].name;2615}26162617if(!name)2618 found =dwim_reverse_initial(revs, &name);2619if(!name)2620die("No commit to dig up from?");26212622if(name_p)2623*name_p =xstrdup(name);2624return found;2625}26262627voidinit_scoreboard(struct blame_scoreboard *sb)2628{2629memset(sb,0,sizeof(struct blame_scoreboard));2630 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;2631 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;2632}26332634voidsetup_scoreboard(struct blame_scoreboard *sb,2635const char*path,2636struct blame_origin **orig)2637{2638const char*final_commit_name = NULL;2639struct blame_origin *o;2640struct commit *final_commit = NULL;2641enum object_type type;26422643init_blame_suspects(&blame_suspects);26442645if(sb->reverse && sb->contents_from)2646die(_("--contents and --reverse do not blend well."));26472648if(!sb->repo)2649BUG("repo is NULL");26502651if(!sb->reverse) {2652 sb->final =find_single_final(sb->revs, &final_commit_name);2653 sb->commits.compare = compare_commits_by_commit_date;2654}else{2655 sb->final =find_single_initial(sb->revs, &final_commit_name);2656 sb->commits.compare = compare_commits_by_reverse_commit_date;2657}26582659if(sb->final && sb->contents_from)2660die(_("cannot use --contents with final commit object name"));26612662if(sb->reverse && sb->revs->first_parent_only)2663 sb->revs->children.name = NULL;26642665if(!sb->final) {2666/*2667 * "--not A B -- path" without anything positive;2668 * do not default to HEAD, but use the working tree2669 * or "--contents".2670 */2671setup_work_tree();2672 sb->final =fake_working_tree_commit(sb->repo,2673&sb->revs->diffopt,2674 path, sb->contents_from);2675add_pending_object(sb->revs, &(sb->final->object),":");2676}26772678if(sb->reverse && sb->revs->first_parent_only) {2679 final_commit =find_single_final(sb->revs, NULL);2680if(!final_commit)2681die(_("--reverse and --first-parent together require specified latest commit"));2682}26832684/*2685 * If we have bottom, this will mark the ancestors of the2686 * bottom commits we would reach while traversing as2687 * uninteresting.2688 */2689if(prepare_revision_walk(sb->revs))2690die(_("revision walk setup failed"));26912692if(sb->reverse && sb->revs->first_parent_only) {2693struct commit *c = final_commit;26942695 sb->revs->children.name ="children";2696while(c->parents &&2697!oideq(&c->object.oid, &sb->final->object.oid)) {2698struct commit_list *l =xcalloc(1,sizeof(*l));26992700 l->item = c;2701if(add_decoration(&sb->revs->children,2702&c->parents->item->object, l))2703BUG("not unique item in first-parent chain");2704 c = c->parents->item;2705}27062707if(!oideq(&c->object.oid, &sb->final->object.oid))2708die(_("--reverse --first-parent together require range along first-parent chain"));2709}27102711if(is_null_oid(&sb->final->object.oid)) {2712 o =get_blame_suspects(sb->final);2713 sb->final_buf =xmemdupz(o->file.ptr, o->file.size);2714 sb->final_buf_size = o->file.size;2715}2716else{2717 o =get_origin(sb->final, path);2718if(fill_blob_sha1_and_mode(sb->repo, o))2719die(_("no such path%sin%s"), path, final_commit_name);27202721if(sb->revs->diffopt.flags.allow_textconv &&2722textconv_object(sb->repo, path, o->mode, &o->blob_oid,1, (char**) &sb->final_buf,2723&sb->final_buf_size))2724;2725else2726 sb->final_buf =read_object_file(&o->blob_oid, &type,2727&sb->final_buf_size);27282729if(!sb->final_buf)2730die(_("cannot read blob%sfor path%s"),2731oid_to_hex(&o->blob_oid),2732 path);2733}2734 sb->num_read_blob++;2735prepare_lines(sb);27362737if(orig)2738*orig = o;27392740free((char*)final_commit_name);2741}2742274327442745struct blame_entry *blame_entry_prepend(struct blame_entry *head,2746long start,long end,2747struct blame_origin *o)2748{2749struct blame_entry *new_head =xcalloc(1,sizeof(struct blame_entry));2750 new_head->lno = start;2751 new_head->num_lines = end - start;2752 new_head->suspect = o;2753 new_head->s_lno = start;2754 new_head->next = head;2755blame_origin_incref(o);2756return new_head;2757}