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 short mode; 103 104if(!get_tree_entry(r, 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 191repo_read_index(r); 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", 208 WANT_BLANK_IDENT, NULL,0); 209strbuf_addstr(&msg,"tree 0000000000000000000000000000000000000000\n"); 210for(parent = commit->parents; parent; parent = parent->next) 211strbuf_addf(&msg,"parent%s\n", 212oid_to_hex(&parent->item->object.oid)); 213strbuf_addf(&msg, 214"author%s\n" 215"committer%s\n\n" 216"Version of%sfrom%s\n", 217 ident, ident, path, 218(!contents_from ? path : 219(!strcmp(contents_from,"-") ?"standard input": contents_from))); 220set_commit_buffer_from_strbuf(r, commit, &msg); 221 222if(!contents_from ||strcmp("-", contents_from)) { 223struct stat st; 224const char*read_from; 225char*buf_ptr; 226unsigned long buf_len; 227 228if(contents_from) { 229if(stat(contents_from, &st) <0) 230die_errno("Cannot stat '%s'", contents_from); 231 read_from = contents_from; 232} 233else{ 234if(lstat(path, &st) <0) 235die_errno("Cannot lstat '%s'", path); 236 read_from = path; 237} 238 mode =canon_mode(st.st_mode); 239 240switch(st.st_mode & S_IFMT) { 241case S_IFREG: 242if(opt->flags.allow_textconv && 243textconv_object(r, read_from, mode, &null_oid,0, &buf_ptr, &buf_len)) 244strbuf_attach(&buf, buf_ptr, buf_len, buf_len +1); 245else if(strbuf_read_file(&buf, read_from, st.st_size) != st.st_size) 246die_errno("cannot open or read '%s'", read_from); 247break; 248case S_IFLNK: 249if(strbuf_readlink(&buf, read_from, st.st_size) <0) 250die_errno("cannot readlink '%s'", read_from); 251break; 252default: 253die("unsupported file type%s", read_from); 254} 255} 256else{ 257/* Reading from stdin */ 258 mode =0; 259if(strbuf_read(&buf,0,0) <0) 260die_errno("failed to read from stdin"); 261} 262convert_to_git(r->index, path, buf.buf, buf.len, &buf,0); 263 origin->file.ptr = buf.buf; 264 origin->file.size = buf.len; 265pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid); 266 267/* 268 * Read the current index, replace the path entry with 269 * origin->blob_sha1 without mucking with its mode or type 270 * bits; we are not going to write this index out -- we just 271 * want to run "diff-index --cached". 272 */ 273discard_index(r->index); 274repo_read_index(r); 275 276 len =strlen(path); 277if(!mode) { 278int pos =index_name_pos(r->index, path, len); 279if(0<= pos) 280 mode = r->index->cache[pos]->ce_mode; 281else 282/* Let's not bother reading from HEAD tree */ 283 mode = S_IFREG |0644; 284} 285 ce =make_empty_cache_entry(r->index, len); 286oidcpy(&ce->oid, &origin->blob_oid); 287memcpy(ce->name, path, len); 288 ce->ce_flags =create_ce_flags(0); 289 ce->ce_namelen = len; 290 ce->ce_mode =create_ce_mode(mode); 291add_index_entry(r->index, ce, 292 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 293 294cache_tree_invalidate_path(r->index, path); 295 296return commit; 297} 298 299 300 301static intdiff_hunks(mmfile_t *file_a, mmfile_t *file_b, 302 xdl_emit_hunk_consume_func_t hunk_func,void*cb_data,int xdl_opts) 303{ 304 xpparam_t xpp = {0}; 305 xdemitconf_t xecfg = {0}; 306 xdemitcb_t ecb = {NULL}; 307 308 xpp.flags = xdl_opts; 309 xecfg.hunk_func = hunk_func; 310 ecb.priv = cb_data; 311returnxdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 312} 313 314static const char*get_next_line(const char*start,const char*end) 315{ 316const char*nl =memchr(start,'\n', end - start); 317 318return nl ? nl +1: end; 319} 320 321static intfind_line_starts(int**line_starts,const char*buf, 322unsigned long len) 323{ 324const char*end = buf + len; 325const char*p; 326int*lineno; 327int num =0; 328 329for(p = buf; p < end; p =get_next_line(p, end)) 330 num++; 331 332ALLOC_ARRAY(*line_starts, num +1); 333 lineno = *line_starts; 334 335for(p = buf; p < end; p =get_next_line(p, end)) 336*lineno++ = p - buf; 337 338*lineno = len; 339 340return num; 341} 342 343struct fingerprint_entry; 344 345/* A fingerprint is intended to loosely represent a string, such that two 346 * fingerprints can be quickly compared to give an indication of the similarity 347 * of the strings that they represent. 348 * 349 * A fingerprint is represented as a multiset of the lower-cased byte pairs in 350 * the string that it represents. Whitespace is added at each end of the 351 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'. 352 * For example, the string "Darth Radar" will be converted to the following 353 * fingerprint: 354 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"} 355 * 356 * The similarity between two fingerprints is the size of the intersection of 357 * their multisets, including repeated elements. See fingerprint_similarity for 358 * examples. 359 * 360 * For ease of implementation, the fingerprint is implemented as a map 361 * of byte pairs to the count of that byte pair in the string, instead of 362 * allowing repeated elements in a set. 363 */ 364struct fingerprint { 365struct hashmap map; 366/* As we know the maximum number of entries in advance, it's 367 * convenient to store the entries in a single array instead of having 368 * the hashmap manage the memory. 369 */ 370struct fingerprint_entry *entries; 371}; 372 373/* A byte pair in a fingerprint. Stores the number of times the byte pair 374 * occurs in the string that the fingerprint represents. 375 */ 376struct fingerprint_entry { 377/* The hashmap entry - the hash represents the byte pair in its 378 * entirety so we don't need to store the byte pair separately. 379 */ 380struct hashmap_entry entry; 381/* The number of times the byte pair occurs in the string that the 382 * fingerprint represents. 383 */ 384int count; 385}; 386 387/* See `struct fingerprint` for an explanation of what a fingerprint is. 388 * \param result the fingerprint of the string is stored here. This must be 389 * freed later using free_fingerprint. 390 * \param line_begin the start of the string 391 * \param line_end the end of the string 392 */ 393static voidget_fingerprint(struct fingerprint *result, 394const char*line_begin, 395const char*line_end) 396{ 397unsigned int hash, c0 =0, c1; 398const char*p; 399int max_map_entry_count =1+ line_end - line_begin; 400struct fingerprint_entry *entry =xcalloc(max_map_entry_count, 401sizeof(struct fingerprint_entry)); 402struct fingerprint_entry *found_entry; 403 404hashmap_init(&result->map, NULL, NULL, max_map_entry_count); 405 result->entries = entry; 406for(p = line_begin; p <= line_end; ++p, c0 = c1) { 407/* Always terminate the string with whitespace. 408 * Normalise whitespace to 0, and normalise letters to 409 * lower case. This won't work for multibyte characters but at 410 * worst will match some unrelated characters. 411 */ 412if((p == line_end) ||isspace(*p)) 413 c1 =0; 414else 415 c1 =tolower(*p); 416 hash = c0 | (c1 <<8); 417/* Ignore whitespace pairs */ 418if(hash ==0) 419continue; 420hashmap_entry_init(entry, hash); 421 422 found_entry =hashmap_get(&result->map, entry, NULL); 423if(found_entry) { 424 found_entry->count +=1; 425}else{ 426 entry->count =1; 427hashmap_add(&result->map, entry); 428++entry; 429} 430} 431} 432 433static voidfree_fingerprint(struct fingerprint *f) 434{ 435hashmap_free(&f->map,0); 436free(f->entries); 437} 438 439/* Calculates the similarity between two fingerprints as the size of the 440 * intersection of their multisets, including repeated elements. See 441 * `struct fingerprint` for an explanation of the fingerprint representation. 442 * The similarity between "cat mat" and "father rather" is 2 because "at" is 443 * present twice in both strings while the similarity between "tim" and "mit" 444 * is 0. 445 */ 446static intfingerprint_similarity(struct fingerprint *a,struct fingerprint *b) 447{ 448int intersection =0; 449struct hashmap_iter iter; 450const struct fingerprint_entry *entry_a, *entry_b; 451 452hashmap_iter_init(&b->map, &iter); 453 454while((entry_b =hashmap_iter_next(&iter))) { 455if((entry_a =hashmap_get(&a->map, entry_b, NULL))) { 456 intersection += entry_a->count < entry_b->count ? 457 entry_a->count : entry_b->count; 458} 459} 460return intersection; 461} 462 463/* Subtracts byte-pair elements in B from A, modifying A in place. 464 */ 465static voidfingerprint_subtract(struct fingerprint *a,struct fingerprint *b) 466{ 467struct hashmap_iter iter; 468struct fingerprint_entry *entry_a; 469const struct fingerprint_entry *entry_b; 470 471hashmap_iter_init(&b->map, &iter); 472 473while((entry_b =hashmap_iter_next(&iter))) { 474if((entry_a =hashmap_get(&a->map, entry_b, NULL))) { 475if(entry_a->count <= entry_b->count) 476hashmap_remove(&a->map, entry_b, NULL); 477else 478 entry_a->count -= entry_b->count; 479} 480} 481} 482 483/* Calculate fingerprints for a series of lines. 484 * Puts the fingerprints in the fingerprints array, which must have been 485 * preallocated to allow storing line_count elements. 486 */ 487static voidget_line_fingerprints(struct fingerprint *fingerprints, 488const char*content,const int*line_starts, 489long first_line,long line_count) 490{ 491int i; 492const char*linestart, *lineend; 493 494 line_starts += first_line; 495for(i =0; i < line_count; ++i) { 496 linestart = content + line_starts[i]; 497 lineend = content + line_starts[i +1]; 498get_fingerprint(fingerprints + i, linestart, lineend); 499} 500} 501 502static voidfree_line_fingerprints(struct fingerprint *fingerprints, 503int nr_fingerprints) 504{ 505int i; 506 507for(i =0; i < nr_fingerprints; i++) 508free_fingerprint(&fingerprints[i]); 509} 510 511/* This contains the data necessary to linearly map a line number in one half 512 * of a diff chunk to the line in the other half of the diff chunk that is 513 * closest in terms of its position as a fraction of the length of the chunk. 514 */ 515struct line_number_mapping { 516int destination_start, destination_length, 517 source_start, source_length; 518}; 519 520/* Given a line number in one range, offset and scale it to map it onto the 521 * other range. 522 * Essentially this mapping is a simple linear equation but the calculation is 523 * more complicated to allow performing it with integer operations. 524 * Another complication is that if a line could map onto many lines in the 525 * destination range then we want to choose the line at the center of those 526 * possibilities. 527 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the 528 * first 5 lines in B will map onto the first line in the A chunk, while the 529 * last 5 lines will all map onto the second line in the A chunk. 530 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line 531 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A. 532 */ 533static intmap_line_number(int line_number, 534const struct line_number_mapping *mapping) 535{ 536return((line_number - mapping->source_start) *2+1) * 537 mapping->destination_length / 538(mapping->source_length *2) + 539 mapping->destination_start; 540} 541 542/* Get a pointer to the element storing the similarity between a line in A 543 * and a line in B. 544 * 545 * The similarities are stored in a 2-dimensional array. Each "row" in the 546 * array contains the similarities for a line in B. The similarities stored in 547 * a row are the similarities between the line in B and the nearby lines in A. 548 * To keep the length of each row the same, it is padded out with values of -1 549 * where the search range extends beyond the lines in A. 550 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk 551 * look like this: 552 * a | m 553 * b | n 554 * c | o 555 * d | p 556 * e | q 557 * Then the similarity array will contain: 558 * [-1, -1, am, bm, cm, 559 * -1, an, bn, cn, dn, 560 * ao, bo, co, do, eo, 561 * bp, cp, dp, ep, -1, 562 * cq, dq, eq, -1, -1] 563 * Where similarities are denoted either by -1 for invalid, or the 564 * concatenation of the two lines in the diff being compared. 565 * 566 * \param similarities array of similarities between lines in A and B 567 * \param line_a the index of the line in A, in the same frame of reference as 568 * closest_line_a. 569 * \param local_line_b the index of the line in B, relative to the first line 570 * in B that similarities represents. 571 * \param closest_line_a the index of the line in A that is deemed to be 572 * closest to local_line_b. This must be in the same 573 * frame of reference as line_a. This value defines 574 * where similarities is centered for the line in B. 575 * \param max_search_distance_a maximum distance in lines from the closest line 576 * in A for other lines in A for which 577 * similarities may be calculated. 578 */ 579static int*get_similarity(int*similarities, 580int line_a,int local_line_b, 581int closest_line_a,int max_search_distance_a) 582{ 583assert(abs(line_a - closest_line_a) <= 584 max_search_distance_a); 585return similarities + line_a - closest_line_a + 586 max_search_distance_a + 587 local_line_b * (max_search_distance_a *2+1); 588} 589 590#define CERTAIN_NOTHING_MATCHES -2 591#define CERTAINTY_NOT_CALCULATED -1 592 593/* Given a line in B, first calculate its similarities with nearby lines in A 594 * if not already calculated, then identify the most similar and second most 595 * similar lines. The "certainty" is calculated based on those two 596 * similarities. 597 * 598 * \param start_a the index of the first line of the chunk in A 599 * \param length_a the length in lines of the chunk in A 600 * \param local_line_b the index of the line in B, relative to the first line 601 * in the chunk. 602 * \param fingerprints_a array of fingerprints for the chunk in A 603 * \param fingerprints_b array of fingerprints for the chunk in B 604 * \param similarities 2-dimensional array of similarities between lines in A 605 * and B. See get_similarity() for more details. 606 * \param certainties array of values indicating how strongly a line in B is 607 * matched with some line in A. 608 * \param second_best_result array of absolute indices in A for the second 609 * closest match of a line in B. 610 * \param result array of absolute indices in A for the closest match of a line 611 * in B. 612 * \param max_search_distance_a maximum distance in lines from the closest line 613 * in A for other lines in A for which 614 * similarities may be calculated. 615 * \param map_line_number_in_b_to_a parameter to map_line_number(). 616 */ 617static voidfind_best_line_matches( 618int start_a, 619int length_a, 620int start_b, 621int local_line_b, 622struct fingerprint *fingerprints_a, 623struct fingerprint *fingerprints_b, 624int*similarities, 625int*certainties, 626int*second_best_result, 627int*result, 628const int max_search_distance_a, 629const struct line_number_mapping *map_line_number_in_b_to_a) 630{ 631 632int i, search_start, search_end, closest_local_line_a, *similarity, 633 best_similarity =0, second_best_similarity =0, 634 best_similarity_index =0, second_best_similarity_index =0; 635 636/* certainty has already been calculated so no need to redo the work */ 637if(certainties[local_line_b] != CERTAINTY_NOT_CALCULATED) 638return; 639 640 closest_local_line_a =map_line_number( 641 local_line_b + start_b, map_line_number_in_b_to_a) - start_a; 642 643 search_start = closest_local_line_a - max_search_distance_a; 644if(search_start <0) 645 search_start =0; 646 647 search_end = closest_local_line_a + max_search_distance_a +1; 648if(search_end > length_a) 649 search_end = length_a; 650 651for(i = search_start; i < search_end; ++i) { 652 similarity =get_similarity(similarities, 653 i, local_line_b, 654 closest_local_line_a, 655 max_search_distance_a); 656if(*similarity == -1) { 657/* This value will never exceed 10 but assert just in 658 * case 659 */ 660assert(abs(i - closest_local_line_a) <1000); 661/* scale the similarity by (1000 - distance from 662 * closest line) to act as a tie break between lines 663 * that otherwise are equally similar. 664 */ 665*similarity =fingerprint_similarity( 666 fingerprints_b + local_line_b, 667 fingerprints_a + i) * 668(1000-abs(i - closest_local_line_a)); 669} 670if(*similarity > best_similarity) { 671 second_best_similarity = best_similarity; 672 second_best_similarity_index = best_similarity_index; 673 best_similarity = *similarity; 674 best_similarity_index = i; 675}else if(*similarity > second_best_similarity) { 676 second_best_similarity = *similarity; 677 second_best_similarity_index = i; 678} 679} 680 681if(best_similarity ==0) { 682/* this line definitely doesn't match with anything. Mark it 683 * with this special value so it doesn't get invalidated and 684 * won't be recalculated. 685 */ 686 certainties[local_line_b] = CERTAIN_NOTHING_MATCHES; 687 result[local_line_b] = -1; 688}else{ 689/* Calculate the certainty with which this line matches. 690 * If the line matches well with two lines then that reduces 691 * the certainty. However we still want to prioritise matching 692 * a line that matches very well with two lines over matching a 693 * line that matches poorly with one line, hence doubling 694 * best_similarity. 695 * This means that if we have 696 * line X that matches only one line with a score of 3, 697 * line Y that matches two lines equally with a score of 5, 698 * and line Z that matches only one line with a score or 2, 699 * then the lines in order of certainty are X, Y, Z. 700 */ 701 certainties[local_line_b] = best_similarity *2- 702 second_best_similarity; 703 704/* We keep both the best and second best results to allow us to 705 * check at a later stage of the matching process whether the 706 * result needs to be invalidated. 707 */ 708 result[local_line_b] = start_a + best_similarity_index; 709 second_best_result[local_line_b] = 710 start_a + second_best_similarity_index; 711} 712} 713 714/* 715 * This finds the line that we can match with the most confidence, and 716 * uses it as a partition. It then calls itself on the lines on either side of 717 * that partition. In this way we avoid lines appearing out of order, and 718 * retain a sensible line ordering. 719 * \param start_a index of the first line in A with which lines in B may be 720 * compared. 721 * \param start_b index of the first line in B for which matching should be 722 * done. 723 * \param length_a number of lines in A with which lines in B may be compared. 724 * \param length_b number of lines in B for which matching should be done. 725 * \param fingerprints_a mutable array of fingerprints in A. The first element 726 * corresponds to the line at start_a. 727 * \param fingerprints_b array of fingerprints in B. The first element 728 * corresponds to the line at start_b. 729 * \param similarities 2-dimensional array of similarities between lines in A 730 * and B. See get_similarity() for more details. 731 * \param certainties array of values indicating how strongly a line in B is 732 * matched with some line in A. 733 * \param second_best_result array of absolute indices in A for the second 734 * closest match of a line in B. 735 * \param result array of absolute indices in A for the closest match of a line 736 * in B. 737 * \param max_search_distance_a maximum distance in lines from the closest line 738 * in A for other lines in A for which 739 * similarities may be calculated. 740 * \param max_search_distance_b an upper bound on the greatest possible 741 * distance between lines in B such that they will 742 * both be compared with the same line in A 743 * according to max_search_distance_a. 744 * \param map_line_number_in_b_to_a parameter to map_line_number(). 745 */ 746static voidfuzzy_find_matching_lines_recurse( 747int start_a,int start_b, 748int length_a,int length_b, 749struct fingerprint *fingerprints_a, 750struct fingerprint *fingerprints_b, 751int*similarities, 752int*certainties, 753int*second_best_result, 754int*result, 755int max_search_distance_a, 756int max_search_distance_b, 757const struct line_number_mapping *map_line_number_in_b_to_a) 758{ 759int i, invalidate_min, invalidate_max, offset_b, 760 second_half_start_a, second_half_start_b, 761 second_half_length_a, second_half_length_b, 762 most_certain_line_a, most_certain_local_line_b = -1, 763 most_certain_line_certainty = -1, 764 closest_local_line_a; 765 766for(i =0; i < length_b; ++i) { 767find_best_line_matches(start_a, 768 length_a, 769 start_b, 770 i, 771 fingerprints_a, 772 fingerprints_b, 773 similarities, 774 certainties, 775 second_best_result, 776 result, 777 max_search_distance_a, 778 map_line_number_in_b_to_a); 779 780if(certainties[i] > most_certain_line_certainty) { 781 most_certain_line_certainty = certainties[i]; 782 most_certain_local_line_b = i; 783} 784} 785 786/* No matches. */ 787if(most_certain_local_line_b == -1) 788return; 789 790 most_certain_line_a = result[most_certain_local_line_b]; 791 792/* 793 * Subtract the most certain line's fingerprint in B from the matched 794 * fingerprint in A. This means that other lines in B can't also match 795 * the same parts of the line in A. 796 */ 797fingerprint_subtract(fingerprints_a + most_certain_line_a - start_a, 798 fingerprints_b + most_certain_local_line_b); 799 800/* Invalidate results that may be affected by the choice of most 801 * certain line. 802 */ 803 invalidate_min = most_certain_local_line_b - max_search_distance_b; 804 invalidate_max = most_certain_local_line_b + max_search_distance_b +1; 805if(invalidate_min <0) 806 invalidate_min =0; 807if(invalidate_max > length_b) 808 invalidate_max = length_b; 809 810/* As the fingerprint in A has changed, discard previously calculated 811 * similarity values with that fingerprint. 812 */ 813for(i = invalidate_min; i < invalidate_max; ++i) { 814 closest_local_line_a =map_line_number( 815 i + start_b, map_line_number_in_b_to_a) - start_a; 816 817/* Check that the lines in A and B are close enough that there 818 * is a similarity value for them. 819 */ 820if(abs(most_certain_line_a - start_a - closest_local_line_a) > 821 max_search_distance_a) { 822continue; 823} 824 825*get_similarity(similarities, most_certain_line_a - start_a, 826 i, closest_local_line_a, 827 max_search_distance_a) = -1; 828} 829 830/* More invalidating of results that may be affected by the choice of 831 * most certain line. 832 * Discard the matches for lines in B that are currently matched with a 833 * line in A such that their ordering contradicts the ordering imposed 834 * by the choice of most certain line. 835 */ 836for(i = most_certain_local_line_b -1; i >= invalidate_min; --i) { 837/* In this loop we discard results for lines in B that are 838 * before most-certain-line-B but are matched with a line in A 839 * that is after most-certain-line-A. 840 */ 841if(certainties[i] >=0&& 842(result[i] >= most_certain_line_a || 843 second_best_result[i] >= most_certain_line_a)) { 844 certainties[i] = CERTAINTY_NOT_CALCULATED; 845} 846} 847for(i = most_certain_local_line_b +1; i < invalidate_max; ++i) { 848/* In this loop we discard results for lines in B that are 849 * after most-certain-line-B but are matched with a line in A 850 * that is before most-certain-line-A. 851 */ 852if(certainties[i] >=0&& 853(result[i] <= most_certain_line_a || 854 second_best_result[i] <= most_certain_line_a)) { 855 certainties[i] = CERTAINTY_NOT_CALCULATED; 856} 857} 858 859/* Repeat the matching process for lines before the most certain line. 860 */ 861if(most_certain_local_line_b >0) { 862fuzzy_find_matching_lines_recurse( 863 start_a, start_b, 864 most_certain_line_a +1- start_a, 865 most_certain_local_line_b, 866 fingerprints_a, fingerprints_b, similarities, 867 certainties, second_best_result, result, 868 max_search_distance_a, 869 max_search_distance_b, 870 map_line_number_in_b_to_a); 871} 872/* Repeat the matching process for lines after the most certain line. 873 */ 874if(most_certain_local_line_b +1< length_b) { 875 second_half_start_a = most_certain_line_a; 876 offset_b = most_certain_local_line_b +1; 877 second_half_start_b = start_b + offset_b; 878 second_half_length_a = 879 length_a + start_a - second_half_start_a; 880 second_half_length_b = 881 length_b + start_b - second_half_start_b; 882fuzzy_find_matching_lines_recurse( 883 second_half_start_a, second_half_start_b, 884 second_half_length_a, second_half_length_b, 885 fingerprints_a + second_half_start_a - start_a, 886 fingerprints_b + offset_b, 887 similarities + 888 offset_b * (max_search_distance_a *2+1), 889 certainties + offset_b, 890 second_best_result + offset_b, result + offset_b, 891 max_search_distance_a, 892 max_search_distance_b, 893 map_line_number_in_b_to_a); 894} 895} 896 897/* Find the lines in the parent line range that most closely match the lines in 898 * the target line range. This is accomplished by matching fingerprints in each 899 * blame_origin, and choosing the best matches that preserve the line ordering. 900 * See struct fingerprint for details of fingerprint matching, and 901 * fuzzy_find_matching_lines_recurse for details of preserving line ordering. 902 * 903 * The performance is believed to be O(n log n) in the typical case and O(n^2) 904 * in a pathological case, where n is the number of lines in the target range. 905 */ 906static int*fuzzy_find_matching_lines(struct blame_origin *parent, 907struct blame_origin *target, 908int tlno,int parent_slno,int same, 909int parent_len) 910{ 911/* We use the terminology "A" for the left hand side of the diff AKA 912 * parent, and "B" for the right hand side of the diff AKA target. */ 913int start_a = parent_slno; 914int length_a = parent_len; 915int start_b = tlno; 916int length_b = same - tlno; 917 918struct line_number_mapping map_line_number_in_b_to_a = { 919 start_a, length_a, start_b, length_b 920}; 921 922struct fingerprint *fingerprints_a = parent->fingerprints; 923struct fingerprint *fingerprints_b = target->fingerprints; 924 925int i, *result, *second_best_result, 926*certainties, *similarities, similarity_count; 927 928/* 929 * max_search_distance_a means that given a line in B, compare it to 930 * the line in A that is closest to its position, and the lines in A 931 * that are no greater than max_search_distance_a lines away from the 932 * closest line in A. 933 * 934 * max_search_distance_b is an upper bound on the greatest possible 935 * distance between lines in B such that they will both be compared 936 * with the same line in A according to max_search_distance_a. 937 */ 938int max_search_distance_a =10, max_search_distance_b; 939 940if(length_a <=0) 941return NULL; 942 943if(max_search_distance_a >= length_a) 944 max_search_distance_a = length_a ? length_a -1:0; 945 946 max_search_distance_b = ((2* max_search_distance_a +1) * length_b 947-1) / length_a; 948 949 result =xcalloc(sizeof(int), length_b); 950 second_best_result =xcalloc(sizeof(int), length_b); 951 certainties =xcalloc(sizeof(int), length_b); 952 953/* See get_similarity() for details of similarities. */ 954 similarity_count = length_b * (max_search_distance_a *2+1); 955 similarities =xcalloc(sizeof(int), similarity_count); 956 957for(i =0; i < length_b; ++i) { 958 result[i] = -1; 959 second_best_result[i] = -1; 960 certainties[i] = CERTAINTY_NOT_CALCULATED; 961} 962 963for(i =0; i < similarity_count; ++i) 964 similarities[i] = -1; 965 966fuzzy_find_matching_lines_recurse(start_a, start_b, 967 length_a, length_b, 968 fingerprints_a + start_a, 969 fingerprints_b + start_b, 970 similarities, 971 certainties, 972 second_best_result, 973 result, 974 max_search_distance_a, 975 max_search_distance_b, 976&map_line_number_in_b_to_a); 977 978free(similarities); 979free(certainties); 980free(second_best_result); 981 982return result; 983} 984 985static voidfill_origin_fingerprints(struct blame_origin *o) 986{ 987int*line_starts; 988 989if(o->fingerprints) 990return; 991 o->num_lines =find_line_starts(&line_starts, o->file.ptr, 992 o->file.size); 993 o->fingerprints =xcalloc(sizeof(struct fingerprint), o->num_lines); 994get_line_fingerprints(o->fingerprints, o->file.ptr, line_starts, 9950, o->num_lines); 996free(line_starts); 997} 998 999static voiddrop_origin_fingerprints(struct blame_origin *o)1000{1001if(o->fingerprints) {1002free_line_fingerprints(o->fingerprints, o->num_lines);1003 o->num_lines =0;1004FREE_AND_NULL(o->fingerprints);1005}1006}10071008/*1009 * Given an origin, prepare mmfile_t structure to be used by the1010 * diff machinery1011 */1012static voidfill_origin_blob(struct diff_options *opt,1013struct blame_origin *o, mmfile_t *file,1014int*num_read_blob,int fill_fingerprints)1015{1016if(!o->file.ptr) {1017enum object_type type;1018unsigned long file_size;10191020(*num_read_blob)++;1021if(opt->flags.allow_textconv &&1022textconv_object(opt->repo, o->path, o->mode,1023&o->blob_oid,1, &file->ptr, &file_size))1024;1025else1026 file->ptr =read_object_file(&o->blob_oid, &type,1027&file_size);1028 file->size = file_size;10291030if(!file->ptr)1031die("Cannot read blob%sfor path%s",1032oid_to_hex(&o->blob_oid),1033 o->path);1034 o->file = *file;1035}1036else1037*file = o->file;1038if(fill_fingerprints)1039fill_origin_fingerprints(o);1040}10411042static voiddrop_origin_blob(struct blame_origin *o)1043{1044FREE_AND_NULL(o->file.ptr);1045drop_origin_fingerprints(o);1046}10471048/*1049 * Any merge of blames happens on lists of blames that arrived via1050 * different parents in a single suspect. In this case, we want to1051 * sort according to the suspect line numbers as opposed to the final1052 * image line numbers. The function body is somewhat longish because1053 * it avoids unnecessary writes.1054 */10551056static struct blame_entry *blame_merge(struct blame_entry *list1,1057struct blame_entry *list2)1058{1059struct blame_entry *p1 = list1, *p2 = list2,1060**tail = &list1;10611062if(!p1)1063return p2;1064if(!p2)1065return p1;10661067if(p1->s_lno <= p2->s_lno) {1068do{1069 tail = &p1->next;1070if((p1 = *tail) == NULL) {1071*tail = p2;1072return list1;1073}1074}while(p1->s_lno <= p2->s_lno);1075}1076for(;;) {1077*tail = p2;1078do{1079 tail = &p2->next;1080if((p2 = *tail) == NULL) {1081*tail = p1;1082return list1;1083}1084}while(p1->s_lno > p2->s_lno);1085*tail = p1;1086do{1087 tail = &p1->next;1088if((p1 = *tail) == NULL) {1089*tail = p2;1090return list1;1091}1092}while(p1->s_lno <= p2->s_lno);1093}1094}10951096static void*get_next_blame(const void*p)1097{1098return((struct blame_entry *)p)->next;1099}11001101static voidset_next_blame(void*p1,void*p2)1102{1103((struct blame_entry *)p1)->next = p2;1104}11051106/*1107 * Final image line numbers are all different, so we don't need a1108 * three-way comparison here.1109 */11101111static intcompare_blame_final(const void*p1,const void*p2)1112{1113return((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno1114?1: -1;1115}11161117static intcompare_blame_suspect(const void*p1,const void*p2)1118{1119const struct blame_entry *s1 = p1, *s2 = p2;1120/*1121 * to allow for collating suspects, we sort according to the1122 * respective pointer value as the primary sorting criterion.1123 * The actual relation is pretty unimportant as long as it1124 * establishes a total order. Comparing as integers gives us1125 * that.1126 */1127if(s1->suspect != s2->suspect)1128return(intptr_t)s1->suspect > (intptr_t)s2->suspect ?1: -1;1129if(s1->s_lno == s2->s_lno)1130return0;1131return s1->s_lno > s2->s_lno ?1: -1;1132}11331134voidblame_sort_final(struct blame_scoreboard *sb)1135{1136 sb->ent =llist_mergesort(sb->ent, get_next_blame, set_next_blame,1137 compare_blame_final);1138}11391140static intcompare_commits_by_reverse_commit_date(const void*a,1141const void*b,1142void*c)1143{1144return-compare_commits_by_commit_date(a, b, c);1145}11461147/*1148 * For debugging -- origin is refcounted, and this asserts that1149 * we do not underflow.1150 */1151static voidsanity_check_refcnt(struct blame_scoreboard *sb)1152{1153int baa =0;1154struct blame_entry *ent;11551156for(ent = sb->ent; ent; ent = ent->next) {1157/* Nobody should have zero or negative refcnt */1158if(ent->suspect->refcnt <=0) {1159fprintf(stderr,"%sin%shas negative refcnt%d\n",1160 ent->suspect->path,1161oid_to_hex(&ent->suspect->commit->object.oid),1162 ent->suspect->refcnt);1163 baa =1;1164}1165}1166if(baa)1167 sb->on_sanity_fail(sb, baa);1168}11691170/*1171 * If two blame entries that are next to each other came from1172 * contiguous lines in the same origin (i.e. <commit, path> pair),1173 * merge them together.1174 */1175voidblame_coalesce(struct blame_scoreboard *sb)1176{1177struct blame_entry *ent, *next;11781179for(ent = sb->ent; ent && (next = ent->next); ent = next) {1180if(ent->suspect == next->suspect &&1181 ent->s_lno + ent->num_lines == next->s_lno &&1182 ent->ignored == next->ignored &&1183 ent->unblamable == next->unblamable) {1184 ent->num_lines += next->num_lines;1185 ent->next = next->next;1186blame_origin_decref(next->suspect);1187free(next);1188 ent->score =0;1189 next = ent;/* again */1190}1191}11921193if(sb->debug)/* sanity */1194sanity_check_refcnt(sb);1195}11961197/*1198 * Merge the given sorted list of blames into a preexisting origin.1199 * If there were no previous blames to that commit, it is entered into1200 * the commit priority queue of the score board.1201 */12021203static voidqueue_blames(struct blame_scoreboard *sb,struct blame_origin *porigin,1204struct blame_entry *sorted)1205{1206if(porigin->suspects)1207 porigin->suspects =blame_merge(porigin->suspects, sorted);1208else{1209struct blame_origin *o;1210for(o =get_blame_suspects(porigin->commit); o; o = o->next) {1211if(o->suspects) {1212 porigin->suspects = sorted;1213return;1214}1215}1216 porigin->suspects = sorted;1217prio_queue_put(&sb->commits, porigin->commit);1218}1219}12201221/*1222 * Fill the blob_sha1 field of an origin if it hasn't, so that later1223 * call to fill_origin_blob() can use it to locate the data. blob_sha11224 * for an origin is also used to pass the blame for the entire file to1225 * the parent to detect the case where a child's blob is identical to1226 * that of its parent's.1227 *1228 * This also fills origin->mode for corresponding tree path.1229 */1230static intfill_blob_sha1_and_mode(struct repository *r,1231struct blame_origin *origin)1232{1233if(!is_null_oid(&origin->blob_oid))1234return0;1235if(get_tree_entry(r, &origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))1236goto error_out;1237if(oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)1238goto error_out;1239return0;1240 error_out:1241oidclr(&origin->blob_oid);1242 origin->mode = S_IFINVALID;1243return-1;1244}12451246/*1247 * We have an origin -- check if the same path exists in the1248 * parent and return an origin structure to represent it.1249 */1250static struct blame_origin *find_origin(struct repository *r,1251struct commit *parent,1252struct blame_origin *origin)1253{1254struct blame_origin *porigin;1255struct diff_options diff_opts;1256const char*paths[2];12571258/* First check any existing origins */1259for(porigin =get_blame_suspects(parent); porigin; porigin = porigin->next)1260if(!strcmp(porigin->path, origin->path)) {1261/*1262 * The same path between origin and its parent1263 * without renaming -- the most common case.1264 */1265returnblame_origin_incref(porigin);1266}12671268/* See if the origin->path is different between parent1269 * and origin first. Most of the time they are the1270 * same and diff-tree is fairly efficient about this.1271 */1272repo_diff_setup(r, &diff_opts);1273 diff_opts.flags.recursive =1;1274 diff_opts.detect_rename =0;1275 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;1276 paths[0] = origin->path;1277 paths[1] = NULL;12781279parse_pathspec(&diff_opts.pathspec,1280 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,1281 PATHSPEC_LITERAL_PATH,"", paths);1282diff_setup_done(&diff_opts);12831284if(is_null_oid(&origin->commit->object.oid))1285do_diff_cache(get_commit_tree_oid(parent), &diff_opts);1286else1287diff_tree_oid(get_commit_tree_oid(parent),1288get_commit_tree_oid(origin->commit),1289"", &diff_opts);1290diffcore_std(&diff_opts);12911292if(!diff_queued_diff.nr) {1293/* The path is the same as parent */1294 porigin =get_origin(parent, origin->path);1295oidcpy(&porigin->blob_oid, &origin->blob_oid);1296 porigin->mode = origin->mode;1297}else{1298/*1299 * Since origin->path is a pathspec, if the parent1300 * commit had it as a directory, we will see a whole1301 * bunch of deletion of files in the directory that we1302 * do not care about.1303 */1304int i;1305struct diff_filepair *p = NULL;1306for(i =0; i < diff_queued_diff.nr; i++) {1307const char*name;1308 p = diff_queued_diff.queue[i];1309 name = p->one->path ? p->one->path : p->two->path;1310if(!strcmp(name, origin->path))1311break;1312}1313if(!p)1314die("internal error in blame::find_origin");1315switch(p->status) {1316default:1317die("internal error in blame::find_origin (%c)",1318 p->status);1319case'M':1320 porigin =get_origin(parent, origin->path);1321oidcpy(&porigin->blob_oid, &p->one->oid);1322 porigin->mode = p->one->mode;1323break;1324case'A':1325case'T':1326/* Did not exist in parent, or type changed */1327break;1328}1329}1330diff_flush(&diff_opts);1331clear_pathspec(&diff_opts.pathspec);1332return porigin;1333}13341335/*1336 * We have an origin -- find the path that corresponds to it in its1337 * parent and return an origin structure to represent it.1338 */1339static struct blame_origin *find_rename(struct repository *r,1340struct commit *parent,1341struct blame_origin *origin)1342{1343struct blame_origin *porigin = NULL;1344struct diff_options diff_opts;1345int i;13461347repo_diff_setup(r, &diff_opts);1348 diff_opts.flags.recursive =1;1349 diff_opts.detect_rename = DIFF_DETECT_RENAME;1350 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;1351 diff_opts.single_follow = origin->path;1352diff_setup_done(&diff_opts);13531354if(is_null_oid(&origin->commit->object.oid))1355do_diff_cache(get_commit_tree_oid(parent), &diff_opts);1356else1357diff_tree_oid(get_commit_tree_oid(parent),1358get_commit_tree_oid(origin->commit),1359"", &diff_opts);1360diffcore_std(&diff_opts);13611362for(i =0; i < diff_queued_diff.nr; i++) {1363struct diff_filepair *p = diff_queued_diff.queue[i];1364if((p->status =='R'|| p->status =='C') &&1365!strcmp(p->two->path, origin->path)) {1366 porigin =get_origin(parent, p->one->path);1367oidcpy(&porigin->blob_oid, &p->one->oid);1368 porigin->mode = p->one->mode;1369break;1370}1371}1372diff_flush(&diff_opts);1373clear_pathspec(&diff_opts.pathspec);1374return porigin;1375}13761377/*1378 * Append a new blame entry to a given output queue.1379 */1380static voidadd_blame_entry(struct blame_entry ***queue,1381const struct blame_entry *src)1382{1383struct blame_entry *e =xmalloc(sizeof(*e));1384memcpy(e, src,sizeof(*e));1385blame_origin_incref(e->suspect);13861387 e->next = **queue;1388**queue = e;1389*queue = &e->next;1390}13911392/*1393 * src typically is on-stack; we want to copy the information in it to1394 * a malloced blame_entry that gets added to the given queue. The1395 * origin of dst loses a refcnt.1396 */1397static voiddup_entry(struct blame_entry ***queue,1398struct blame_entry *dst,struct blame_entry *src)1399{1400blame_origin_incref(src->suspect);1401blame_origin_decref(dst->suspect);1402memcpy(dst, src,sizeof(*src));1403 dst->next = **queue;1404**queue = dst;1405*queue = &dst->next;1406}14071408const char*blame_nth_line(struct blame_scoreboard *sb,long lno)1409{1410return sb->final_buf + sb->lineno[lno];1411}14121413/*1414 * It is known that lines between tlno to same came from parent, and e1415 * has an overlap with that range. it also is known that parent's1416 * line plno corresponds to e's line tlno.1417 *1418 * <---- e ----->1419 * <------>1420 * <------------>1421 * <------------>1422 * <------------------>1423 *1424 * Split e into potentially three parts; before this chunk, the chunk1425 * to be blamed for the parent, and after that portion.1426 */1427static voidsplit_overlap(struct blame_entry *split,1428struct blame_entry *e,1429int tlno,int plno,int same,1430struct blame_origin *parent)1431{1432int chunk_end_lno;1433int i;1434memset(split,0,sizeof(struct blame_entry [3]));14351436for(i =0; i <3; i++) {1437 split[i].ignored = e->ignored;1438 split[i].unblamable = e->unblamable;1439}14401441if(e->s_lno < tlno) {1442/* there is a pre-chunk part not blamed on parent */1443 split[0].suspect =blame_origin_incref(e->suspect);1444 split[0].lno = e->lno;1445 split[0].s_lno = e->s_lno;1446 split[0].num_lines = tlno - e->s_lno;1447 split[1].lno = e->lno + tlno - e->s_lno;1448 split[1].s_lno = plno;1449}1450else{1451 split[1].lno = e->lno;1452 split[1].s_lno = plno + (e->s_lno - tlno);1453}14541455if(same < e->s_lno + e->num_lines) {1456/* there is a post-chunk part not blamed on parent */1457 split[2].suspect =blame_origin_incref(e->suspect);1458 split[2].lno = e->lno + (same - e->s_lno);1459 split[2].s_lno = e->s_lno + (same - e->s_lno);1460 split[2].num_lines = e->s_lno + e->num_lines - same;1461 chunk_end_lno = split[2].lno;1462}1463else1464 chunk_end_lno = e->lno + e->num_lines;1465 split[1].num_lines = chunk_end_lno - split[1].lno;14661467/*1468 * if it turns out there is nothing to blame the parent for,1469 * forget about the splitting. !split[1].suspect signals this.1470 */1471if(split[1].num_lines <1)1472return;1473 split[1].suspect =blame_origin_incref(parent);1474}14751476/*1477 * split_overlap() divided an existing blame e into up to three parts1478 * in split. Any assigned blame is moved to queue to1479 * reflect the split.1480 */1481static voidsplit_blame(struct blame_entry ***blamed,1482struct blame_entry ***unblamed,1483struct blame_entry *split,1484struct blame_entry *e)1485{1486if(split[0].suspect && split[2].suspect) {1487/* The first part (reuse storage for the existing entry e) */1488dup_entry(unblamed, e, &split[0]);14891490/* The last part -- me */1491add_blame_entry(unblamed, &split[2]);14921493/* ... and the middle part -- parent */1494add_blame_entry(blamed, &split[1]);1495}1496else if(!split[0].suspect && !split[2].suspect)1497/*1498 * The parent covers the entire area; reuse storage for1499 * e and replace it with the parent.1500 */1501dup_entry(blamed, e, &split[1]);1502else if(split[0].suspect) {1503/* me and then parent */1504dup_entry(unblamed, e, &split[0]);1505add_blame_entry(blamed, &split[1]);1506}1507else{1508/* parent and then me */1509dup_entry(blamed, e, &split[1]);1510add_blame_entry(unblamed, &split[2]);1511}1512}15131514/*1515 * After splitting the blame, the origins used by the1516 * on-stack blame_entry should lose one refcnt each.1517 */1518static voiddecref_split(struct blame_entry *split)1519{1520int i;15211522for(i =0; i <3; i++)1523blame_origin_decref(split[i].suspect);1524}15251526/*1527 * reverse_blame reverses the list given in head, appending tail.1528 * That allows us to build lists in reverse order, then reverse them1529 * afterwards. This can be faster than building the list in proper1530 * order right away. The reason is that building in proper order1531 * requires writing a link in the _previous_ element, while building1532 * in reverse order just requires placing the list head into the1533 * _current_ element.1534 */15351536static struct blame_entry *reverse_blame(struct blame_entry *head,1537struct blame_entry *tail)1538{1539while(head) {1540struct blame_entry *next = head->next;1541 head->next = tail;1542 tail = head;1543 head = next;1544}1545return tail;1546}15471548/*1549 * Splits a blame entry into two entries at 'len' lines. The original 'e'1550 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,1551 * which is returned, consists of the remainder: [e->lno + len, e->lno +1552 * e->num_lines). The caller needs to sort out the reference counting for the1553 * new entry's suspect.1554 */1555static struct blame_entry *split_blame_at(struct blame_entry *e,int len,1556struct blame_origin *new_suspect)1557{1558struct blame_entry *n =xcalloc(1,sizeof(struct blame_entry));15591560 n->suspect = new_suspect;1561 n->ignored = e->ignored;1562 n->unblamable = e->unblamable;1563 n->lno = e->lno + len;1564 n->s_lno = e->s_lno + len;1565 n->num_lines = e->num_lines - len;1566 e->num_lines = len;1567 e->score =0;1568return n;1569}15701571struct blame_line_tracker {1572int is_parent;1573int s_lno;1574};15751576static intare_lines_adjacent(struct blame_line_tracker *first,1577struct blame_line_tracker *second)1578{1579return first->is_parent == second->is_parent &&1580 first->s_lno +1== second->s_lno;1581}15821583static intscan_parent_range(struct fingerprint *p_fps,1584struct fingerprint *t_fps,int t_idx,1585int from,int nr_lines)1586{1587int sim, p_idx;1588#define FINGERPRINT_FILE_THRESHOLD 101589int best_sim_val = FINGERPRINT_FILE_THRESHOLD;1590int best_sim_idx = -1;15911592for(p_idx = from; p_idx < from + nr_lines; p_idx++) {1593 sim =fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);1594if(sim < best_sim_val)1595continue;1596/* Break ties with the closest-to-target line number */1597if(sim == best_sim_val && best_sim_idx != -1&&1598abs(best_sim_idx - t_idx) <abs(p_idx - t_idx))1599continue;1600 best_sim_val = sim;1601 best_sim_idx = p_idx;1602}1603return best_sim_idx;1604}16051606/*1607 * The first pass checks the blame entry (from the target) against the parent's1608 * diff chunk. If that fails for a line, the second pass tries to match that1609 * line to any part of parent file. That catches cases where a change was1610 * broken into two chunks by 'context.'1611 */1612static voidguess_line_blames(struct blame_origin *parent,1613struct blame_origin *target,1614int tlno,int offset,int same,int parent_len,1615struct blame_line_tracker *line_blames)1616{1617int i, best_idx, target_idx;1618int parent_slno = tlno + offset;1619int*fuzzy_matches;16201621 fuzzy_matches =fuzzy_find_matching_lines(parent, target,1622 tlno, parent_slno, same,1623 parent_len);1624for(i =0; i < same - tlno; i++) {1625 target_idx = tlno + i;1626if(fuzzy_matches && fuzzy_matches[i] >=0) {1627 best_idx = fuzzy_matches[i];1628}else{1629 best_idx =scan_parent_range(parent->fingerprints,1630 target->fingerprints,1631 target_idx,0,1632 parent->num_lines);1633}1634if(best_idx >=0) {1635 line_blames[i].is_parent =1;1636 line_blames[i].s_lno = best_idx;1637}else{1638 line_blames[i].is_parent =0;1639 line_blames[i].s_lno = target_idx;1640}1641}1642free(fuzzy_matches);1643}16441645/*1646 * This decides which parts of a blame entry go to the parent (added to the1647 * ignoredp list) and which stay with the target (added to the diffp list). The1648 * actual decision was made in a separate heuristic function, and those answers1649 * for the lines in 'e' are in line_blames. This consumes e, essentially1650 * putting it on a list.1651 *1652 * Note that the blame entries on the ignoredp list are not necessarily sorted1653 * with respect to the parent's line numbers yet.1654 */1655static voidignore_blame_entry(struct blame_entry *e,1656struct blame_origin *parent,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, &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]) {2491if(!sg_origin[i]->suspects)2492drop_origin_blob(sg_origin[i]);2493blame_origin_decref(sg_origin[i]);2494}2495}2496drop_origin_blob(origin);2497if(sg_buf != sg_origin)2498free(sg_origin);2499}25002501/*2502 * The main loop -- while we have blobs with lines whose true origin2503 * is still unknown, pick one blob, and allow its lines to pass blames2504 * to its parents. */2505voidassign_blame(struct blame_scoreboard *sb,int opt)2506{2507struct rev_info *revs = sb->revs;2508struct commit *commit =prio_queue_get(&sb->commits);25092510while(commit) {2511struct blame_entry *ent;2512struct blame_origin *suspect =get_blame_suspects(commit);25132514/* find one suspect to break down */2515while(suspect && !suspect->suspects)2516 suspect = suspect->next;25172518if(!suspect) {2519 commit =prio_queue_get(&sb->commits);2520continue;2521}25222523assert(commit == suspect->commit);25242525/*2526 * We will use this suspect later in the loop,2527 * so hold onto it in the meantime.2528 */2529blame_origin_incref(suspect);2530parse_commit(commit);2531if(sb->reverse ||2532(!(commit->object.flags & UNINTERESTING) &&2533!(revs->max_age != -1&& commit->date < revs->max_age)))2534pass_blame(sb, suspect, opt);2535else{2536 commit->object.flags |= UNINTERESTING;2537if(commit->object.parsed)2538mark_parents_uninteresting(commit);2539}2540/* treat root commit as boundary */2541if(!commit->parents && !sb->show_root)2542 commit->object.flags |= UNINTERESTING;25432544/* Take responsibility for the remaining entries */2545 ent = suspect->suspects;2546if(ent) {2547 suspect->guilty =1;2548for(;;) {2549struct blame_entry *next = ent->next;2550if(sb->found_guilty_entry)2551 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);2552if(next) {2553 ent = next;2554continue;2555}2556 ent->next = sb->ent;2557 sb->ent = suspect->suspects;2558 suspect->suspects = NULL;2559break;2560}2561}2562blame_origin_decref(suspect);25632564if(sb->debug)/* sanity */2565sanity_check_refcnt(sb);2566}2567}25682569/*2570 * To allow quick access to the contents of nth line in the2571 * final image, prepare an index in the scoreboard.2572 */2573static intprepare_lines(struct blame_scoreboard *sb)2574{2575 sb->num_lines =find_line_starts(&sb->lineno, sb->final_buf,2576 sb->final_buf_size);2577return sb->num_lines;2578}25792580static struct commit *find_single_final(struct rev_info *revs,2581const char**name_p)2582{2583int i;2584struct commit *found = NULL;2585const char*name = NULL;25862587for(i =0; i < revs->pending.nr; i++) {2588struct object *obj = revs->pending.objects[i].item;2589if(obj->flags & UNINTERESTING)2590continue;2591 obj =deref_tag(revs->repo, obj, NULL,0);2592if(obj->type != OBJ_COMMIT)2593die("Non commit%s?", revs->pending.objects[i].name);2594if(found)2595die("More than one commit to dig from%sand%s?",2596 revs->pending.objects[i].name, name);2597 found = (struct commit *)obj;2598 name = revs->pending.objects[i].name;2599}2600if(name_p)2601*name_p =xstrdup_or_null(name);2602return found;2603}26042605static struct commit *dwim_reverse_initial(struct rev_info *revs,2606const char**name_p)2607{2608/*2609 * DWIM "git blame --reverse ONE -- PATH" as2610 * "git blame --reverse ONE..HEAD -- PATH" but only do so2611 * when it makes sense.2612 */2613struct object *obj;2614struct commit *head_commit;2615struct object_id head_oid;26162617if(revs->pending.nr !=1)2618return NULL;26192620/* Is that sole rev a committish? */2621 obj = revs->pending.objects[0].item;2622 obj =deref_tag(revs->repo, obj, NULL,0);2623if(obj->type != OBJ_COMMIT)2624return NULL;26252626/* Do we have HEAD? */2627if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))2628return NULL;2629 head_commit =lookup_commit_reference_gently(revs->repo,2630&head_oid,1);2631if(!head_commit)2632return NULL;26332634/* Turn "ONE" into "ONE..HEAD" then */2635 obj->flags |= UNINTERESTING;2636add_pending_object(revs, &head_commit->object,"HEAD");26372638if(name_p)2639*name_p = revs->pending.objects[0].name;2640return(struct commit *)obj;2641}26422643static struct commit *find_single_initial(struct rev_info *revs,2644const char**name_p)2645{2646int i;2647struct commit *found = NULL;2648const char*name = NULL;26492650/*2651 * There must be one and only one negative commit, and it must be2652 * the boundary.2653 */2654for(i =0; i < revs->pending.nr; i++) {2655struct object *obj = revs->pending.objects[i].item;2656if(!(obj->flags & UNINTERESTING))2657continue;2658 obj =deref_tag(revs->repo, obj, NULL,0);2659if(obj->type != OBJ_COMMIT)2660die("Non commit%s?", revs->pending.objects[i].name);2661if(found)2662die("More than one commit to dig up from,%sand%s?",2663 revs->pending.objects[i].name, name);2664 found = (struct commit *) obj;2665 name = revs->pending.objects[i].name;2666}26672668if(!name)2669 found =dwim_reverse_initial(revs, &name);2670if(!name)2671die("No commit to dig up from?");26722673if(name_p)2674*name_p =xstrdup(name);2675return found;2676}26772678voidinit_scoreboard(struct blame_scoreboard *sb)2679{2680memset(sb,0,sizeof(struct blame_scoreboard));2681 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;2682 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;2683}26842685voidsetup_scoreboard(struct blame_scoreboard *sb,2686const char*path,2687struct blame_origin **orig)2688{2689const char*final_commit_name = NULL;2690struct blame_origin *o;2691struct commit *final_commit = NULL;2692enum object_type type;26932694init_blame_suspects(&blame_suspects);26952696if(sb->reverse && sb->contents_from)2697die(_("--contents and --reverse do not blend well."));26982699if(!sb->repo)2700BUG("repo is NULL");27012702if(!sb->reverse) {2703 sb->final =find_single_final(sb->revs, &final_commit_name);2704 sb->commits.compare = compare_commits_by_commit_date;2705}else{2706 sb->final =find_single_initial(sb->revs, &final_commit_name);2707 sb->commits.compare = compare_commits_by_reverse_commit_date;2708}27092710if(sb->final && sb->contents_from)2711die(_("cannot use --contents with final commit object name"));27122713if(sb->reverse && sb->revs->first_parent_only)2714 sb->revs->children.name = NULL;27152716if(!sb->final) {2717/*2718 * "--not A B -- path" without anything positive;2719 * do not default to HEAD, but use the working tree2720 * or "--contents".2721 */2722setup_work_tree();2723 sb->final =fake_working_tree_commit(sb->repo,2724&sb->revs->diffopt,2725 path, sb->contents_from);2726add_pending_object(sb->revs, &(sb->final->object),":");2727}27282729if(sb->reverse && sb->revs->first_parent_only) {2730 final_commit =find_single_final(sb->revs, NULL);2731if(!final_commit)2732die(_("--reverse and --first-parent together require specified latest commit"));2733}27342735/*2736 * If we have bottom, this will mark the ancestors of the2737 * bottom commits we would reach while traversing as2738 * uninteresting.2739 */2740if(prepare_revision_walk(sb->revs))2741die(_("revision walk setup failed"));27422743if(sb->reverse && sb->revs->first_parent_only) {2744struct commit *c = final_commit;27452746 sb->revs->children.name ="children";2747while(c->parents &&2748!oideq(&c->object.oid, &sb->final->object.oid)) {2749struct commit_list *l =xcalloc(1,sizeof(*l));27502751 l->item = c;2752if(add_decoration(&sb->revs->children,2753&c->parents->item->object, l))2754BUG("not unique item in first-parent chain");2755 c = c->parents->item;2756}27572758if(!oideq(&c->object.oid, &sb->final->object.oid))2759die(_("--reverse --first-parent together require range along first-parent chain"));2760}27612762if(is_null_oid(&sb->final->object.oid)) {2763 o =get_blame_suspects(sb->final);2764 sb->final_buf =xmemdupz(o->file.ptr, o->file.size);2765 sb->final_buf_size = o->file.size;2766}2767else{2768 o =get_origin(sb->final, path);2769if(fill_blob_sha1_and_mode(sb->repo, o))2770die(_("no such path%sin%s"), path, final_commit_name);27712772if(sb->revs->diffopt.flags.allow_textconv &&2773textconv_object(sb->repo, path, o->mode, &o->blob_oid,1, (char**) &sb->final_buf,2774&sb->final_buf_size))2775;2776else2777 sb->final_buf =read_object_file(&o->blob_oid, &type,2778&sb->final_buf_size);27792780if(!sb->final_buf)2781die(_("cannot read blob%sfor path%s"),2782oid_to_hex(&o->blob_oid),2783 path);2784}2785 sb->num_read_blob++;2786prepare_lines(sb);27872788if(orig)2789*orig = o;27902791free((char*)final_commit_name);2792}2793279427952796struct blame_entry *blame_entry_prepend(struct blame_entry *head,2797long start,long end,2798struct blame_origin *o)2799{2800struct blame_entry *new_head =xcalloc(1,sizeof(struct blame_entry));2801 new_head->lno = start;2802 new_head->num_lines = end - start;2803 new_head->suspect = o;2804 new_head->s_lno = start;2805 new_head->next = head;2806blame_origin_incref(o);2807return new_head;2808}