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{ 18 struct blame_origin **result; 19 20 result = blame_suspects_peek(&blame_suspects, commit); 21 22 return result ? *result : NULL; 23} 24 25static void set_blame_suspects(struct commit *commit, struct blame_origin *origin) 26{ 27 *blame_suspects_at(&blame_suspects, commit) = origin; 28} 29 30void blame_origin_decref(struct blame_origin *o) 31{ 32 if (o && --o->refcnt <= 0) { 33 struct blame_origin *p, *l = NULL; 34 if (o->previous) 35 blame_origin_decref(o->previous); 36 free(o->file.ptr); 37 /* Should be present exactly once in commit chain */ 38 for (p = get_blame_suspects(o->commit); p; l = p, p = p->next) { 39 if (p == o) { 40 if (l) 41 l->next = p->next; 42 else 43 set_blame_suspects(o->commit, p->next); 44 free(o); 45 return; 46 } 47 } 48 die("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{ 60 struct blame_origin *o; 61 FLEX_ALLOC_STR(o, path, path); 62 o->commit = commit; 63 o->refcnt = 1; 64 o->next = get_blame_suspects(commit); 65 set_blame_suspects(commit, o); 66 return 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{ 75 struct blame_origin *o, *l; 76 77 for (o = get_blame_suspects(commit), l = NULL; o; l = o, o = o->next) { 78 if (!strcmp(o->path, path)) { 79 /* bump to front */ 80 if (l) { 81 l->next = o->next; 82 o->next = get_blame_suspects(commit); 83 set_blame_suspects(commit, o); 84 } 85 return blame_origin_incref(o); 86 } 87 } 88 return make_origin(commit, path); 89} 90 91 92 93static void verify_working_tree_path(struct repository *r, 94 struct commit *work_tree, const char *path) 95{ 96 struct commit_list *parents; 97 int pos; 98 99 for (parents = work_tree->parents; parents; parents = parents->next) { 100 const struct object_id *commit_oid = &parents->item->object.oid; 101 struct object_id blob_oid; 102 unsigned mode; 103 104 if (!get_tree_entry(commit_oid, path, &blob_oid, &mode) && 105 oid_object_info(r, &blob_oid, NULL) == OBJ_BLOB) 106 return; 107 } 108 109 pos = index_name_pos(r->index, path, strlen(path)); 110 if (pos >= 0) 111 ; /* path is in the index */ 112 else if (-1 - pos < r->index->cache_nr && 113 !strcmp(r->index->cache[-1 - pos]->name, path)) 114 ; /* path is in the index, unmerged */ 115 else 116 die("no such path '%s' in HEAD", path); 117} 118 119static struct commit_list **append_parent(struct repository *r, 120 struct commit_list **tail, 121 const struct object_id *oid) 122{ 123 struct commit *parent; 124 125 parent = lookup_commit_reference(r, oid); 126 if (!parent) 127 die("no such commit %s", oid_to_hex(oid)); 128 return &commit_list_insert(parent, tail)->next; 129} 130 131static void append_merge_parents(struct repository *r, 132 struct commit_list **tail) 133{ 134 int merge_head; 135 struct strbuf line = STRBUF_INIT; 136 137 merge_head = open(git_path_merge_head(r), O_RDONLY); 138 if (merge_head < 0) { 139 if (errno == ENOENT) 140 return; 141 die("cannot open '%s' for reading", 142 git_path_merge_head(r)); 143 } 144 145 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) { 146 struct object_id oid; 147 if (line.len < GIT_SHA1_HEXSZ || get_oid_hex(line.buf, &oid)) 148 die("unknown line in '%s': %s", 149 git_path_merge_head(r), line.buf); 150 tail = append_parent(r, tail, &oid); 151 } 152 close(merge_head); 153 strbuf_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 void set_commit_buffer_from_strbuf(struct repository *r, 162 struct commit *c, 163 struct strbuf *sb) 164{ 165 size_t len; 166 void *buf = strbuf_detach(sb, &len); 167 set_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, 175 struct diff_options *opt, 176 const char *path, 177 const char *contents_from) 178{ 179 struct commit *commit; 180 struct blame_origin *origin; 181 struct commit_list **parent_tail, *parent; 182 struct object_id head_oid; 183 struct strbuf buf = STRBUF_INIT; 184 const char *ident; 185 time_t now; 186 int len; 187 struct cache_entry *ce; 188 unsigned mode; 189 struct strbuf msg = STRBUF_INIT; 190 191 read_index(r->index); 192 time(&now); 193 commit = alloc_commit_node(r); 194 commit->object.parsed = 1; 195 commit->date = now; 196 parent_tail = &commit->parents; 197 198 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL)) 199 die("no such ref: HEAD"); 200 201 parent_tail = append_parent(r, parent_tail, &head_oid); 202 append_merge_parents(r, parent_tail); 203 verify_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); 208 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n"); 209 for (parent = commit->parents; parent; parent = parent->next) 210 strbuf_addf(&msg, "parent %s\n", 211 oid_to_hex(&parent->item->object.oid)); 212 strbuf_addf(&msg, 213 "author %s\n" 214 "committer %s\n\n" 215 "Version of %s from %s\n", 216 ident, ident, path, 217 (!contents_from ? path : 218 (!strcmp(contents_from, "-") ? "standard input" : contents_from))); 219 set_commit_buffer_from_strbuf(r, commit, &msg); 220 221 if (!contents_from || strcmp("-", contents_from)) { 222 struct stat st; 223 const char *read_from; 224 char *buf_ptr; 225 unsigned long buf_len; 226 227 if (contents_from) { 228 if (stat(contents_from, &st) < 0) 229 die_errno("Cannot stat '%s'", contents_from); 230 read_from = contents_from; 231 } 232 else { 233 if (lstat(path, &st) < 0) 234 die_errno("Cannot lstat '%s'", path); 235 read_from = path; 236 } 237 mode = canon_mode(st.st_mode); 238 239 switch (st.st_mode & S_IFMT) { 240 case S_IFREG: 241 if (opt->flags.allow_textconv && 242 textconv_object(r, read_from, mode, &null_oid, 0, &buf_ptr, &buf_len)) 243 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1); 244 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size) 245 die_errno("cannot open or read '%s'", read_from); 246 break; 247 case S_IFLNK: 248 if (strbuf_readlink(&buf, read_from, st.st_size) < 0) 249 die_errno("cannot readlink '%s'", read_from); 250 break; 251 default: 252 die("unsupported file type %s", read_from); 253 } 254 } 255 else { 256 /* Reading from stdin */ 257 mode = 0; 258 if (strbuf_read(&buf, 0, 0) < 0) 259 die_errno("failed to read from stdin"); 260 } 261 convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0); 262 origin->file.ptr = buf.buf; 263 origin->file.size = buf.len; 264 pretend_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 */ 272 discard_index(r->index); 273 read_index(r->index); 274 275 len = strlen(path); 276 if (!mode) { 277 int pos = index_name_pos(r->index, path, len); 278 if (0 <= pos) 279 mode = r->index->cache[pos]->ce_mode; 280 else 281 /* Let's not bother reading from HEAD tree */ 282 mode = S_IFREG | 0644; 283 } 284 ce = make_empty_cache_entry(r->index, len); 285 oidcpy(&ce->oid, &origin->blob_oid); 286 memcpy(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); 290 add_index_entry(r->index, ce, 291 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); 292 293 cache_tree_invalidate_path(r->index, path); 294 295 return commit; 296} 297 298 299 300static int diff_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; 310 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb); 311} 312 313static const char *get_next_line(const char *start, const char *end) 314{ 315 const char *nl = memchr(start, '\n', end - start); 316 317 return nl ? nl + 1 : end; 318} 319 320static int find_line_starts(int **line_starts, const char *buf, 321 unsigned long len) 322{ 323 const char *end = buf + len; 324 const char *p; 325 int *lineno; 326 int num = 0; 327 328 for (p = buf; p < end; p = get_next_line(p, end)) 329 num++; 330 331 ALLOC_ARRAY(*line_starts, num + 1); 332 lineno = *line_starts; 333 334 for (p = buf; p < end; p = get_next_line(p, end)) 335 *lineno++ = p - buf; 336 337 *lineno = len; 338 339 return 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 { 364 struct 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 */ 369 struct 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 */ 379 struct hashmap_entry entry; 380 /* The number of times the byte pair occurs in the string that the 381 * fingerprint represents. 382 */ 383 int 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 void get_fingerprint(struct fingerprint *result, 393 const char *line_begin, 394 const char *line_end) 395{ 396 unsigned int hash, c0 = 0, c1; 397 const char *p; 398 int max_map_entry_count = 1 + line_end - line_begin; 399 struct fingerprint_entry *entry = xcalloc(max_map_entry_count, 400 sizeof(struct fingerprint_entry)); 401 struct fingerprint_entry *found_entry; 402 403 hashmap_init(&result->map, NULL, NULL, max_map_entry_count); 404 result->entries = entry; 405 for (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 */ 411 if ((p == line_end) || isspace(*p)) 412 c1 = 0; 413 else 414 c1 = tolower(*p); 415 hash = c0 | (c1 << 8); 416 /* Ignore whitespace pairs */ 417 if (hash == 0) 418 continue; 419 hashmap_entry_init(entry, hash); 420 421 found_entry = hashmap_get(&result->map, entry, NULL); 422 if (found_entry) { 423 found_entry->count += 1; 424 } else { 425 entry->count = 1; 426 hashmap_add(&result->map, entry); 427 ++entry; 428 } 429 } 430} 431 432static void free_fingerprint(struct fingerprint *f) 433{ 434 hashmap_free(&f->map, 0); 435 free(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 int fingerprint_similarity(struct fingerprint *a, struct fingerprint *b) 446{ 447 int intersection = 0; 448 struct hashmap_iter iter; 449 const struct fingerprint_entry *entry_a, *entry_b; 450 451 hashmap_iter_init(&b->map, &iter); 452 453 while ((entry_b = hashmap_iter_next(&iter))) { 454 if ((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 } 459 return intersection; 460} 461 462/* Subtracts byte-pair elements in B from A, modifying A in place. 463 */ 464static void fingerprint_subtract(struct fingerprint *a, struct fingerprint *b) 465{ 466 struct hashmap_iter iter; 467 struct fingerprint_entry *entry_a; 468 const struct fingerprint_entry *entry_b; 469 470 hashmap_iter_init(&b->map, &iter); 471 472 while ((entry_b = hashmap_iter_next(&iter))) { 473 if ((entry_a = hashmap_get(&a->map, entry_b, NULL))) { 474 if (entry_a->count <= entry_b->count) 475 hashmap_remove(&a->map, entry_b, NULL); 476 else 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 void get_line_fingerprints(struct fingerprint *fingerprints, 487 const char *content, const int *line_starts, 488 long first_line, long line_count) 489{ 490 int i; 491 const char *linestart, *lineend; 492 493 line_starts += first_line; 494 for (i = 0; i < line_count; ++i) { 495 linestart = content + line_starts[i]; 496 lineend = content + line_starts[i + 1]; 497 get_fingerprint(fingerprints + i, linestart, lineend); 498 } 499} 500 501static void free_line_fingerprints(struct fingerprint *fingerprints, 502 int nr_fingerprints) 503{ 504 int i; 505 506 for (i = 0; i < nr_fingerprints; i++) 507 free_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 { 515 int 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 int map_line_number(int line_number, 533 const struct line_number_mapping *mapping) 534{ 535 return ((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, 579 int line_a, int local_line_b, 580 int closest_line_a, int max_search_distance_a) 581{ 582 assert(abs(line_a - closest_line_a) <= 583 max_search_distance_a); 584 return 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 void find_best_line_matches( 617 int start_a, 618 int length_a, 619 int start_b, 620 int local_line_b, 621 struct fingerprint *fingerprints_a, 622 struct fingerprint *fingerprints_b, 623 int *similarities, 624 int *certainties, 625 int *second_best_result, 626 int *result, 627 const int max_search_distance_a, 628 const struct line_number_mapping *map_line_number_in_b_to_a) 629{ 630 631 int 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 */ 636 if (certainties[local_line_b] != CERTAINTY_NOT_CALCULATED) 637 return; 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; 643 if (search_start < 0) 644 search_start = 0; 645 646 search_end = closest_local_line_a + max_search_distance_a + 1; 647 if (search_end > length_a) 648 search_end = length_a; 649 650 for (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); 655 if (*similarity == -1) { 656 /* This value will never exceed 10 but assert just in 657 * case 658 */ 659 assert(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 } 669 if (*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 680 if (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 void fuzzy_find_matching_lines_recurse( 746 int start_a, int start_b, 747 int length_a, int length_b, 748 struct fingerprint *fingerprints_a, 749 struct fingerprint *fingerprints_b, 750 int *similarities, 751 int *certainties, 752 int *second_best_result, 753 int *result, 754 int max_search_distance_a, 755 int max_search_distance_b, 756 const struct line_number_mapping *map_line_number_in_b_to_a) 757{ 758 int 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 765 for (i = 0; i < length_b; ++i) { 766 find_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 779 if (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. */ 786 if (most_certain_local_line_b == -1) 787 return; 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 */ 796 fingerprint_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; 804 if (invalidate_min < 0) 805 invalidate_min = 0; 806 if (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 */ 812 for (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 */ 819 if (abs(most_certain_line_a - start_a - closest_local_line_a) > 820 max_search_distance_a) { 821 continue; 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 */ 835 for (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 */ 840 if (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 } 846 for (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 */ 851 if (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 */ 860 if (most_certain_local_line_b > 0) { 861 fuzzy_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 */ 873 if (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; 881 fuzzy_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, 906 struct blame_origin *target, 907 int tlno, int parent_slno, int same, 908 int 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. */ 912 int start_a = parent_slno; 913 int length_a = parent_len; 914 int start_b = tlno; 915 int length_b = same - tlno; 916 917 struct line_number_mapping map_line_number_in_b_to_a = { 918 start_a, length_a, start_b, length_b 919 }; 920 921 struct fingerprint *fingerprints_a = parent->fingerprints; 922 struct fingerprint *fingerprints_b = target->fingerprints; 923 924 int 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 */ 937 int max_search_distance_a = 10, max_search_distance_b; 938 939 if (length_a <= 0) 940 return NULL; 941 942 if (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 956 for (i = 0; i < length_b; ++i) { 957 result[i] = -1; 958 second_best_result[i] = -1; 959 certainties[i] = CERTAINTY_NOT_CALCULATED; 960 } 961 962 for (i = 0; i < similarity_count; ++i) 963 similarities[i] = -1; 964 965 fuzzy_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 977 free(similarities); 978 free(certainties); 979 free(second_best_result); 980 981 return result; 982} 983 984static void fill_origin_fingerprints(struct blame_origin *o, mmfile_t *file) 985{ 986 int *line_starts; 987 988 if (o->fingerprints) 989 return; 990 o->num_lines = find_line_starts(&line_starts, o->file.ptr, 991 o->file.size); 992 /* TODO: Will fill in fingerprints in a future commit */ 993 free(line_starts); 994} 995 996static void drop_origin_fingerprints(struct blame_origin *o) 997{ 998} 9991000/*1001 * Given an origin, prepare mmfile_t structure to be used by the1002 * diff machinery1003 */1004static void fill_origin_blob(struct diff_options *opt,1005 struct blame_origin *o, mmfile_t *file,1006 int *num_read_blob, int fill_fingerprints)1007{1008 if (!o->file.ptr) {1009 enum object_type type;1010 unsigned long file_size;10111012 (*num_read_blob)++;1013 if (opt->flags.allow_textconv &&1014 textconv_object(opt->repo, o->path, o->mode,1015 &o->blob_oid, 1, &file->ptr, &file_size))1016 ;1017 else1018 file->ptr = read_object_file(&o->blob_oid, &type,1019 &file_size);1020 file->size = file_size;10211022 if (!file->ptr)1023 die("Cannot read blob %s for path %s",1024 oid_to_hex(&o->blob_oid),1025 o->path);1026 o->file = *file;1027 }1028 else1029 *file = o->file;1030 if (fill_fingerprints)1031 fill_origin_fingerprints(o, file);1032}10331034static void drop_origin_blob(struct blame_origin *o)1035{1036 FREE_AND_NULL(o->file.ptr);1037 drop_origin_fingerprints(o);1038}10391040/*1041 * Any merge of blames happens on lists of blames that arrived via1042 * different parents in a single suspect. In this case, we want to1043 * sort according to the suspect line numbers as opposed to the final1044 * image line numbers. The function body is somewhat longish because1045 * it avoids unnecessary writes.1046 */10471048static struct blame_entry *blame_merge(struct blame_entry *list1,1049 struct blame_entry *list2)1050{1051 struct blame_entry *p1 = list1, *p2 = list2,1052 **tail = &list1;10531054 if (!p1)1055 return p2;1056 if (!p2)1057 return p1;10581059 if (p1->s_lno <= p2->s_lno) {1060 do {1061 tail = &p1->next;1062 if ((p1 = *tail) == NULL) {1063 *tail = p2;1064 return list1;1065 }1066 } while (p1->s_lno <= p2->s_lno);1067 }1068 for (;;) {1069 *tail = p2;1070 do {1071 tail = &p2->next;1072 if ((p2 = *tail) == NULL) {1073 *tail = p1;1074 return list1;1075 }1076 } while (p1->s_lno > p2->s_lno);1077 *tail = p1;1078 do {1079 tail = &p1->next;1080 if ((p1 = *tail) == NULL) {1081 *tail = p2;1082 return list1;1083 }1084 } while (p1->s_lno <= p2->s_lno);1085 }1086}10871088static void *get_next_blame(const void *p)1089{1090 return ((struct blame_entry *)p)->next;1091}10921093static void set_next_blame(void *p1, void *p2)1094{1095 ((struct blame_entry *)p1)->next = p2;1096}10971098/*1099 * Final image line numbers are all different, so we don't need a1100 * three-way comparison here.1101 */11021103static int compare_blame_final(const void *p1, const void *p2)1104{1105 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno1106 ? 1 : -1;1107}11081109static int compare_blame_suspect(const void *p1, const void *p2)1110{1111 const struct blame_entry *s1 = p1, *s2 = p2;1112 /*1113 * to allow for collating suspects, we sort according to the1114 * respective pointer value as the primary sorting criterion.1115 * The actual relation is pretty unimportant as long as it1116 * establishes a total order. Comparing as integers gives us1117 * that.1118 */1119 if (s1->suspect != s2->suspect)1120 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;1121 if (s1->s_lno == s2->s_lno)1122 return 0;1123 return s1->s_lno > s2->s_lno ? 1 : -1;1124}11251126void blame_sort_final(struct blame_scoreboard *sb)1127{1128 sb->ent = llist_mergesort(sb->ent, get_next_blame, set_next_blame,1129 compare_blame_final);1130}11311132static int compare_commits_by_reverse_commit_date(const void *a,1133 const void *b,1134 void *c)1135{1136 return -compare_commits_by_commit_date(a, b, c);1137}11381139/*1140 * For debugging -- origin is refcounted, and this asserts that1141 * we do not underflow.1142 */1143static void sanity_check_refcnt(struct blame_scoreboard *sb)1144{1145 int baa = 0;1146 struct blame_entry *ent;11471148 for (ent = sb->ent; ent; ent = ent->next) {1149 /* Nobody should have zero or negative refcnt */1150 if (ent->suspect->refcnt <= 0) {1151 fprintf(stderr, "%s in %s has negative refcnt %d\n",1152 ent->suspect->path,1153 oid_to_hex(&ent->suspect->commit->object.oid),1154 ent->suspect->refcnt);1155 baa = 1;1156 }1157 }1158 if (baa)1159 sb->on_sanity_fail(sb, baa);1160}11611162/*1163 * If two blame entries that are next to each other came from1164 * contiguous lines in the same origin (i.e. <commit, path> pair),1165 * merge them together.1166 */1167void blame_coalesce(struct blame_scoreboard *sb)1168{1169 struct blame_entry *ent, *next;11701171 for (ent = sb->ent; ent && (next = ent->next); ent = next) {1172 if (ent->suspect == next->suspect &&1173 ent->s_lno + ent->num_lines == next->s_lno &&1174 ent->ignored == next->ignored &&1175 ent->unblamable == next->unblamable) {1176 ent->num_lines += next->num_lines;1177 ent->next = next->next;1178 blame_origin_decref(next->suspect);1179 free(next);1180 ent->score = 0;1181 next = ent; /* again */1182 }1183 }11841185 if (sb->debug) /* sanity */1186 sanity_check_refcnt(sb);1187}11881189/*1190 * Merge the given sorted list of blames into a preexisting origin.1191 * If there were no previous blames to that commit, it is entered into1192 * the commit priority queue of the score board.1193 */11941195static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,1196 struct blame_entry *sorted)1197{1198 if (porigin->suspects)1199 porigin->suspects = blame_merge(porigin->suspects, sorted);1200 else {1201 struct blame_origin *o;1202 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {1203 if (o->suspects) {1204 porigin->suspects = sorted;1205 return;1206 }1207 }1208 porigin->suspects = sorted;1209 prio_queue_put(&sb->commits, porigin->commit);1210 }1211}12121213/*1214 * Fill the blob_sha1 field of an origin if it hasn't, so that later1215 * call to fill_origin_blob() can use it to locate the data. blob_sha11216 * for an origin is also used to pass the blame for the entire file to1217 * the parent to detect the case where a child's blob is identical to1218 * that of its parent's.1219 *1220 * This also fills origin->mode for corresponding tree path.1221 */1222static int fill_blob_sha1_and_mode(struct repository *r,1223 struct blame_origin *origin)1224{1225 if (!is_null_oid(&origin->blob_oid))1226 return 0;1227 if (get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))1228 goto error_out;1229 if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)1230 goto error_out;1231 return 0;1232 error_out:1233 oidclr(&origin->blob_oid);1234 origin->mode = S_IFINVALID;1235 return -1;1236}12371238/*1239 * We have an origin -- check if the same path exists in the1240 * parent and return an origin structure to represent it.1241 */1242static struct blame_origin *find_origin(struct repository *r,1243 struct commit *parent,1244 struct blame_origin *origin)1245{1246 struct blame_origin *porigin;1247 struct diff_options diff_opts;1248 const char *paths[2];12491250 /* First check any existing origins */1251 for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)1252 if (!strcmp(porigin->path, origin->path)) {1253 /*1254 * The same path between origin and its parent1255 * without renaming -- the most common case.1256 */1257 return blame_origin_incref (porigin);1258 }12591260 /* See if the origin->path is different between parent1261 * and origin first. Most of the time they are the1262 * same and diff-tree is fairly efficient about this.1263 */1264 repo_diff_setup(r, &diff_opts);1265 diff_opts.flags.recursive = 1;1266 diff_opts.detect_rename = 0;1267 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;1268 paths[0] = origin->path;1269 paths[1] = NULL;12701271 parse_pathspec(&diff_opts.pathspec,1272 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,1273 PATHSPEC_LITERAL_PATH, "", paths);1274 diff_setup_done(&diff_opts);12751276 if (is_null_oid(&origin->commit->object.oid))1277 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);1278 else1279 diff_tree_oid(get_commit_tree_oid(parent),1280 get_commit_tree_oid(origin->commit),1281 "", &diff_opts);1282 diffcore_std(&diff_opts);12831284 if (!diff_queued_diff.nr) {1285 /* The path is the same as parent */1286 porigin = get_origin(parent, origin->path);1287 oidcpy(&porigin->blob_oid, &origin->blob_oid);1288 porigin->mode = origin->mode;1289 } else {1290 /*1291 * Since origin->path is a pathspec, if the parent1292 * commit had it as a directory, we will see a whole1293 * bunch of deletion of files in the directory that we1294 * do not care about.1295 */1296 int i;1297 struct diff_filepair *p = NULL;1298 for (i = 0; i < diff_queued_diff.nr; i++) {1299 const char *name;1300 p = diff_queued_diff.queue[i];1301 name = p->one->path ? p->one->path : p->two->path;1302 if (!strcmp(name, origin->path))1303 break;1304 }1305 if (!p)1306 die("internal error in blame::find_origin");1307 switch (p->status) {1308 default:1309 die("internal error in blame::find_origin (%c)",1310 p->status);1311 case 'M':1312 porigin = get_origin(parent, origin->path);1313 oidcpy(&porigin->blob_oid, &p->one->oid);1314 porigin->mode = p->one->mode;1315 break;1316 case 'A':1317 case 'T':1318 /* Did not exist in parent, or type changed */1319 break;1320 }1321 }1322 diff_flush(&diff_opts);1323 clear_pathspec(&diff_opts.pathspec);1324 return porigin;1325}13261327/*1328 * We have an origin -- find the path that corresponds to it in its1329 * parent and return an origin structure to represent it.1330 */1331static struct blame_origin *find_rename(struct repository *r,1332 struct commit *parent,1333 struct blame_origin *origin)1334{1335 struct blame_origin *porigin = NULL;1336 struct diff_options diff_opts;1337 int i;13381339 repo_diff_setup(r, &diff_opts);1340 diff_opts.flags.recursive = 1;1341 diff_opts.detect_rename = DIFF_DETECT_RENAME;1342 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;1343 diff_opts.single_follow = origin->path;1344 diff_setup_done(&diff_opts);13451346 if (is_null_oid(&origin->commit->object.oid))1347 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);1348 else1349 diff_tree_oid(get_commit_tree_oid(parent),1350 get_commit_tree_oid(origin->commit),1351 "", &diff_opts);1352 diffcore_std(&diff_opts);13531354 for (i = 0; i < diff_queued_diff.nr; i++) {1355 struct diff_filepair *p = diff_queued_diff.queue[i];1356 if ((p->status == 'R' || p->status == 'C') &&1357 !strcmp(p->two->path, origin->path)) {1358 porigin = get_origin(parent, p->one->path);1359 oidcpy(&porigin->blob_oid, &p->one->oid);1360 porigin->mode = p->one->mode;1361 break;1362 }1363 }1364 diff_flush(&diff_opts);1365 clear_pathspec(&diff_opts.pathspec);1366 return porigin;1367}13681369/*1370 * Append a new blame entry to a given output queue.1371 */1372static void add_blame_entry(struct blame_entry ***queue,1373 const struct blame_entry *src)1374{1375 struct blame_entry *e = xmalloc(sizeof(*e));1376 memcpy(e, src, sizeof(*e));1377 blame_origin_incref(e->suspect);13781379 e->next = **queue;1380 **queue = e;1381 *queue = &e->next;1382}13831384/*1385 * src typically is on-stack; we want to copy the information in it to1386 * a malloced blame_entry that gets added to the given queue. The1387 * origin of dst loses a refcnt.1388 */1389static void dup_entry(struct blame_entry ***queue,1390 struct blame_entry *dst, struct blame_entry *src)1391{1392 blame_origin_incref(src->suspect);1393 blame_origin_decref(dst->suspect);1394 memcpy(dst, src, sizeof(*src));1395 dst->next = **queue;1396 **queue = dst;1397 *queue = &dst->next;1398}13991400const char *blame_nth_line(struct blame_scoreboard *sb, long lno)1401{1402 return sb->final_buf + sb->lineno[lno];1403}14041405/*1406 * It is known that lines between tlno to same came from parent, and e1407 * has an overlap with that range. it also is known that parent's1408 * line plno corresponds to e's line tlno.1409 *1410 * <---- e ----->1411 * <------>1412 * <------------>1413 * <------------>1414 * <------------------>1415 *1416 * Split e into potentially three parts; before this chunk, the chunk1417 * to be blamed for the parent, and after that portion.1418 */1419static void split_overlap(struct blame_entry *split,1420 struct blame_entry *e,1421 int tlno, int plno, int same,1422 struct blame_origin *parent)1423{1424 int chunk_end_lno;1425 int i;1426 memset(split, 0, sizeof(struct blame_entry [3]));14271428 for (i = 0; i < 3; i++) {1429 split[i].ignored = e->ignored;1430 split[i].unblamable = e->unblamable;1431 }14321433 if (e->s_lno < tlno) {1434 /* there is a pre-chunk part not blamed on parent */1435 split[0].suspect = blame_origin_incref(e->suspect);1436 split[0].lno = e->lno;1437 split[0].s_lno = e->s_lno;1438 split[0].num_lines = tlno - e->s_lno;1439 split[1].lno = e->lno + tlno - e->s_lno;1440 split[1].s_lno = plno;1441 }1442 else {1443 split[1].lno = e->lno;1444 split[1].s_lno = plno + (e->s_lno - tlno);1445 }14461447 if (same < e->s_lno + e->num_lines) {1448 /* there is a post-chunk part not blamed on parent */1449 split[2].suspect = blame_origin_incref(e->suspect);1450 split[2].lno = e->lno + (same - e->s_lno);1451 split[2].s_lno = e->s_lno + (same - e->s_lno);1452 split[2].num_lines = e->s_lno + e->num_lines - same;1453 chunk_end_lno = split[2].lno;1454 }1455 else1456 chunk_end_lno = e->lno + e->num_lines;1457 split[1].num_lines = chunk_end_lno - split[1].lno;14581459 /*1460 * if it turns out there is nothing to blame the parent for,1461 * forget about the splitting. !split[1].suspect signals this.1462 */1463 if (split[1].num_lines < 1)1464 return;1465 split[1].suspect = blame_origin_incref(parent);1466}14671468/*1469 * split_overlap() divided an existing blame e into up to three parts1470 * in split. Any assigned blame is moved to queue to1471 * reflect the split.1472 */1473static void split_blame(struct blame_entry ***blamed,1474 struct blame_entry ***unblamed,1475 struct blame_entry *split,1476 struct blame_entry *e)1477{1478 if (split[0].suspect && split[2].suspect) {1479 /* The first part (reuse storage for the existing entry e) */1480 dup_entry(unblamed, e, &split[0]);14811482 /* The last part -- me */1483 add_blame_entry(unblamed, &split[2]);14841485 /* ... and the middle part -- parent */1486 add_blame_entry(blamed, &split[1]);1487 }1488 else if (!split[0].suspect && !split[2].suspect)1489 /*1490 * The parent covers the entire area; reuse storage for1491 * e and replace it with the parent.1492 */1493 dup_entry(blamed, e, &split[1]);1494 else if (split[0].suspect) {1495 /* me and then parent */1496 dup_entry(unblamed, e, &split[0]);1497 add_blame_entry(blamed, &split[1]);1498 }1499 else {1500 /* parent and then me */1501 dup_entry(blamed, e, &split[1]);1502 add_blame_entry(unblamed, &split[2]);1503 }1504}15051506/*1507 * After splitting the blame, the origins used by the1508 * on-stack blame_entry should lose one refcnt each.1509 */1510static void decref_split(struct blame_entry *split)1511{1512 int i;15131514 for (i = 0; i < 3; i++)1515 blame_origin_decref(split[i].suspect);1516}15171518/*1519 * reverse_blame reverses the list given in head, appending tail.1520 * That allows us to build lists in reverse order, then reverse them1521 * afterwards. This can be faster than building the list in proper1522 * order right away. The reason is that building in proper order1523 * requires writing a link in the _previous_ element, while building1524 * in reverse order just requires placing the list head into the1525 * _current_ element.1526 */15271528static struct blame_entry *reverse_blame(struct blame_entry *head,1529 struct blame_entry *tail)1530{1531 while (head) {1532 struct blame_entry *next = head->next;1533 head->next = tail;1534 tail = head;1535 head = next;1536 }1537 return tail;1538}15391540/*1541 * Splits a blame entry into two entries at 'len' lines. The original 'e'1542 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,1543 * which is returned, consists of the remainder: [e->lno + len, e->lno +1544 * e->num_lines). The caller needs to sort out the reference counting for the1545 * new entry's suspect.1546 */1547static struct blame_entry *split_blame_at(struct blame_entry *e, int len,1548 struct blame_origin *new_suspect)1549{1550 struct blame_entry *n = xcalloc(1, sizeof(struct blame_entry));15511552 n->suspect = new_suspect;1553 n->ignored = e->ignored;1554 n->unblamable = e->unblamable;1555 n->lno = e->lno + len;1556 n->s_lno = e->s_lno + len;1557 n->num_lines = e->num_lines - len;1558 e->num_lines = len;1559 e->score = 0;1560 return n;1561}15621563struct blame_line_tracker {1564 int is_parent;1565 int s_lno;1566};15671568static int are_lines_adjacent(struct blame_line_tracker *first,1569 struct blame_line_tracker *second)1570{1571 return first->is_parent == second->is_parent &&1572 first->s_lno + 1 == second->s_lno;1573}15741575/*1576 * This cheap heuristic assigns lines in the chunk to their relative location in1577 * the parent's chunk. Any additional lines are left with the target.1578 */1579static void guess_line_blames(struct blame_origin *parent,1580 struct blame_origin *target,1581 int tlno, int offset, int same, int parent_len,1582 struct blame_line_tracker *line_blames)1583{1584 int i, best_idx, target_idx;1585 int parent_slno = tlno + offset;15861587 for (i = 0; i < same - tlno; i++) {1588 target_idx = tlno + i;1589 best_idx = target_idx + offset;1590 if (best_idx < parent_slno + parent_len) {1591 line_blames[i].is_parent = 1;1592 line_blames[i].s_lno = best_idx;1593 } else {1594 line_blames[i].is_parent = 0;1595 line_blames[i].s_lno = target_idx;1596 }1597 }1598}15991600/*1601 * This decides which parts of a blame entry go to the parent (added to the1602 * ignoredp list) and which stay with the target (added to the diffp list). The1603 * actual decision was made in a separate heuristic function, and those answers1604 * for the lines in 'e' are in line_blames. This consumes e, essentially1605 * putting it on a list.1606 *1607 * Note that the blame entries on the ignoredp list are not necessarily sorted1608 * with respect to the parent's line numbers yet.1609 */1610static void ignore_blame_entry(struct blame_entry *e,1611 struct blame_origin *parent,1612 struct blame_origin *target,1613 struct blame_entry **diffp,1614 struct blame_entry **ignoredp,1615 struct blame_line_tracker *line_blames)1616{1617 int entry_len, nr_lines, i;16181619 /*1620 * We carve new entries off the front of e. Each entry comes from a1621 * contiguous chunk of lines: adjacent lines from the same origin1622 * (either the parent or the target).1623 */1624 entry_len = 1;1625 nr_lines = e->num_lines; /* e changes in the loop */1626 for (i = 0; i < nr_lines; i++) {1627 struct blame_entry *next = NULL;16281629 /*1630 * We are often adjacent to the next line - only split the blame1631 * entry when we have to.1632 */1633 if (i + 1 < nr_lines) {1634 if (are_lines_adjacent(&line_blames[i],1635 &line_blames[i + 1])) {1636 entry_len++;1637 continue;1638 }1639 next = split_blame_at(e, entry_len,1640 blame_origin_incref(e->suspect));1641 }1642 if (line_blames[i].is_parent) {1643 e->ignored = 1;1644 blame_origin_decref(e->suspect);1645 e->suspect = blame_origin_incref(parent);1646 e->s_lno = line_blames[i - entry_len + 1].s_lno;1647 e->next = *ignoredp;1648 *ignoredp = e;1649 } else {1650 e->unblamable = 1;1651 /* e->s_lno is already in the target's address space. */1652 e->next = *diffp;1653 *diffp = e;1654 }1655 assert(e->num_lines == entry_len);1656 e = next;1657 entry_len = 1;1658 }1659 assert(!e);1660}16611662/*1663 * Process one hunk from the patch between the current suspect for1664 * blame_entry e and its parent. This first blames any unfinished1665 * entries before the chunk (which is where target and parent start1666 * differing) on the parent, and then splits blame entries at the1667 * start and at the end of the difference region. Since use of -M and1668 * -C options may lead to overlapping/duplicate source line number1669 * ranges, all we can rely on from sorting/merging is the order of the1670 * first suspect line number.1671 *1672 * tlno: line number in the target where this chunk begins1673 * same: line number in the target where this chunk ends1674 * offset: add to tlno to get the chunk starting point in the parent1675 * parent_len: number of lines in the parent chunk1676 */1677static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,1678 int tlno, int offset, int same, int parent_len,1679 struct blame_origin *parent,1680 struct blame_origin *target, int ignore_diffs)1681{1682 struct blame_entry *e = **srcq;1683 struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;1684 struct blame_line_tracker *line_blames = NULL;16851686 while (e && e->s_lno < tlno) {1687 struct blame_entry *next = e->next;1688 /*1689 * current record starts before differing portion. If1690 * it reaches into it, we need to split it up and1691 * examine the second part separately.1692 */1693 if (e->s_lno + e->num_lines > tlno) {1694 /* Move second half to a new record */1695 struct blame_entry *n;16961697 n = split_blame_at(e, tlno - e->s_lno, e->suspect);1698 /* Push new record to diffp */1699 n->next = diffp;1700 diffp = n;1701 } else1702 blame_origin_decref(e->suspect);1703 /* Pass blame for everything before the differing1704 * chunk to the parent */1705 e->suspect = blame_origin_incref(parent);1706 e->s_lno += offset;1707 e->next = samep;1708 samep = e;1709 e = next;1710 }1711 /*1712 * As we don't know how much of a common stretch after this1713 * diff will occur, the currently blamed parts are all that we1714 * can assign to the parent for now.1715 */17161717 if (samep) {1718 **dstq = reverse_blame(samep, **dstq);1719 *dstq = &samep->next;1720 }1721 /*1722 * Prepend the split off portions: everything after e starts1723 * after the blameable portion.1724 */1725 e = reverse_blame(diffp, e);17261727 /*1728 * Now retain records on the target while parts are different1729 * from the parent.1730 */1731 samep = NULL;1732 diffp = NULL;17331734 if (ignore_diffs && same - tlno > 0) {1735 line_blames = xcalloc(sizeof(struct blame_line_tracker),1736 same - tlno);1737 guess_line_blames(parent, target, tlno, offset, same,1738 parent_len, line_blames);1739 }17401741 while (e && e->s_lno < same) {1742 struct blame_entry *next = e->next;17431744 /*1745 * If current record extends into sameness, need to split.1746 */1747 if (e->s_lno + e->num_lines > same) {1748 /*1749 * Move second half to a new record to be1750 * processed by later chunks1751 */1752 struct blame_entry *n;17531754 n = split_blame_at(e, same - e->s_lno,1755 blame_origin_incref(e->suspect));1756 /* Push new record to samep */1757 n->next = samep;1758 samep = n;1759 }1760 if (ignore_diffs) {1761 ignore_blame_entry(e, parent, target, &diffp, &ignoredp,1762 line_blames + e->s_lno - tlno);1763 } else {1764 e->next = diffp;1765 diffp = e;1766 }1767 e = next;1768 }1769 free(line_blames);1770 if (ignoredp) {1771 /*1772 * Note ignoredp is not sorted yet, and thus neither is dstq.1773 * That list must be sorted before we queue_blames(). We defer1774 * sorting until after all diff hunks are processed, so that1775 * guess_line_blames() can pick *any* line in the parent. The1776 * slight drawback is that we end up sorting all blame entries1777 * passed to the parent, including those that are unrelated to1778 * changes made by the ignored commit.1779 */1780 **dstq = reverse_blame(ignoredp, **dstq);1781 *dstq = &ignoredp->next;1782 }1783 **srcq = reverse_blame(diffp, reverse_blame(samep, e));1784 /* Move across elements that are in the unblamable portion */1785 if (diffp)1786 *srcq = &diffp->next;1787}17881789struct blame_chunk_cb_data {1790 struct blame_origin *parent;1791 struct blame_origin *target;1792 long offset;1793 int ignore_diffs;1794 struct blame_entry **dstq;1795 struct blame_entry **srcq;1796};17971798/* diff chunks are from parent to target */1799static int blame_chunk_cb(long start_a, long count_a,1800 long start_b, long count_b, void *data)1801{1802 struct blame_chunk_cb_data *d = data;1803 if (start_a - start_b != d->offset)1804 die("internal error in blame::blame_chunk_cb");1805 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,1806 start_b + count_b, count_a, d->parent, d->target,1807 d->ignore_diffs);1808 d->offset = start_a + count_a - (start_b + count_b);1809 return 0;1810}18111812/*1813 * We are looking at the origin 'target' and aiming to pass blame1814 * for the lines it is suspected to its parent. Run diff to find1815 * which lines came from parent and pass blame for them.1816 */1817static void pass_blame_to_parent(struct blame_scoreboard *sb,1818 struct blame_origin *target,1819 struct blame_origin *parent, int ignore_diffs)1820{1821 mmfile_t file_p, file_o;1822 struct blame_chunk_cb_data d;1823 struct blame_entry *newdest = NULL;18241825 if (!target->suspects)1826 return; /* nothing remains for this target */18271828 d.parent = parent;1829 d.target = target;1830 d.offset = 0;1831 d.ignore_diffs = ignore_diffs;1832 d.dstq = &newdest; d.srcq = &target->suspects;18331834 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,1835 &sb->num_read_blob, ignore_diffs);1836 fill_origin_blob(&sb->revs->diffopt, target, &file_o,1837 &sb->num_read_blob, ignore_diffs);1838 sb->num_get_patch++;18391840 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))1841 die("unable to generate diff (%s -> %s)",1842 oid_to_hex(&parent->commit->object.oid),1843 oid_to_hex(&target->commit->object.oid));1844 /* The rest are the same as the parent */1845 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, 0,1846 parent, target, 0);1847 *d.dstq = NULL;1848 if (ignore_diffs)1849 newdest = llist_mergesort(newdest, get_next_blame,1850 set_next_blame,1851 compare_blame_suspect);1852 queue_blames(sb, parent, newdest);18531854 return;1855}18561857/*1858 * The lines in blame_entry after splitting blames many times can become1859 * very small and trivial, and at some point it becomes pointless to1860 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any1861 * ordinary C program, and it is not worth to say it was copied from1862 * totally unrelated file in the parent.1863 *1864 * Compute how trivial the lines in the blame_entry are.1865 */1866unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)1867{1868 unsigned score;1869 const char *cp, *ep;18701871 if (e->score)1872 return e->score;18731874 score = 1;1875 cp = blame_nth_line(sb, e->lno);1876 ep = blame_nth_line(sb, e->lno + e->num_lines);1877 while (cp < ep) {1878 unsigned ch = *((unsigned char *)cp);1879 if (isalnum(ch))1880 score++;1881 cp++;1882 }1883 e->score = score;1884 return score;1885}18861887/*1888 * best_so_far[] and potential[] are both a split of an existing blame_entry1889 * that passes blame to the parent. Maintain best_so_far the best split so1890 * far, by comparing potential and best_so_far and copying potential into1891 * bst_so_far as needed.1892 */1893static void copy_split_if_better(struct blame_scoreboard *sb,1894 struct blame_entry *best_so_far,1895 struct blame_entry *potential)1896{1897 int i;18981899 if (!potential[1].suspect)1900 return;1901 if (best_so_far[1].suspect) {1902 if (blame_entry_score(sb, &potential[1]) <1903 blame_entry_score(sb, &best_so_far[1]))1904 return;1905 }19061907 for (i = 0; i < 3; i++)1908 blame_origin_incref(potential[i].suspect);1909 decref_split(best_so_far);1910 memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));1911}19121913/*1914 * We are looking at a part of the final image represented by1915 * ent (tlno and same are offset by ent->s_lno).1916 * tlno is where we are looking at in the final image.1917 * up to (but not including) same match preimage.1918 * plno is where we are looking at in the preimage.1919 *1920 * <-------------- final image ---------------------->1921 * <------ent------>1922 * ^tlno ^same1923 * <---------preimage----->1924 * ^plno1925 *1926 * All line numbers are 0-based.1927 */1928static void handle_split(struct blame_scoreboard *sb,1929 struct blame_entry *ent,1930 int tlno, int plno, int same,1931 struct blame_origin *parent,1932 struct blame_entry *split)1933{1934 if (ent->num_lines <= tlno)1935 return;1936 if (tlno < same) {1937 struct blame_entry potential[3];1938 tlno += ent->s_lno;1939 same += ent->s_lno;1940 split_overlap(potential, ent, tlno, plno, same, parent);1941 copy_split_if_better(sb, split, potential);1942 decref_split(potential);1943 }1944}19451946struct handle_split_cb_data {1947 struct blame_scoreboard *sb;1948 struct blame_entry *ent;1949 struct blame_origin *parent;1950 struct blame_entry *split;1951 long plno;1952 long tlno;1953};19541955static int handle_split_cb(long start_a, long count_a,1956 long start_b, long count_b, void *data)1957{1958 struct handle_split_cb_data *d = data;1959 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,1960 d->split);1961 d->plno = start_a + count_a;1962 d->tlno = start_b + count_b;1963 return 0;1964}19651966/*1967 * Find the lines from parent that are the same as ent so that1968 * we can pass blames to it. file_p has the blob contents for1969 * the parent.1970 */1971static void find_copy_in_blob(struct blame_scoreboard *sb,1972 struct blame_entry *ent,1973 struct blame_origin *parent,1974 struct blame_entry *split,1975 mmfile_t *file_p)1976{1977 const char *cp;1978 mmfile_t file_o;1979 struct handle_split_cb_data d;19801981 memset(&d, 0, sizeof(d));1982 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;1983 /*1984 * Prepare mmfile that contains only the lines in ent.1985 */1986 cp = blame_nth_line(sb, ent->lno);1987 file_o.ptr = (char *) cp;1988 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;19891990 /*1991 * file_o is a part of final image we are annotating.1992 * file_p partially may match that image.1993 */1994 memset(split, 0, sizeof(struct blame_entry [3]));1995 if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))1996 die("unable to generate diff (%s)",1997 oid_to_hex(&parent->commit->object.oid));1998 /* remainder, if any, all match the preimage */1999 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);2000}20012002/* Move all blame entries from list *source that have a score smaller2003 * than score_min to the front of list *small.2004 * Returns a pointer to the link pointing to the old head of the small list.2005 */20062007static struct blame_entry **filter_small(struct blame_scoreboard *sb,2008 struct blame_entry **small,2009 struct blame_entry **source,2010 unsigned score_min)2011{2012 struct blame_entry *p = *source;2013 struct blame_entry *oldsmall = *small;2014 while (p) {2015 if (blame_entry_score(sb, p) <= score_min) {2016 *small = p;2017 small = &p->next;2018 p = *small;2019 } else {2020 *source = p;2021 source = &p->next;2022 p = *source;2023 }2024 }2025 *small = oldsmall;2026 *source = NULL;2027 return small;2028}20292030/*2031 * See if lines currently target is suspected for can be attributed to2032 * parent.2033 */2034static void find_move_in_parent(struct blame_scoreboard *sb,2035 struct blame_entry ***blamed,2036 struct blame_entry **toosmall,2037 struct blame_origin *target,2038 struct blame_origin *parent)2039{2040 struct blame_entry *e, split[3];2041 struct blame_entry *unblamed = target->suspects;2042 struct blame_entry *leftover = NULL;2043 mmfile_t file_p;20442045 if (!unblamed)2046 return; /* nothing remains for this target */20472048 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,2049 &sb->num_read_blob, 0);2050 if (!file_p.ptr)2051 return;20522053 /* At each iteration, unblamed has a NULL-terminated list of2054 * entries that have not yet been tested for blame. leftover2055 * contains the reversed list of entries that have been tested2056 * without being assignable to the parent.2057 */2058 do {2059 struct blame_entry **unblamedtail = &unblamed;2060 struct blame_entry *next;2061 for (e = unblamed; e; e = next) {2062 next = e->next;2063 find_copy_in_blob(sb, e, parent, split, &file_p);2064 if (split[1].suspect &&2065 sb->move_score < blame_entry_score(sb, &split[1])) {2066 split_blame(blamed, &unblamedtail, split, e);2067 } else {2068 e->next = leftover;2069 leftover = e;2070 }2071 decref_split(split);2072 }2073 *unblamedtail = NULL;2074 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);2075 } while (unblamed);2076 target->suspects = reverse_blame(leftover, NULL);2077}20782079struct blame_list {2080 struct blame_entry *ent;2081 struct blame_entry split[3];2082};20832084/*2085 * Count the number of entries the target is suspected for,2086 * and prepare a list of entry and the best split.2087 */2088static struct blame_list *setup_blame_list(struct blame_entry *unblamed,2089 int *num_ents_p)2090{2091 struct blame_entry *e;2092 int num_ents, i;2093 struct blame_list *blame_list = NULL;20942095 for (e = unblamed, num_ents = 0; e; e = e->next)2096 num_ents++;2097 if (num_ents) {2098 blame_list = xcalloc(num_ents, sizeof(struct blame_list));2099 for (e = unblamed, i = 0; e; e = e->next)2100 blame_list[i++].ent = e;2101 }2102 *num_ents_p = num_ents;2103 return blame_list;2104}21052106/*2107 * For lines target is suspected for, see if we can find code movement2108 * across file boundary from the parent commit. porigin is the path2109 * in the parent we already tried.2110 */2111static void find_copy_in_parent(struct blame_scoreboard *sb,2112 struct blame_entry ***blamed,2113 struct blame_entry **toosmall,2114 struct blame_origin *target,2115 struct commit *parent,2116 struct blame_origin *porigin,2117 int opt)2118{2119 struct diff_options diff_opts;2120 int i, j;2121 struct blame_list *blame_list;2122 int num_ents;2123 struct blame_entry *unblamed = target->suspects;2124 struct blame_entry *leftover = NULL;21252126 if (!unblamed)2127 return; /* nothing remains for this target */21282129 repo_diff_setup(sb->repo, &diff_opts);2130 diff_opts.flags.recursive = 1;2131 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;21322133 diff_setup_done(&diff_opts);21342135 /* Try "find copies harder" on new path if requested;2136 * we do not want to use diffcore_rename() actually to2137 * match things up; find_copies_harder is set only to2138 * force diff_tree_oid() to feed all filepairs to diff_queue,2139 * and this code needs to be after diff_setup_done(), which2140 * usually makes find-copies-harder imply copy detection.2141 */2142 if ((opt & PICKAXE_BLAME_COPY_HARDEST)2143 || ((opt & PICKAXE_BLAME_COPY_HARDER)2144 && (!porigin || strcmp(target->path, porigin->path))))2145 diff_opts.flags.find_copies_harder = 1;21462147 if (is_null_oid(&target->commit->object.oid))2148 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);2149 else2150 diff_tree_oid(get_commit_tree_oid(parent),2151 get_commit_tree_oid(target->commit),2152 "", &diff_opts);21532154 if (!diff_opts.flags.find_copies_harder)2155 diffcore_std(&diff_opts);21562157 do {2158 struct blame_entry **unblamedtail = &unblamed;2159 blame_list = setup_blame_list(unblamed, &num_ents);21602161 for (i = 0; i < diff_queued_diff.nr; i++) {2162 struct diff_filepair *p = diff_queued_diff.queue[i];2163 struct blame_origin *norigin;2164 mmfile_t file_p;2165 struct blame_entry potential[3];21662167 if (!DIFF_FILE_VALID(p->one))2168 continue; /* does not exist in parent */2169 if (S_ISGITLINK(p->one->mode))2170 continue; /* ignore git links */2171 if (porigin && !strcmp(p->one->path, porigin->path))2172 /* find_move already dealt with this path */2173 continue;21742175 norigin = get_origin(parent, p->one->path);2176 oidcpy(&norigin->blob_oid, &p->one->oid);2177 norigin->mode = p->one->mode;2178 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,2179 &sb->num_read_blob, 0);2180 if (!file_p.ptr)2181 continue;21822183 for (j = 0; j < num_ents; j++) {2184 find_copy_in_blob(sb, blame_list[j].ent,2185 norigin, potential, &file_p);2186 copy_split_if_better(sb, blame_list[j].split,2187 potential);2188 decref_split(potential);2189 }2190 blame_origin_decref(norigin);2191 }21922193 for (j = 0; j < num_ents; j++) {2194 struct blame_entry *split = blame_list[j].split;2195 if (split[1].suspect &&2196 sb->copy_score < blame_entry_score(sb, &split[1])) {2197 split_blame(blamed, &unblamedtail, split,2198 blame_list[j].ent);2199 } else {2200 blame_list[j].ent->next = leftover;2201 leftover = blame_list[j].ent;2202 }2203 decref_split(split);2204 }2205 free(blame_list);2206 *unblamedtail = NULL;2207 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);2208 } while (unblamed);2209 target->suspects = reverse_blame(leftover, NULL);2210 diff_flush(&diff_opts);2211 clear_pathspec(&diff_opts.pathspec);2212}22132214/*2215 * The blobs of origin and porigin exactly match, so everything2216 * origin is suspected for can be blamed on the parent.2217 */2218static void pass_whole_blame(struct blame_scoreboard *sb,2219 struct blame_origin *origin, struct blame_origin *porigin)2220{2221 struct blame_entry *e, *suspects;22222223 if (!porigin->file.ptr && origin->file.ptr) {2224 /* Steal its file */2225 porigin->file = origin->file;2226 origin->file.ptr = NULL;2227 }2228 suspects = origin->suspects;2229 origin->suspects = NULL;2230 for (e = suspects; e; e = e->next) {2231 blame_origin_incref(porigin);2232 blame_origin_decref(e->suspect);2233 e->suspect = porigin;2234 }2235 queue_blames(sb, porigin, suspects);2236}22372238/*2239 * We pass blame from the current commit to its parents. We keep saying2240 * "parent" (and "porigin"), but what we mean is to find scapegoat to2241 * exonerate ourselves.2242 */2243static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,2244 int reverse)2245{2246 if (!reverse) {2247 if (revs->first_parent_only &&2248 commit->parents &&2249 commit->parents->next) {2250 free_commit_list(commit->parents->next);2251 commit->parents->next = NULL;2252 }2253 return commit->parents;2254 }2255 return lookup_decoration(&revs->children, &commit->object);2256}22572258static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)2259{2260 struct commit_list *l = first_scapegoat(revs, commit, reverse);2261 return commit_list_count(l);2262}22632264/* Distribute collected unsorted blames to the respected sorted lists2265 * in the various origins.2266 */2267static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)2268{2269 blamed = llist_mergesort(blamed, get_next_blame, set_next_blame,2270 compare_blame_suspect);2271 while (blamed)2272 {2273 struct blame_origin *porigin = blamed->suspect;2274 struct blame_entry *suspects = NULL;2275 do {2276 struct blame_entry *next = blamed->next;2277 blamed->next = suspects;2278 suspects = blamed;2279 blamed = next;2280 } while (blamed && blamed->suspect == porigin);2281 suspects = reverse_blame(suspects, NULL);2282 queue_blames(sb, porigin, suspects);2283 }2284}22852286#define MAXSG 1622872288static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)2289{2290 struct rev_info *revs = sb->revs;2291 int i, pass, num_sg;2292 struct commit *commit = origin->commit;2293 struct commit_list *sg;2294 struct blame_origin *sg_buf[MAXSG];2295 struct blame_origin *porigin, **sg_origin = sg_buf;2296 struct blame_entry *toosmall = NULL;2297 struct blame_entry *blames, **blametail = &blames;22982299 num_sg = num_scapegoats(revs, commit, sb->reverse);2300 if (!num_sg)2301 goto finish;2302 else if (num_sg < ARRAY_SIZE(sg_buf))2303 memset(sg_buf, 0, sizeof(sg_buf));2304 else2305 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));23062307 /*2308 * The first pass looks for unrenamed path to optimize for2309 * common cases, then we look for renames in the second pass.2310 */2311 for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {2312 struct blame_origin *(*find)(struct repository *, struct commit *, struct blame_origin *);2313 find = pass ? find_rename : find_origin;23142315 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);2316 i < num_sg && sg;2317 sg = sg->next, i++) {2318 struct commit *p = sg->item;2319 int j, same;23202321 if (sg_origin[i])2322 continue;2323 if (parse_commit(p))2324 continue;2325 porigin = find(sb->repo, p, origin);2326 if (!porigin)2327 continue;2328 if (oideq(&porigin->blob_oid, &origin->blob_oid)) {2329 pass_whole_blame(sb, origin, porigin);2330 blame_origin_decref(porigin);2331 goto finish;2332 }2333 for (j = same = 0; j < i; j++)2334 if (sg_origin[j] &&2335 oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {2336 same = 1;2337 break;2338 }2339 if (!same)2340 sg_origin[i] = porigin;2341 else2342 blame_origin_decref(porigin);2343 }2344 }23452346 sb->num_commits++;2347 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);2348 i < num_sg && sg;2349 sg = sg->next, i++) {2350 struct blame_origin *porigin = sg_origin[i];2351 if (!porigin)2352 continue;2353 if (!origin->previous) {2354 blame_origin_incref(porigin);2355 origin->previous = porigin;2356 }2357 pass_blame_to_parent(sb, origin, porigin, 0);2358 if (!origin->suspects)2359 goto finish;2360 }23612362 /*2363 * Pass remaining suspects for ignored commits to their parents.2364 */2365 if (oidset_contains(&sb->ignore_list, &commit->object.oid)) {2366 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);2367 i < num_sg && sg;2368 sg = sg->next, i++) {2369 struct blame_origin *porigin = sg_origin[i];23702371 if (!porigin)2372 continue;2373 pass_blame_to_parent(sb, origin, porigin, 1);2374 if (!origin->suspects)2375 goto finish;2376 }2377 }23782379 /*2380 * Optionally find moves in parents' files.2381 */2382 if (opt & PICKAXE_BLAME_MOVE) {2383 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);2384 if (origin->suspects) {2385 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);2386 i < num_sg && sg;2387 sg = sg->next, i++) {2388 struct blame_origin *porigin = sg_origin[i];2389 if (!porigin)2390 continue;2391 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);2392 if (!origin->suspects)2393 break;2394 }2395 }2396 }23972398 /*2399 * Optionally find copies from parents' files.2400 */2401 if (opt & PICKAXE_BLAME_COPY) {2402 if (sb->copy_score > sb->move_score)2403 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);2404 else if (sb->copy_score < sb->move_score) {2405 origin->suspects = blame_merge(origin->suspects, toosmall);2406 toosmall = NULL;2407 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);2408 }2409 if (!origin->suspects)2410 goto finish;24112412 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);2413 i < num_sg && sg;2414 sg = sg->next, i++) {2415 struct blame_origin *porigin = sg_origin[i];2416 find_copy_in_parent(sb, &blametail, &toosmall,2417 origin, sg->item, porigin, opt);2418 if (!origin->suspects)2419 goto finish;2420 }2421 }24222423finish:2424 *blametail = NULL;2425 distribute_blame(sb, blames);2426 /*2427 * prepend toosmall to origin->suspects2428 *2429 * There is no point in sorting: this ends up on a big2430 * unsorted list in the caller anyway.2431 */2432 if (toosmall) {2433 struct blame_entry **tail = &toosmall;2434 while (*tail)2435 tail = &(*tail)->next;2436 *tail = origin->suspects;2437 origin->suspects = toosmall;2438 }2439 for (i = 0; i < num_sg; i++) {2440 if (sg_origin[i]) {2441 drop_origin_blob(sg_origin[i]);2442 blame_origin_decref(sg_origin[i]);2443 }2444 }2445 drop_origin_blob(origin);2446 if (sg_buf != sg_origin)2447 free(sg_origin);2448}24492450/*2451 * The main loop -- while we have blobs with lines whose true origin2452 * is still unknown, pick one blob, and allow its lines to pass blames2453 * to its parents. */2454void assign_blame(struct blame_scoreboard *sb, int opt)2455{2456 struct rev_info *revs = sb->revs;2457 struct commit *commit = prio_queue_get(&sb->commits);24582459 while (commit) {2460 struct blame_entry *ent;2461 struct blame_origin *suspect = get_blame_suspects(commit);24622463 /* find one suspect to break down */2464 while (suspect && !suspect->suspects)2465 suspect = suspect->next;24662467 if (!suspect) {2468 commit = prio_queue_get(&sb->commits);2469 continue;2470 }24712472 assert(commit == suspect->commit);24732474 /*2475 * We will use this suspect later in the loop,2476 * so hold onto it in the meantime.2477 */2478 blame_origin_incref(suspect);2479 parse_commit(commit);2480 if (sb->reverse ||2481 (!(commit->object.flags & UNINTERESTING) &&2482 !(revs->max_age != -1 && commit->date < revs->max_age)))2483 pass_blame(sb, suspect, opt);2484 else {2485 commit->object.flags |= UNINTERESTING;2486 if (commit->object.parsed)2487 mark_parents_uninteresting(commit);2488 }2489 /* treat root commit as boundary */2490 if (!commit->parents && !sb->show_root)2491 commit->object.flags |= UNINTERESTING;24922493 /* Take responsibility for the remaining entries */2494 ent = suspect->suspects;2495 if (ent) {2496 suspect->guilty = 1;2497 for (;;) {2498 struct blame_entry *next = ent->next;2499 if (sb->found_guilty_entry)2500 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);2501 if (next) {2502 ent = next;2503 continue;2504 }2505 ent->next = sb->ent;2506 sb->ent = suspect->suspects;2507 suspect->suspects = NULL;2508 break;2509 }2510 }2511 blame_origin_decref(suspect);25122513 if (sb->debug) /* sanity */2514 sanity_check_refcnt(sb);2515 }2516}25172518/*2519 * To allow quick access to the contents of nth line in the2520 * final image, prepare an index in the scoreboard.2521 */2522static int prepare_lines(struct blame_scoreboard *sb)2523{2524 sb->num_lines = find_line_starts(&sb->lineno, sb->final_buf,2525 sb->final_buf_size);2526 return sb->num_lines;2527}25282529static struct commit *find_single_final(struct rev_info *revs,2530 const char **name_p)2531{2532 int i;2533 struct commit *found = NULL;2534 const char *name = NULL;25352536 for (i = 0; i < revs->pending.nr; i++) {2537 struct object *obj = revs->pending.objects[i].item;2538 if (obj->flags & UNINTERESTING)2539 continue;2540 obj = deref_tag(revs->repo, obj, NULL, 0);2541 if (obj->type != OBJ_COMMIT)2542 die("Non commit %s?", revs->pending.objects[i].name);2543 if (found)2544 die("More than one commit to dig from %s and %s?",2545 revs->pending.objects[i].name, name);2546 found = (struct commit *)obj;2547 name = revs->pending.objects[i].name;2548 }2549 if (name_p)2550 *name_p = xstrdup_or_null(name);2551 return found;2552}25532554static struct commit *dwim_reverse_initial(struct rev_info *revs,2555 const char **name_p)2556{2557 /*2558 * DWIM "git blame --reverse ONE -- PATH" as2559 * "git blame --reverse ONE..HEAD -- PATH" but only do so2560 * when it makes sense.2561 */2562 struct object *obj;2563 struct commit *head_commit;2564 struct object_id head_oid;25652566 if (revs->pending.nr != 1)2567 return NULL;25682569 /* Is that sole rev a committish? */2570 obj = revs->pending.objects[0].item;2571 obj = deref_tag(revs->repo, obj, NULL, 0);2572 if (obj->type != OBJ_COMMIT)2573 return NULL;25742575 /* Do we have HEAD? */2576 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))2577 return NULL;2578 head_commit = lookup_commit_reference_gently(revs->repo,2579 &head_oid, 1);2580 if (!head_commit)2581 return NULL;25822583 /* Turn "ONE" into "ONE..HEAD" then */2584 obj->flags |= UNINTERESTING;2585 add_pending_object(revs, &head_commit->object, "HEAD");25862587 if (name_p)2588 *name_p = revs->pending.objects[0].name;2589 return (struct commit *)obj;2590}25912592static struct commit *find_single_initial(struct rev_info *revs,2593 const char **name_p)2594{2595 int i;2596 struct commit *found = NULL;2597 const char *name = NULL;25982599 /*2600 * There must be one and only one negative commit, and it must be2601 * the boundary.2602 */2603 for (i = 0; i < revs->pending.nr; i++) {2604 struct object *obj = revs->pending.objects[i].item;2605 if (!(obj->flags & UNINTERESTING))2606 continue;2607 obj = deref_tag(revs->repo, obj, NULL, 0);2608 if (obj->type != OBJ_COMMIT)2609 die("Non commit %s?", revs->pending.objects[i].name);2610 if (found)2611 die("More than one commit to dig up from, %s and %s?",2612 revs->pending.objects[i].name, name);2613 found = (struct commit *) obj;2614 name = revs->pending.objects[i].name;2615 }26162617 if (!name)2618 found = dwim_reverse_initial(revs, &name);2619 if (!name)2620 die("No commit to dig up from?");26212622 if (name_p)2623 *name_p = xstrdup(name);2624 return found;2625}26262627void init_scoreboard(struct blame_scoreboard *sb)2628{2629 memset(sb, 0, sizeof(struct blame_scoreboard));2630 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;2631 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;2632}26332634void setup_scoreboard(struct blame_scoreboard *sb,2635 const char *path,2636 struct blame_origin **orig)2637{2638 const char *final_commit_name = NULL;2639 struct blame_origin *o;2640 struct commit *final_commit = NULL;2641 enum object_type type;26422643 init_blame_suspects(&blame_suspects);26442645 if (sb->reverse && sb->contents_from)2646 die(_("--contents and --reverse do not blend well."));26472648 if (!sb->repo)2649 BUG("repo is NULL");26502651 if (!sb->reverse) {2652 sb->final = find_single_final(sb->revs, &final_commit_name);2653 sb->commits.compare = compare_commits_by_commit_date;2654 } else {2655 sb->final = find_single_initial(sb->revs, &final_commit_name);2656 sb->commits.compare = compare_commits_by_reverse_commit_date;2657 }26582659 if (sb->final && sb->contents_from)2660 die(_("cannot use --contents with final commit object name"));26612662 if (sb->reverse && sb->revs->first_parent_only)2663 sb->revs->children.name = NULL;26642665 if (!sb->final) {2666 /*2667 * "--not A B -- path" without anything positive;2668 * do not default to HEAD, but use the working tree2669 * or "--contents".2670 */2671 setup_work_tree();2672 sb->final = fake_working_tree_commit(sb->repo,2673 &sb->revs->diffopt,2674 path, sb->contents_from);2675 add_pending_object(sb->revs, &(sb->final->object), ":");2676 }26772678 if (sb->reverse && sb->revs->first_parent_only) {2679 final_commit = find_single_final(sb->revs, NULL);2680 if (!final_commit)2681 die(_("--reverse and --first-parent together require specified latest commit"));2682 }26832684 /*2685 * If we have bottom, this will mark the ancestors of the2686 * bottom commits we would reach while traversing as2687 * uninteresting.2688 */2689 if (prepare_revision_walk(sb->revs))2690 die(_("revision walk setup failed"));26912692 if (sb->reverse && sb->revs->first_parent_only) {2693 struct commit *c = final_commit;26942695 sb->revs->children.name = "children";2696 while (c->parents &&2697 !oideq(&c->object.oid, &sb->final->object.oid)) {2698 struct commit_list *l = xcalloc(1, sizeof(*l));26992700 l->item = c;2701 if (add_decoration(&sb->revs->children,2702 &c->parents->item->object, l))2703 BUG("not unique item in first-parent chain");2704 c = c->parents->item;2705 }27062707 if (!oideq(&c->object.oid, &sb->final->object.oid))2708 die(_("--reverse --first-parent together require range along first-parent chain"));2709 }27102711 if (is_null_oid(&sb->final->object.oid)) {2712 o = get_blame_suspects(sb->final);2713 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);2714 sb->final_buf_size = o->file.size;2715 }2716 else {2717 o = get_origin(sb->final, path);2718 if (fill_blob_sha1_and_mode(sb->repo, o))2719 die(_("no such path %s in %s"), path, final_commit_name);27202721 if (sb->revs->diffopt.flags.allow_textconv &&2722 textconv_object(sb->repo, path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,2723 &sb->final_buf_size))2724 ;2725 else2726 sb->final_buf = read_object_file(&o->blob_oid, &type,2727 &sb->final_buf_size);27282729 if (!sb->final_buf)2730 die(_("cannot read blob %s for path %s"),2731 oid_to_hex(&o->blob_oid),2732 path);2733 }2734 sb->num_read_blob++;2735 prepare_lines(sb);27362737 if (orig)2738 *orig = o;27392740 free((char *)final_commit_name);2741}2742274327442745struct blame_entry *blame_entry_prepend(struct blame_entry *head,2746 long start, long end,2747 struct blame_origin *o)2748{2749 struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));2750 new_head->lno = start;2751 new_head->num_lines = end - start;2752 new_head->suspect = o;2753 new_head->s_lno = start;2754 new_head->next = head;2755 blame_origin_incref(o);2756 return new_head;2757}