t1006: don't strip timestamps from expected results
[alt-git.git] / blame.c
blobb8306540627faef3ae82525a815b5870f8ab37d7
1 #include "cache.h"
2 #include "refs.h"
3 #include "object-store.h"
4 #include "cache-tree.h"
5 #include "mergesort.h"
6 #include "convert.h"
7 #include "diff.h"
8 #include "diffcore.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "setup.h"
12 #include "tag.h"
13 #include "trace2.h"
14 #include "blame.h"
15 #include "alloc.h"
16 #include "commit-slab.h"
17 #include "bloom.h"
18 #include "commit-graph.h"
20 define_commit_slab(blame_suspects, struct blame_origin *);
21 static struct blame_suspects blame_suspects;
23 struct blame_origin *get_blame_suspects(struct commit *commit)
25 struct blame_origin **result;
27 result = blame_suspects_peek(&blame_suspects, commit);
29 return result ? *result : NULL;
32 static void set_blame_suspects(struct commit *commit, struct blame_origin *origin)
34 *blame_suspects_at(&blame_suspects, commit) = origin;
37 void blame_origin_decref(struct blame_origin *o)
39 if (o && --o->refcnt <= 0) {
40 struct blame_origin *p, *l = NULL;
41 if (o->previous)
42 blame_origin_decref(o->previous);
43 free(o->file.ptr);
44 /* Should be present exactly once in commit chain */
45 for (p = get_blame_suspects(o->commit); p; l = p, p = p->next) {
46 if (p == o) {
47 if (l)
48 l->next = p->next;
49 else
50 set_blame_suspects(o->commit, p->next);
51 free(o);
52 return;
55 die("internal error in blame_origin_decref");
60 * Given a commit and a path in it, create a new origin structure.
61 * The callers that add blame to the scoreboard should use
62 * get_origin() to obtain shared, refcounted copy instead of calling
63 * this function directly.
65 static struct blame_origin *make_origin(struct commit *commit, const char *path)
67 struct blame_origin *o;
68 FLEX_ALLOC_STR(o, path, path);
69 o->commit = commit;
70 o->refcnt = 1;
71 o->next = get_blame_suspects(commit);
72 set_blame_suspects(commit, o);
73 return o;
77 * Locate an existing origin or create a new one.
78 * This moves the origin to front position in the commit util list.
80 static struct blame_origin *get_origin(struct commit *commit, const char *path)
82 struct blame_origin *o, *l;
84 for (o = get_blame_suspects(commit), l = NULL; o; l = o, o = o->next) {
85 if (!strcmp(o->path, path)) {
86 /* bump to front */
87 if (l) {
88 l->next = o->next;
89 o->next = get_blame_suspects(commit);
90 set_blame_suspects(commit, o);
92 return blame_origin_incref(o);
95 return make_origin(commit, path);
100 static void verify_working_tree_path(struct repository *r,
101 struct commit *work_tree, const char *path)
103 struct commit_list *parents;
104 int pos;
106 for (parents = work_tree->parents; parents; parents = parents->next) {
107 const struct object_id *commit_oid = &parents->item->object.oid;
108 struct object_id blob_oid;
109 unsigned short mode;
111 if (!get_tree_entry(r, commit_oid, path, &blob_oid, &mode) &&
112 oid_object_info(r, &blob_oid, NULL) == OBJ_BLOB)
113 return;
116 pos = index_name_pos(r->index, path, strlen(path));
117 if (pos >= 0)
118 ; /* path is in the index */
119 else if (-1 - pos < r->index->cache_nr &&
120 !strcmp(r->index->cache[-1 - pos]->name, path))
121 ; /* path is in the index, unmerged */
122 else
123 die("no such path '%s' in HEAD", path);
126 static struct commit_list **append_parent(struct repository *r,
127 struct commit_list **tail,
128 const struct object_id *oid)
130 struct commit *parent;
132 parent = lookup_commit_reference(r, oid);
133 if (!parent)
134 die("no such commit %s", oid_to_hex(oid));
135 return &commit_list_insert(parent, tail)->next;
138 static void append_merge_parents(struct repository *r,
139 struct commit_list **tail)
141 int merge_head;
142 struct strbuf line = STRBUF_INIT;
144 merge_head = open(git_path_merge_head(r), O_RDONLY);
145 if (merge_head < 0) {
146 if (errno == ENOENT)
147 return;
148 die("cannot open '%s' for reading",
149 git_path_merge_head(r));
152 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
153 struct object_id oid;
154 if (get_oid_hex(line.buf, &oid))
155 die("unknown line in '%s': %s",
156 git_path_merge_head(r), line.buf);
157 tail = append_parent(r, tail, &oid);
159 close(merge_head);
160 strbuf_release(&line);
164 * This isn't as simple as passing sb->buf and sb->len, because we
165 * want to transfer ownership of the buffer to the commit (so we
166 * must use detach).
168 static void set_commit_buffer_from_strbuf(struct repository *r,
169 struct commit *c,
170 struct strbuf *sb)
172 size_t len;
173 void *buf = strbuf_detach(sb, &len);
174 set_commit_buffer(r, c, buf, len);
178 * Prepare a dummy commit that represents the work tree (or staged) item.
179 * Note that annotating work tree item never works in the reverse.
181 static struct commit *fake_working_tree_commit(struct repository *r,
182 struct diff_options *opt,
183 const char *path,
184 const char *contents_from,
185 struct object_id *oid)
187 struct commit *commit;
188 struct blame_origin *origin;
189 struct commit_list **parent_tail, *parent;
190 struct strbuf buf = STRBUF_INIT;
191 const char *ident;
192 time_t now;
193 int len;
194 struct cache_entry *ce;
195 unsigned mode;
196 struct strbuf msg = STRBUF_INIT;
198 repo_read_index(r);
199 time(&now);
200 commit = alloc_commit_node(r);
201 commit->object.parsed = 1;
202 commit->date = now;
203 parent_tail = &commit->parents;
205 parent_tail = append_parent(r, parent_tail, oid);
206 append_merge_parents(r, parent_tail);
207 verify_working_tree_path(r, commit, path);
209 origin = make_origin(commit, path);
211 if (contents_from)
212 ident = fmt_ident("External file (--contents)", "external.file",
213 WANT_BLANK_IDENT, NULL, 0);
214 else
215 ident = fmt_ident("Not Committed Yet", "not.committed.yet",
216 WANT_BLANK_IDENT, NULL, 0);
217 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
218 for (parent = commit->parents; parent; parent = parent->next)
219 strbuf_addf(&msg, "parent %s\n",
220 oid_to_hex(&parent->item->object.oid));
221 strbuf_addf(&msg,
222 "author %s\n"
223 "committer %s\n\n"
224 "Version of %s from %s\n",
225 ident, ident, path,
226 (!contents_from ? path :
227 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
228 set_commit_buffer_from_strbuf(r, commit, &msg);
230 if (!contents_from || strcmp("-", contents_from)) {
231 struct stat st;
232 const char *read_from;
233 char *buf_ptr;
234 unsigned long buf_len;
236 if (contents_from) {
237 if (stat(contents_from, &st) < 0)
238 die_errno("Cannot stat '%s'", contents_from);
239 read_from = contents_from;
241 else {
242 if (lstat(path, &st) < 0)
243 die_errno("Cannot lstat '%s'", path);
244 read_from = path;
246 mode = canon_mode(st.st_mode);
248 switch (st.st_mode & S_IFMT) {
249 case S_IFREG:
250 if (opt->flags.allow_textconv &&
251 textconv_object(r, read_from, mode, null_oid(), 0, &buf_ptr, &buf_len))
252 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
253 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
254 die_errno("cannot open or read '%s'", read_from);
255 break;
256 case S_IFLNK:
257 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
258 die_errno("cannot readlink '%s'", read_from);
259 break;
260 default:
261 die("unsupported file type %s", read_from);
264 else {
265 /* Reading from stdin */
266 mode = 0;
267 if (strbuf_read(&buf, 0, 0) < 0)
268 die_errno("failed to read from stdin");
270 convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
271 origin->file.ptr = buf.buf;
272 origin->file.size = buf.len;
273 pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
276 * Read the current index, replace the path entry with
277 * origin->blob_sha1 without mucking with its mode or type
278 * bits; we are not going to write this index out -- we just
279 * want to run "diff-index --cached".
281 discard_index(r->index);
282 repo_read_index(r);
284 len = strlen(path);
285 if (!mode) {
286 int pos = index_name_pos(r->index, path, len);
287 if (0 <= pos)
288 mode = r->index->cache[pos]->ce_mode;
289 else
290 /* Let's not bother reading from HEAD tree */
291 mode = S_IFREG | 0644;
293 ce = make_empty_cache_entry(r->index, len);
294 oidcpy(&ce->oid, &origin->blob_oid);
295 memcpy(ce->name, path, len);
296 ce->ce_flags = create_ce_flags(0);
297 ce->ce_namelen = len;
298 ce->ce_mode = create_ce_mode(mode);
299 add_index_entry(r->index, ce,
300 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
302 cache_tree_invalidate_path(r->index, path);
304 return commit;
309 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
310 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
312 xpparam_t xpp = {0};
313 xdemitconf_t xecfg = {0};
314 xdemitcb_t ecb = {NULL};
316 xpp.flags = xdl_opts;
317 xecfg.hunk_func = hunk_func;
318 ecb.priv = cb_data;
319 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
322 static const char *get_next_line(const char *start, const char *end)
324 const char *nl = memchr(start, '\n', end - start);
326 return nl ? nl + 1 : end;
329 static int find_line_starts(int **line_starts, const char *buf,
330 unsigned long len)
332 const char *end = buf + len;
333 const char *p;
334 int *lineno;
335 int num = 0;
337 for (p = buf; p < end; p = get_next_line(p, end))
338 num++;
340 ALLOC_ARRAY(*line_starts, num + 1);
341 lineno = *line_starts;
343 for (p = buf; p < end; p = get_next_line(p, end))
344 *lineno++ = p - buf;
346 *lineno = len;
348 return num;
351 struct fingerprint_entry;
353 /* A fingerprint is intended to loosely represent a string, such that two
354 * fingerprints can be quickly compared to give an indication of the similarity
355 * of the strings that they represent.
357 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
358 * the string that it represents. Whitespace is added at each end of the
359 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
360 * For example, the string "Darth Radar" will be converted to the following
361 * fingerprint:
362 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
364 * The similarity between two fingerprints is the size of the intersection of
365 * their multisets, including repeated elements. See fingerprint_similarity for
366 * examples.
368 * For ease of implementation, the fingerprint is implemented as a map
369 * of byte pairs to the count of that byte pair in the string, instead of
370 * allowing repeated elements in a set.
372 struct fingerprint {
373 struct hashmap map;
374 /* As we know the maximum number of entries in advance, it's
375 * convenient to store the entries in a single array instead of having
376 * the hashmap manage the memory.
378 struct fingerprint_entry *entries;
381 /* A byte pair in a fingerprint. Stores the number of times the byte pair
382 * occurs in the string that the fingerprint represents.
384 struct fingerprint_entry {
385 /* The hashmap entry - the hash represents the byte pair in its
386 * entirety so we don't need to store the byte pair separately.
388 struct hashmap_entry entry;
389 /* The number of times the byte pair occurs in the string that the
390 * fingerprint represents.
392 int count;
395 /* See `struct fingerprint` for an explanation of what a fingerprint is.
396 * \param result the fingerprint of the string is stored here. This must be
397 * freed later using free_fingerprint.
398 * \param line_begin the start of the string
399 * \param line_end the end of the string
401 static void get_fingerprint(struct fingerprint *result,
402 const char *line_begin,
403 const char *line_end)
405 unsigned int hash, c0 = 0, c1;
406 const char *p;
407 int max_map_entry_count = 1 + line_end - line_begin;
408 struct fingerprint_entry *entry = xcalloc(max_map_entry_count,
409 sizeof(struct fingerprint_entry));
410 struct fingerprint_entry *found_entry;
412 hashmap_init(&result->map, NULL, NULL, max_map_entry_count);
413 result->entries = entry;
414 for (p = line_begin; p <= line_end; ++p, c0 = c1) {
415 /* Always terminate the string with whitespace.
416 * Normalise whitespace to 0, and normalise letters to
417 * lower case. This won't work for multibyte characters but at
418 * worst will match some unrelated characters.
420 if ((p == line_end) || isspace(*p))
421 c1 = 0;
422 else
423 c1 = tolower(*p);
424 hash = c0 | (c1 << 8);
425 /* Ignore whitespace pairs */
426 if (hash == 0)
427 continue;
428 hashmap_entry_init(&entry->entry, hash);
430 found_entry = hashmap_get_entry(&result->map, entry,
431 /* member name */ entry, NULL);
432 if (found_entry) {
433 found_entry->count += 1;
434 } else {
435 entry->count = 1;
436 hashmap_add(&result->map, &entry->entry);
437 ++entry;
442 static void free_fingerprint(struct fingerprint *f)
444 hashmap_clear(&f->map);
445 free(f->entries);
448 /* Calculates the similarity between two fingerprints as the size of the
449 * intersection of their multisets, including repeated elements. See
450 * `struct fingerprint` for an explanation of the fingerprint representation.
451 * The similarity between "cat mat" and "father rather" is 2 because "at" is
452 * present twice in both strings while the similarity between "tim" and "mit"
453 * is 0.
455 static int fingerprint_similarity(struct fingerprint *a, struct fingerprint *b)
457 int intersection = 0;
458 struct hashmap_iter iter;
459 const struct fingerprint_entry *entry_a, *entry_b;
461 hashmap_for_each_entry(&b->map, &iter, entry_b,
462 entry /* member name */) {
463 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
464 if (entry_a) {
465 intersection += entry_a->count < entry_b->count ?
466 entry_a->count : entry_b->count;
469 return intersection;
472 /* Subtracts byte-pair elements in B from A, modifying A in place.
474 static void fingerprint_subtract(struct fingerprint *a, struct fingerprint *b)
476 struct hashmap_iter iter;
477 struct fingerprint_entry *entry_a;
478 const struct fingerprint_entry *entry_b;
480 hashmap_iter_init(&b->map, &iter);
482 hashmap_for_each_entry(&b->map, &iter, entry_b,
483 entry /* member name */) {
484 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
485 if (entry_a) {
486 if (entry_a->count <= entry_b->count)
487 hashmap_remove(&a->map, &entry_b->entry, NULL);
488 else
489 entry_a->count -= entry_b->count;
494 /* Calculate fingerprints for a series of lines.
495 * Puts the fingerprints in the fingerprints array, which must have been
496 * preallocated to allow storing line_count elements.
498 static void get_line_fingerprints(struct fingerprint *fingerprints,
499 const char *content, const int *line_starts,
500 long first_line, long line_count)
502 int i;
503 const char *linestart, *lineend;
505 line_starts += first_line;
506 for (i = 0; i < line_count; ++i) {
507 linestart = content + line_starts[i];
508 lineend = content + line_starts[i + 1];
509 get_fingerprint(fingerprints + i, linestart, lineend);
513 static void free_line_fingerprints(struct fingerprint *fingerprints,
514 int nr_fingerprints)
516 int i;
518 for (i = 0; i < nr_fingerprints; i++)
519 free_fingerprint(&fingerprints[i]);
522 /* This contains the data necessary to linearly map a line number in one half
523 * of a diff chunk to the line in the other half of the diff chunk that is
524 * closest in terms of its position as a fraction of the length of the chunk.
526 struct line_number_mapping {
527 int destination_start, destination_length,
528 source_start, source_length;
531 /* Given a line number in one range, offset and scale it to map it onto the
532 * other range.
533 * Essentially this mapping is a simple linear equation but the calculation is
534 * more complicated to allow performing it with integer operations.
535 * Another complication is that if a line could map onto many lines in the
536 * destination range then we want to choose the line at the center of those
537 * possibilities.
538 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
539 * first 5 lines in B will map onto the first line in the A chunk, while the
540 * last 5 lines will all map onto the second line in the A chunk.
541 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
542 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
544 static int map_line_number(int line_number,
545 const struct line_number_mapping *mapping)
547 return ((line_number - mapping->source_start) * 2 + 1) *
548 mapping->destination_length /
549 (mapping->source_length * 2) +
550 mapping->destination_start;
553 /* Get a pointer to the element storing the similarity between a line in A
554 * and a line in B.
556 * The similarities are stored in a 2-dimensional array. Each "row" in the
557 * array contains the similarities for a line in B. The similarities stored in
558 * a row are the similarities between the line in B and the nearby lines in A.
559 * To keep the length of each row the same, it is padded out with values of -1
560 * where the search range extends beyond the lines in A.
561 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
562 * look like this:
563 * a | m
564 * b | n
565 * c | o
566 * d | p
567 * e | q
568 * Then the similarity array will contain:
569 * [-1, -1, am, bm, cm,
570 * -1, an, bn, cn, dn,
571 * ao, bo, co, do, eo,
572 * bp, cp, dp, ep, -1,
573 * cq, dq, eq, -1, -1]
574 * Where similarities are denoted either by -1 for invalid, or the
575 * concatenation of the two lines in the diff being compared.
577 * \param similarities array of similarities between lines in A and B
578 * \param line_a the index of the line in A, in the same frame of reference as
579 * closest_line_a.
580 * \param local_line_b the index of the line in B, relative to the first line
581 * in B that similarities represents.
582 * \param closest_line_a the index of the line in A that is deemed to be
583 * closest to local_line_b. This must be in the same
584 * frame of reference as line_a. This value defines
585 * where similarities is centered for the line in B.
586 * \param max_search_distance_a maximum distance in lines from the closest line
587 * in A for other lines in A for which
588 * similarities may be calculated.
590 static int *get_similarity(int *similarities,
591 int line_a, int local_line_b,
592 int closest_line_a, int max_search_distance_a)
594 assert(abs(line_a - closest_line_a) <=
595 max_search_distance_a);
596 return similarities + line_a - closest_line_a +
597 max_search_distance_a +
598 local_line_b * (max_search_distance_a * 2 + 1);
601 #define CERTAIN_NOTHING_MATCHES -2
602 #define CERTAINTY_NOT_CALCULATED -1
604 /* Given a line in B, first calculate its similarities with nearby lines in A
605 * if not already calculated, then identify the most similar and second most
606 * similar lines. The "certainty" is calculated based on those two
607 * similarities.
609 * \param start_a the index of the first line of the chunk in A
610 * \param length_a the length in lines of the chunk in A
611 * \param local_line_b the index of the line in B, relative to the first line
612 * in the chunk.
613 * \param fingerprints_a array of fingerprints for the chunk in A
614 * \param fingerprints_b array of fingerprints for the chunk in B
615 * \param similarities 2-dimensional array of similarities between lines in A
616 * and B. See get_similarity() for more details.
617 * \param certainties array of values indicating how strongly a line in B is
618 * matched with some line in A.
619 * \param second_best_result array of absolute indices in A for the second
620 * closest match of a line in B.
621 * \param result array of absolute indices in A for the closest match of a line
622 * in B.
623 * \param max_search_distance_a maximum distance in lines from the closest line
624 * in A for other lines in A for which
625 * similarities may be calculated.
626 * \param map_line_number_in_b_to_a parameter to map_line_number().
628 static void find_best_line_matches(
629 int start_a,
630 int length_a,
631 int start_b,
632 int local_line_b,
633 struct fingerprint *fingerprints_a,
634 struct fingerprint *fingerprints_b,
635 int *similarities,
636 int *certainties,
637 int *second_best_result,
638 int *result,
639 const int max_search_distance_a,
640 const struct line_number_mapping *map_line_number_in_b_to_a)
643 int i, search_start, search_end, closest_local_line_a, *similarity,
644 best_similarity = 0, second_best_similarity = 0,
645 best_similarity_index = 0, second_best_similarity_index = 0;
647 /* certainty has already been calculated so no need to redo the work */
648 if (certainties[local_line_b] != CERTAINTY_NOT_CALCULATED)
649 return;
651 closest_local_line_a = map_line_number(
652 local_line_b + start_b, map_line_number_in_b_to_a) - start_a;
654 search_start = closest_local_line_a - max_search_distance_a;
655 if (search_start < 0)
656 search_start = 0;
658 search_end = closest_local_line_a + max_search_distance_a + 1;
659 if (search_end > length_a)
660 search_end = length_a;
662 for (i = search_start; i < search_end; ++i) {
663 similarity = get_similarity(similarities,
664 i, local_line_b,
665 closest_local_line_a,
666 max_search_distance_a);
667 if (*similarity == -1) {
668 /* This value will never exceed 10 but assert just in
669 * case
671 assert(abs(i - closest_local_line_a) < 1000);
672 /* scale the similarity by (1000 - distance from
673 * closest line) to act as a tie break between lines
674 * that otherwise are equally similar.
676 *similarity = fingerprint_similarity(
677 fingerprints_b + local_line_b,
678 fingerprints_a + i) *
679 (1000 - abs(i - closest_local_line_a));
681 if (*similarity > best_similarity) {
682 second_best_similarity = best_similarity;
683 second_best_similarity_index = best_similarity_index;
684 best_similarity = *similarity;
685 best_similarity_index = i;
686 } else if (*similarity > second_best_similarity) {
687 second_best_similarity = *similarity;
688 second_best_similarity_index = i;
692 if (best_similarity == 0) {
693 /* this line definitely doesn't match with anything. Mark it
694 * with this special value so it doesn't get invalidated and
695 * won't be recalculated.
697 certainties[local_line_b] = CERTAIN_NOTHING_MATCHES;
698 result[local_line_b] = -1;
699 } else {
700 /* Calculate the certainty with which this line matches.
701 * If the line matches well with two lines then that reduces
702 * the certainty. However we still want to prioritise matching
703 * a line that matches very well with two lines over matching a
704 * line that matches poorly with one line, hence doubling
705 * best_similarity.
706 * This means that if we have
707 * line X that matches only one line with a score of 3,
708 * line Y that matches two lines equally with a score of 5,
709 * and line Z that matches only one line with a score or 2,
710 * then the lines in order of certainty are X, Y, Z.
712 certainties[local_line_b] = best_similarity * 2 -
713 second_best_similarity;
715 /* We keep both the best and second best results to allow us to
716 * check at a later stage of the matching process whether the
717 * result needs to be invalidated.
719 result[local_line_b] = start_a + best_similarity_index;
720 second_best_result[local_line_b] =
721 start_a + second_best_similarity_index;
726 * This finds the line that we can match with the most confidence, and
727 * uses it as a partition. It then calls itself on the lines on either side of
728 * that partition. In this way we avoid lines appearing out of order, and
729 * retain a sensible line ordering.
730 * \param start_a index of the first line in A with which lines in B may be
731 * compared.
732 * \param start_b index of the first line in B for which matching should be
733 * done.
734 * \param length_a number of lines in A with which lines in B may be compared.
735 * \param length_b number of lines in B for which matching should be done.
736 * \param fingerprints_a mutable array of fingerprints in A. The first element
737 * corresponds to the line at start_a.
738 * \param fingerprints_b array of fingerprints in B. The first element
739 * corresponds to the line at start_b.
740 * \param similarities 2-dimensional array of similarities between lines in A
741 * and B. See get_similarity() for more details.
742 * \param certainties array of values indicating how strongly a line in B is
743 * matched with some line in A.
744 * \param second_best_result array of absolute indices in A for the second
745 * closest match of a line in B.
746 * \param result array of absolute indices in A for the closest match of a line
747 * in B.
748 * \param max_search_distance_a maximum distance in lines from the closest line
749 * in A for other lines in A for which
750 * similarities may be calculated.
751 * \param max_search_distance_b an upper bound on the greatest possible
752 * distance between lines in B such that they will
753 * both be compared with the same line in A
754 * according to max_search_distance_a.
755 * \param map_line_number_in_b_to_a parameter to map_line_number().
757 static void fuzzy_find_matching_lines_recurse(
758 int start_a, int start_b,
759 int length_a, int length_b,
760 struct fingerprint *fingerprints_a,
761 struct fingerprint *fingerprints_b,
762 int *similarities,
763 int *certainties,
764 int *second_best_result,
765 int *result,
766 int max_search_distance_a,
767 int max_search_distance_b,
768 const struct line_number_mapping *map_line_number_in_b_to_a)
770 int i, invalidate_min, invalidate_max, offset_b,
771 second_half_start_a, second_half_start_b,
772 second_half_length_a, second_half_length_b,
773 most_certain_line_a, most_certain_local_line_b = -1,
774 most_certain_line_certainty = -1,
775 closest_local_line_a;
777 for (i = 0; i < length_b; ++i) {
778 find_best_line_matches(start_a,
779 length_a,
780 start_b,
782 fingerprints_a,
783 fingerprints_b,
784 similarities,
785 certainties,
786 second_best_result,
787 result,
788 max_search_distance_a,
789 map_line_number_in_b_to_a);
791 if (certainties[i] > most_certain_line_certainty) {
792 most_certain_line_certainty = certainties[i];
793 most_certain_local_line_b = i;
797 /* No matches. */
798 if (most_certain_local_line_b == -1)
799 return;
801 most_certain_line_a = result[most_certain_local_line_b];
804 * Subtract the most certain line's fingerprint in B from the matched
805 * fingerprint in A. This means that other lines in B can't also match
806 * the same parts of the line in A.
808 fingerprint_subtract(fingerprints_a + most_certain_line_a - start_a,
809 fingerprints_b + most_certain_local_line_b);
811 /* Invalidate results that may be affected by the choice of most
812 * certain line.
814 invalidate_min = most_certain_local_line_b - max_search_distance_b;
815 invalidate_max = most_certain_local_line_b + max_search_distance_b + 1;
816 if (invalidate_min < 0)
817 invalidate_min = 0;
818 if (invalidate_max > length_b)
819 invalidate_max = length_b;
821 /* As the fingerprint in A has changed, discard previously calculated
822 * similarity values with that fingerprint.
824 for (i = invalidate_min; i < invalidate_max; ++i) {
825 closest_local_line_a = map_line_number(
826 i + start_b, map_line_number_in_b_to_a) - start_a;
828 /* Check that the lines in A and B are close enough that there
829 * is a similarity value for them.
831 if (abs(most_certain_line_a - start_a - closest_local_line_a) >
832 max_search_distance_a) {
833 continue;
836 *get_similarity(similarities, most_certain_line_a - start_a,
837 i, closest_local_line_a,
838 max_search_distance_a) = -1;
841 /* More invalidating of results that may be affected by the choice of
842 * most certain line.
843 * Discard the matches for lines in B that are currently matched with a
844 * line in A such that their ordering contradicts the ordering imposed
845 * by the choice of most certain line.
847 for (i = most_certain_local_line_b - 1; i >= invalidate_min; --i) {
848 /* In this loop we discard results for lines in B that are
849 * before most-certain-line-B but are matched with a line in A
850 * that is after most-certain-line-A.
852 if (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;
858 for (i = most_certain_local_line_b + 1; i < invalidate_max; ++i) {
859 /* In this loop we discard results for lines in B that are
860 * after most-certain-line-B but are matched with a line in A
861 * that is before most-certain-line-A.
863 if (certainties[i] >= 0 &&
864 (result[i] <= most_certain_line_a ||
865 second_best_result[i] <= most_certain_line_a)) {
866 certainties[i] = CERTAINTY_NOT_CALCULATED;
870 /* Repeat the matching process for lines before the most certain line.
872 if (most_certain_local_line_b > 0) {
873 fuzzy_find_matching_lines_recurse(
874 start_a, start_b,
875 most_certain_line_a + 1 - start_a,
876 most_certain_local_line_b,
877 fingerprints_a, fingerprints_b, similarities,
878 certainties, second_best_result, result,
879 max_search_distance_a,
880 max_search_distance_b,
881 map_line_number_in_b_to_a);
883 /* Repeat the matching process for lines after the most certain line.
885 if (most_certain_local_line_b + 1 < length_b) {
886 second_half_start_a = most_certain_line_a;
887 offset_b = most_certain_local_line_b + 1;
888 second_half_start_b = start_b + offset_b;
889 second_half_length_a =
890 length_a + start_a - second_half_start_a;
891 second_half_length_b =
892 length_b + start_b - second_half_start_b;
893 fuzzy_find_matching_lines_recurse(
894 second_half_start_a, second_half_start_b,
895 second_half_length_a, second_half_length_b,
896 fingerprints_a + second_half_start_a - start_a,
897 fingerprints_b + offset_b,
898 similarities +
899 offset_b * (max_search_distance_a * 2 + 1),
900 certainties + offset_b,
901 second_best_result + offset_b, result + offset_b,
902 max_search_distance_a,
903 max_search_distance_b,
904 map_line_number_in_b_to_a);
908 /* Find the lines in the parent line range that most closely match the lines in
909 * the target line range. This is accomplished by matching fingerprints in each
910 * blame_origin, and choosing the best matches that preserve the line ordering.
911 * See struct fingerprint for details of fingerprint matching, and
912 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
914 * The performance is believed to be O(n log n) in the typical case and O(n^2)
915 * in a pathological case, where n is the number of lines in the target range.
917 static int *fuzzy_find_matching_lines(struct blame_origin *parent,
918 struct blame_origin *target,
919 int tlno, int parent_slno, int same,
920 int parent_len)
922 /* We use the terminology "A" for the left hand side of the diff AKA
923 * parent, and "B" for the right hand side of the diff AKA target. */
924 int start_a = parent_slno;
925 int length_a = parent_len;
926 int start_b = tlno;
927 int length_b = same - tlno;
929 struct line_number_mapping map_line_number_in_b_to_a = {
930 start_a, length_a, start_b, length_b
933 struct fingerprint *fingerprints_a = parent->fingerprints;
934 struct fingerprint *fingerprints_b = target->fingerprints;
936 int i, *result, *second_best_result,
937 *certainties, *similarities, similarity_count;
940 * max_search_distance_a means that given a line in B, compare it to
941 * the line in A that is closest to its position, and the lines in A
942 * that are no greater than max_search_distance_a lines away from the
943 * closest line in A.
945 * max_search_distance_b is an upper bound on the greatest possible
946 * distance between lines in B such that they will both be compared
947 * with the same line in A according to max_search_distance_a.
949 int max_search_distance_a = 10, max_search_distance_b;
951 if (length_a <= 0)
952 return NULL;
954 if (max_search_distance_a >= length_a)
955 max_search_distance_a = length_a ? length_a - 1 : 0;
957 max_search_distance_b = ((2 * max_search_distance_a + 1) * length_b
958 - 1) / length_a;
960 CALLOC_ARRAY(result, length_b);
961 CALLOC_ARRAY(second_best_result, length_b);
962 CALLOC_ARRAY(certainties, length_b);
964 /* See get_similarity() for details of similarities. */
965 similarity_count = length_b * (max_search_distance_a * 2 + 1);
966 CALLOC_ARRAY(similarities, similarity_count);
968 for (i = 0; i < length_b; ++i) {
969 result[i] = -1;
970 second_best_result[i] = -1;
971 certainties[i] = CERTAINTY_NOT_CALCULATED;
974 for (i = 0; i < similarity_count; ++i)
975 similarities[i] = -1;
977 fuzzy_find_matching_lines_recurse(start_a, start_b,
978 length_a, length_b,
979 fingerprints_a + start_a,
980 fingerprints_b + start_b,
981 similarities,
982 certainties,
983 second_best_result,
984 result,
985 max_search_distance_a,
986 max_search_distance_b,
987 &map_line_number_in_b_to_a);
989 free(similarities);
990 free(certainties);
991 free(second_best_result);
993 return result;
996 static void fill_origin_fingerprints(struct blame_origin *o)
998 int *line_starts;
1000 if (o->fingerprints)
1001 return;
1002 o->num_lines = find_line_starts(&line_starts, o->file.ptr,
1003 o->file.size);
1004 CALLOC_ARRAY(o->fingerprints, o->num_lines);
1005 get_line_fingerprints(o->fingerprints, o->file.ptr, line_starts,
1006 0, o->num_lines);
1007 free(line_starts);
1010 static void drop_origin_fingerprints(struct blame_origin *o)
1012 if (o->fingerprints) {
1013 free_line_fingerprints(o->fingerprints, o->num_lines);
1014 o->num_lines = 0;
1015 FREE_AND_NULL(o->fingerprints);
1020 * Given an origin, prepare mmfile_t structure to be used by the
1021 * diff machinery
1023 static void fill_origin_blob(struct diff_options *opt,
1024 struct blame_origin *o, mmfile_t *file,
1025 int *num_read_blob, int fill_fingerprints)
1027 if (!o->file.ptr) {
1028 enum object_type type;
1029 unsigned long file_size;
1031 (*num_read_blob)++;
1032 if (opt->flags.allow_textconv &&
1033 textconv_object(opt->repo, o->path, o->mode,
1034 &o->blob_oid, 1, &file->ptr, &file_size))
1036 else
1037 file->ptr = repo_read_object_file(the_repository,
1038 &o->blob_oid, &type,
1039 &file_size);
1040 file->size = file_size;
1042 if (!file->ptr)
1043 die("Cannot read blob %s for path %s",
1044 oid_to_hex(&o->blob_oid),
1045 o->path);
1046 o->file = *file;
1048 else
1049 *file = o->file;
1050 if (fill_fingerprints)
1051 fill_origin_fingerprints(o);
1054 static void drop_origin_blob(struct blame_origin *o)
1056 FREE_AND_NULL(o->file.ptr);
1057 drop_origin_fingerprints(o);
1061 * Any merge of blames happens on lists of blames that arrived via
1062 * different parents in a single suspect. In this case, we want to
1063 * sort according to the suspect line numbers as opposed to the final
1064 * image line numbers. The function body is somewhat longish because
1065 * it avoids unnecessary writes.
1068 static struct blame_entry *blame_merge(struct blame_entry *list1,
1069 struct blame_entry *list2)
1071 struct blame_entry *p1 = list1, *p2 = list2,
1072 **tail = &list1;
1074 if (!p1)
1075 return p2;
1076 if (!p2)
1077 return p1;
1079 if (p1->s_lno <= p2->s_lno) {
1080 do {
1081 tail = &p1->next;
1082 if (!(p1 = *tail)) {
1083 *tail = p2;
1084 return list1;
1086 } while (p1->s_lno <= p2->s_lno);
1088 for (;;) {
1089 *tail = p2;
1090 do {
1091 tail = &p2->next;
1092 if (!(p2 = *tail)) {
1093 *tail = p1;
1094 return list1;
1096 } while (p1->s_lno > p2->s_lno);
1097 *tail = p1;
1098 do {
1099 tail = &p1->next;
1100 if (!(p1 = *tail)) {
1101 *tail = p2;
1102 return list1;
1104 } while (p1->s_lno <= p2->s_lno);
1108 DEFINE_LIST_SORT(static, sort_blame_entries, struct blame_entry, next);
1111 * Final image line numbers are all different, so we don't need a
1112 * three-way comparison here.
1115 static int compare_blame_final(const struct blame_entry *e1,
1116 const struct blame_entry *e2)
1118 return e1->lno > e2->lno ? 1 : -1;
1121 static int compare_blame_suspect(const struct blame_entry *s1,
1122 const struct blame_entry *s2)
1125 * to allow for collating suspects, we sort according to the
1126 * respective pointer value as the primary sorting criterion.
1127 * The actual relation is pretty unimportant as long as it
1128 * establishes a total order. Comparing as integers gives us
1129 * that.
1131 if (s1->suspect != s2->suspect)
1132 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
1133 if (s1->s_lno == s2->s_lno)
1134 return 0;
1135 return s1->s_lno > s2->s_lno ? 1 : -1;
1138 void blame_sort_final(struct blame_scoreboard *sb)
1140 sort_blame_entries(&sb->ent, compare_blame_final);
1143 static int compare_commits_by_reverse_commit_date(const void *a,
1144 const void *b,
1145 void *c)
1147 return -compare_commits_by_commit_date(a, b, c);
1151 * For debugging -- origin is refcounted, and this asserts that
1152 * we do not underflow.
1154 static void sanity_check_refcnt(struct blame_scoreboard *sb)
1156 int baa = 0;
1157 struct blame_entry *ent;
1159 for (ent = sb->ent; ent; ent = ent->next) {
1160 /* Nobody should have zero or negative refcnt */
1161 if (ent->suspect->refcnt <= 0) {
1162 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1163 ent->suspect->path,
1164 oid_to_hex(&ent->suspect->commit->object.oid),
1165 ent->suspect->refcnt);
1166 baa = 1;
1169 if (baa)
1170 sb->on_sanity_fail(sb, baa);
1174 * If two blame entries that are next to each other came from
1175 * contiguous lines in the same origin (i.e. <commit, path> pair),
1176 * merge them together.
1178 void blame_coalesce(struct blame_scoreboard *sb)
1180 struct blame_entry *ent, *next;
1182 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
1183 if (ent->suspect == next->suspect &&
1184 ent->s_lno + ent->num_lines == next->s_lno &&
1185 ent->lno + ent->num_lines == next->lno &&
1186 ent->ignored == next->ignored &&
1187 ent->unblamable == next->unblamable) {
1188 ent->num_lines += next->num_lines;
1189 ent->next = next->next;
1190 blame_origin_decref(next->suspect);
1191 free(next);
1192 ent->score = 0;
1193 next = ent; /* again */
1197 if (sb->debug) /* sanity */
1198 sanity_check_refcnt(sb);
1202 * Merge the given sorted list of blames into a preexisting origin.
1203 * If there were no previous blames to that commit, it is entered into
1204 * the commit priority queue of the score board.
1207 static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
1208 struct blame_entry *sorted)
1210 if (porigin->suspects)
1211 porigin->suspects = blame_merge(porigin->suspects, sorted);
1212 else {
1213 struct blame_origin *o;
1214 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
1215 if (o->suspects) {
1216 porigin->suspects = sorted;
1217 return;
1220 porigin->suspects = sorted;
1221 prio_queue_put(&sb->commits, porigin->commit);
1226 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1227 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1228 * for an origin is also used to pass the blame for the entire file to
1229 * the parent to detect the case where a child's blob is identical to
1230 * that of its parent's.
1232 * This also fills origin->mode for corresponding tree path.
1234 static int fill_blob_sha1_and_mode(struct repository *r,
1235 struct blame_origin *origin)
1237 if (!is_null_oid(&origin->blob_oid))
1238 return 0;
1239 if (get_tree_entry(r, &origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
1240 goto error_out;
1241 if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
1242 goto error_out;
1243 return 0;
1244 error_out:
1245 oidclr(&origin->blob_oid);
1246 origin->mode = S_IFINVALID;
1247 return -1;
1250 struct blame_bloom_data {
1252 * Changed-path Bloom filter keys. These can help prevent
1253 * computing diffs against first parents, but we need to
1254 * expand the list as code is moved or files are renamed.
1256 struct bloom_filter_settings *settings;
1257 struct bloom_key **keys;
1258 int nr;
1259 int alloc;
1262 static int bloom_count_queries = 0;
1263 static int bloom_count_no = 0;
1264 static int maybe_changed_path(struct repository *r,
1265 struct blame_origin *origin,
1266 struct blame_bloom_data *bd)
1268 int i;
1269 struct bloom_filter *filter;
1271 if (!bd)
1272 return 1;
1274 if (commit_graph_generation(origin->commit) == GENERATION_NUMBER_INFINITY)
1275 return 1;
1277 filter = get_bloom_filter(r, origin->commit);
1279 if (!filter)
1280 return 1;
1282 bloom_count_queries++;
1283 for (i = 0; i < bd->nr; i++) {
1284 if (bloom_filter_contains(filter,
1285 bd->keys[i],
1286 bd->settings))
1287 return 1;
1290 bloom_count_no++;
1291 return 0;
1294 static void add_bloom_key(struct blame_bloom_data *bd,
1295 const char *path)
1297 if (!bd)
1298 return;
1300 if (bd->nr >= bd->alloc) {
1301 bd->alloc *= 2;
1302 REALLOC_ARRAY(bd->keys, bd->alloc);
1305 bd->keys[bd->nr] = xmalloc(sizeof(struct bloom_key));
1306 fill_bloom_key(path, strlen(path), bd->keys[bd->nr], bd->settings);
1307 bd->nr++;
1311 * We have an origin -- check if the same path exists in the
1312 * parent and return an origin structure to represent it.
1314 static struct blame_origin *find_origin(struct repository *r,
1315 struct commit *parent,
1316 struct blame_origin *origin,
1317 struct blame_bloom_data *bd)
1319 struct blame_origin *porigin;
1320 struct diff_options diff_opts;
1321 const char *paths[2];
1323 /* First check any existing origins */
1324 for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
1325 if (!strcmp(porigin->path, origin->path)) {
1327 * The same path between origin and its parent
1328 * without renaming -- the most common case.
1330 return blame_origin_incref (porigin);
1333 /* See if the origin->path is different between parent
1334 * and origin first. Most of the time they are the
1335 * same and diff-tree is fairly efficient about this.
1337 repo_diff_setup(r, &diff_opts);
1338 diff_opts.flags.recursive = 1;
1339 diff_opts.detect_rename = 0;
1340 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1341 paths[0] = origin->path;
1342 paths[1] = NULL;
1344 parse_pathspec(&diff_opts.pathspec,
1345 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1346 PATHSPEC_LITERAL_PATH, "", paths);
1347 diff_setup_done(&diff_opts);
1349 if (is_null_oid(&origin->commit->object.oid))
1350 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1351 else {
1352 int compute_diff = 1;
1353 if (origin->commit->parents &&
1354 oideq(&parent->object.oid,
1355 &origin->commit->parents->item->object.oid))
1356 compute_diff = maybe_changed_path(r, origin, bd);
1358 if (compute_diff)
1359 diff_tree_oid(get_commit_tree_oid(parent),
1360 get_commit_tree_oid(origin->commit),
1361 "", &diff_opts);
1363 diffcore_std(&diff_opts);
1365 if (!diff_queued_diff.nr) {
1366 /* The path is the same as parent */
1367 porigin = get_origin(parent, origin->path);
1368 oidcpy(&porigin->blob_oid, &origin->blob_oid);
1369 porigin->mode = origin->mode;
1370 } else {
1372 * Since origin->path is a pathspec, if the parent
1373 * commit had it as a directory, we will see a whole
1374 * bunch of deletion of files in the directory that we
1375 * do not care about.
1377 int i;
1378 struct diff_filepair *p = NULL;
1379 for (i = 0; i < diff_queued_diff.nr; i++) {
1380 const char *name;
1381 p = diff_queued_diff.queue[i];
1382 name = p->one->path ? p->one->path : p->two->path;
1383 if (!strcmp(name, origin->path))
1384 break;
1386 if (!p)
1387 die("internal error in blame::find_origin");
1388 switch (p->status) {
1389 default:
1390 die("internal error in blame::find_origin (%c)",
1391 p->status);
1392 case 'M':
1393 porigin = get_origin(parent, origin->path);
1394 oidcpy(&porigin->blob_oid, &p->one->oid);
1395 porigin->mode = p->one->mode;
1396 break;
1397 case 'A':
1398 case 'T':
1399 /* Did not exist in parent, or type changed */
1400 break;
1403 diff_flush(&diff_opts);
1404 return porigin;
1408 * We have an origin -- find the path that corresponds to it in its
1409 * parent and return an origin structure to represent it.
1411 static struct blame_origin *find_rename(struct repository *r,
1412 struct commit *parent,
1413 struct blame_origin *origin,
1414 struct blame_bloom_data *bd)
1416 struct blame_origin *porigin = NULL;
1417 struct diff_options diff_opts;
1418 int i;
1420 repo_diff_setup(r, &diff_opts);
1421 diff_opts.flags.recursive = 1;
1422 diff_opts.detect_rename = DIFF_DETECT_RENAME;
1423 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1424 diff_opts.single_follow = origin->path;
1425 diff_setup_done(&diff_opts);
1427 if (is_null_oid(&origin->commit->object.oid))
1428 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1429 else
1430 diff_tree_oid(get_commit_tree_oid(parent),
1431 get_commit_tree_oid(origin->commit),
1432 "", &diff_opts);
1433 diffcore_std(&diff_opts);
1435 for (i = 0; i < diff_queued_diff.nr; i++) {
1436 struct diff_filepair *p = diff_queued_diff.queue[i];
1437 if ((p->status == 'R' || p->status == 'C') &&
1438 !strcmp(p->two->path, origin->path)) {
1439 add_bloom_key(bd, p->one->path);
1440 porigin = get_origin(parent, p->one->path);
1441 oidcpy(&porigin->blob_oid, &p->one->oid);
1442 porigin->mode = p->one->mode;
1443 break;
1446 diff_flush(&diff_opts);
1447 return porigin;
1451 * Append a new blame entry to a given output queue.
1453 static void add_blame_entry(struct blame_entry ***queue,
1454 const struct blame_entry *src)
1456 struct blame_entry *e = xmalloc(sizeof(*e));
1457 memcpy(e, src, sizeof(*e));
1458 blame_origin_incref(e->suspect);
1460 e->next = **queue;
1461 **queue = e;
1462 *queue = &e->next;
1466 * src typically is on-stack; we want to copy the information in it to
1467 * a malloced blame_entry that gets added to the given queue. The
1468 * origin of dst loses a refcnt.
1470 static void dup_entry(struct blame_entry ***queue,
1471 struct blame_entry *dst, struct blame_entry *src)
1473 blame_origin_incref(src->suspect);
1474 blame_origin_decref(dst->suspect);
1475 memcpy(dst, src, sizeof(*src));
1476 dst->next = **queue;
1477 **queue = dst;
1478 *queue = &dst->next;
1481 const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
1483 return sb->final_buf + sb->lineno[lno];
1487 * It is known that lines between tlno to same came from parent, and e
1488 * has an overlap with that range. it also is known that parent's
1489 * line plno corresponds to e's line tlno.
1491 * <---- e ----->
1492 * <------>
1493 * <------------>
1494 * <------------>
1495 * <------------------>
1497 * Split e into potentially three parts; before this chunk, the chunk
1498 * to be blamed for the parent, and after that portion.
1500 static void split_overlap(struct blame_entry *split,
1501 struct blame_entry *e,
1502 int tlno, int plno, int same,
1503 struct blame_origin *parent)
1505 int chunk_end_lno;
1506 int i;
1507 memset(split, 0, sizeof(struct blame_entry [3]));
1509 for (i = 0; i < 3; i++) {
1510 split[i].ignored = e->ignored;
1511 split[i].unblamable = e->unblamable;
1514 if (e->s_lno < tlno) {
1515 /* there is a pre-chunk part not blamed on parent */
1516 split[0].suspect = blame_origin_incref(e->suspect);
1517 split[0].lno = e->lno;
1518 split[0].s_lno = e->s_lno;
1519 split[0].num_lines = tlno - e->s_lno;
1520 split[1].lno = e->lno + tlno - e->s_lno;
1521 split[1].s_lno = plno;
1523 else {
1524 split[1].lno = e->lno;
1525 split[1].s_lno = plno + (e->s_lno - tlno);
1528 if (same < e->s_lno + e->num_lines) {
1529 /* there is a post-chunk part not blamed on parent */
1530 split[2].suspect = blame_origin_incref(e->suspect);
1531 split[2].lno = e->lno + (same - e->s_lno);
1532 split[2].s_lno = e->s_lno + (same - e->s_lno);
1533 split[2].num_lines = e->s_lno + e->num_lines - same;
1534 chunk_end_lno = split[2].lno;
1536 else
1537 chunk_end_lno = e->lno + e->num_lines;
1538 split[1].num_lines = chunk_end_lno - split[1].lno;
1541 * if it turns out there is nothing to blame the parent for,
1542 * forget about the splitting. !split[1].suspect signals this.
1544 if (split[1].num_lines < 1)
1545 return;
1546 split[1].suspect = blame_origin_incref(parent);
1550 * split_overlap() divided an existing blame e into up to three parts
1551 * in split. Any assigned blame is moved to queue to
1552 * reflect the split.
1554 static void split_blame(struct blame_entry ***blamed,
1555 struct blame_entry ***unblamed,
1556 struct blame_entry *split,
1557 struct blame_entry *e)
1559 if (split[0].suspect && split[2].suspect) {
1560 /* The first part (reuse storage for the existing entry e) */
1561 dup_entry(unblamed, e, &split[0]);
1563 /* The last part -- me */
1564 add_blame_entry(unblamed, &split[2]);
1566 /* ... and the middle part -- parent */
1567 add_blame_entry(blamed, &split[1]);
1569 else if (!split[0].suspect && !split[2].suspect)
1571 * The parent covers the entire area; reuse storage for
1572 * e and replace it with the parent.
1574 dup_entry(blamed, e, &split[1]);
1575 else if (split[0].suspect) {
1576 /* me and then parent */
1577 dup_entry(unblamed, e, &split[0]);
1578 add_blame_entry(blamed, &split[1]);
1580 else {
1581 /* parent and then me */
1582 dup_entry(blamed, e, &split[1]);
1583 add_blame_entry(unblamed, &split[2]);
1588 * After splitting the blame, the origins used by the
1589 * on-stack blame_entry should lose one refcnt each.
1591 static void decref_split(struct blame_entry *split)
1593 int i;
1595 for (i = 0; i < 3; i++)
1596 blame_origin_decref(split[i].suspect);
1600 * reverse_blame reverses the list given in head, appending tail.
1601 * That allows us to build lists in reverse order, then reverse them
1602 * afterwards. This can be faster than building the list in proper
1603 * order right away. The reason is that building in proper order
1604 * requires writing a link in the _previous_ element, while building
1605 * in reverse order just requires placing the list head into the
1606 * _current_ element.
1609 static struct blame_entry *reverse_blame(struct blame_entry *head,
1610 struct blame_entry *tail)
1612 while (head) {
1613 struct blame_entry *next = head->next;
1614 head->next = tail;
1615 tail = head;
1616 head = next;
1618 return tail;
1622 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1623 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1624 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1625 * e->num_lines). The caller needs to sort out the reference counting for the
1626 * new entry's suspect.
1628 static struct blame_entry *split_blame_at(struct blame_entry *e, int len,
1629 struct blame_origin *new_suspect)
1631 struct blame_entry *n = xcalloc(1, sizeof(struct blame_entry));
1633 n->suspect = new_suspect;
1634 n->ignored = e->ignored;
1635 n->unblamable = e->unblamable;
1636 n->lno = e->lno + len;
1637 n->s_lno = e->s_lno + len;
1638 n->num_lines = e->num_lines - len;
1639 e->num_lines = len;
1640 e->score = 0;
1641 return n;
1644 struct blame_line_tracker {
1645 int is_parent;
1646 int s_lno;
1649 static int are_lines_adjacent(struct blame_line_tracker *first,
1650 struct blame_line_tracker *second)
1652 return first->is_parent == second->is_parent &&
1653 first->s_lno + 1 == second->s_lno;
1656 static int scan_parent_range(struct fingerprint *p_fps,
1657 struct fingerprint *t_fps, int t_idx,
1658 int from, int nr_lines)
1660 int sim, p_idx;
1661 #define FINGERPRINT_FILE_THRESHOLD 10
1662 int best_sim_val = FINGERPRINT_FILE_THRESHOLD;
1663 int best_sim_idx = -1;
1665 for (p_idx = from; p_idx < from + nr_lines; p_idx++) {
1666 sim = fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);
1667 if (sim < best_sim_val)
1668 continue;
1669 /* Break ties with the closest-to-target line number */
1670 if (sim == best_sim_val && best_sim_idx != -1 &&
1671 abs(best_sim_idx - t_idx) < abs(p_idx - t_idx))
1672 continue;
1673 best_sim_val = sim;
1674 best_sim_idx = p_idx;
1676 return best_sim_idx;
1680 * The first pass checks the blame entry (from the target) against the parent's
1681 * diff chunk. If that fails for a line, the second pass tries to match that
1682 * line to any part of parent file. That catches cases where a change was
1683 * broken into two chunks by 'context.'
1685 static void guess_line_blames(struct blame_origin *parent,
1686 struct blame_origin *target,
1687 int tlno, int offset, int same, int parent_len,
1688 struct blame_line_tracker *line_blames)
1690 int i, best_idx, target_idx;
1691 int parent_slno = tlno + offset;
1692 int *fuzzy_matches;
1694 fuzzy_matches = fuzzy_find_matching_lines(parent, target,
1695 tlno, parent_slno, same,
1696 parent_len);
1697 for (i = 0; i < same - tlno; i++) {
1698 target_idx = tlno + i;
1699 if (fuzzy_matches && fuzzy_matches[i] >= 0) {
1700 best_idx = fuzzy_matches[i];
1701 } else {
1702 best_idx = scan_parent_range(parent->fingerprints,
1703 target->fingerprints,
1704 target_idx, 0,
1705 parent->num_lines);
1707 if (best_idx >= 0) {
1708 line_blames[i].is_parent = 1;
1709 line_blames[i].s_lno = best_idx;
1710 } else {
1711 line_blames[i].is_parent = 0;
1712 line_blames[i].s_lno = target_idx;
1715 free(fuzzy_matches);
1719 * This decides which parts of a blame entry go to the parent (added to the
1720 * ignoredp list) and which stay with the target (added to the diffp list). The
1721 * actual decision was made in a separate heuristic function, and those answers
1722 * for the lines in 'e' are in line_blames. This consumes e, essentially
1723 * putting it on a list.
1725 * Note that the blame entries on the ignoredp list are not necessarily sorted
1726 * with respect to the parent's line numbers yet.
1728 static void ignore_blame_entry(struct blame_entry *e,
1729 struct blame_origin *parent,
1730 struct blame_entry **diffp,
1731 struct blame_entry **ignoredp,
1732 struct blame_line_tracker *line_blames)
1734 int entry_len, nr_lines, i;
1737 * We carve new entries off the front of e. Each entry comes from a
1738 * contiguous chunk of lines: adjacent lines from the same origin
1739 * (either the parent or the target).
1741 entry_len = 1;
1742 nr_lines = e->num_lines; /* e changes in the loop */
1743 for (i = 0; i < nr_lines; i++) {
1744 struct blame_entry *next = NULL;
1747 * We are often adjacent to the next line - only split the blame
1748 * entry when we have to.
1750 if (i + 1 < nr_lines) {
1751 if (are_lines_adjacent(&line_blames[i],
1752 &line_blames[i + 1])) {
1753 entry_len++;
1754 continue;
1756 next = split_blame_at(e, entry_len,
1757 blame_origin_incref(e->suspect));
1759 if (line_blames[i].is_parent) {
1760 e->ignored = 1;
1761 blame_origin_decref(e->suspect);
1762 e->suspect = blame_origin_incref(parent);
1763 e->s_lno = line_blames[i - entry_len + 1].s_lno;
1764 e->next = *ignoredp;
1765 *ignoredp = e;
1766 } else {
1767 e->unblamable = 1;
1768 /* e->s_lno is already in the target's address space. */
1769 e->next = *diffp;
1770 *diffp = e;
1772 assert(e->num_lines == entry_len);
1773 e = next;
1774 entry_len = 1;
1776 assert(!e);
1780 * Process one hunk from the patch between the current suspect for
1781 * blame_entry e and its parent. This first blames any unfinished
1782 * entries before the chunk (which is where target and parent start
1783 * differing) on the parent, and then splits blame entries at the
1784 * start and at the end of the difference region. Since use of -M and
1785 * -C options may lead to overlapping/duplicate source line number
1786 * ranges, all we can rely on from sorting/merging is the order of the
1787 * first suspect line number.
1789 * tlno: line number in the target where this chunk begins
1790 * same: line number in the target where this chunk ends
1791 * offset: add to tlno to get the chunk starting point in the parent
1792 * parent_len: number of lines in the parent chunk
1794 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
1795 int tlno, int offset, int same, int parent_len,
1796 struct blame_origin *parent,
1797 struct blame_origin *target, int ignore_diffs)
1799 struct blame_entry *e = **srcq;
1800 struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;
1801 struct blame_line_tracker *line_blames = NULL;
1803 while (e && e->s_lno < tlno) {
1804 struct blame_entry *next = e->next;
1806 * current record starts before differing portion. If
1807 * it reaches into it, we need to split it up and
1808 * examine the second part separately.
1810 if (e->s_lno + e->num_lines > tlno) {
1811 /* Move second half to a new record */
1812 struct blame_entry *n;
1814 n = split_blame_at(e, tlno - e->s_lno, e->suspect);
1815 /* Push new record to diffp */
1816 n->next = diffp;
1817 diffp = n;
1818 } else
1819 blame_origin_decref(e->suspect);
1820 /* Pass blame for everything before the differing
1821 * chunk to the parent */
1822 e->suspect = blame_origin_incref(parent);
1823 e->s_lno += offset;
1824 e->next = samep;
1825 samep = e;
1826 e = next;
1829 * As we don't know how much of a common stretch after this
1830 * diff will occur, the currently blamed parts are all that we
1831 * can assign to the parent for now.
1834 if (samep) {
1835 **dstq = reverse_blame(samep, **dstq);
1836 *dstq = &samep->next;
1839 * Prepend the split off portions: everything after e starts
1840 * after the blameable portion.
1842 e = reverse_blame(diffp, e);
1845 * Now retain records on the target while parts are different
1846 * from the parent.
1848 samep = NULL;
1849 diffp = NULL;
1851 if (ignore_diffs && same - tlno > 0) {
1852 CALLOC_ARRAY(line_blames, same - tlno);
1853 guess_line_blames(parent, target, tlno, offset, same,
1854 parent_len, line_blames);
1857 while (e && e->s_lno < same) {
1858 struct blame_entry *next = e->next;
1861 * If current record extends into sameness, need to split.
1863 if (e->s_lno + e->num_lines > same) {
1865 * Move second half to a new record to be
1866 * processed by later chunks
1868 struct blame_entry *n;
1870 n = split_blame_at(e, same - e->s_lno,
1871 blame_origin_incref(e->suspect));
1872 /* Push new record to samep */
1873 n->next = samep;
1874 samep = n;
1876 if (ignore_diffs) {
1877 ignore_blame_entry(e, parent, &diffp, &ignoredp,
1878 line_blames + e->s_lno - tlno);
1879 } else {
1880 e->next = diffp;
1881 diffp = e;
1883 e = next;
1885 free(line_blames);
1886 if (ignoredp) {
1888 * Note ignoredp is not sorted yet, and thus neither is dstq.
1889 * That list must be sorted before we queue_blames(). We defer
1890 * sorting until after all diff hunks are processed, so that
1891 * guess_line_blames() can pick *any* line in the parent. The
1892 * slight drawback is that we end up sorting all blame entries
1893 * passed to the parent, including those that are unrelated to
1894 * changes made by the ignored commit.
1896 **dstq = reverse_blame(ignoredp, **dstq);
1897 *dstq = &ignoredp->next;
1899 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
1900 /* Move across elements that are in the unblamable portion */
1901 if (diffp)
1902 *srcq = &diffp->next;
1905 struct blame_chunk_cb_data {
1906 struct blame_origin *parent;
1907 struct blame_origin *target;
1908 long offset;
1909 int ignore_diffs;
1910 struct blame_entry **dstq;
1911 struct blame_entry **srcq;
1914 /* diff chunks are from parent to target */
1915 static int blame_chunk_cb(long start_a, long count_a,
1916 long start_b, long count_b, void *data)
1918 struct blame_chunk_cb_data *d = data;
1919 if (start_a - start_b != d->offset)
1920 die("internal error in blame::blame_chunk_cb");
1921 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
1922 start_b + count_b, count_a, d->parent, d->target,
1923 d->ignore_diffs);
1924 d->offset = start_a + count_a - (start_b + count_b);
1925 return 0;
1929 * We are looking at the origin 'target' and aiming to pass blame
1930 * for the lines it is suspected to its parent. Run diff to find
1931 * which lines came from parent and pass blame for them.
1933 static void pass_blame_to_parent(struct blame_scoreboard *sb,
1934 struct blame_origin *target,
1935 struct blame_origin *parent, int ignore_diffs)
1937 mmfile_t file_p, file_o;
1938 struct blame_chunk_cb_data d;
1939 struct blame_entry *newdest = NULL;
1941 if (!target->suspects)
1942 return; /* nothing remains for this target */
1944 d.parent = parent;
1945 d.target = target;
1946 d.offset = 0;
1947 d.ignore_diffs = ignore_diffs;
1948 d.dstq = &newdest; d.srcq = &target->suspects;
1950 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
1951 &sb->num_read_blob, ignore_diffs);
1952 fill_origin_blob(&sb->revs->diffopt, target, &file_o,
1953 &sb->num_read_blob, ignore_diffs);
1954 sb->num_get_patch++;
1956 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
1957 die("unable to generate diff (%s -> %s)",
1958 oid_to_hex(&parent->commit->object.oid),
1959 oid_to_hex(&target->commit->object.oid));
1960 /* The rest are the same as the parent */
1961 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, 0,
1962 parent, target, 0);
1963 *d.dstq = NULL;
1964 if (ignore_diffs)
1965 sort_blame_entries(&newdest, compare_blame_suspect);
1966 queue_blames(sb, parent, newdest);
1968 return;
1972 * The lines in blame_entry after splitting blames many times can become
1973 * very small and trivial, and at some point it becomes pointless to
1974 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1975 * ordinary C program, and it is not worth to say it was copied from
1976 * totally unrelated file in the parent.
1978 * Compute how trivial the lines in the blame_entry are.
1980 unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1982 unsigned score;
1983 const char *cp, *ep;
1985 if (e->score)
1986 return e->score;
1988 score = 1;
1989 cp = blame_nth_line(sb, e->lno);
1990 ep = blame_nth_line(sb, e->lno + e->num_lines);
1991 while (cp < ep) {
1992 unsigned ch = *((unsigned char *)cp);
1993 if (isalnum(ch))
1994 score++;
1995 cp++;
1997 e->score = score;
1998 return score;
2002 * best_so_far[] and potential[] are both a split of an existing blame_entry
2003 * that passes blame to the parent. Maintain best_so_far the best split so
2004 * far, by comparing potential and best_so_far and copying potential into
2005 * bst_so_far as needed.
2007 static void copy_split_if_better(struct blame_scoreboard *sb,
2008 struct blame_entry *best_so_far,
2009 struct blame_entry *potential)
2011 int i;
2013 if (!potential[1].suspect)
2014 return;
2015 if (best_so_far[1].suspect) {
2016 if (blame_entry_score(sb, &potential[1]) <
2017 blame_entry_score(sb, &best_so_far[1]))
2018 return;
2021 for (i = 0; i < 3; i++)
2022 blame_origin_incref(potential[i].suspect);
2023 decref_split(best_so_far);
2024 memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
2028 * We are looking at a part of the final image represented by
2029 * ent (tlno and same are offset by ent->s_lno).
2030 * tlno is where we are looking at in the final image.
2031 * up to (but not including) same match preimage.
2032 * plno is where we are looking at in the preimage.
2034 * <-------------- final image ---------------------->
2035 * <------ent------>
2036 * ^tlno ^same
2037 * <---------preimage----->
2038 * ^plno
2040 * All line numbers are 0-based.
2042 static void handle_split(struct blame_scoreboard *sb,
2043 struct blame_entry *ent,
2044 int tlno, int plno, int same,
2045 struct blame_origin *parent,
2046 struct blame_entry *split)
2048 if (ent->num_lines <= tlno)
2049 return;
2050 if (tlno < same) {
2051 struct blame_entry potential[3];
2052 tlno += ent->s_lno;
2053 same += ent->s_lno;
2054 split_overlap(potential, ent, tlno, plno, same, parent);
2055 copy_split_if_better(sb, split, potential);
2056 decref_split(potential);
2060 struct handle_split_cb_data {
2061 struct blame_scoreboard *sb;
2062 struct blame_entry *ent;
2063 struct blame_origin *parent;
2064 struct blame_entry *split;
2065 long plno;
2066 long tlno;
2069 static int handle_split_cb(long start_a, long count_a,
2070 long start_b, long count_b, void *data)
2072 struct handle_split_cb_data *d = data;
2073 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
2074 d->split);
2075 d->plno = start_a + count_a;
2076 d->tlno = start_b + count_b;
2077 return 0;
2081 * Find the lines from parent that are the same as ent so that
2082 * we can pass blames to it. file_p has the blob contents for
2083 * the parent.
2085 static void find_copy_in_blob(struct blame_scoreboard *sb,
2086 struct blame_entry *ent,
2087 struct blame_origin *parent,
2088 struct blame_entry *split,
2089 mmfile_t *file_p)
2091 const char *cp;
2092 mmfile_t file_o;
2093 struct handle_split_cb_data d;
2095 memset(&d, 0, sizeof(d));
2096 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
2098 * Prepare mmfile that contains only the lines in ent.
2100 cp = blame_nth_line(sb, ent->lno);
2101 file_o.ptr = (char *) cp;
2102 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
2105 * file_o is a part of final image we are annotating.
2106 * file_p partially may match that image.
2108 memset(split, 0, sizeof(struct blame_entry [3]));
2109 if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
2110 die("unable to generate diff (%s)",
2111 oid_to_hex(&parent->commit->object.oid));
2112 /* remainder, if any, all match the preimage */
2113 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
2116 /* Move all blame entries from list *source that have a score smaller
2117 * than score_min to the front of list *small.
2118 * Returns a pointer to the link pointing to the old head of the small list.
2121 static struct blame_entry **filter_small(struct blame_scoreboard *sb,
2122 struct blame_entry **small,
2123 struct blame_entry **source,
2124 unsigned score_min)
2126 struct blame_entry *p = *source;
2127 struct blame_entry *oldsmall = *small;
2128 while (p) {
2129 if (blame_entry_score(sb, p) <= score_min) {
2130 *small = p;
2131 small = &p->next;
2132 p = *small;
2133 } else {
2134 *source = p;
2135 source = &p->next;
2136 p = *source;
2139 *small = oldsmall;
2140 *source = NULL;
2141 return small;
2145 * See if lines currently target is suspected for can be attributed to
2146 * parent.
2148 static void find_move_in_parent(struct blame_scoreboard *sb,
2149 struct blame_entry ***blamed,
2150 struct blame_entry **toosmall,
2151 struct blame_origin *target,
2152 struct blame_origin *parent)
2154 struct blame_entry *e, split[3];
2155 struct blame_entry *unblamed = target->suspects;
2156 struct blame_entry *leftover = NULL;
2157 mmfile_t file_p;
2159 if (!unblamed)
2160 return; /* nothing remains for this target */
2162 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
2163 &sb->num_read_blob, 0);
2164 if (!file_p.ptr)
2165 return;
2167 /* At each iteration, unblamed has a NULL-terminated list of
2168 * entries that have not yet been tested for blame. leftover
2169 * contains the reversed list of entries that have been tested
2170 * without being assignable to the parent.
2172 do {
2173 struct blame_entry **unblamedtail = &unblamed;
2174 struct blame_entry *next;
2175 for (e = unblamed; e; e = next) {
2176 next = e->next;
2177 find_copy_in_blob(sb, e, parent, split, &file_p);
2178 if (split[1].suspect &&
2179 sb->move_score < blame_entry_score(sb, &split[1])) {
2180 split_blame(blamed, &unblamedtail, split, e);
2181 } else {
2182 e->next = leftover;
2183 leftover = e;
2185 decref_split(split);
2187 *unblamedtail = NULL;
2188 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
2189 } while (unblamed);
2190 target->suspects = reverse_blame(leftover, NULL);
2193 struct blame_list {
2194 struct blame_entry *ent;
2195 struct blame_entry split[3];
2199 * Count the number of entries the target is suspected for,
2200 * and prepare a list of entry and the best split.
2202 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
2203 int *num_ents_p)
2205 struct blame_entry *e;
2206 int num_ents, i;
2207 struct blame_list *blame_list = NULL;
2209 for (e = unblamed, num_ents = 0; e; e = e->next)
2210 num_ents++;
2211 if (num_ents) {
2212 CALLOC_ARRAY(blame_list, num_ents);
2213 for (e = unblamed, i = 0; e; e = e->next)
2214 blame_list[i++].ent = e;
2216 *num_ents_p = num_ents;
2217 return blame_list;
2221 * For lines target is suspected for, see if we can find code movement
2222 * across file boundary from the parent commit. porigin is the path
2223 * in the parent we already tried.
2225 static void find_copy_in_parent(struct blame_scoreboard *sb,
2226 struct blame_entry ***blamed,
2227 struct blame_entry **toosmall,
2228 struct blame_origin *target,
2229 struct commit *parent,
2230 struct blame_origin *porigin,
2231 int opt)
2233 struct diff_options diff_opts;
2234 int i, j;
2235 struct blame_list *blame_list;
2236 int num_ents;
2237 struct blame_entry *unblamed = target->suspects;
2238 struct blame_entry *leftover = NULL;
2240 if (!unblamed)
2241 return; /* nothing remains for this target */
2243 repo_diff_setup(sb->repo, &diff_opts);
2244 diff_opts.flags.recursive = 1;
2245 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2247 diff_setup_done(&diff_opts);
2249 /* Try "find copies harder" on new path if requested;
2250 * we do not want to use diffcore_rename() actually to
2251 * match things up; find_copies_harder is set only to
2252 * force diff_tree_oid() to feed all filepairs to diff_queue,
2253 * and this code needs to be after diff_setup_done(), which
2254 * usually makes find-copies-harder imply copy detection.
2256 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
2257 || ((opt & PICKAXE_BLAME_COPY_HARDER)
2258 && (!porigin || strcmp(target->path, porigin->path))))
2259 diff_opts.flags.find_copies_harder = 1;
2261 if (is_null_oid(&target->commit->object.oid))
2262 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
2263 else
2264 diff_tree_oid(get_commit_tree_oid(parent),
2265 get_commit_tree_oid(target->commit),
2266 "", &diff_opts);
2268 if (!diff_opts.flags.find_copies_harder)
2269 diffcore_std(&diff_opts);
2271 do {
2272 struct blame_entry **unblamedtail = &unblamed;
2273 blame_list = setup_blame_list(unblamed, &num_ents);
2275 for (i = 0; i < diff_queued_diff.nr; i++) {
2276 struct diff_filepair *p = diff_queued_diff.queue[i];
2277 struct blame_origin *norigin;
2278 mmfile_t file_p;
2279 struct blame_entry potential[3];
2281 if (!DIFF_FILE_VALID(p->one))
2282 continue; /* does not exist in parent */
2283 if (S_ISGITLINK(p->one->mode))
2284 continue; /* ignore git links */
2285 if (porigin && !strcmp(p->one->path, porigin->path))
2286 /* find_move already dealt with this path */
2287 continue;
2289 norigin = get_origin(parent, p->one->path);
2290 oidcpy(&norigin->blob_oid, &p->one->oid);
2291 norigin->mode = p->one->mode;
2292 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,
2293 &sb->num_read_blob, 0);
2294 if (!file_p.ptr)
2295 continue;
2297 for (j = 0; j < num_ents; j++) {
2298 find_copy_in_blob(sb, blame_list[j].ent,
2299 norigin, potential, &file_p);
2300 copy_split_if_better(sb, blame_list[j].split,
2301 potential);
2302 decref_split(potential);
2304 blame_origin_decref(norigin);
2307 for (j = 0; j < num_ents; j++) {
2308 struct blame_entry *split = blame_list[j].split;
2309 if (split[1].suspect &&
2310 sb->copy_score < blame_entry_score(sb, &split[1])) {
2311 split_blame(blamed, &unblamedtail, split,
2312 blame_list[j].ent);
2313 } else {
2314 blame_list[j].ent->next = leftover;
2315 leftover = blame_list[j].ent;
2317 decref_split(split);
2319 free(blame_list);
2320 *unblamedtail = NULL;
2321 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
2322 } while (unblamed);
2323 target->suspects = reverse_blame(leftover, NULL);
2324 diff_flush(&diff_opts);
2328 * The blobs of origin and porigin exactly match, so everything
2329 * origin is suspected for can be blamed on the parent.
2331 static void pass_whole_blame(struct blame_scoreboard *sb,
2332 struct blame_origin *origin, struct blame_origin *porigin)
2334 struct blame_entry *e, *suspects;
2336 if (!porigin->file.ptr && origin->file.ptr) {
2337 /* Steal its file */
2338 porigin->file = origin->file;
2339 origin->file.ptr = NULL;
2341 suspects = origin->suspects;
2342 origin->suspects = NULL;
2343 for (e = suspects; e; e = e->next) {
2344 blame_origin_incref(porigin);
2345 blame_origin_decref(e->suspect);
2346 e->suspect = porigin;
2348 queue_blames(sb, porigin, suspects);
2352 * We pass blame from the current commit to its parents. We keep saying
2353 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2354 * exonerate ourselves.
2356 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
2357 int reverse)
2359 if (!reverse) {
2360 if (revs->first_parent_only &&
2361 commit->parents &&
2362 commit->parents->next) {
2363 free_commit_list(commit->parents->next);
2364 commit->parents->next = NULL;
2366 return commit->parents;
2368 return lookup_decoration(&revs->children, &commit->object);
2371 static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
2373 struct commit_list *l = first_scapegoat(revs, commit, reverse);
2374 return commit_list_count(l);
2377 /* Distribute collected unsorted blames to the respected sorted lists
2378 * in the various origins.
2380 static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
2382 sort_blame_entries(&blamed, compare_blame_suspect);
2383 while (blamed)
2385 struct blame_origin *porigin = blamed->suspect;
2386 struct blame_entry *suspects = NULL;
2387 do {
2388 struct blame_entry *next = blamed->next;
2389 blamed->next = suspects;
2390 suspects = blamed;
2391 blamed = next;
2392 } while (blamed && blamed->suspect == porigin);
2393 suspects = reverse_blame(suspects, NULL);
2394 queue_blames(sb, porigin, suspects);
2398 #define MAXSG 16
2400 typedef struct blame_origin *(*blame_find_alg)(struct repository *,
2401 struct commit *,
2402 struct blame_origin *,
2403 struct blame_bloom_data *);
2405 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
2407 struct rev_info *revs = sb->revs;
2408 int i, pass, num_sg;
2409 struct commit *commit = origin->commit;
2410 struct commit_list *sg;
2411 struct blame_origin *sg_buf[MAXSG];
2412 struct blame_origin *porigin, **sg_origin = sg_buf;
2413 struct blame_entry *toosmall = NULL;
2414 struct blame_entry *blames, **blametail = &blames;
2416 num_sg = num_scapegoats(revs, commit, sb->reverse);
2417 if (!num_sg)
2418 goto finish;
2419 else if (num_sg < ARRAY_SIZE(sg_buf))
2420 memset(sg_buf, 0, sizeof(sg_buf));
2421 else
2422 CALLOC_ARRAY(sg_origin, num_sg);
2425 * The first pass looks for unrenamed path to optimize for
2426 * common cases, then we look for renames in the second pass.
2428 for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
2429 blame_find_alg find = pass ? find_rename : find_origin;
2431 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2432 i < num_sg && sg;
2433 sg = sg->next, i++) {
2434 struct commit *p = sg->item;
2435 int j, same;
2437 if (sg_origin[i])
2438 continue;
2439 if (repo_parse_commit(the_repository, p))
2440 continue;
2441 porigin = find(sb->repo, p, origin, sb->bloom_data);
2442 if (!porigin)
2443 continue;
2444 if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
2445 pass_whole_blame(sb, origin, porigin);
2446 blame_origin_decref(porigin);
2447 goto finish;
2449 for (j = same = 0; j < i; j++)
2450 if (sg_origin[j] &&
2451 oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
2452 same = 1;
2453 break;
2455 if (!same)
2456 sg_origin[i] = porigin;
2457 else
2458 blame_origin_decref(porigin);
2462 sb->num_commits++;
2463 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2464 i < num_sg && sg;
2465 sg = sg->next, i++) {
2466 struct blame_origin *porigin = sg_origin[i];
2467 if (!porigin)
2468 continue;
2469 if (!origin->previous) {
2470 blame_origin_incref(porigin);
2471 origin->previous = porigin;
2473 pass_blame_to_parent(sb, origin, porigin, 0);
2474 if (!origin->suspects)
2475 goto finish;
2479 * Pass remaining suspects for ignored commits to their parents.
2481 if (oidset_contains(&sb->ignore_list, &commit->object.oid)) {
2482 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2483 i < num_sg && sg;
2484 sg = sg->next, i++) {
2485 struct blame_origin *porigin = sg_origin[i];
2487 if (!porigin)
2488 continue;
2489 pass_blame_to_parent(sb, origin, porigin, 1);
2491 * Preemptively drop porigin so we can refresh the
2492 * fingerprints if we use the parent again, which can
2493 * occur if you ignore back-to-back commits.
2495 drop_origin_blob(porigin);
2496 if (!origin->suspects)
2497 goto finish;
2502 * Optionally find moves in parents' files.
2504 if (opt & PICKAXE_BLAME_MOVE) {
2505 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
2506 if (origin->suspects) {
2507 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2508 i < num_sg && sg;
2509 sg = sg->next, i++) {
2510 struct blame_origin *porigin = sg_origin[i];
2511 if (!porigin)
2512 continue;
2513 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
2514 if (!origin->suspects)
2515 break;
2521 * Optionally find copies from parents' files.
2523 if (opt & PICKAXE_BLAME_COPY) {
2524 if (sb->copy_score > sb->move_score)
2525 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2526 else if (sb->copy_score < sb->move_score) {
2527 origin->suspects = blame_merge(origin->suspects, toosmall);
2528 toosmall = NULL;
2529 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2531 if (!origin->suspects)
2532 goto finish;
2534 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2535 i < num_sg && sg;
2536 sg = sg->next, i++) {
2537 struct blame_origin *porigin = sg_origin[i];
2538 find_copy_in_parent(sb, &blametail, &toosmall,
2539 origin, sg->item, porigin, opt);
2540 if (!origin->suspects)
2541 goto finish;
2545 finish:
2546 *blametail = NULL;
2547 distribute_blame(sb, blames);
2549 * prepend toosmall to origin->suspects
2551 * There is no point in sorting: this ends up on a big
2552 * unsorted list in the caller anyway.
2554 if (toosmall) {
2555 struct blame_entry **tail = &toosmall;
2556 while (*tail)
2557 tail = &(*tail)->next;
2558 *tail = origin->suspects;
2559 origin->suspects = toosmall;
2561 for (i = 0; i < num_sg; i++) {
2562 if (sg_origin[i]) {
2563 if (!sg_origin[i]->suspects)
2564 drop_origin_blob(sg_origin[i]);
2565 blame_origin_decref(sg_origin[i]);
2568 drop_origin_blob(origin);
2569 if (sg_buf != sg_origin)
2570 free(sg_origin);
2574 * The main loop -- while we have blobs with lines whose true origin
2575 * is still unknown, pick one blob, and allow its lines to pass blames
2576 * to its parents. */
2577 void assign_blame(struct blame_scoreboard *sb, int opt)
2579 struct rev_info *revs = sb->revs;
2580 struct commit *commit = prio_queue_get(&sb->commits);
2582 while (commit) {
2583 struct blame_entry *ent;
2584 struct blame_origin *suspect = get_blame_suspects(commit);
2586 /* find one suspect to break down */
2587 while (suspect && !suspect->suspects)
2588 suspect = suspect->next;
2590 if (!suspect) {
2591 commit = prio_queue_get(&sb->commits);
2592 continue;
2595 assert(commit == suspect->commit);
2598 * We will use this suspect later in the loop,
2599 * so hold onto it in the meantime.
2601 blame_origin_incref(suspect);
2602 repo_parse_commit(the_repository, commit);
2603 if (sb->reverse ||
2604 (!(commit->object.flags & UNINTERESTING) &&
2605 !(revs->max_age != -1 && commit->date < revs->max_age)))
2606 pass_blame(sb, suspect, opt);
2607 else {
2608 commit->object.flags |= UNINTERESTING;
2609 if (commit->object.parsed)
2610 mark_parents_uninteresting(sb->revs, commit);
2612 /* treat root commit as boundary */
2613 if (!commit->parents && !sb->show_root)
2614 commit->object.flags |= UNINTERESTING;
2616 /* Take responsibility for the remaining entries */
2617 ent = suspect->suspects;
2618 if (ent) {
2619 suspect->guilty = 1;
2620 for (;;) {
2621 struct blame_entry *next = ent->next;
2622 if (sb->found_guilty_entry)
2623 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
2624 if (next) {
2625 ent = next;
2626 continue;
2628 ent->next = sb->ent;
2629 sb->ent = suspect->suspects;
2630 suspect->suspects = NULL;
2631 break;
2634 blame_origin_decref(suspect);
2636 if (sb->debug) /* sanity */
2637 sanity_check_refcnt(sb);
2642 * To allow quick access to the contents of nth line in the
2643 * final image, prepare an index in the scoreboard.
2645 static int prepare_lines(struct blame_scoreboard *sb)
2647 sb->num_lines = find_line_starts(&sb->lineno, sb->final_buf,
2648 sb->final_buf_size);
2649 return sb->num_lines;
2652 static struct commit *find_single_final(struct rev_info *revs,
2653 const char **name_p)
2655 int i;
2656 struct commit *found = NULL;
2657 const char *name = NULL;
2659 for (i = 0; i < revs->pending.nr; i++) {
2660 struct object *obj = revs->pending.objects[i].item;
2661 if (obj->flags & UNINTERESTING)
2662 continue;
2663 obj = deref_tag(revs->repo, obj, NULL, 0);
2664 if (!obj || obj->type != OBJ_COMMIT)
2665 die("Non commit %s?", revs->pending.objects[i].name);
2666 if (found)
2667 die("More than one commit to dig from %s and %s?",
2668 revs->pending.objects[i].name, name);
2669 found = (struct commit *)obj;
2670 name = revs->pending.objects[i].name;
2672 if (name_p)
2673 *name_p = xstrdup_or_null(name);
2674 return found;
2677 static struct commit *dwim_reverse_initial(struct rev_info *revs,
2678 const char **name_p)
2681 * DWIM "git blame --reverse ONE -- PATH" as
2682 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2683 * when it makes sense.
2685 struct object *obj;
2686 struct commit *head_commit;
2687 struct object_id head_oid;
2689 if (revs->pending.nr != 1)
2690 return NULL;
2692 /* Is that sole rev a committish? */
2693 obj = revs->pending.objects[0].item;
2694 obj = deref_tag(revs->repo, obj, NULL, 0);
2695 if (!obj || obj->type != OBJ_COMMIT)
2696 return NULL;
2698 /* Do we have HEAD? */
2699 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
2700 return NULL;
2701 head_commit = lookup_commit_reference_gently(revs->repo,
2702 &head_oid, 1);
2703 if (!head_commit)
2704 return NULL;
2706 /* Turn "ONE" into "ONE..HEAD" then */
2707 obj->flags |= UNINTERESTING;
2708 add_pending_object(revs, &head_commit->object, "HEAD");
2710 if (name_p)
2711 *name_p = revs->pending.objects[0].name;
2712 return (struct commit *)obj;
2715 static struct commit *find_single_initial(struct rev_info *revs,
2716 const char **name_p)
2718 int i;
2719 struct commit *found = NULL;
2720 const char *name = NULL;
2723 * There must be one and only one negative commit, and it must be
2724 * the boundary.
2726 for (i = 0; i < revs->pending.nr; i++) {
2727 struct object *obj = revs->pending.objects[i].item;
2728 if (!(obj->flags & UNINTERESTING))
2729 continue;
2730 obj = deref_tag(revs->repo, obj, NULL, 0);
2731 if (!obj || obj->type != OBJ_COMMIT)
2732 die("Non commit %s?", revs->pending.objects[i].name);
2733 if (found)
2734 die("More than one commit to dig up from, %s and %s?",
2735 revs->pending.objects[i].name, name);
2736 found = (struct commit *) obj;
2737 name = revs->pending.objects[i].name;
2740 if (!name)
2741 found = dwim_reverse_initial(revs, &name);
2742 if (!name)
2743 die("No commit to dig up from?");
2745 if (name_p)
2746 *name_p = xstrdup(name);
2747 return found;
2750 void init_scoreboard(struct blame_scoreboard *sb)
2752 memset(sb, 0, sizeof(struct blame_scoreboard));
2753 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
2754 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
2757 void setup_scoreboard(struct blame_scoreboard *sb,
2758 struct blame_origin **orig)
2760 const char *final_commit_name = NULL;
2761 struct blame_origin *o;
2762 struct commit *final_commit = NULL;
2763 enum object_type type;
2765 init_blame_suspects(&blame_suspects);
2767 if (sb->reverse && sb->contents_from)
2768 die(_("--contents and --reverse do not blend well."));
2770 if (!sb->repo)
2771 BUG("repo is NULL");
2773 if (!sb->reverse) {
2774 sb->final = find_single_final(sb->revs, &final_commit_name);
2775 sb->commits.compare = compare_commits_by_commit_date;
2776 } else {
2777 sb->final = find_single_initial(sb->revs, &final_commit_name);
2778 sb->commits.compare = compare_commits_by_reverse_commit_date;
2781 if (sb->reverse && sb->revs->first_parent_only)
2782 sb->revs->children.name = NULL;
2784 if (sb->contents_from || !sb->final) {
2785 struct object_id head_oid, *parent_oid;
2788 * Build a fake commit at the top of the history, when
2789 * (1) "git blame [^A] --path", i.e. with no positive end
2790 * of the history range, in which case we build such
2791 * a fake commit on top of the HEAD to blame in-tree
2792 * modifications.
2793 * (2) "git blame --contents=file [A] -- path", with or
2794 * without positive end of the history range but with
2795 * --contents, in which case we pretend that there is
2796 * a fake commit on top of the positive end (defaulting to
2797 * HEAD) that has the given contents in the path.
2799 if (sb->final) {
2800 parent_oid = &sb->final->object.oid;
2801 } else {
2802 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
2803 die("no such ref: HEAD");
2804 parent_oid = &head_oid;
2807 setup_work_tree();
2808 sb->final = fake_working_tree_commit(sb->repo,
2809 &sb->revs->diffopt,
2810 sb->path, sb->contents_from,
2811 parent_oid);
2812 add_pending_object(sb->revs, &(sb->final->object), ":");
2815 if (sb->reverse && sb->revs->first_parent_only) {
2816 final_commit = find_single_final(sb->revs, NULL);
2817 if (!final_commit)
2818 die(_("--reverse and --first-parent together require specified latest commit"));
2822 * If we have bottom, this will mark the ancestors of the
2823 * bottom commits we would reach while traversing as
2824 * uninteresting.
2826 if (prepare_revision_walk(sb->revs))
2827 die(_("revision walk setup failed"));
2829 if (sb->reverse && sb->revs->first_parent_only) {
2830 struct commit *c = final_commit;
2832 sb->revs->children.name = "children";
2833 while (c->parents &&
2834 !oideq(&c->object.oid, &sb->final->object.oid)) {
2835 struct commit_list *l = xcalloc(1, sizeof(*l));
2837 l->item = c;
2838 if (add_decoration(&sb->revs->children,
2839 &c->parents->item->object, l))
2840 BUG("not unique item in first-parent chain");
2841 c = c->parents->item;
2844 if (!oideq(&c->object.oid, &sb->final->object.oid))
2845 die(_("--reverse --first-parent together require range along first-parent chain"));
2848 if (is_null_oid(&sb->final->object.oid)) {
2849 o = get_blame_suspects(sb->final);
2850 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
2851 sb->final_buf_size = o->file.size;
2853 else {
2854 o = get_origin(sb->final, sb->path);
2855 if (fill_blob_sha1_and_mode(sb->repo, o))
2856 die(_("no such path %s in %s"), sb->path, final_commit_name);
2858 if (sb->revs->diffopt.flags.allow_textconv &&
2859 textconv_object(sb->repo, sb->path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
2860 &sb->final_buf_size))
2862 else
2863 sb->final_buf = repo_read_object_file(the_repository,
2864 &o->blob_oid,
2865 &type,
2866 &sb->final_buf_size);
2868 if (!sb->final_buf)
2869 die(_("cannot read blob %s for path %s"),
2870 oid_to_hex(&o->blob_oid),
2871 sb->path);
2873 sb->num_read_blob++;
2874 prepare_lines(sb);
2876 if (orig)
2877 *orig = o;
2879 free((char *)final_commit_name);
2884 struct blame_entry *blame_entry_prepend(struct blame_entry *head,
2885 long start, long end,
2886 struct blame_origin *o)
2888 struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
2889 new_head->lno = start;
2890 new_head->num_lines = end - start;
2891 new_head->suspect = o;
2892 new_head->s_lno = start;
2893 new_head->next = head;
2894 blame_origin_incref(o);
2895 return new_head;
2898 void setup_blame_bloom_data(struct blame_scoreboard *sb)
2900 struct blame_bloom_data *bd;
2901 struct bloom_filter_settings *bs;
2903 if (!sb->repo->objects->commit_graph)
2904 return;
2906 bs = get_bloom_filter_settings(sb->repo);
2907 if (!bs)
2908 return;
2910 bd = xmalloc(sizeof(struct blame_bloom_data));
2912 bd->settings = bs;
2914 bd->alloc = 4;
2915 bd->nr = 0;
2916 ALLOC_ARRAY(bd->keys, bd->alloc);
2918 add_bloom_key(bd, sb->path);
2920 sb->bloom_data = bd;
2923 void cleanup_scoreboard(struct blame_scoreboard *sb)
2925 if (sb->bloom_data) {
2926 int i;
2927 for (i = 0; i < sb->bloom_data->nr; i++) {
2928 free(sb->bloom_data->keys[i]->hashes);
2929 free(sb->bloom_data->keys[i]);
2931 free(sb->bloom_data->keys);
2932 FREE_AND_NULL(sb->bloom_data);
2934 trace2_data_intmax("blame", sb->repo,
2935 "bloom/queries", bloom_count_queries);
2936 trace2_data_intmax("blame", sb->repo,
2937 "bloom/response-no", bloom_count_no);