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 o->fingerprints =xcalloc(sizeof(struct fingerprint), o->num_lines); 993get_line_fingerprints(o->fingerprints, o->file.ptr, line_starts, 9940, o->num_lines); 995free(line_starts); 996} 997 998static voiddrop_origin_fingerprints(struct blame_origin *o) 999{1000if(o->fingerprints) {1001free_line_fingerprints(o->fingerprints, o->num_lines);1002 o->num_lines =0;1003FREE_AND_NULL(o->fingerprints);1004}1005}10061007/*1008 * Given an origin, prepare mmfile_t structure to be used by the1009 * diff machinery1010 */1011static voidfill_origin_blob(struct diff_options *opt,1012struct blame_origin *o, mmfile_t *file,1013int*num_read_blob,int fill_fingerprints)1014{1015if(!o->file.ptr) {1016enum object_type type;1017unsigned long file_size;10181019(*num_read_blob)++;1020if(opt->flags.allow_textconv &&1021textconv_object(opt->repo, o->path, o->mode,1022&o->blob_oid,1, &file->ptr, &file_size))1023;1024else1025 file->ptr =read_object_file(&o->blob_oid, &type,1026&file_size);1027 file->size = file_size;10281029if(!file->ptr)1030die("Cannot read blob%sfor path%s",1031oid_to_hex(&o->blob_oid),1032 o->path);1033 o->file = *file;1034}1035else1036*file = o->file;1037if(fill_fingerprints)1038fill_origin_fingerprints(o, file);1039}10401041static voiddrop_origin_blob(struct blame_origin *o)1042{1043FREE_AND_NULL(o->file.ptr);1044drop_origin_fingerprints(o);1045}10461047/*1048 * Any merge of blames happens on lists of blames that arrived via1049 * different parents in a single suspect. In this case, we want to1050 * sort according to the suspect line numbers as opposed to the final1051 * image line numbers. The function body is somewhat longish because1052 * it avoids unnecessary writes.1053 */10541055static struct blame_entry *blame_merge(struct blame_entry *list1,1056struct blame_entry *list2)1057{1058struct blame_entry *p1 = list1, *p2 = list2,1059**tail = &list1;10601061if(!p1)1062return p2;1063if(!p2)1064return p1;10651066if(p1->s_lno <= p2->s_lno) {1067do{1068 tail = &p1->next;1069if((p1 = *tail) == NULL) {1070*tail = p2;1071return list1;1072}1073}while(p1->s_lno <= p2->s_lno);1074}1075for(;;) {1076*tail = p2;1077do{1078 tail = &p2->next;1079if((p2 = *tail) == NULL) {1080*tail = p1;1081return list1;1082}1083}while(p1->s_lno > p2->s_lno);1084*tail = p1;1085do{1086 tail = &p1->next;1087if((p1 = *tail) == NULL) {1088*tail = p2;1089return list1;1090}1091}while(p1->s_lno <= p2->s_lno);1092}1093}10941095static void*get_next_blame(const void*p)1096{1097return((struct blame_entry *)p)->next;1098}10991100static voidset_next_blame(void*p1,void*p2)1101{1102((struct blame_entry *)p1)->next = p2;1103}11041105/*1106 * Final image line numbers are all different, so we don't need a1107 * three-way comparison here.1108 */11091110static intcompare_blame_final(const void*p1,const void*p2)1111{1112return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno1113?1: -1;1114}11151116static intcompare_blame_suspect(const void*p1,const void*p2)1117{1118const struct blame_entry *s1 = p1, *s2 = p2;1119/*1120 * to allow for collating suspects, we sort according to the1121 * respective pointer value as the primary sorting criterion.1122 * The actual relation is pretty unimportant as long as it1123 * establishes a total order. Comparing as integers gives us1124 * that.1125 */1126if(s1->suspect != s2->suspect)1127return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1;1128if(s1->s_lno == s2->s_lno)1129return0;1130return s1->s_lno > s2->s_lno ?1: -1;1131}11321133voidblame_sort_final(struct blame_scoreboard *sb)1134{1135 sb->ent =llist_mergesort(sb->ent, get_next_blame, set_next_blame,1136 compare_blame_final);1137}11381139static intcompare_commits_by_reverse_commit_date(const void*a,1140const void*b,1141void*c)1142{1143return-compare_commits_by_commit_date(a, b, c);1144}11451146/*1147 * For debugging -- origin is refcounted, and this asserts that1148 * we do not underflow.1149 */1150static voidsanity_check_refcnt(struct blame_scoreboard *sb)1151{1152int baa =0;1153struct blame_entry *ent;11541155for(ent = sb->ent; ent; ent = ent->next) {1156/* Nobody should have zero or negative refcnt */1157if(ent->suspect->refcnt <=0) {1158fprintf(stderr,"%sin%shas negative refcnt%d\n",1159 ent->suspect->path,1160oid_to_hex(&ent->suspect->commit->object.oid),1161 ent->suspect->refcnt);1162 baa =1;1163}1164}1165if(baa)1166 sb->on_sanity_fail(sb, baa);1167}11681169/*1170 * If two blame entries that are next to each other came from1171 * contiguous lines in the same origin (i.e. <commit, path> pair),1172 * merge them together.1173 */1174voidblame_coalesce(struct blame_scoreboard *sb)1175{1176struct blame_entry *ent, *next;11771178for(ent = sb->ent; ent && (next = ent->next); ent = next) {1179if(ent->suspect == next->suspect &&1180 ent->s_lno + ent->num_lines == next->s_lno &&1181 ent->ignored == next->ignored &&1182 ent->unblamable == next->unblamable) {1183 ent->num_lines += next->num_lines;1184 ent->next = next->next;1185blame_origin_decref(next->suspect);1186free(next);1187 ent->score =0;1188 next = ent;/* again */1189}1190}11911192if(sb->debug)/* sanity */1193sanity_check_refcnt(sb);1194}11951196/*1197 * Merge the given sorted list of blames into a preexisting origin.1198 * If there were no previous blames to that commit, it is entered into1199 * the commit priority queue of the score board.1200 */12011202static voidqueue_blames(struct blame_scoreboard *sb,struct blame_origin *porigin,1203struct blame_entry *sorted)1204{1205if(porigin->suspects)1206 porigin->suspects =blame_merge(porigin->suspects, sorted);1207else{1208struct blame_origin *o;1209for(o =get_blame_suspects(porigin->commit); o; o = o->next) {1210if(o->suspects) {1211 porigin->suspects = sorted;1212return;1213}1214}1215 porigin->suspects = sorted;1216prio_queue_put(&sb->commits, porigin->commit);1217}1218}12191220/*1221 * Fill the blob_sha1 field of an origin if it hasn't, so that later1222 * call to fill_origin_blob() can use it to locate the data. blob_sha11223 * for an origin is also used to pass the blame for the entire file to1224 * the parent to detect the case where a child's blob is identical to1225 * that of its parent's.1226 *1227 * This also fills origin->mode for corresponding tree path.1228 */1229static intfill_blob_sha1_and_mode(struct repository *r,1230struct blame_origin *origin)1231{1232if(!is_null_oid(&origin->blob_oid))1233return0;1234if(get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))1235goto error_out;1236if(oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)1237goto error_out;1238return0;1239 error_out:1240oidclr(&origin->blob_oid);1241 origin->mode = S_IFINVALID;1242return-1;1243}12441245/*1246 * We have an origin -- check if the same path exists in the1247 * parent and return an origin structure to represent it.1248 */1249static struct blame_origin *find_origin(struct repository *r,1250struct commit *parent,1251struct blame_origin *origin)1252{1253struct blame_origin *porigin;1254struct diff_options diff_opts;1255const char*paths[2];12561257/* First check any existing origins */1258for(porigin =get_blame_suspects(parent); porigin; porigin = porigin->next)1259if(!strcmp(porigin->path, origin->path)) {1260/*1261 * The same path between origin and its parent1262 * without renaming -- the most common case.1263 */1264returnblame_origin_incref(porigin);1265}12661267/* See if the origin->path is different between parent1268 * and origin first. Most of the time they are the1269 * same and diff-tree is fairly efficient about this.1270 */1271repo_diff_setup(r, &diff_opts);1272 diff_opts.flags.recursive =1;1273 diff_opts.detect_rename =0;1274 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;1275 paths[0] = origin->path;1276 paths[1] = NULL;12771278parse_pathspec(&diff_opts.pathspec,1279 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,1280 PATHSPEC_LITERAL_PATH,"", paths);1281diff_setup_done(&diff_opts);12821283if(is_null_oid(&origin->commit->object.oid))1284do_diff_cache(get_commit_tree_oid(parent), &diff_opts);1285else1286diff_tree_oid(get_commit_tree_oid(parent),1287get_commit_tree_oid(origin->commit),1288"", &diff_opts);1289diffcore_std(&diff_opts);12901291if(!diff_queued_diff.nr) {1292/* The path is the same as parent */1293 porigin =get_origin(parent, origin->path);1294oidcpy(&porigin->blob_oid, &origin->blob_oid);1295 porigin->mode = origin->mode;1296}else{1297/*1298 * Since origin->path is a pathspec, if the parent1299 * commit had it as a directory, we will see a whole1300 * bunch of deletion of files in the directory that we1301 * do not care about.1302 */1303int i;1304struct diff_filepair *p = NULL;1305for(i =0; i < diff_queued_diff.nr; i++) {1306const char*name;1307 p = diff_queued_diff.queue[i];1308 name = p->one->path ? p->one->path : p->two->path;1309if(!strcmp(name, origin->path))1310break;1311}1312if(!p)1313die("internal error in blame::find_origin");1314switch(p->status) {1315default:1316die("internal error in blame::find_origin (%c)",1317 p->status);1318case'M':1319 porigin =get_origin(parent, origin->path);1320oidcpy(&porigin->blob_oid, &p->one->oid);1321 porigin->mode = p->one->mode;1322break;1323case'A':1324case'T':1325/* Did not exist in parent, or type changed */1326break;1327}1328}1329diff_flush(&diff_opts);1330clear_pathspec(&diff_opts.pathspec);1331return porigin;1332}13331334/*1335 * We have an origin -- find the path that corresponds to it in its1336 * parent and return an origin structure to represent it.1337 */1338static struct blame_origin *find_rename(struct repository *r,1339struct commit *parent,1340struct blame_origin *origin)1341{1342struct blame_origin *porigin = NULL;1343struct diff_options diff_opts;1344int i;13451346repo_diff_setup(r, &diff_opts);1347 diff_opts.flags.recursive =1;1348 diff_opts.detect_rename = DIFF_DETECT_RENAME;1349 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;1350 diff_opts.single_follow = origin->path;1351diff_setup_done(&diff_opts);13521353if(is_null_oid(&origin->commit->object.oid))1354do_diff_cache(get_commit_tree_oid(parent), &diff_opts);1355else1356diff_tree_oid(get_commit_tree_oid(parent),1357get_commit_tree_oid(origin->commit),1358"", &diff_opts);1359diffcore_std(&diff_opts);13601361for(i =0; i < diff_queued_diff.nr; i++) {1362struct diff_filepair *p = diff_queued_diff.queue[i];1363if((p->status =='R'|| p->status =='C') &&1364!strcmp(p->two->path, origin->path)) {1365 porigin =get_origin(parent, p->one->path);1366oidcpy(&porigin->blob_oid, &p->one->oid);1367 porigin->mode = p->one->mode;1368break;1369}1370}1371diff_flush(&diff_opts);1372clear_pathspec(&diff_opts.pathspec);1373return porigin;1374}13751376/*1377 * Append a new blame entry to a given output queue.1378 */1379static voidadd_blame_entry(struct blame_entry ***queue,1380const struct blame_entry *src)1381{1382struct blame_entry *e =xmalloc(sizeof(*e));1383memcpy(e, src,sizeof(*e));1384blame_origin_incref(e->suspect);13851386 e->next = **queue;1387**queue = e;1388*queue = &e->next;1389}13901391/*1392 * src typically is on-stack; we want to copy the information in it to1393 * a malloced blame_entry that gets added to the given queue. The1394 * origin of dst loses a refcnt.1395 */1396static voiddup_entry(struct blame_entry ***queue,1397struct blame_entry *dst,struct blame_entry *src)1398{1399blame_origin_incref(src->suspect);1400blame_origin_decref(dst->suspect);1401memcpy(dst, src,sizeof(*src));1402 dst->next = **queue;1403**queue = dst;1404*queue = &dst->next;1405}14061407const char*blame_nth_line(struct blame_scoreboard *sb,long lno)1408{1409return sb->final_buf + sb->lineno[lno];1410}14111412/*1413 * It is known that lines between tlno to same came from parent, and e1414 * has an overlap with that range. it also is known that parent's1415 * line plno corresponds to e's line tlno.1416 *1417 * <---- e ----->1418 * <------>1419 * <------------>1420 * <------------>1421 * <------------------>1422 *1423 * Split e into potentially three parts; before this chunk, the chunk1424 * to be blamed for the parent, and after that portion.1425 */1426static voidsplit_overlap(struct blame_entry *split,1427struct blame_entry *e,1428int tlno,int plno,int same,1429struct blame_origin *parent)1430{1431int chunk_end_lno;1432int i;1433memset(split,0,sizeof(struct blame_entry [3]));14341435for(i =0; i <3; i++) {1436 split[i].ignored = e->ignored;1437 split[i].unblamable = e->unblamable;1438}14391440if(e->s_lno < tlno) {1441/* there is a pre-chunk part not blamed on parent */1442 split[0].suspect =blame_origin_incref(e->suspect);1443 split[0].lno = e->lno;1444 split[0].s_lno = e->s_lno;1445 split[0].num_lines = tlno - e->s_lno;1446 split[1].lno = e->lno + tlno - e->s_lno;1447 split[1].s_lno = plno;1448}1449else{1450 split[1].lno = e->lno;1451 split[1].s_lno = plno + (e->s_lno - tlno);1452}14531454if(same < e->s_lno + e->num_lines) {1455/* there is a post-chunk part not blamed on parent */1456 split[2].suspect =blame_origin_incref(e->suspect);1457 split[2].lno = e->lno + (same - e->s_lno);1458 split[2].s_lno = e->s_lno + (same - e->s_lno);1459 split[2].num_lines = e->s_lno + e->num_lines - same;1460 chunk_end_lno = split[2].lno;1461}1462else1463 chunk_end_lno = e->lno + e->num_lines;1464 split[1].num_lines = chunk_end_lno - split[1].lno;14651466/*1467 * if it turns out there is nothing to blame the parent for,1468 * forget about the splitting. !split[1].suspect signals this.1469 */1470if(split[1].num_lines <1)1471return;1472 split[1].suspect =blame_origin_incref(parent);1473}14741475/*1476 * split_overlap() divided an existing blame e into up to three parts1477 * in split. Any assigned blame is moved to queue to1478 * reflect the split.1479 */1480static voidsplit_blame(struct blame_entry ***blamed,1481struct blame_entry ***unblamed,1482struct blame_entry *split,1483struct blame_entry *e)1484{1485if(split[0].suspect && split[2].suspect) {1486/* The first part (reuse storage for the existing entry e) */1487dup_entry(unblamed, e, &split[0]);14881489/* The last part -- me */1490add_blame_entry(unblamed, &split[2]);14911492/* ... and the middle part -- parent */1493add_blame_entry(blamed, &split[1]);1494}1495else if(!split[0].suspect && !split[2].suspect)1496/*1497 * The parent covers the entire area; reuse storage for1498 * e and replace it with the parent.1499 */1500dup_entry(blamed, e, &split[1]);1501else if(split[0].suspect) {1502/* me and then parent */1503dup_entry(unblamed, e, &split[0]);1504add_blame_entry(blamed, &split[1]);1505}1506else{1507/* parent and then me */1508dup_entry(blamed, e, &split[1]);1509add_blame_entry(unblamed, &split[2]);1510}1511}15121513/*1514 * After splitting the blame, the origins used by the1515 * on-stack blame_entry should lose one refcnt each.1516 */1517static voiddecref_split(struct blame_entry *split)1518{1519int i;15201521for(i =0; i <3; i++)1522blame_origin_decref(split[i].suspect);1523}15241525/*1526 * reverse_blame reverses the list given in head, appending tail.1527 * That allows us to build lists in reverse order, then reverse them1528 * afterwards. This can be faster than building the list in proper1529 * order right away. The reason is that building in proper order1530 * requires writing a link in the _previous_ element, while building1531 * in reverse order just requires placing the list head into the1532 * _current_ element.1533 */15341535static struct blame_entry *reverse_blame(struct blame_entry *head,1536struct blame_entry *tail)1537{1538while(head) {1539struct blame_entry *next = head->next;1540 head->next = tail;1541 tail = head;1542 head = next;1543}1544return tail;1545}15461547/*1548 * Splits a blame entry into two entries at 'len' lines. The original 'e'1549 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,1550 * which is returned, consists of the remainder: [e->lno + len, e->lno +1551 * e->num_lines). The caller needs to sort out the reference counting for the1552 * new entry's suspect.1553 */1554static struct blame_entry *split_blame_at(struct blame_entry *e,int len,1555struct blame_origin *new_suspect)1556{1557struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry));15581559 n->suspect = new_suspect;1560 n->ignored = e->ignored;1561 n->unblamable = e->unblamable;1562 n->lno = e->lno + len;1563 n->s_lno = e->s_lno + len;1564 n->num_lines = e->num_lines - len;1565 e->num_lines = len;1566 e->score =0;1567return n;1568}15691570struct blame_line_tracker {1571int is_parent;1572int s_lno;1573};15741575static intare_lines_adjacent(struct blame_line_tracker *first,1576struct blame_line_tracker *second)1577{1578return first->is_parent == second->is_parent &&1579 first->s_lno +1== second->s_lno;1580}15811582static intscan_parent_range(struct fingerprint *p_fps,1583struct fingerprint *t_fps,int t_idx,1584int from,int nr_lines)1585{1586int sim, p_idx;1587#define FINGERPRINT_FILE_THRESHOLD 101588int best_sim_val = FINGERPRINT_FILE_THRESHOLD;1589int best_sim_idx = -1;15901591for(p_idx = from; p_idx < from + nr_lines; p_idx++) {1592 sim =fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);1593if(sim < best_sim_val)1594continue;1595/* Break ties with the closest-to-target line number */1596if(sim == best_sim_val && best_sim_idx != -1&&1597abs(best_sim_idx - t_idx) <abs(p_idx - t_idx))1598continue;1599 best_sim_val = sim;1600 best_sim_idx = p_idx;1601}1602return best_sim_idx;1603}16041605/*1606 * The first pass checks the blame entry (from the target) against the parent's1607 * diff chunk. If that fails for a line, the second pass tries to match that1608 * line to any part of parent file. That catches cases where a change was1609 * broken into two chunks by 'context.'1610 */1611static voidguess_line_blames(struct blame_origin *parent,1612struct blame_origin *target,1613int tlno,int offset,int same,int parent_len,1614struct blame_line_tracker *line_blames)1615{1616int i, best_idx, target_idx;1617int parent_slno = tlno + offset;1618int*fuzzy_matches;16191620 fuzzy_matches =fuzzy_find_matching_lines(parent, target,1621 tlno, parent_slno, same,1622 parent_len);1623for(i =0; i < same - tlno; i++) {1624 target_idx = tlno + i;1625if(fuzzy_matches && fuzzy_matches[i] >=0) {1626 best_idx = fuzzy_matches[i];1627}else{1628 best_idx =scan_parent_range(parent->fingerprints,1629 target->fingerprints,1630 target_idx,0,1631 parent->num_lines);1632}1633if(best_idx >=0) {1634 line_blames[i].is_parent =1;1635 line_blames[i].s_lno = best_idx;1636}else{1637 line_blames[i].is_parent =0;1638 line_blames[i].s_lno = target_idx;1639}1640}1641free(fuzzy_matches);1642}16431644/*1645 * This decides which parts of a blame entry go to the parent (added to the1646 * ignoredp list) and which stay with the target (added to the diffp list). The1647 * actual decision was made in a separate heuristic function, and those answers1648 * for the lines in 'e' are in line_blames. This consumes e, essentially1649 * putting it on a list.1650 *1651 * Note that the blame entries on the ignoredp list are not necessarily sorted1652 * with respect to the parent's line numbers yet.1653 */1654static voidignore_blame_entry(struct blame_entry *e,1655struct blame_origin *parent,1656struct blame_origin *target,1657struct blame_entry **diffp,1658struct blame_entry **ignoredp,1659struct blame_line_tracker *line_blames)1660{1661int entry_len, nr_lines, i;16621663/*1664 * We carve new entries off the front of e. Each entry comes from a1665 * contiguous chunk of lines: adjacent lines from the same origin1666 * (either the parent or the target).1667 */1668 entry_len =1;1669 nr_lines = e->num_lines;/* e changes in the loop */1670for(i =0; i < nr_lines; i++) {1671struct blame_entry *next = NULL;16721673/*1674 * We are often adjacent to the next line - only split the blame1675 * entry when we have to.1676 */1677if(i +1< nr_lines) {1678if(are_lines_adjacent(&line_blames[i],1679&line_blames[i +1])) {1680 entry_len++;1681continue;1682}1683 next =split_blame_at(e, entry_len,1684blame_origin_incref(e->suspect));1685}1686if(line_blames[i].is_parent) {1687 e->ignored =1;1688blame_origin_decref(e->suspect);1689 e->suspect =blame_origin_incref(parent);1690 e->s_lno = line_blames[i - entry_len +1].s_lno;1691 e->next = *ignoredp;1692*ignoredp = e;1693}else{1694 e->unblamable =1;1695/* e->s_lno is already in the target's address space. */1696 e->next = *diffp;1697*diffp = e;1698}1699assert(e->num_lines == entry_len);1700 e = next;1701 entry_len =1;1702}1703assert(!e);1704}17051706/*1707 * Process one hunk from the patch between the current suspect for1708 * blame_entry e and its parent. This first blames any unfinished1709 * entries before the chunk (which is where target and parent start1710 * differing) on the parent, and then splits blame entries at the1711 * start and at the end of the difference region. Since use of -M and1712 * -C options may lead to overlapping/duplicate source line number1713 * ranges, all we can rely on from sorting/merging is the order of the1714 * first suspect line number.1715 *1716 * tlno: line number in the target where this chunk begins1717 * same: line number in the target where this chunk ends1718 * offset: add to tlno to get the chunk starting point in the parent1719 * parent_len: number of lines in the parent chunk1720 */1721static voidblame_chunk(struct blame_entry ***dstq,struct blame_entry ***srcq,1722int tlno,int offset,int same,int parent_len,1723struct blame_origin *parent,1724struct blame_origin *target,int ignore_diffs)1725{1726struct blame_entry *e = **srcq;1727struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;1728struct blame_line_tracker *line_blames = NULL;17291730while(e && e->s_lno < tlno) {1731struct blame_entry *next = e->next;1732/*1733 * current record starts before differing portion. If1734 * it reaches into it, we need to split it up and1735 * examine the second part separately.1736 */1737if(e->s_lno + e->num_lines > tlno) {1738/* Move second half to a new record */1739struct blame_entry *n;17401741 n =split_blame_at(e, tlno - e->s_lno, e->suspect);1742/* Push new record to diffp */1743 n->next = diffp;1744 diffp = n;1745}else1746blame_origin_decref(e->suspect);1747/* Pass blame for everything before the differing1748 * chunk to the parent */1749 e->suspect =blame_origin_incref(parent);1750 e->s_lno += offset;1751 e->next = samep;1752 samep = e;1753 e = next;1754}1755/*1756 * As we don't know how much of a common stretch after this1757 * diff will occur, the currently blamed parts are all that we1758 * can assign to the parent for now.1759 */17601761if(samep) {1762**dstq =reverse_blame(samep, **dstq);1763*dstq = &samep->next;1764}1765/*1766 * Prepend the split off portions: everything after e starts1767 * after the blameable portion.1768 */1769 e =reverse_blame(diffp, e);17701771/*1772 * Now retain records on the target while parts are different1773 * from the parent.1774 */1775 samep = NULL;1776 diffp = NULL;17771778if(ignore_diffs && same - tlno >0) {1779 line_blames =xcalloc(sizeof(struct blame_line_tracker),1780 same - tlno);1781guess_line_blames(parent, target, tlno, offset, same,1782 parent_len, line_blames);1783}17841785while(e && e->s_lno < same) {1786struct blame_entry *next = e->next;17871788/*1789 * If current record extends into sameness, need to split.1790 */1791if(e->s_lno + e->num_lines > same) {1792/*1793 * Move second half to a new record to be1794 * processed by later chunks1795 */1796struct blame_entry *n;17971798 n =split_blame_at(e, same - e->s_lno,1799blame_origin_incref(e->suspect));1800/* Push new record to samep */1801 n->next = samep;1802 samep = n;1803}1804if(ignore_diffs) {1805ignore_blame_entry(e, parent, target, &diffp, &ignoredp,1806 line_blames + e->s_lno - tlno);1807}else{1808 e->next = diffp;1809 diffp = e;1810}1811 e = next;1812}1813free(line_blames);1814if(ignoredp) {1815/*1816 * Note ignoredp is not sorted yet, and thus neither is dstq.1817 * That list must be sorted before we queue_blames(). We defer1818 * sorting until after all diff hunks are processed, so that1819 * guess_line_blames() can pick *any* line in the parent. The1820 * slight drawback is that we end up sorting all blame entries1821 * passed to the parent, including those that are unrelated to1822 * changes made by the ignored commit.1823 */1824**dstq =reverse_blame(ignoredp, **dstq);1825*dstq = &ignoredp->next;1826}1827**srcq =reverse_blame(diffp,reverse_blame(samep, e));1828/* Move across elements that are in the unblamable portion */1829if(diffp)1830*srcq = &diffp->next;1831}18321833struct blame_chunk_cb_data {1834struct blame_origin *parent;1835struct blame_origin *target;1836long offset;1837int ignore_diffs;1838struct blame_entry **dstq;1839struct blame_entry **srcq;1840};18411842/* diff chunks are from parent to target */1843static intblame_chunk_cb(long start_a,long count_a,1844long start_b,long count_b,void*data)1845{1846struct blame_chunk_cb_data *d = data;1847if(start_a - start_b != d->offset)1848die("internal error in blame::blame_chunk_cb");1849blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,1850 start_b + count_b, count_a, d->parent, d->target,1851 d->ignore_diffs);1852 d->offset = start_a + count_a - (start_b + count_b);1853return0;1854}18551856/*1857 * We are looking at the origin 'target' and aiming to pass blame1858 * for the lines it is suspected to its parent. Run diff to find1859 * which lines came from parent and pass blame for them.1860 */1861static voidpass_blame_to_parent(struct blame_scoreboard *sb,1862struct blame_origin *target,1863struct blame_origin *parent,int ignore_diffs)1864{1865 mmfile_t file_p, file_o;1866struct blame_chunk_cb_data d;1867struct blame_entry *newdest = NULL;18681869if(!target->suspects)1870return;/* nothing remains for this target */18711872 d.parent = parent;1873 d.target = target;1874 d.offset =0;1875 d.ignore_diffs = ignore_diffs;1876 d.dstq = &newdest; d.srcq = &target->suspects;18771878fill_origin_blob(&sb->revs->diffopt, parent, &file_p,1879&sb->num_read_blob, ignore_diffs);1880fill_origin_blob(&sb->revs->diffopt, target, &file_o,1881&sb->num_read_blob, ignore_diffs);1882 sb->num_get_patch++;18831884if(diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))1885die("unable to generate diff (%s->%s)",1886oid_to_hex(&parent->commit->object.oid),1887oid_to_hex(&target->commit->object.oid));1888/* The rest are the same as the parent */1889blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX,0,1890 parent, target,0);1891*d.dstq = NULL;1892if(ignore_diffs)1893 newdest =llist_mergesort(newdest, get_next_blame,1894 set_next_blame,1895 compare_blame_suspect);1896queue_blames(sb, parent, newdest);18971898return;1899}19001901/*1902 * The lines in blame_entry after splitting blames many times can become1903 * very small and trivial, and at some point it becomes pointless to1904 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any1905 * ordinary C program, and it is not worth to say it was copied from1906 * totally unrelated file in the parent.1907 *1908 * Compute how trivial the lines in the blame_entry are.1909 */1910unsignedblame_entry_score(struct blame_scoreboard *sb,struct blame_entry *e)1911{1912unsigned score;1913const char*cp, *ep;19141915if(e->score)1916return e->score;19171918 score =1;1919 cp =blame_nth_line(sb, e->lno);1920 ep =blame_nth_line(sb, e->lno + e->num_lines);1921while(cp < ep) {1922unsigned ch = *((unsigned char*)cp);1923if(isalnum(ch))1924 score++;1925 cp++;1926}1927 e->score = score;1928return score;1929}19301931/*1932 * best_so_far[] and potential[] are both a split of an existing blame_entry1933 * that passes blame to the parent. Maintain best_so_far the best split so1934 * far, by comparing potential and best_so_far and copying potential into1935 * bst_so_far as needed.1936 */1937static voidcopy_split_if_better(struct blame_scoreboard *sb,1938struct blame_entry *best_so_far,1939struct blame_entry *potential)1940{1941int i;19421943if(!potential[1].suspect)1944return;1945if(best_so_far[1].suspect) {1946if(blame_entry_score(sb, &potential[1]) <1947blame_entry_score(sb, &best_so_far[1]))1948return;1949}19501951for(i =0; i <3; i++)1952blame_origin_incref(potential[i].suspect);1953decref_split(best_so_far);1954memcpy(best_so_far, potential,sizeof(struct blame_entry[3]));1955}19561957/*1958 * We are looking at a part of the final image represented by1959 * ent (tlno and same are offset by ent->s_lno).1960 * tlno is where we are looking at in the final image.1961 * up to (but not including) same match preimage.1962 * plno is where we are looking at in the preimage.1963 *1964 * <-------------- final image ---------------------->1965 * <------ent------>1966 * ^tlno ^same1967 * <---------preimage----->1968 * ^plno1969 *1970 * All line numbers are 0-based.1971 */1972static voidhandle_split(struct blame_scoreboard *sb,1973struct blame_entry *ent,1974int tlno,int plno,int same,1975struct blame_origin *parent,1976struct blame_entry *split)1977{1978if(ent->num_lines <= tlno)1979return;1980if(tlno < same) {1981struct blame_entry potential[3];1982 tlno += ent->s_lno;1983 same += ent->s_lno;1984split_overlap(potential, ent, tlno, plno, same, parent);1985copy_split_if_better(sb, split, potential);1986decref_split(potential);1987}1988}19891990struct handle_split_cb_data {1991struct blame_scoreboard *sb;1992struct blame_entry *ent;1993struct blame_origin *parent;1994struct blame_entry *split;1995long plno;1996long tlno;1997};19981999static inthandle_split_cb(long start_a,long count_a,2000long start_b,long count_b,void*data)2001{2002struct handle_split_cb_data *d = data;2003handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,2004 d->split);2005 d->plno = start_a + count_a;2006 d->tlno = start_b + count_b;2007return0;2008}20092010/*2011 * Find the lines from parent that are the same as ent so that2012 * we can pass blames to it. file_p has the blob contents for2013 * the parent.2014 */2015static voidfind_copy_in_blob(struct blame_scoreboard *sb,2016struct blame_entry *ent,2017struct blame_origin *parent,2018struct blame_entry *split,2019 mmfile_t *file_p)2020{2021const char*cp;2022 mmfile_t file_o;2023struct handle_split_cb_data d;20242025memset(&d,0,sizeof(d));2026 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;2027/*2028 * Prepare mmfile that contains only the lines in ent.2029 */2030 cp =blame_nth_line(sb, ent->lno);2031 file_o.ptr = (char*) cp;2032 file_o.size =blame_nth_line(sb, ent->lno + ent->num_lines) - cp;20332034/*2035 * file_o is a part of final image we are annotating.2036 * file_p partially may match that image.2037 */2038memset(split,0,sizeof(struct blame_entry [3]));2039if(diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))2040die("unable to generate diff (%s)",2041oid_to_hex(&parent->commit->object.oid));2042/* remainder, if any, all match the preimage */2043handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);2044}20452046/* Move all blame entries from list *source that have a score smaller2047 * than score_min to the front of list *small.2048 * Returns a pointer to the link pointing to the old head of the small list.2049 */20502051static struct blame_entry **filter_small(struct blame_scoreboard *sb,2052struct blame_entry **small,2053struct blame_entry **source,2054unsigned score_min)2055{2056struct blame_entry *p = *source;2057struct blame_entry *oldsmall = *small;2058while(p) {2059if(blame_entry_score(sb, p) <= score_min) {2060*small = p;2061 small = &p->next;2062 p = *small;2063}else{2064*source = p;2065 source = &p->next;2066 p = *source;2067}2068}2069*small = oldsmall;2070*source = NULL;2071return small;2072}20732074/*2075 * See if lines currently target is suspected for can be attributed to2076 * parent.2077 */2078static voidfind_move_in_parent(struct blame_scoreboard *sb,2079struct blame_entry ***blamed,2080struct blame_entry **toosmall,2081struct blame_origin *target,2082struct blame_origin *parent)2083{2084struct blame_entry *e, split[3];2085struct blame_entry *unblamed = target->suspects;2086struct blame_entry *leftover = NULL;2087 mmfile_t file_p;20882089if(!unblamed)2090return;/* nothing remains for this target */20912092fill_origin_blob(&sb->revs->diffopt, parent, &file_p,2093&sb->num_read_blob,0);2094if(!file_p.ptr)2095return;20962097/* At each iteration, unblamed has a NULL-terminated list of2098 * entries that have not yet been tested for blame. leftover2099 * contains the reversed list of entries that have been tested2100 * without being assignable to the parent.2101 */2102do{2103struct blame_entry **unblamedtail = &unblamed;2104struct blame_entry *next;2105for(e = unblamed; e; e = next) {2106 next = e->next;2107find_copy_in_blob(sb, e, parent, split, &file_p);2108if(split[1].suspect &&2109 sb->move_score <blame_entry_score(sb, &split[1])) {2110split_blame(blamed, &unblamedtail, split, e);2111}else{2112 e->next = leftover;2113 leftover = e;2114}2115decref_split(split);2116}2117*unblamedtail = NULL;2118 toosmall =filter_small(sb, toosmall, &unblamed, sb->move_score);2119}while(unblamed);2120 target->suspects =reverse_blame(leftover, NULL);2121}21222123struct blame_list {2124struct blame_entry *ent;2125struct blame_entry split[3];2126};21272128/*2129 * Count the number of entries the target is suspected for,2130 * and prepare a list of entry and the best split.2131 */2132static struct blame_list *setup_blame_list(struct blame_entry *unblamed,2133int*num_ents_p)2134{2135struct blame_entry *e;2136int num_ents, i;2137struct blame_list *blame_list = NULL;21382139for(e = unblamed, num_ents =0; e; e = e->next)2140 num_ents++;2141if(num_ents) {2142 blame_list =xcalloc(num_ents,sizeof(struct blame_list));2143for(e = unblamed, i =0; e; e = e->next)2144 blame_list[i++].ent = e;2145}2146*num_ents_p = num_ents;2147return blame_list;2148}21492150/*2151 * For lines target is suspected for, see if we can find code movement2152 * across file boundary from the parent commit. porigin is the path2153 * in the parent we already tried.2154 */2155static voidfind_copy_in_parent(struct blame_scoreboard *sb,2156struct blame_entry ***blamed,2157struct blame_entry **toosmall,2158struct blame_origin *target,2159struct commit *parent,2160struct blame_origin *porigin,2161int opt)2162{2163struct diff_options diff_opts;2164int i, j;2165struct blame_list *blame_list;2166int num_ents;2167struct blame_entry *unblamed = target->suspects;2168struct blame_entry *leftover = NULL;21692170if(!unblamed)2171return;/* nothing remains for this target */21722173repo_diff_setup(sb->repo, &diff_opts);2174 diff_opts.flags.recursive =1;2175 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;21762177diff_setup_done(&diff_opts);21782179/* Try "find copies harder" on new path if requested;2180 * we do not want to use diffcore_rename() actually to2181 * match things up; find_copies_harder is set only to2182 * force diff_tree_oid() to feed all filepairs to diff_queue,2183 * and this code needs to be after diff_setup_done(), which2184 * usually makes find-copies-harder imply copy detection.2185 */2186if((opt & PICKAXE_BLAME_COPY_HARDEST)2187|| ((opt & PICKAXE_BLAME_COPY_HARDER)2188&& (!porigin ||strcmp(target->path, porigin->path))))2189 diff_opts.flags.find_copies_harder =1;21902191if(is_null_oid(&target->commit->object.oid))2192do_diff_cache(get_commit_tree_oid(parent), &diff_opts);2193else2194diff_tree_oid(get_commit_tree_oid(parent),2195get_commit_tree_oid(target->commit),2196"", &diff_opts);21972198if(!diff_opts.flags.find_copies_harder)2199diffcore_std(&diff_opts);22002201do{2202struct blame_entry **unblamedtail = &unblamed;2203 blame_list =setup_blame_list(unblamed, &num_ents);22042205for(i =0; i < diff_queued_diff.nr; i++) {2206struct diff_filepair *p = diff_queued_diff.queue[i];2207struct blame_origin *norigin;2208 mmfile_t file_p;2209struct blame_entry potential[3];22102211if(!DIFF_FILE_VALID(p->one))2212continue;/* does not exist in parent */2213if(S_ISGITLINK(p->one->mode))2214continue;/* ignore git links */2215if(porigin && !strcmp(p->one->path, porigin->path))2216/* find_move already dealt with this path */2217continue;22182219 norigin =get_origin(parent, p->one->path);2220oidcpy(&norigin->blob_oid, &p->one->oid);2221 norigin->mode = p->one->mode;2222fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,2223&sb->num_read_blob,0);2224if(!file_p.ptr)2225continue;22262227for(j =0; j < num_ents; j++) {2228find_copy_in_blob(sb, blame_list[j].ent,2229 norigin, potential, &file_p);2230copy_split_if_better(sb, blame_list[j].split,2231 potential);2232decref_split(potential);2233}2234blame_origin_decref(norigin);2235}22362237for(j =0; j < num_ents; j++) {2238struct blame_entry *split = blame_list[j].split;2239if(split[1].suspect &&2240 sb->copy_score <blame_entry_score(sb, &split[1])) {2241split_blame(blamed, &unblamedtail, split,2242 blame_list[j].ent);2243}else{2244 blame_list[j].ent->next = leftover;2245 leftover = blame_list[j].ent;2246}2247decref_split(split);2248}2249free(blame_list);2250*unblamedtail = NULL;2251 toosmall =filter_small(sb, toosmall, &unblamed, sb->copy_score);2252}while(unblamed);2253 target->suspects =reverse_blame(leftover, NULL);2254diff_flush(&diff_opts);2255clear_pathspec(&diff_opts.pathspec);2256}22572258/*2259 * The blobs of origin and porigin exactly match, so everything2260 * origin is suspected for can be blamed on the parent.2261 */2262static voidpass_whole_blame(struct blame_scoreboard *sb,2263struct blame_origin *origin,struct blame_origin *porigin)2264{2265struct blame_entry *e, *suspects;22662267if(!porigin->file.ptr && origin->file.ptr) {2268/* Steal its file */2269 porigin->file = origin->file;2270 origin->file.ptr = NULL;2271}2272 suspects = origin->suspects;2273 origin->suspects = NULL;2274for(e = suspects; e; e = e->next) {2275blame_origin_incref(porigin);2276blame_origin_decref(e->suspect);2277 e->suspect = porigin;2278}2279queue_blames(sb, porigin, suspects);2280}22812282/*2283 * We pass blame from the current commit to its parents. We keep saying2284 * "parent" (and "porigin"), but what we mean is to find scapegoat to2285 * exonerate ourselves.2286 */2287static struct commit_list *first_scapegoat(struct rev_info *revs,struct commit *commit,2288int reverse)2289{2290if(!reverse) {2291if(revs->first_parent_only &&2292 commit->parents &&2293 commit->parents->next) {2294free_commit_list(commit->parents->next);2295 commit->parents->next = NULL;2296}2297return commit->parents;2298}2299returnlookup_decoration(&revs->children, &commit->object);2300}23012302static intnum_scapegoats(struct rev_info *revs,struct commit *commit,int reverse)2303{2304struct commit_list *l =first_scapegoat(revs, commit, reverse);2305returncommit_list_count(l);2306}23072308/* Distribute collected unsorted blames to the respected sorted lists2309 * in the various origins.2310 */2311static voiddistribute_blame(struct blame_scoreboard *sb,struct blame_entry *blamed)2312{2313 blamed =llist_mergesort(blamed, get_next_blame, set_next_blame,2314 compare_blame_suspect);2315while(blamed)2316{2317struct blame_origin *porigin = blamed->suspect;2318struct blame_entry *suspects = NULL;2319do{2320struct blame_entry *next = blamed->next;2321 blamed->next = suspects;2322 suspects = blamed;2323 blamed = next;2324}while(blamed && blamed->suspect == porigin);2325 suspects =reverse_blame(suspects, NULL);2326queue_blames(sb, porigin, suspects);2327}2328}23292330#define MAXSG 1623312332static voidpass_blame(struct blame_scoreboard *sb,struct blame_origin *origin,int opt)2333{2334struct rev_info *revs = sb->revs;2335int i, pass, num_sg;2336struct commit *commit = origin->commit;2337struct commit_list *sg;2338struct blame_origin *sg_buf[MAXSG];2339struct blame_origin *porigin, **sg_origin = sg_buf;2340struct blame_entry *toosmall = NULL;2341struct blame_entry *blames, **blametail = &blames;23422343 num_sg =num_scapegoats(revs, commit, sb->reverse);2344if(!num_sg)2345goto finish;2346else if(num_sg <ARRAY_SIZE(sg_buf))2347memset(sg_buf,0,sizeof(sg_buf));2348else2349 sg_origin =xcalloc(num_sg,sizeof(*sg_origin));23502351/*2352 * The first pass looks for unrenamed path to optimize for2353 * common cases, then we look for renames in the second pass.2354 */2355for(pass =0; pass <2- sb->no_whole_file_rename; pass++) {2356struct blame_origin *(*find)(struct repository *,struct commit *,struct blame_origin *);2357 find = pass ? find_rename : find_origin;23582359for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2360 i < num_sg && sg;2361 sg = sg->next, i++) {2362struct commit *p = sg->item;2363int j, same;23642365if(sg_origin[i])2366continue;2367if(parse_commit(p))2368continue;2369 porigin =find(sb->repo, p, origin);2370if(!porigin)2371continue;2372if(oideq(&porigin->blob_oid, &origin->blob_oid)) {2373pass_whole_blame(sb, origin, porigin);2374blame_origin_decref(porigin);2375goto finish;2376}2377for(j = same =0; j < i; j++)2378if(sg_origin[j] &&2379oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {2380 same =1;2381break;2382}2383if(!same)2384 sg_origin[i] = porigin;2385else2386blame_origin_decref(porigin);2387}2388}23892390 sb->num_commits++;2391for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2392 i < num_sg && sg;2393 sg = sg->next, i++) {2394struct blame_origin *porigin = sg_origin[i];2395if(!porigin)2396continue;2397if(!origin->previous) {2398blame_origin_incref(porigin);2399 origin->previous = porigin;2400}2401pass_blame_to_parent(sb, origin, porigin,0);2402if(!origin->suspects)2403goto finish;2404}24052406/*2407 * Pass remaining suspects for ignored commits to their parents.2408 */2409if(oidset_contains(&sb->ignore_list, &commit->object.oid)) {2410for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2411 i < num_sg && sg;2412 sg = sg->next, i++) {2413struct blame_origin *porigin = sg_origin[i];24142415if(!porigin)2416continue;2417pass_blame_to_parent(sb, origin, porigin,1);2418/*2419 * Preemptively drop porigin so we can refresh the2420 * fingerprints if we use the parent again, which can2421 * occur if you ignore back-to-back commits.2422 */2423drop_origin_blob(porigin);2424if(!origin->suspects)2425goto finish;2426}2427}24282429/*2430 * Optionally find moves in parents' files.2431 */2432if(opt & PICKAXE_BLAME_MOVE) {2433filter_small(sb, &toosmall, &origin->suspects, sb->move_score);2434if(origin->suspects) {2435for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2436 i < num_sg && sg;2437 sg = sg->next, i++) {2438struct blame_origin *porigin = sg_origin[i];2439if(!porigin)2440continue;2441find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);2442if(!origin->suspects)2443break;2444}2445}2446}24472448/*2449 * Optionally find copies from parents' files.2450 */2451if(opt & PICKAXE_BLAME_COPY) {2452if(sb->copy_score > sb->move_score)2453filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);2454else if(sb->copy_score < sb->move_score) {2455 origin->suspects =blame_merge(origin->suspects, toosmall);2456 toosmall = NULL;2457filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);2458}2459if(!origin->suspects)2460goto finish;24612462for(i =0, sg =first_scapegoat(revs, commit, sb->reverse);2463 i < num_sg && sg;2464 sg = sg->next, i++) {2465struct blame_origin *porigin = sg_origin[i];2466find_copy_in_parent(sb, &blametail, &toosmall,2467 origin, sg->item, porigin, opt);2468if(!origin->suspects)2469goto finish;2470}2471}24722473finish:2474*blametail = NULL;2475distribute_blame(sb, blames);2476/*2477 * prepend toosmall to origin->suspects2478 *2479 * There is no point in sorting: this ends up on a big2480 * unsorted list in the caller anyway.2481 */2482if(toosmall) {2483struct blame_entry **tail = &toosmall;2484while(*tail)2485 tail = &(*tail)->next;2486*tail = origin->suspects;2487 origin->suspects = toosmall;2488}2489for(i =0; i < num_sg; i++) {2490if(sg_origin[i]) {2491drop_origin_blob(sg_origin[i]);2492blame_origin_decref(sg_origin[i]);2493}2494}2495drop_origin_blob(origin);2496if(sg_buf != sg_origin)2497free(sg_origin);2498}24992500/*2501 * The main loop -- while we have blobs with lines whose true origin2502 * is still unknown, pick one blob, and allow its lines to pass blames2503 * to its parents. */2504voidassign_blame(struct blame_scoreboard *sb,int opt)2505{2506struct rev_info *revs = sb->revs;2507struct commit *commit =prio_queue_get(&sb->commits);25082509while(commit) {2510struct blame_entry *ent;2511struct blame_origin *suspect =get_blame_suspects(commit);25122513/* find one suspect to break down */2514while(suspect && !suspect->suspects)2515 suspect = suspect->next;25162517if(!suspect) {2518 commit =prio_queue_get(&sb->commits);2519continue;2520}25212522assert(commit == suspect->commit);25232524/*2525 * We will use this suspect later in the loop,2526 * so hold onto it in the meantime.2527 */2528blame_origin_incref(suspect);2529parse_commit(commit);2530if(sb->reverse ||2531(!(commit->object.flags & UNINTERESTING) &&2532!(revs->max_age != -1&& commit->date < revs->max_age)))2533pass_blame(sb, suspect, opt);2534else{2535 commit->object.flags |= UNINTERESTING;2536if(commit->object.parsed)2537mark_parents_uninteresting(commit);2538}2539/* treat root commit as boundary */2540if(!commit->parents && !sb->show_root)2541 commit->object.flags |= UNINTERESTING;25422543/* Take responsibility for the remaining entries */2544 ent = suspect->suspects;2545if(ent) {2546 suspect->guilty =1;2547for(;;) {2548struct blame_entry *next = ent->next;2549if(sb->found_guilty_entry)2550 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);2551if(next) {2552 ent = next;2553continue;2554}2555 ent->next = sb->ent;2556 sb->ent = suspect->suspects;2557 suspect->suspects = NULL;2558break;2559}2560}2561blame_origin_decref(suspect);25622563if(sb->debug)/* sanity */2564sanity_check_refcnt(sb);2565}2566}25672568/*2569 * To allow quick access to the contents of nth line in the2570 * final image, prepare an index in the scoreboard.2571 */2572static intprepare_lines(struct blame_scoreboard *sb)2573{2574 sb->num_lines =find_line_starts(&sb->lineno, sb->final_buf,2575 sb->final_buf_size);2576return sb->num_lines;2577}25782579static struct commit *find_single_final(struct rev_info *revs,2580const char**name_p)2581{2582int i;2583struct commit *found = NULL;2584const char*name = NULL;25852586for(i =0; i < revs->pending.nr; i++) {2587struct object *obj = revs->pending.objects[i].item;2588if(obj->flags & UNINTERESTING)2589continue;2590 obj =deref_tag(revs->repo, obj, NULL,0);2591if(obj->type != OBJ_COMMIT)2592die("Non commit%s?", revs->pending.objects[i].name);2593if(found)2594die("More than one commit to dig from%sand%s?",2595 revs->pending.objects[i].name, name);2596 found = (struct commit *)obj;2597 name = revs->pending.objects[i].name;2598}2599if(name_p)2600*name_p =xstrdup_or_null(name);2601return found;2602}26032604static struct commit *dwim_reverse_initial(struct rev_info *revs,2605const char**name_p)2606{2607/*2608 * DWIM "git blame --reverse ONE -- PATH" as2609 * "git blame --reverse ONE..HEAD -- PATH" but only do so2610 * when it makes sense.2611 */2612struct object *obj;2613struct commit *head_commit;2614struct object_id head_oid;26152616if(revs->pending.nr !=1)2617return NULL;26182619/* Is that sole rev a committish? */2620 obj = revs->pending.objects[0].item;2621 obj =deref_tag(revs->repo, obj, NULL,0);2622if(obj->type != OBJ_COMMIT)2623return NULL;26242625/* Do we have HEAD? */2626if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))2627return NULL;2628 head_commit =lookup_commit_reference_gently(revs->repo,2629&head_oid,1);2630if(!head_commit)2631return NULL;26322633/* Turn "ONE" into "ONE..HEAD" then */2634 obj->flags |= UNINTERESTING;2635add_pending_object(revs, &head_commit->object,"HEAD");26362637if(name_p)2638*name_p = revs->pending.objects[0].name;2639return(struct commit *)obj;2640}26412642static struct commit *find_single_initial(struct rev_info *revs,2643const char**name_p)2644{2645int i;2646struct commit *found = NULL;2647const char*name = NULL;26482649/*2650 * There must be one and only one negative commit, and it must be2651 * the boundary.2652 */2653for(i =0; i < revs->pending.nr; i++) {2654struct object *obj = revs->pending.objects[i].item;2655if(!(obj->flags & UNINTERESTING))2656continue;2657 obj =deref_tag(revs->repo, obj, NULL,0);2658if(obj->type != OBJ_COMMIT)2659die("Non commit%s?", revs->pending.objects[i].name);2660if(found)2661die("More than one commit to dig up from,%sand%s?",2662 revs->pending.objects[i].name, name);2663 found = (struct commit *) obj;2664 name = revs->pending.objects[i].name;2665}26662667if(!name)2668 found =dwim_reverse_initial(revs, &name);2669if(!name)2670die("No commit to dig up from?");26712672if(name_p)2673*name_p =xstrdup(name);2674return found;2675}26762677voidinit_scoreboard(struct blame_scoreboard *sb)2678{2679memset(sb,0,sizeof(struct blame_scoreboard));2680 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;2681 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;2682}26832684voidsetup_scoreboard(struct blame_scoreboard *sb,2685const char*path,2686struct blame_origin **orig)2687{2688const char*final_commit_name = NULL;2689struct blame_origin *o;2690struct commit *final_commit = NULL;2691enum object_type type;26922693init_blame_suspects(&blame_suspects);26942695if(sb->reverse && sb->contents_from)2696die(_("--contents and --reverse do not blend well."));26972698if(!sb->repo)2699BUG("repo is NULL");27002701if(!sb->reverse) {2702 sb->final =find_single_final(sb->revs, &final_commit_name);2703 sb->commits.compare = compare_commits_by_commit_date;2704}else{2705 sb->final =find_single_initial(sb->revs, &final_commit_name);2706 sb->commits.compare = compare_commits_by_reverse_commit_date;2707}27082709if(sb->final && sb->contents_from)2710die(_("cannot use --contents with final commit object name"));27112712if(sb->reverse && sb->revs->first_parent_only)2713 sb->revs->children.name = NULL;27142715if(!sb->final) {2716/*2717 * "--not A B -- path" without anything positive;2718 * do not default to HEAD, but use the working tree2719 * or "--contents".2720 */2721setup_work_tree();2722 sb->final =fake_working_tree_commit(sb->repo,2723&sb->revs->diffopt,2724 path, sb->contents_from);2725add_pending_object(sb->revs, &(sb->final->object),":");2726}27272728if(sb->reverse && sb->revs->first_parent_only) {2729 final_commit =find_single_final(sb->revs, NULL);2730if(!final_commit)2731die(_("--reverse and --first-parent together require specified latest commit"));2732}27332734/*2735 * If we have bottom, this will mark the ancestors of the2736 * bottom commits we would reach while traversing as2737 * uninteresting.2738 */2739if(prepare_revision_walk(sb->revs))2740die(_("revision walk setup failed"));27412742if(sb->reverse && sb->revs->first_parent_only) {2743struct commit *c = final_commit;27442745 sb->revs->children.name ="children";2746while(c->parents &&2747!oideq(&c->object.oid, &sb->final->object.oid)) {2748struct commit_list *l =xcalloc(1,sizeof(*l));27492750 l->item = c;2751if(add_decoration(&sb->revs->children,2752&c->parents->item->object, l))2753BUG("not unique item in first-parent chain");2754 c = c->parents->item;2755}27562757if(!oideq(&c->object.oid, &sb->final->object.oid))2758die(_("--reverse --first-parent together require range along first-parent chain"));2759}27602761if(is_null_oid(&sb->final->object.oid)) {2762 o =get_blame_suspects(sb->final);2763 sb->final_buf =xmemdupz(o->file.ptr, o->file.size);2764 sb->final_buf_size = o->file.size;2765}2766else{2767 o =get_origin(sb->final, path);2768if(fill_blob_sha1_and_mode(sb->repo, o))2769die(_("no such path%sin%s"), path, final_commit_name);27702771if(sb->revs->diffopt.flags.allow_textconv &&2772textconv_object(sb->repo, path, o->mode, &o->blob_oid,1, (char**) &sb->final_buf,2773&sb->final_buf_size))2774;2775else2776 sb->final_buf =read_object_file(&o->blob_oid, &type,2777&sb->final_buf_size);27782779if(!sb->final_buf)2780die(_("cannot read blob%sfor path%s"),2781oid_to_hex(&o->blob_oid),2782 path);2783}2784 sb->num_read_blob++;2785prepare_lines(sb);27862787if(orig)2788*orig = o;27892790free((char*)final_commit_name);2791}2792279327942795struct blame_entry *blame_entry_prepend(struct blame_entry *head,2796long start,long end,2797struct blame_origin *o)2798{2799struct blame_entry *new_head =xcalloc(1,sizeof(struct blame_entry));2800 new_head->lno = start;2801 new_head->num_lines = end - start;2802 new_head->suspect = o;2803 new_head->s_lno = start;2804 new_head->next = head;2805blame_origin_incref(o);2806return new_head;2807}