Merge branch 'jk/blame-contents-with-arbitrary-commit'
[alt-git.git] / blame.c
blob63ce7eb6301a92c785fdfebf16d5452be437a623
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 "hex.h"
9 #include "tag.h"
10 #include "blame.h"
11 #include "alloc.h"
12 #include "commit-slab.h"
13 #include "bloom.h"
14 #include "commit-graph.h"
16 define_commit_slab(blame_suspects, struct blame_origin *);
17 static struct blame_suspects blame_suspects;
19 struct blame_origin *get_blame_suspects(struct commit *commit)
21 struct blame_origin **result;
23 result = blame_suspects_peek(&blame_suspects, commit);
25 return result ? *result : NULL;
28 static void set_blame_suspects(struct commit *commit, struct blame_origin *origin)
30 *blame_suspects_at(&blame_suspects, commit) = origin;
33 void blame_origin_decref(struct blame_origin *o)
35 if (o && --o->refcnt <= 0) {
36 struct blame_origin *p, *l = NULL;
37 if (o->previous)
38 blame_origin_decref(o->previous);
39 free(o->file.ptr);
40 /* Should be present exactly once in commit chain */
41 for (p = get_blame_suspects(o->commit); p; l = p, p = p->next) {
42 if (p == o) {
43 if (l)
44 l->next = p->next;
45 else
46 set_blame_suspects(o->commit, p->next);
47 free(o);
48 return;
51 die("internal error in blame_origin_decref");
56 * Given a commit and a path in it, create a new origin structure.
57 * The callers that add blame to the scoreboard should use
58 * get_origin() to obtain shared, refcounted copy instead of calling
59 * this function directly.
61 static struct blame_origin *make_origin(struct commit *commit, const char *path)
63 struct blame_origin *o;
64 FLEX_ALLOC_STR(o, path, path);
65 o->commit = commit;
66 o->refcnt = 1;
67 o->next = get_blame_suspects(commit);
68 set_blame_suspects(commit, o);
69 return o;
73 * Locate an existing origin or create a new one.
74 * This moves the origin to front position in the commit util list.
76 static struct blame_origin *get_origin(struct commit *commit, const char *path)
78 struct blame_origin *o, *l;
80 for (o = get_blame_suspects(commit), l = NULL; o; l = o, o = o->next) {
81 if (!strcmp(o->path, path)) {
82 /* bump to front */
83 if (l) {
84 l->next = o->next;
85 o->next = get_blame_suspects(commit);
86 set_blame_suspects(commit, o);
88 return blame_origin_incref(o);
91 return make_origin(commit, path);
96 static void verify_working_tree_path(struct repository *r,
97 struct commit *work_tree, const char *path)
99 struct commit_list *parents;
100 int pos;
102 for (parents = work_tree->parents; parents; parents = parents->next) {
103 const struct object_id *commit_oid = &parents->item->object.oid;
104 struct object_id blob_oid;
105 unsigned short mode;
107 if (!get_tree_entry(r, commit_oid, path, &blob_oid, &mode) &&
108 oid_object_info(r, &blob_oid, NULL) == OBJ_BLOB)
109 return;
112 pos = index_name_pos(r->index, path, strlen(path));
113 if (pos >= 0)
114 ; /* path is in the index */
115 else if (-1 - pos < r->index->cache_nr &&
116 !strcmp(r->index->cache[-1 - pos]->name, path))
117 ; /* path is in the index, unmerged */
118 else
119 die("no such path '%s' in HEAD", path);
122 static struct commit_list **append_parent(struct repository *r,
123 struct commit_list **tail,
124 const struct object_id *oid)
126 struct commit *parent;
128 parent = lookup_commit_reference(r, oid);
129 if (!parent)
130 die("no such commit %s", oid_to_hex(oid));
131 return &commit_list_insert(parent, tail)->next;
134 static void append_merge_parents(struct repository *r,
135 struct commit_list **tail)
137 int merge_head;
138 struct strbuf line = STRBUF_INIT;
140 merge_head = open(git_path_merge_head(r), O_RDONLY);
141 if (merge_head < 0) {
142 if (errno == ENOENT)
143 return;
144 die("cannot open '%s' for reading",
145 git_path_merge_head(r));
148 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
149 struct object_id oid;
150 if (get_oid_hex(line.buf, &oid))
151 die("unknown line in '%s': %s",
152 git_path_merge_head(r), line.buf);
153 tail = append_parent(r, tail, &oid);
155 close(merge_head);
156 strbuf_release(&line);
160 * This isn't as simple as passing sb->buf and sb->len, because we
161 * want to transfer ownership of the buffer to the commit (so we
162 * must use detach).
164 static void set_commit_buffer_from_strbuf(struct repository *r,
165 struct commit *c,
166 struct strbuf *sb)
168 size_t len;
169 void *buf = strbuf_detach(sb, &len);
170 set_commit_buffer(r, c, buf, len);
174 * Prepare a dummy commit that represents the work tree (or staged) item.
175 * Note that annotating work tree item never works in the reverse.
177 static struct commit *fake_working_tree_commit(struct repository *r,
178 struct diff_options *opt,
179 const char *path,
180 const char *contents_from,
181 struct object_id *oid)
183 struct commit *commit;
184 struct blame_origin *origin;
185 struct commit_list **parent_tail, *parent;
186 struct strbuf buf = STRBUF_INIT;
187 const char *ident;
188 time_t now;
189 int len;
190 struct cache_entry *ce;
191 unsigned mode;
192 struct strbuf msg = STRBUF_INIT;
194 repo_read_index(r);
195 time(&now);
196 commit = alloc_commit_node(r);
197 commit->object.parsed = 1;
198 commit->date = now;
199 parent_tail = &commit->parents;
201 parent_tail = append_parent(r, parent_tail, oid);
202 append_merge_parents(r, parent_tail);
203 verify_working_tree_path(r, commit, path);
205 origin = make_origin(commit, path);
207 ident = fmt_ident("Not Committed Yet", "not.committed.yet",
208 WANT_BLANK_IDENT, NULL, 0);
209 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
210 for (parent = commit->parents; parent; parent = parent->next)
211 strbuf_addf(&msg, "parent %s\n",
212 oid_to_hex(&parent->item->object.oid));
213 strbuf_addf(&msg,
214 "author %s\n"
215 "committer %s\n\n"
216 "Version of %s from %s\n",
217 ident, ident, path,
218 (!contents_from ? path :
219 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
220 set_commit_buffer_from_strbuf(r, commit, &msg);
222 if (!contents_from || strcmp("-", contents_from)) {
223 struct stat st;
224 const char *read_from;
225 char *buf_ptr;
226 unsigned long buf_len;
228 if (contents_from) {
229 if (stat(contents_from, &st) < 0)
230 die_errno("Cannot stat '%s'", contents_from);
231 read_from = contents_from;
233 else {
234 if (lstat(path, &st) < 0)
235 die_errno("Cannot lstat '%s'", path);
236 read_from = path;
238 mode = canon_mode(st.st_mode);
240 switch (st.st_mode & S_IFMT) {
241 case S_IFREG:
242 if (opt->flags.allow_textconv &&
243 textconv_object(r, read_from, mode, null_oid(), 0, &buf_ptr, &buf_len))
244 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
245 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
246 die_errno("cannot open or read '%s'", read_from);
247 break;
248 case S_IFLNK:
249 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
250 die_errno("cannot readlink '%s'", read_from);
251 break;
252 default:
253 die("unsupported file type %s", read_from);
256 else {
257 /* Reading from stdin */
258 mode = 0;
259 if (strbuf_read(&buf, 0, 0) < 0)
260 die_errno("failed to read from stdin");
262 convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
263 origin->file.ptr = buf.buf;
264 origin->file.size = buf.len;
265 pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
268 * Read the current index, replace the path entry with
269 * origin->blob_sha1 without mucking with its mode or type
270 * bits; we are not going to write this index out -- we just
271 * want to run "diff-index --cached".
273 discard_index(r->index);
274 repo_read_index(r);
276 len = strlen(path);
277 if (!mode) {
278 int pos = index_name_pos(r->index, path, len);
279 if (0 <= pos)
280 mode = r->index->cache[pos]->ce_mode;
281 else
282 /* Let's not bother reading from HEAD tree */
283 mode = S_IFREG | 0644;
285 ce = make_empty_cache_entry(r->index, len);
286 oidcpy(&ce->oid, &origin->blob_oid);
287 memcpy(ce->name, path, len);
288 ce->ce_flags = create_ce_flags(0);
289 ce->ce_namelen = len;
290 ce->ce_mode = create_ce_mode(mode);
291 add_index_entry(r->index, ce,
292 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
294 cache_tree_invalidate_path(r->index, path);
296 return commit;
301 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
302 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
304 xpparam_t xpp = {0};
305 xdemitconf_t xecfg = {0};
306 xdemitcb_t ecb = {NULL};
308 xpp.flags = xdl_opts;
309 xecfg.hunk_func = hunk_func;
310 ecb.priv = cb_data;
311 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
314 static const char *get_next_line(const char *start, const char *end)
316 const char *nl = memchr(start, '\n', end - start);
318 return nl ? nl + 1 : end;
321 static int find_line_starts(int **line_starts, const char *buf,
322 unsigned long len)
324 const char *end = buf + len;
325 const char *p;
326 int *lineno;
327 int num = 0;
329 for (p = buf; p < end; p = get_next_line(p, end))
330 num++;
332 ALLOC_ARRAY(*line_starts, num + 1);
333 lineno = *line_starts;
335 for (p = buf; p < end; p = get_next_line(p, end))
336 *lineno++ = p - buf;
338 *lineno = len;
340 return num;
343 struct fingerprint_entry;
345 /* A fingerprint is intended to loosely represent a string, such that two
346 * fingerprints can be quickly compared to give an indication of the similarity
347 * of the strings that they represent.
349 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
350 * the string that it represents. Whitespace is added at each end of the
351 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
352 * For example, the string "Darth Radar" will be converted to the following
353 * fingerprint:
354 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
356 * The similarity between two fingerprints is the size of the intersection of
357 * their multisets, including repeated elements. See fingerprint_similarity for
358 * examples.
360 * For ease of implementation, the fingerprint is implemented as a map
361 * of byte pairs to the count of that byte pair in the string, instead of
362 * allowing repeated elements in a set.
364 struct fingerprint {
365 struct hashmap map;
366 /* As we know the maximum number of entries in advance, it's
367 * convenient to store the entries in a single array instead of having
368 * the hashmap manage the memory.
370 struct fingerprint_entry *entries;
373 /* A byte pair in a fingerprint. Stores the number of times the byte pair
374 * occurs in the string that the fingerprint represents.
376 struct fingerprint_entry {
377 /* The hashmap entry - the hash represents the byte pair in its
378 * entirety so we don't need to store the byte pair separately.
380 struct hashmap_entry entry;
381 /* The number of times the byte pair occurs in the string that the
382 * fingerprint represents.
384 int count;
387 /* See `struct fingerprint` for an explanation of what a fingerprint is.
388 * \param result the fingerprint of the string is stored here. This must be
389 * freed later using free_fingerprint.
390 * \param line_begin the start of the string
391 * \param line_end the end of the string
393 static void get_fingerprint(struct fingerprint *result,
394 const char *line_begin,
395 const char *line_end)
397 unsigned int hash, c0 = 0, c1;
398 const char *p;
399 int max_map_entry_count = 1 + line_end - line_begin;
400 struct fingerprint_entry *entry = xcalloc(max_map_entry_count,
401 sizeof(struct fingerprint_entry));
402 struct fingerprint_entry *found_entry;
404 hashmap_init(&result->map, NULL, NULL, max_map_entry_count);
405 result->entries = entry;
406 for (p = line_begin; p <= line_end; ++p, c0 = c1) {
407 /* Always terminate the string with whitespace.
408 * Normalise whitespace to 0, and normalise letters to
409 * lower case. This won't work for multibyte characters but at
410 * worst will match some unrelated characters.
412 if ((p == line_end) || isspace(*p))
413 c1 = 0;
414 else
415 c1 = tolower(*p);
416 hash = c0 | (c1 << 8);
417 /* Ignore whitespace pairs */
418 if (hash == 0)
419 continue;
420 hashmap_entry_init(&entry->entry, hash);
422 found_entry = hashmap_get_entry(&result->map, entry,
423 /* member name */ entry, NULL);
424 if (found_entry) {
425 found_entry->count += 1;
426 } else {
427 entry->count = 1;
428 hashmap_add(&result->map, &entry->entry);
429 ++entry;
434 static void free_fingerprint(struct fingerprint *f)
436 hashmap_clear(&f->map);
437 free(f->entries);
440 /* Calculates the similarity between two fingerprints as the size of the
441 * intersection of their multisets, including repeated elements. See
442 * `struct fingerprint` for an explanation of the fingerprint representation.
443 * The similarity between "cat mat" and "father rather" is 2 because "at" is
444 * present twice in both strings while the similarity between "tim" and "mit"
445 * is 0.
447 static int fingerprint_similarity(struct fingerprint *a, struct fingerprint *b)
449 int intersection = 0;
450 struct hashmap_iter iter;
451 const struct fingerprint_entry *entry_a, *entry_b;
453 hashmap_for_each_entry(&b->map, &iter, entry_b,
454 entry /* member name */) {
455 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
456 if (entry_a) {
457 intersection += entry_a->count < entry_b->count ?
458 entry_a->count : entry_b->count;
461 return intersection;
464 /* Subtracts byte-pair elements in B from A, modifying A in place.
466 static void fingerprint_subtract(struct fingerprint *a, struct fingerprint *b)
468 struct hashmap_iter iter;
469 struct fingerprint_entry *entry_a;
470 const struct fingerprint_entry *entry_b;
472 hashmap_iter_init(&b->map, &iter);
474 hashmap_for_each_entry(&b->map, &iter, entry_b,
475 entry /* member name */) {
476 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
477 if (entry_a) {
478 if (entry_a->count <= entry_b->count)
479 hashmap_remove(&a->map, &entry_b->entry, NULL);
480 else
481 entry_a->count -= entry_b->count;
486 /* Calculate fingerprints for a series of lines.
487 * Puts the fingerprints in the fingerprints array, which must have been
488 * preallocated to allow storing line_count elements.
490 static void get_line_fingerprints(struct fingerprint *fingerprints,
491 const char *content, const int *line_starts,
492 long first_line, long line_count)
494 int i;
495 const char *linestart, *lineend;
497 line_starts += first_line;
498 for (i = 0; i < line_count; ++i) {
499 linestart = content + line_starts[i];
500 lineend = content + line_starts[i + 1];
501 get_fingerprint(fingerprints + i, linestart, lineend);
505 static void free_line_fingerprints(struct fingerprint *fingerprints,
506 int nr_fingerprints)
508 int i;
510 for (i = 0; i < nr_fingerprints; i++)
511 free_fingerprint(&fingerprints[i]);
514 /* This contains the data necessary to linearly map a line number in one half
515 * of a diff chunk to the line in the other half of the diff chunk that is
516 * closest in terms of its position as a fraction of the length of the chunk.
518 struct line_number_mapping {
519 int destination_start, destination_length,
520 source_start, source_length;
523 /* Given a line number in one range, offset and scale it to map it onto the
524 * other range.
525 * Essentially this mapping is a simple linear equation but the calculation is
526 * more complicated to allow performing it with integer operations.
527 * Another complication is that if a line could map onto many lines in the
528 * destination range then we want to choose the line at the center of those
529 * possibilities.
530 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
531 * first 5 lines in B will map onto the first line in the A chunk, while the
532 * last 5 lines will all map onto the second line in the A chunk.
533 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
534 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
536 static int map_line_number(int line_number,
537 const struct line_number_mapping *mapping)
539 return ((line_number - mapping->source_start) * 2 + 1) *
540 mapping->destination_length /
541 (mapping->source_length * 2) +
542 mapping->destination_start;
545 /* Get a pointer to the element storing the similarity between a line in A
546 * and a line in B.
548 * The similarities are stored in a 2-dimensional array. Each "row" in the
549 * array contains the similarities for a line in B. The similarities stored in
550 * a row are the similarities between the line in B and the nearby lines in A.
551 * To keep the length of each row the same, it is padded out with values of -1
552 * where the search range extends beyond the lines in A.
553 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
554 * look like this:
555 * a | m
556 * b | n
557 * c | o
558 * d | p
559 * e | q
560 * Then the similarity array will contain:
561 * [-1, -1, am, bm, cm,
562 * -1, an, bn, cn, dn,
563 * ao, bo, co, do, eo,
564 * bp, cp, dp, ep, -1,
565 * cq, dq, eq, -1, -1]
566 * Where similarities are denoted either by -1 for invalid, or the
567 * concatenation of the two lines in the diff being compared.
569 * \param similarities array of similarities between lines in A and B
570 * \param line_a the index of the line in A, in the same frame of reference as
571 * closest_line_a.
572 * \param local_line_b the index of the line in B, relative to the first line
573 * in B that similarities represents.
574 * \param closest_line_a the index of the line in A that is deemed to be
575 * closest to local_line_b. This must be in the same
576 * frame of reference as line_a. This value defines
577 * where similarities is centered for the line in B.
578 * \param max_search_distance_a maximum distance in lines from the closest line
579 * in A for other lines in A for which
580 * similarities may be calculated.
582 static int *get_similarity(int *similarities,
583 int line_a, int local_line_b,
584 int closest_line_a, int max_search_distance_a)
586 assert(abs(line_a - closest_line_a) <=
587 max_search_distance_a);
588 return similarities + line_a - closest_line_a +
589 max_search_distance_a +
590 local_line_b * (max_search_distance_a * 2 + 1);
593 #define CERTAIN_NOTHING_MATCHES -2
594 #define CERTAINTY_NOT_CALCULATED -1
596 /* Given a line in B, first calculate its similarities with nearby lines in A
597 * if not already calculated, then identify the most similar and second most
598 * similar lines. The "certainty" is calculated based on those two
599 * similarities.
601 * \param start_a the index of the first line of the chunk in A
602 * \param length_a the length in lines of the chunk in A
603 * \param local_line_b the index of the line in B, relative to the first line
604 * in the chunk.
605 * \param fingerprints_a array of fingerprints for the chunk in A
606 * \param fingerprints_b array of fingerprints for the chunk in B
607 * \param similarities 2-dimensional array of similarities between lines in A
608 * and B. See get_similarity() for more details.
609 * \param certainties array of values indicating how strongly a line in B is
610 * matched with some line in A.
611 * \param second_best_result array of absolute indices in A for the second
612 * closest match of a line in B.
613 * \param result array of absolute indices in A for the closest match of a line
614 * in B.
615 * \param max_search_distance_a maximum distance in lines from the closest line
616 * in A for other lines in A for which
617 * similarities may be calculated.
618 * \param map_line_number_in_b_to_a parameter to map_line_number().
620 static void find_best_line_matches(
621 int start_a,
622 int length_a,
623 int start_b,
624 int local_line_b,
625 struct fingerprint *fingerprints_a,
626 struct fingerprint *fingerprints_b,
627 int *similarities,
628 int *certainties,
629 int *second_best_result,
630 int *result,
631 const int max_search_distance_a,
632 const struct line_number_mapping *map_line_number_in_b_to_a)
635 int i, search_start, search_end, closest_local_line_a, *similarity,
636 best_similarity = 0, second_best_similarity = 0,
637 best_similarity_index = 0, second_best_similarity_index = 0;
639 /* certainty has already been calculated so no need to redo the work */
640 if (certainties[local_line_b] != CERTAINTY_NOT_CALCULATED)
641 return;
643 closest_local_line_a = map_line_number(
644 local_line_b + start_b, map_line_number_in_b_to_a) - start_a;
646 search_start = closest_local_line_a - max_search_distance_a;
647 if (search_start < 0)
648 search_start = 0;
650 search_end = closest_local_line_a + max_search_distance_a + 1;
651 if (search_end > length_a)
652 search_end = length_a;
654 for (i = search_start; i < search_end; ++i) {
655 similarity = get_similarity(similarities,
656 i, local_line_b,
657 closest_local_line_a,
658 max_search_distance_a);
659 if (*similarity == -1) {
660 /* This value will never exceed 10 but assert just in
661 * case
663 assert(abs(i - closest_local_line_a) < 1000);
664 /* scale the similarity by (1000 - distance from
665 * closest line) to act as a tie break between lines
666 * that otherwise are equally similar.
668 *similarity = fingerprint_similarity(
669 fingerprints_b + local_line_b,
670 fingerprints_a + i) *
671 (1000 - abs(i - closest_local_line_a));
673 if (*similarity > best_similarity) {
674 second_best_similarity = best_similarity;
675 second_best_similarity_index = best_similarity_index;
676 best_similarity = *similarity;
677 best_similarity_index = i;
678 } else if (*similarity > second_best_similarity) {
679 second_best_similarity = *similarity;
680 second_best_similarity_index = i;
684 if (best_similarity == 0) {
685 /* this line definitely doesn't match with anything. Mark it
686 * with this special value so it doesn't get invalidated and
687 * won't be recalculated.
689 certainties[local_line_b] = CERTAIN_NOTHING_MATCHES;
690 result[local_line_b] = -1;
691 } else {
692 /* Calculate the certainty with which this line matches.
693 * If the line matches well with two lines then that reduces
694 * the certainty. However we still want to prioritise matching
695 * a line that matches very well with two lines over matching a
696 * line that matches poorly with one line, hence doubling
697 * best_similarity.
698 * This means that if we have
699 * line X that matches only one line with a score of 3,
700 * line Y that matches two lines equally with a score of 5,
701 * and line Z that matches only one line with a score or 2,
702 * then the lines in order of certainty are X, Y, Z.
704 certainties[local_line_b] = best_similarity * 2 -
705 second_best_similarity;
707 /* We keep both the best and second best results to allow us to
708 * check at a later stage of the matching process whether the
709 * result needs to be invalidated.
711 result[local_line_b] = start_a + best_similarity_index;
712 second_best_result[local_line_b] =
713 start_a + second_best_similarity_index;
718 * This finds the line that we can match with the most confidence, and
719 * uses it as a partition. It then calls itself on the lines on either side of
720 * that partition. In this way we avoid lines appearing out of order, and
721 * retain a sensible line ordering.
722 * \param start_a index of the first line in A with which lines in B may be
723 * compared.
724 * \param start_b index of the first line in B for which matching should be
725 * done.
726 * \param length_a number of lines in A with which lines in B may be compared.
727 * \param length_b number of lines in B for which matching should be done.
728 * \param fingerprints_a mutable array of fingerprints in A. The first element
729 * corresponds to the line at start_a.
730 * \param fingerprints_b array of fingerprints in B. The first element
731 * corresponds to the line at start_b.
732 * \param similarities 2-dimensional array of similarities between lines in A
733 * and B. See get_similarity() for more details.
734 * \param certainties array of values indicating how strongly a line in B is
735 * matched with some line in A.
736 * \param second_best_result array of absolute indices in A for the second
737 * closest match of a line in B.
738 * \param result array of absolute indices in A for the closest match of a line
739 * in B.
740 * \param max_search_distance_a maximum distance in lines from the closest line
741 * in A for other lines in A for which
742 * similarities may be calculated.
743 * \param max_search_distance_b an upper bound on the greatest possible
744 * distance between lines in B such that they will
745 * both be compared with the same line in A
746 * according to max_search_distance_a.
747 * \param map_line_number_in_b_to_a parameter to map_line_number().
749 static void fuzzy_find_matching_lines_recurse(
750 int start_a, int start_b,
751 int length_a, int length_b,
752 struct fingerprint *fingerprints_a,
753 struct fingerprint *fingerprints_b,
754 int *similarities,
755 int *certainties,
756 int *second_best_result,
757 int *result,
758 int max_search_distance_a,
759 int max_search_distance_b,
760 const struct line_number_mapping *map_line_number_in_b_to_a)
762 int i, invalidate_min, invalidate_max, offset_b,
763 second_half_start_a, second_half_start_b,
764 second_half_length_a, second_half_length_b,
765 most_certain_line_a, most_certain_local_line_b = -1,
766 most_certain_line_certainty = -1,
767 closest_local_line_a;
769 for (i = 0; i < length_b; ++i) {
770 find_best_line_matches(start_a,
771 length_a,
772 start_b,
774 fingerprints_a,
775 fingerprints_b,
776 similarities,
777 certainties,
778 second_best_result,
779 result,
780 max_search_distance_a,
781 map_line_number_in_b_to_a);
783 if (certainties[i] > most_certain_line_certainty) {
784 most_certain_line_certainty = certainties[i];
785 most_certain_local_line_b = i;
789 /* No matches. */
790 if (most_certain_local_line_b == -1)
791 return;
793 most_certain_line_a = result[most_certain_local_line_b];
796 * Subtract the most certain line's fingerprint in B from the matched
797 * fingerprint in A. This means that other lines in B can't also match
798 * the same parts of the line in A.
800 fingerprint_subtract(fingerprints_a + most_certain_line_a - start_a,
801 fingerprints_b + most_certain_local_line_b);
803 /* Invalidate results that may be affected by the choice of most
804 * certain line.
806 invalidate_min = most_certain_local_line_b - max_search_distance_b;
807 invalidate_max = most_certain_local_line_b + max_search_distance_b + 1;
808 if (invalidate_min < 0)
809 invalidate_min = 0;
810 if (invalidate_max > length_b)
811 invalidate_max = length_b;
813 /* As the fingerprint in A has changed, discard previously calculated
814 * similarity values with that fingerprint.
816 for (i = invalidate_min; i < invalidate_max; ++i) {
817 closest_local_line_a = map_line_number(
818 i + start_b, map_line_number_in_b_to_a) - start_a;
820 /* Check that the lines in A and B are close enough that there
821 * is a similarity value for them.
823 if (abs(most_certain_line_a - start_a - closest_local_line_a) >
824 max_search_distance_a) {
825 continue;
828 *get_similarity(similarities, most_certain_line_a - start_a,
829 i, closest_local_line_a,
830 max_search_distance_a) = -1;
833 /* More invalidating of results that may be affected by the choice of
834 * most certain line.
835 * Discard the matches for lines in B that are currently matched with a
836 * line in A such that their ordering contradicts the ordering imposed
837 * by the choice of most certain line.
839 for (i = most_certain_local_line_b - 1; i >= invalidate_min; --i) {
840 /* In this loop we discard results for lines in B that are
841 * before most-certain-line-B but are matched with a line in A
842 * that is after most-certain-line-A.
844 if (certainties[i] >= 0 &&
845 (result[i] >= most_certain_line_a ||
846 second_best_result[i] >= most_certain_line_a)) {
847 certainties[i] = CERTAINTY_NOT_CALCULATED;
850 for (i = most_certain_local_line_b + 1; i < invalidate_max; ++i) {
851 /* In this loop we discard results for lines in B that are
852 * after most-certain-line-B but are matched with a line in A
853 * that is before most-certain-line-A.
855 if (certainties[i] >= 0 &&
856 (result[i] <= most_certain_line_a ||
857 second_best_result[i] <= most_certain_line_a)) {
858 certainties[i] = CERTAINTY_NOT_CALCULATED;
862 /* Repeat the matching process for lines before the most certain line.
864 if (most_certain_local_line_b > 0) {
865 fuzzy_find_matching_lines_recurse(
866 start_a, start_b,
867 most_certain_line_a + 1 - start_a,
868 most_certain_local_line_b,
869 fingerprints_a, fingerprints_b, similarities,
870 certainties, second_best_result, result,
871 max_search_distance_a,
872 max_search_distance_b,
873 map_line_number_in_b_to_a);
875 /* Repeat the matching process for lines after the most certain line.
877 if (most_certain_local_line_b + 1 < length_b) {
878 second_half_start_a = most_certain_line_a;
879 offset_b = most_certain_local_line_b + 1;
880 second_half_start_b = start_b + offset_b;
881 second_half_length_a =
882 length_a + start_a - second_half_start_a;
883 second_half_length_b =
884 length_b + start_b - second_half_start_b;
885 fuzzy_find_matching_lines_recurse(
886 second_half_start_a, second_half_start_b,
887 second_half_length_a, second_half_length_b,
888 fingerprints_a + second_half_start_a - start_a,
889 fingerprints_b + offset_b,
890 similarities +
891 offset_b * (max_search_distance_a * 2 + 1),
892 certainties + offset_b,
893 second_best_result + offset_b, result + offset_b,
894 max_search_distance_a,
895 max_search_distance_b,
896 map_line_number_in_b_to_a);
900 /* Find the lines in the parent line range that most closely match the lines in
901 * the target line range. This is accomplished by matching fingerprints in each
902 * blame_origin, and choosing the best matches that preserve the line ordering.
903 * See struct fingerprint for details of fingerprint matching, and
904 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
906 * The performance is believed to be O(n log n) in the typical case and O(n^2)
907 * in a pathological case, where n is the number of lines in the target range.
909 static int *fuzzy_find_matching_lines(struct blame_origin *parent,
910 struct blame_origin *target,
911 int tlno, int parent_slno, int same,
912 int parent_len)
914 /* We use the terminology "A" for the left hand side of the diff AKA
915 * parent, and "B" for the right hand side of the diff AKA target. */
916 int start_a = parent_slno;
917 int length_a = parent_len;
918 int start_b = tlno;
919 int length_b = same - tlno;
921 struct line_number_mapping map_line_number_in_b_to_a = {
922 start_a, length_a, start_b, length_b
925 struct fingerprint *fingerprints_a = parent->fingerprints;
926 struct fingerprint *fingerprints_b = target->fingerprints;
928 int i, *result, *second_best_result,
929 *certainties, *similarities, similarity_count;
932 * max_search_distance_a means that given a line in B, compare it to
933 * the line in A that is closest to its position, and the lines in A
934 * that are no greater than max_search_distance_a lines away from the
935 * closest line in A.
937 * max_search_distance_b is an upper bound on the greatest possible
938 * distance between lines in B such that they will both be compared
939 * with the same line in A according to max_search_distance_a.
941 int max_search_distance_a = 10, max_search_distance_b;
943 if (length_a <= 0)
944 return NULL;
946 if (max_search_distance_a >= length_a)
947 max_search_distance_a = length_a ? length_a - 1 : 0;
949 max_search_distance_b = ((2 * max_search_distance_a + 1) * length_b
950 - 1) / length_a;
952 CALLOC_ARRAY(result, length_b);
953 CALLOC_ARRAY(second_best_result, length_b);
954 CALLOC_ARRAY(certainties, length_b);
956 /* See get_similarity() for details of similarities. */
957 similarity_count = length_b * (max_search_distance_a * 2 + 1);
958 CALLOC_ARRAY(similarities, similarity_count);
960 for (i = 0; i < length_b; ++i) {
961 result[i] = -1;
962 second_best_result[i] = -1;
963 certainties[i] = CERTAINTY_NOT_CALCULATED;
966 for (i = 0; i < similarity_count; ++i)
967 similarities[i] = -1;
969 fuzzy_find_matching_lines_recurse(start_a, start_b,
970 length_a, length_b,
971 fingerprints_a + start_a,
972 fingerprints_b + start_b,
973 similarities,
974 certainties,
975 second_best_result,
976 result,
977 max_search_distance_a,
978 max_search_distance_b,
979 &map_line_number_in_b_to_a);
981 free(similarities);
982 free(certainties);
983 free(second_best_result);
985 return result;
988 static void fill_origin_fingerprints(struct blame_origin *o)
990 int *line_starts;
992 if (o->fingerprints)
993 return;
994 o->num_lines = find_line_starts(&line_starts, o->file.ptr,
995 o->file.size);
996 CALLOC_ARRAY(o->fingerprints, o->num_lines);
997 get_line_fingerprints(o->fingerprints, o->file.ptr, line_starts,
998 0, o->num_lines);
999 free(line_starts);
1002 static void drop_origin_fingerprints(struct blame_origin *o)
1004 if (o->fingerprints) {
1005 free_line_fingerprints(o->fingerprints, o->num_lines);
1006 o->num_lines = 0;
1007 FREE_AND_NULL(o->fingerprints);
1012 * Given an origin, prepare mmfile_t structure to be used by the
1013 * diff machinery
1015 static void fill_origin_blob(struct diff_options *opt,
1016 struct blame_origin *o, mmfile_t *file,
1017 int *num_read_blob, int fill_fingerprints)
1019 if (!o->file.ptr) {
1020 enum object_type type;
1021 unsigned long file_size;
1023 (*num_read_blob)++;
1024 if (opt->flags.allow_textconv &&
1025 textconv_object(opt->repo, o->path, o->mode,
1026 &o->blob_oid, 1, &file->ptr, &file_size))
1028 else
1029 file->ptr = read_object_file(&o->blob_oid, &type,
1030 &file_size);
1031 file->size = file_size;
1033 if (!file->ptr)
1034 die("Cannot read blob %s for path %s",
1035 oid_to_hex(&o->blob_oid),
1036 o->path);
1037 o->file = *file;
1039 else
1040 *file = o->file;
1041 if (fill_fingerprints)
1042 fill_origin_fingerprints(o);
1045 static void drop_origin_blob(struct blame_origin *o)
1047 FREE_AND_NULL(o->file.ptr);
1048 drop_origin_fingerprints(o);
1052 * Any merge of blames happens on lists of blames that arrived via
1053 * different parents in a single suspect. In this case, we want to
1054 * sort according to the suspect line numbers as opposed to the final
1055 * image line numbers. The function body is somewhat longish because
1056 * it avoids unnecessary writes.
1059 static struct blame_entry *blame_merge(struct blame_entry *list1,
1060 struct blame_entry *list2)
1062 struct blame_entry *p1 = list1, *p2 = list2,
1063 **tail = &list1;
1065 if (!p1)
1066 return p2;
1067 if (!p2)
1068 return p1;
1070 if (p1->s_lno <= p2->s_lno) {
1071 do {
1072 tail = &p1->next;
1073 if (!(p1 = *tail)) {
1074 *tail = p2;
1075 return list1;
1077 } while (p1->s_lno <= p2->s_lno);
1079 for (;;) {
1080 *tail = p2;
1081 do {
1082 tail = &p2->next;
1083 if (!(p2 = *tail)) {
1084 *tail = p1;
1085 return list1;
1087 } while (p1->s_lno > p2->s_lno);
1088 *tail = p1;
1089 do {
1090 tail = &p1->next;
1091 if (!(p1 = *tail)) {
1092 *tail = p2;
1093 return list1;
1095 } while (p1->s_lno <= p2->s_lno);
1099 DEFINE_LIST_SORT(static, sort_blame_entries, struct blame_entry, next);
1102 * Final image line numbers are all different, so we don't need a
1103 * three-way comparison here.
1106 static int compare_blame_final(const struct blame_entry *e1,
1107 const struct blame_entry *e2)
1109 return e1->lno > e2->lno ? 1 : -1;
1112 static int compare_blame_suspect(const struct blame_entry *s1,
1113 const struct blame_entry *s2)
1116 * to allow for collating suspects, we sort according to the
1117 * respective pointer value as the primary sorting criterion.
1118 * The actual relation is pretty unimportant as long as it
1119 * establishes a total order. Comparing as integers gives us
1120 * that.
1122 if (s1->suspect != s2->suspect)
1123 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
1124 if (s1->s_lno == s2->s_lno)
1125 return 0;
1126 return s1->s_lno > s2->s_lno ? 1 : -1;
1129 void blame_sort_final(struct blame_scoreboard *sb)
1131 sort_blame_entries(&sb->ent, compare_blame_final);
1134 static int compare_commits_by_reverse_commit_date(const void *a,
1135 const void *b,
1136 void *c)
1138 return -compare_commits_by_commit_date(a, b, c);
1142 * For debugging -- origin is refcounted, and this asserts that
1143 * we do not underflow.
1145 static void sanity_check_refcnt(struct blame_scoreboard *sb)
1147 int baa = 0;
1148 struct blame_entry *ent;
1150 for (ent = sb->ent; ent; ent = ent->next) {
1151 /* Nobody should have zero or negative refcnt */
1152 if (ent->suspect->refcnt <= 0) {
1153 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1154 ent->suspect->path,
1155 oid_to_hex(&ent->suspect->commit->object.oid),
1156 ent->suspect->refcnt);
1157 baa = 1;
1160 if (baa)
1161 sb->on_sanity_fail(sb, baa);
1165 * If two blame entries that are next to each other came from
1166 * contiguous lines in the same origin (i.e. <commit, path> pair),
1167 * merge them together.
1169 void blame_coalesce(struct blame_scoreboard *sb)
1171 struct blame_entry *ent, *next;
1173 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
1174 if (ent->suspect == next->suspect &&
1175 ent->s_lno + ent->num_lines == next->s_lno &&
1176 ent->lno + ent->num_lines == next->lno &&
1177 ent->ignored == next->ignored &&
1178 ent->unblamable == next->unblamable) {
1179 ent->num_lines += next->num_lines;
1180 ent->next = next->next;
1181 blame_origin_decref(next->suspect);
1182 free(next);
1183 ent->score = 0;
1184 next = ent; /* again */
1188 if (sb->debug) /* sanity */
1189 sanity_check_refcnt(sb);
1193 * Merge the given sorted list of blames into a preexisting origin.
1194 * If there were no previous blames to that commit, it is entered into
1195 * the commit priority queue of the score board.
1198 static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
1199 struct blame_entry *sorted)
1201 if (porigin->suspects)
1202 porigin->suspects = blame_merge(porigin->suspects, sorted);
1203 else {
1204 struct blame_origin *o;
1205 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
1206 if (o->suspects) {
1207 porigin->suspects = sorted;
1208 return;
1211 porigin->suspects = sorted;
1212 prio_queue_put(&sb->commits, porigin->commit);
1217 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1218 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1219 * for an origin is also used to pass the blame for the entire file to
1220 * the parent to detect the case where a child's blob is identical to
1221 * that of its parent's.
1223 * This also fills origin->mode for corresponding tree path.
1225 static int fill_blob_sha1_and_mode(struct repository *r,
1226 struct blame_origin *origin)
1228 if (!is_null_oid(&origin->blob_oid))
1229 return 0;
1230 if (get_tree_entry(r, &origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
1231 goto error_out;
1232 if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
1233 goto error_out;
1234 return 0;
1235 error_out:
1236 oidclr(&origin->blob_oid);
1237 origin->mode = S_IFINVALID;
1238 return -1;
1241 struct blame_bloom_data {
1243 * Changed-path Bloom filter keys. These can help prevent
1244 * computing diffs against first parents, but we need to
1245 * expand the list as code is moved or files are renamed.
1247 struct bloom_filter_settings *settings;
1248 struct bloom_key **keys;
1249 int nr;
1250 int alloc;
1253 static int bloom_count_queries = 0;
1254 static int bloom_count_no = 0;
1255 static int maybe_changed_path(struct repository *r,
1256 struct blame_origin *origin,
1257 struct blame_bloom_data *bd)
1259 int i;
1260 struct bloom_filter *filter;
1262 if (!bd)
1263 return 1;
1265 if (commit_graph_generation(origin->commit) == GENERATION_NUMBER_INFINITY)
1266 return 1;
1268 filter = get_bloom_filter(r, origin->commit);
1270 if (!filter)
1271 return 1;
1273 bloom_count_queries++;
1274 for (i = 0; i < bd->nr; i++) {
1275 if (bloom_filter_contains(filter,
1276 bd->keys[i],
1277 bd->settings))
1278 return 1;
1281 bloom_count_no++;
1282 return 0;
1285 static void add_bloom_key(struct blame_bloom_data *bd,
1286 const char *path)
1288 if (!bd)
1289 return;
1291 if (bd->nr >= bd->alloc) {
1292 bd->alloc *= 2;
1293 REALLOC_ARRAY(bd->keys, bd->alloc);
1296 bd->keys[bd->nr] = xmalloc(sizeof(struct bloom_key));
1297 fill_bloom_key(path, strlen(path), bd->keys[bd->nr], bd->settings);
1298 bd->nr++;
1302 * We have an origin -- check if the same path exists in the
1303 * parent and return an origin structure to represent it.
1305 static struct blame_origin *find_origin(struct repository *r,
1306 struct commit *parent,
1307 struct blame_origin *origin,
1308 struct blame_bloom_data *bd)
1310 struct blame_origin *porigin;
1311 struct diff_options diff_opts;
1312 const char *paths[2];
1314 /* First check any existing origins */
1315 for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
1316 if (!strcmp(porigin->path, origin->path)) {
1318 * The same path between origin and its parent
1319 * without renaming -- the most common case.
1321 return blame_origin_incref (porigin);
1324 /* See if the origin->path is different between parent
1325 * and origin first. Most of the time they are the
1326 * same and diff-tree is fairly efficient about this.
1328 repo_diff_setup(r, &diff_opts);
1329 diff_opts.flags.recursive = 1;
1330 diff_opts.detect_rename = 0;
1331 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1332 paths[0] = origin->path;
1333 paths[1] = NULL;
1335 parse_pathspec(&diff_opts.pathspec,
1336 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1337 PATHSPEC_LITERAL_PATH, "", paths);
1338 diff_setup_done(&diff_opts);
1340 if (is_null_oid(&origin->commit->object.oid))
1341 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1342 else {
1343 int compute_diff = 1;
1344 if (origin->commit->parents &&
1345 oideq(&parent->object.oid,
1346 &origin->commit->parents->item->object.oid))
1347 compute_diff = maybe_changed_path(r, origin, bd);
1349 if (compute_diff)
1350 diff_tree_oid(get_commit_tree_oid(parent),
1351 get_commit_tree_oid(origin->commit),
1352 "", &diff_opts);
1354 diffcore_std(&diff_opts);
1356 if (!diff_queued_diff.nr) {
1357 /* The path is the same as parent */
1358 porigin = get_origin(parent, origin->path);
1359 oidcpy(&porigin->blob_oid, &origin->blob_oid);
1360 porigin->mode = origin->mode;
1361 } else {
1363 * Since origin->path is a pathspec, if the parent
1364 * commit had it as a directory, we will see a whole
1365 * bunch of deletion of files in the directory that we
1366 * do not care about.
1368 int i;
1369 struct diff_filepair *p = NULL;
1370 for (i = 0; i < diff_queued_diff.nr; i++) {
1371 const char *name;
1372 p = diff_queued_diff.queue[i];
1373 name = p->one->path ? p->one->path : p->two->path;
1374 if (!strcmp(name, origin->path))
1375 break;
1377 if (!p)
1378 die("internal error in blame::find_origin");
1379 switch (p->status) {
1380 default:
1381 die("internal error in blame::find_origin (%c)",
1382 p->status);
1383 case 'M':
1384 porigin = get_origin(parent, origin->path);
1385 oidcpy(&porigin->blob_oid, &p->one->oid);
1386 porigin->mode = p->one->mode;
1387 break;
1388 case 'A':
1389 case 'T':
1390 /* Did not exist in parent, or type changed */
1391 break;
1394 diff_flush(&diff_opts);
1395 return porigin;
1399 * We have an origin -- find the path that corresponds to it in its
1400 * parent and return an origin structure to represent it.
1402 static struct blame_origin *find_rename(struct repository *r,
1403 struct commit *parent,
1404 struct blame_origin *origin,
1405 struct blame_bloom_data *bd)
1407 struct blame_origin *porigin = NULL;
1408 struct diff_options diff_opts;
1409 int i;
1411 repo_diff_setup(r, &diff_opts);
1412 diff_opts.flags.recursive = 1;
1413 diff_opts.detect_rename = DIFF_DETECT_RENAME;
1414 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1415 diff_opts.single_follow = origin->path;
1416 diff_setup_done(&diff_opts);
1418 if (is_null_oid(&origin->commit->object.oid))
1419 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1420 else
1421 diff_tree_oid(get_commit_tree_oid(parent),
1422 get_commit_tree_oid(origin->commit),
1423 "", &diff_opts);
1424 diffcore_std(&diff_opts);
1426 for (i = 0; i < diff_queued_diff.nr; i++) {
1427 struct diff_filepair *p = diff_queued_diff.queue[i];
1428 if ((p->status == 'R' || p->status == 'C') &&
1429 !strcmp(p->two->path, origin->path)) {
1430 add_bloom_key(bd, p->one->path);
1431 porigin = get_origin(parent, p->one->path);
1432 oidcpy(&porigin->blob_oid, &p->one->oid);
1433 porigin->mode = p->one->mode;
1434 break;
1437 diff_flush(&diff_opts);
1438 return porigin;
1442 * Append a new blame entry to a given output queue.
1444 static void add_blame_entry(struct blame_entry ***queue,
1445 const struct blame_entry *src)
1447 struct blame_entry *e = xmalloc(sizeof(*e));
1448 memcpy(e, src, sizeof(*e));
1449 blame_origin_incref(e->suspect);
1451 e->next = **queue;
1452 **queue = e;
1453 *queue = &e->next;
1457 * src typically is on-stack; we want to copy the information in it to
1458 * a malloced blame_entry that gets added to the given queue. The
1459 * origin of dst loses a refcnt.
1461 static void dup_entry(struct blame_entry ***queue,
1462 struct blame_entry *dst, struct blame_entry *src)
1464 blame_origin_incref(src->suspect);
1465 blame_origin_decref(dst->suspect);
1466 memcpy(dst, src, sizeof(*src));
1467 dst->next = **queue;
1468 **queue = dst;
1469 *queue = &dst->next;
1472 const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
1474 return sb->final_buf + sb->lineno[lno];
1478 * It is known that lines between tlno to same came from parent, and e
1479 * has an overlap with that range. it also is known that parent's
1480 * line plno corresponds to e's line tlno.
1482 * <---- e ----->
1483 * <------>
1484 * <------------>
1485 * <------------>
1486 * <------------------>
1488 * Split e into potentially three parts; before this chunk, the chunk
1489 * to be blamed for the parent, and after that portion.
1491 static void split_overlap(struct blame_entry *split,
1492 struct blame_entry *e,
1493 int tlno, int plno, int same,
1494 struct blame_origin *parent)
1496 int chunk_end_lno;
1497 int i;
1498 memset(split, 0, sizeof(struct blame_entry [3]));
1500 for (i = 0; i < 3; i++) {
1501 split[i].ignored = e->ignored;
1502 split[i].unblamable = e->unblamable;
1505 if (e->s_lno < tlno) {
1506 /* there is a pre-chunk part not blamed on parent */
1507 split[0].suspect = blame_origin_incref(e->suspect);
1508 split[0].lno = e->lno;
1509 split[0].s_lno = e->s_lno;
1510 split[0].num_lines = tlno - e->s_lno;
1511 split[1].lno = e->lno + tlno - e->s_lno;
1512 split[1].s_lno = plno;
1514 else {
1515 split[1].lno = e->lno;
1516 split[1].s_lno = plno + (e->s_lno - tlno);
1519 if (same < e->s_lno + e->num_lines) {
1520 /* there is a post-chunk part not blamed on parent */
1521 split[2].suspect = blame_origin_incref(e->suspect);
1522 split[2].lno = e->lno + (same - e->s_lno);
1523 split[2].s_lno = e->s_lno + (same - e->s_lno);
1524 split[2].num_lines = e->s_lno + e->num_lines - same;
1525 chunk_end_lno = split[2].lno;
1527 else
1528 chunk_end_lno = e->lno + e->num_lines;
1529 split[1].num_lines = chunk_end_lno - split[1].lno;
1532 * if it turns out there is nothing to blame the parent for,
1533 * forget about the splitting. !split[1].suspect signals this.
1535 if (split[1].num_lines < 1)
1536 return;
1537 split[1].suspect = blame_origin_incref(parent);
1541 * split_overlap() divided an existing blame e into up to three parts
1542 * in split. Any assigned blame is moved to queue to
1543 * reflect the split.
1545 static void split_blame(struct blame_entry ***blamed,
1546 struct blame_entry ***unblamed,
1547 struct blame_entry *split,
1548 struct blame_entry *e)
1550 if (split[0].suspect && split[2].suspect) {
1551 /* The first part (reuse storage for the existing entry e) */
1552 dup_entry(unblamed, e, &split[0]);
1554 /* The last part -- me */
1555 add_blame_entry(unblamed, &split[2]);
1557 /* ... and the middle part -- parent */
1558 add_blame_entry(blamed, &split[1]);
1560 else if (!split[0].suspect && !split[2].suspect)
1562 * The parent covers the entire area; reuse storage for
1563 * e and replace it with the parent.
1565 dup_entry(blamed, e, &split[1]);
1566 else if (split[0].suspect) {
1567 /* me and then parent */
1568 dup_entry(unblamed, e, &split[0]);
1569 add_blame_entry(blamed, &split[1]);
1571 else {
1572 /* parent and then me */
1573 dup_entry(blamed, e, &split[1]);
1574 add_blame_entry(unblamed, &split[2]);
1579 * After splitting the blame, the origins used by the
1580 * on-stack blame_entry should lose one refcnt each.
1582 static void decref_split(struct blame_entry *split)
1584 int i;
1586 for (i = 0; i < 3; i++)
1587 blame_origin_decref(split[i].suspect);
1591 * reverse_blame reverses the list given in head, appending tail.
1592 * That allows us to build lists in reverse order, then reverse them
1593 * afterwards. This can be faster than building the list in proper
1594 * order right away. The reason is that building in proper order
1595 * requires writing a link in the _previous_ element, while building
1596 * in reverse order just requires placing the list head into the
1597 * _current_ element.
1600 static struct blame_entry *reverse_blame(struct blame_entry *head,
1601 struct blame_entry *tail)
1603 while (head) {
1604 struct blame_entry *next = head->next;
1605 head->next = tail;
1606 tail = head;
1607 head = next;
1609 return tail;
1613 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1614 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1615 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1616 * e->num_lines). The caller needs to sort out the reference counting for the
1617 * new entry's suspect.
1619 static struct blame_entry *split_blame_at(struct blame_entry *e, int len,
1620 struct blame_origin *new_suspect)
1622 struct blame_entry *n = xcalloc(1, sizeof(struct blame_entry));
1624 n->suspect = new_suspect;
1625 n->ignored = e->ignored;
1626 n->unblamable = e->unblamable;
1627 n->lno = e->lno + len;
1628 n->s_lno = e->s_lno + len;
1629 n->num_lines = e->num_lines - len;
1630 e->num_lines = len;
1631 e->score = 0;
1632 return n;
1635 struct blame_line_tracker {
1636 int is_parent;
1637 int s_lno;
1640 static int are_lines_adjacent(struct blame_line_tracker *first,
1641 struct blame_line_tracker *second)
1643 return first->is_parent == second->is_parent &&
1644 first->s_lno + 1 == second->s_lno;
1647 static int scan_parent_range(struct fingerprint *p_fps,
1648 struct fingerprint *t_fps, int t_idx,
1649 int from, int nr_lines)
1651 int sim, p_idx;
1652 #define FINGERPRINT_FILE_THRESHOLD 10
1653 int best_sim_val = FINGERPRINT_FILE_THRESHOLD;
1654 int best_sim_idx = -1;
1656 for (p_idx = from; p_idx < from + nr_lines; p_idx++) {
1657 sim = fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);
1658 if (sim < best_sim_val)
1659 continue;
1660 /* Break ties with the closest-to-target line number */
1661 if (sim == best_sim_val && best_sim_idx != -1 &&
1662 abs(best_sim_idx - t_idx) < abs(p_idx - t_idx))
1663 continue;
1664 best_sim_val = sim;
1665 best_sim_idx = p_idx;
1667 return best_sim_idx;
1671 * The first pass checks the blame entry (from the target) against the parent's
1672 * diff chunk. If that fails for a line, the second pass tries to match that
1673 * line to any part of parent file. That catches cases where a change was
1674 * broken into two chunks by 'context.'
1676 static void guess_line_blames(struct blame_origin *parent,
1677 struct blame_origin *target,
1678 int tlno, int offset, int same, int parent_len,
1679 struct blame_line_tracker *line_blames)
1681 int i, best_idx, target_idx;
1682 int parent_slno = tlno + offset;
1683 int *fuzzy_matches;
1685 fuzzy_matches = fuzzy_find_matching_lines(parent, target,
1686 tlno, parent_slno, same,
1687 parent_len);
1688 for (i = 0; i < same - tlno; i++) {
1689 target_idx = tlno + i;
1690 if (fuzzy_matches && fuzzy_matches[i] >= 0) {
1691 best_idx = fuzzy_matches[i];
1692 } else {
1693 best_idx = scan_parent_range(parent->fingerprints,
1694 target->fingerprints,
1695 target_idx, 0,
1696 parent->num_lines);
1698 if (best_idx >= 0) {
1699 line_blames[i].is_parent = 1;
1700 line_blames[i].s_lno = best_idx;
1701 } else {
1702 line_blames[i].is_parent = 0;
1703 line_blames[i].s_lno = target_idx;
1706 free(fuzzy_matches);
1710 * This decides which parts of a blame entry go to the parent (added to the
1711 * ignoredp list) and which stay with the target (added to the diffp list). The
1712 * actual decision was made in a separate heuristic function, and those answers
1713 * for the lines in 'e' are in line_blames. This consumes e, essentially
1714 * putting it on a list.
1716 * Note that the blame entries on the ignoredp list are not necessarily sorted
1717 * with respect to the parent's line numbers yet.
1719 static void ignore_blame_entry(struct blame_entry *e,
1720 struct blame_origin *parent,
1721 struct blame_entry **diffp,
1722 struct blame_entry **ignoredp,
1723 struct blame_line_tracker *line_blames)
1725 int entry_len, nr_lines, i;
1728 * We carve new entries off the front of e. Each entry comes from a
1729 * contiguous chunk of lines: adjacent lines from the same origin
1730 * (either the parent or the target).
1732 entry_len = 1;
1733 nr_lines = e->num_lines; /* e changes in the loop */
1734 for (i = 0; i < nr_lines; i++) {
1735 struct blame_entry *next = NULL;
1738 * We are often adjacent to the next line - only split the blame
1739 * entry when we have to.
1741 if (i + 1 < nr_lines) {
1742 if (are_lines_adjacent(&line_blames[i],
1743 &line_blames[i + 1])) {
1744 entry_len++;
1745 continue;
1747 next = split_blame_at(e, entry_len,
1748 blame_origin_incref(e->suspect));
1750 if (line_blames[i].is_parent) {
1751 e->ignored = 1;
1752 blame_origin_decref(e->suspect);
1753 e->suspect = blame_origin_incref(parent);
1754 e->s_lno = line_blames[i - entry_len + 1].s_lno;
1755 e->next = *ignoredp;
1756 *ignoredp = e;
1757 } else {
1758 e->unblamable = 1;
1759 /* e->s_lno is already in the target's address space. */
1760 e->next = *diffp;
1761 *diffp = e;
1763 assert(e->num_lines == entry_len);
1764 e = next;
1765 entry_len = 1;
1767 assert(!e);
1771 * Process one hunk from the patch between the current suspect for
1772 * blame_entry e and its parent. This first blames any unfinished
1773 * entries before the chunk (which is where target and parent start
1774 * differing) on the parent, and then splits blame entries at the
1775 * start and at the end of the difference region. Since use of -M and
1776 * -C options may lead to overlapping/duplicate source line number
1777 * ranges, all we can rely on from sorting/merging is the order of the
1778 * first suspect line number.
1780 * tlno: line number in the target where this chunk begins
1781 * same: line number in the target where this chunk ends
1782 * offset: add to tlno to get the chunk starting point in the parent
1783 * parent_len: number of lines in the parent chunk
1785 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
1786 int tlno, int offset, int same, int parent_len,
1787 struct blame_origin *parent,
1788 struct blame_origin *target, int ignore_diffs)
1790 struct blame_entry *e = **srcq;
1791 struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;
1792 struct blame_line_tracker *line_blames = NULL;
1794 while (e && e->s_lno < tlno) {
1795 struct blame_entry *next = e->next;
1797 * current record starts before differing portion. If
1798 * it reaches into it, we need to split it up and
1799 * examine the second part separately.
1801 if (e->s_lno + e->num_lines > tlno) {
1802 /* Move second half to a new record */
1803 struct blame_entry *n;
1805 n = split_blame_at(e, tlno - e->s_lno, e->suspect);
1806 /* Push new record to diffp */
1807 n->next = diffp;
1808 diffp = n;
1809 } else
1810 blame_origin_decref(e->suspect);
1811 /* Pass blame for everything before the differing
1812 * chunk to the parent */
1813 e->suspect = blame_origin_incref(parent);
1814 e->s_lno += offset;
1815 e->next = samep;
1816 samep = e;
1817 e = next;
1820 * As we don't know how much of a common stretch after this
1821 * diff will occur, the currently blamed parts are all that we
1822 * can assign to the parent for now.
1825 if (samep) {
1826 **dstq = reverse_blame(samep, **dstq);
1827 *dstq = &samep->next;
1830 * Prepend the split off portions: everything after e starts
1831 * after the blameable portion.
1833 e = reverse_blame(diffp, e);
1836 * Now retain records on the target while parts are different
1837 * from the parent.
1839 samep = NULL;
1840 diffp = NULL;
1842 if (ignore_diffs && same - tlno > 0) {
1843 CALLOC_ARRAY(line_blames, same - tlno);
1844 guess_line_blames(parent, target, tlno, offset, same,
1845 parent_len, line_blames);
1848 while (e && e->s_lno < same) {
1849 struct blame_entry *next = e->next;
1852 * If current record extends into sameness, need to split.
1854 if (e->s_lno + e->num_lines > same) {
1856 * Move second half to a new record to be
1857 * processed by later chunks
1859 struct blame_entry *n;
1861 n = split_blame_at(e, same - e->s_lno,
1862 blame_origin_incref(e->suspect));
1863 /* Push new record to samep */
1864 n->next = samep;
1865 samep = n;
1867 if (ignore_diffs) {
1868 ignore_blame_entry(e, parent, &diffp, &ignoredp,
1869 line_blames + e->s_lno - tlno);
1870 } else {
1871 e->next = diffp;
1872 diffp = e;
1874 e = next;
1876 free(line_blames);
1877 if (ignoredp) {
1879 * Note ignoredp is not sorted yet, and thus neither is dstq.
1880 * That list must be sorted before we queue_blames(). We defer
1881 * sorting until after all diff hunks are processed, so that
1882 * guess_line_blames() can pick *any* line in the parent. The
1883 * slight drawback is that we end up sorting all blame entries
1884 * passed to the parent, including those that are unrelated to
1885 * changes made by the ignored commit.
1887 **dstq = reverse_blame(ignoredp, **dstq);
1888 *dstq = &ignoredp->next;
1890 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
1891 /* Move across elements that are in the unblamable portion */
1892 if (diffp)
1893 *srcq = &diffp->next;
1896 struct blame_chunk_cb_data {
1897 struct blame_origin *parent;
1898 struct blame_origin *target;
1899 long offset;
1900 int ignore_diffs;
1901 struct blame_entry **dstq;
1902 struct blame_entry **srcq;
1905 /* diff chunks are from parent to target */
1906 static int blame_chunk_cb(long start_a, long count_a,
1907 long start_b, long count_b, void *data)
1909 struct blame_chunk_cb_data *d = data;
1910 if (start_a - start_b != d->offset)
1911 die("internal error in blame::blame_chunk_cb");
1912 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
1913 start_b + count_b, count_a, d->parent, d->target,
1914 d->ignore_diffs);
1915 d->offset = start_a + count_a - (start_b + count_b);
1916 return 0;
1920 * We are looking at the origin 'target' and aiming to pass blame
1921 * for the lines it is suspected to its parent. Run diff to find
1922 * which lines came from parent and pass blame for them.
1924 static void pass_blame_to_parent(struct blame_scoreboard *sb,
1925 struct blame_origin *target,
1926 struct blame_origin *parent, int ignore_diffs)
1928 mmfile_t file_p, file_o;
1929 struct blame_chunk_cb_data d;
1930 struct blame_entry *newdest = NULL;
1932 if (!target->suspects)
1933 return; /* nothing remains for this target */
1935 d.parent = parent;
1936 d.target = target;
1937 d.offset = 0;
1938 d.ignore_diffs = ignore_diffs;
1939 d.dstq = &newdest; d.srcq = &target->suspects;
1941 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
1942 &sb->num_read_blob, ignore_diffs);
1943 fill_origin_blob(&sb->revs->diffopt, target, &file_o,
1944 &sb->num_read_blob, ignore_diffs);
1945 sb->num_get_patch++;
1947 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
1948 die("unable to generate diff (%s -> %s)",
1949 oid_to_hex(&parent->commit->object.oid),
1950 oid_to_hex(&target->commit->object.oid));
1951 /* The rest are the same as the parent */
1952 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, 0,
1953 parent, target, 0);
1954 *d.dstq = NULL;
1955 if (ignore_diffs)
1956 sort_blame_entries(&newdest, compare_blame_suspect);
1957 queue_blames(sb, parent, newdest);
1959 return;
1963 * The lines in blame_entry after splitting blames many times can become
1964 * very small and trivial, and at some point it becomes pointless to
1965 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1966 * ordinary C program, and it is not worth to say it was copied from
1967 * totally unrelated file in the parent.
1969 * Compute how trivial the lines in the blame_entry are.
1971 unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1973 unsigned score;
1974 const char *cp, *ep;
1976 if (e->score)
1977 return e->score;
1979 score = 1;
1980 cp = blame_nth_line(sb, e->lno);
1981 ep = blame_nth_line(sb, e->lno + e->num_lines);
1982 while (cp < ep) {
1983 unsigned ch = *((unsigned char *)cp);
1984 if (isalnum(ch))
1985 score++;
1986 cp++;
1988 e->score = score;
1989 return score;
1993 * best_so_far[] and potential[] are both a split of an existing blame_entry
1994 * that passes blame to the parent. Maintain best_so_far the best split so
1995 * far, by comparing potential and best_so_far and copying potential into
1996 * bst_so_far as needed.
1998 static void copy_split_if_better(struct blame_scoreboard *sb,
1999 struct blame_entry *best_so_far,
2000 struct blame_entry *potential)
2002 int i;
2004 if (!potential[1].suspect)
2005 return;
2006 if (best_so_far[1].suspect) {
2007 if (blame_entry_score(sb, &potential[1]) <
2008 blame_entry_score(sb, &best_so_far[1]))
2009 return;
2012 for (i = 0; i < 3; i++)
2013 blame_origin_incref(potential[i].suspect);
2014 decref_split(best_so_far);
2015 memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
2019 * We are looking at a part of the final image represented by
2020 * ent (tlno and same are offset by ent->s_lno).
2021 * tlno is where we are looking at in the final image.
2022 * up to (but not including) same match preimage.
2023 * plno is where we are looking at in the preimage.
2025 * <-------------- final image ---------------------->
2026 * <------ent------>
2027 * ^tlno ^same
2028 * <---------preimage----->
2029 * ^plno
2031 * All line numbers are 0-based.
2033 static void handle_split(struct blame_scoreboard *sb,
2034 struct blame_entry *ent,
2035 int tlno, int plno, int same,
2036 struct blame_origin *parent,
2037 struct blame_entry *split)
2039 if (ent->num_lines <= tlno)
2040 return;
2041 if (tlno < same) {
2042 struct blame_entry potential[3];
2043 tlno += ent->s_lno;
2044 same += ent->s_lno;
2045 split_overlap(potential, ent, tlno, plno, same, parent);
2046 copy_split_if_better(sb, split, potential);
2047 decref_split(potential);
2051 struct handle_split_cb_data {
2052 struct blame_scoreboard *sb;
2053 struct blame_entry *ent;
2054 struct blame_origin *parent;
2055 struct blame_entry *split;
2056 long plno;
2057 long tlno;
2060 static int handle_split_cb(long start_a, long count_a,
2061 long start_b, long count_b, void *data)
2063 struct handle_split_cb_data *d = data;
2064 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
2065 d->split);
2066 d->plno = start_a + count_a;
2067 d->tlno = start_b + count_b;
2068 return 0;
2072 * Find the lines from parent that are the same as ent so that
2073 * we can pass blames to it. file_p has the blob contents for
2074 * the parent.
2076 static void find_copy_in_blob(struct blame_scoreboard *sb,
2077 struct blame_entry *ent,
2078 struct blame_origin *parent,
2079 struct blame_entry *split,
2080 mmfile_t *file_p)
2082 const char *cp;
2083 mmfile_t file_o;
2084 struct handle_split_cb_data d;
2086 memset(&d, 0, sizeof(d));
2087 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
2089 * Prepare mmfile that contains only the lines in ent.
2091 cp = blame_nth_line(sb, ent->lno);
2092 file_o.ptr = (char *) cp;
2093 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
2096 * file_o is a part of final image we are annotating.
2097 * file_p partially may match that image.
2099 memset(split, 0, sizeof(struct blame_entry [3]));
2100 if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
2101 die("unable to generate diff (%s)",
2102 oid_to_hex(&parent->commit->object.oid));
2103 /* remainder, if any, all match the preimage */
2104 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
2107 /* Move all blame entries from list *source that have a score smaller
2108 * than score_min to the front of list *small.
2109 * Returns a pointer to the link pointing to the old head of the small list.
2112 static struct blame_entry **filter_small(struct blame_scoreboard *sb,
2113 struct blame_entry **small,
2114 struct blame_entry **source,
2115 unsigned score_min)
2117 struct blame_entry *p = *source;
2118 struct blame_entry *oldsmall = *small;
2119 while (p) {
2120 if (blame_entry_score(sb, p) <= score_min) {
2121 *small = p;
2122 small = &p->next;
2123 p = *small;
2124 } else {
2125 *source = p;
2126 source = &p->next;
2127 p = *source;
2130 *small = oldsmall;
2131 *source = NULL;
2132 return small;
2136 * See if lines currently target is suspected for can be attributed to
2137 * parent.
2139 static void find_move_in_parent(struct blame_scoreboard *sb,
2140 struct blame_entry ***blamed,
2141 struct blame_entry **toosmall,
2142 struct blame_origin *target,
2143 struct blame_origin *parent)
2145 struct blame_entry *e, split[3];
2146 struct blame_entry *unblamed = target->suspects;
2147 struct blame_entry *leftover = NULL;
2148 mmfile_t file_p;
2150 if (!unblamed)
2151 return; /* nothing remains for this target */
2153 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
2154 &sb->num_read_blob, 0);
2155 if (!file_p.ptr)
2156 return;
2158 /* At each iteration, unblamed has a NULL-terminated list of
2159 * entries that have not yet been tested for blame. leftover
2160 * contains the reversed list of entries that have been tested
2161 * without being assignable to the parent.
2163 do {
2164 struct blame_entry **unblamedtail = &unblamed;
2165 struct blame_entry *next;
2166 for (e = unblamed; e; e = next) {
2167 next = e->next;
2168 find_copy_in_blob(sb, e, parent, split, &file_p);
2169 if (split[1].suspect &&
2170 sb->move_score < blame_entry_score(sb, &split[1])) {
2171 split_blame(blamed, &unblamedtail, split, e);
2172 } else {
2173 e->next = leftover;
2174 leftover = e;
2176 decref_split(split);
2178 *unblamedtail = NULL;
2179 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
2180 } while (unblamed);
2181 target->suspects = reverse_blame(leftover, NULL);
2184 struct blame_list {
2185 struct blame_entry *ent;
2186 struct blame_entry split[3];
2190 * Count the number of entries the target is suspected for,
2191 * and prepare a list of entry and the best split.
2193 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
2194 int *num_ents_p)
2196 struct blame_entry *e;
2197 int num_ents, i;
2198 struct blame_list *blame_list = NULL;
2200 for (e = unblamed, num_ents = 0; e; e = e->next)
2201 num_ents++;
2202 if (num_ents) {
2203 CALLOC_ARRAY(blame_list, num_ents);
2204 for (e = unblamed, i = 0; e; e = e->next)
2205 blame_list[i++].ent = e;
2207 *num_ents_p = num_ents;
2208 return blame_list;
2212 * For lines target is suspected for, see if we can find code movement
2213 * across file boundary from the parent commit. porigin is the path
2214 * in the parent we already tried.
2216 static void find_copy_in_parent(struct blame_scoreboard *sb,
2217 struct blame_entry ***blamed,
2218 struct blame_entry **toosmall,
2219 struct blame_origin *target,
2220 struct commit *parent,
2221 struct blame_origin *porigin,
2222 int opt)
2224 struct diff_options diff_opts;
2225 int i, j;
2226 struct blame_list *blame_list;
2227 int num_ents;
2228 struct blame_entry *unblamed = target->suspects;
2229 struct blame_entry *leftover = NULL;
2231 if (!unblamed)
2232 return; /* nothing remains for this target */
2234 repo_diff_setup(sb->repo, &diff_opts);
2235 diff_opts.flags.recursive = 1;
2236 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2238 diff_setup_done(&diff_opts);
2240 /* Try "find copies harder" on new path if requested;
2241 * we do not want to use diffcore_rename() actually to
2242 * match things up; find_copies_harder is set only to
2243 * force diff_tree_oid() to feed all filepairs to diff_queue,
2244 * and this code needs to be after diff_setup_done(), which
2245 * usually makes find-copies-harder imply copy detection.
2247 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
2248 || ((opt & PICKAXE_BLAME_COPY_HARDER)
2249 && (!porigin || strcmp(target->path, porigin->path))))
2250 diff_opts.flags.find_copies_harder = 1;
2252 if (is_null_oid(&target->commit->object.oid))
2253 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
2254 else
2255 diff_tree_oid(get_commit_tree_oid(parent),
2256 get_commit_tree_oid(target->commit),
2257 "", &diff_opts);
2259 if (!diff_opts.flags.find_copies_harder)
2260 diffcore_std(&diff_opts);
2262 do {
2263 struct blame_entry **unblamedtail = &unblamed;
2264 blame_list = setup_blame_list(unblamed, &num_ents);
2266 for (i = 0; i < diff_queued_diff.nr; i++) {
2267 struct diff_filepair *p = diff_queued_diff.queue[i];
2268 struct blame_origin *norigin;
2269 mmfile_t file_p;
2270 struct blame_entry potential[3];
2272 if (!DIFF_FILE_VALID(p->one))
2273 continue; /* does not exist in parent */
2274 if (S_ISGITLINK(p->one->mode))
2275 continue; /* ignore git links */
2276 if (porigin && !strcmp(p->one->path, porigin->path))
2277 /* find_move already dealt with this path */
2278 continue;
2280 norigin = get_origin(parent, p->one->path);
2281 oidcpy(&norigin->blob_oid, &p->one->oid);
2282 norigin->mode = p->one->mode;
2283 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,
2284 &sb->num_read_blob, 0);
2285 if (!file_p.ptr)
2286 continue;
2288 for (j = 0; j < num_ents; j++) {
2289 find_copy_in_blob(sb, blame_list[j].ent,
2290 norigin, potential, &file_p);
2291 copy_split_if_better(sb, blame_list[j].split,
2292 potential);
2293 decref_split(potential);
2295 blame_origin_decref(norigin);
2298 for (j = 0; j < num_ents; j++) {
2299 struct blame_entry *split = blame_list[j].split;
2300 if (split[1].suspect &&
2301 sb->copy_score < blame_entry_score(sb, &split[1])) {
2302 split_blame(blamed, &unblamedtail, split,
2303 blame_list[j].ent);
2304 } else {
2305 blame_list[j].ent->next = leftover;
2306 leftover = blame_list[j].ent;
2308 decref_split(split);
2310 free(blame_list);
2311 *unblamedtail = NULL;
2312 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
2313 } while (unblamed);
2314 target->suspects = reverse_blame(leftover, NULL);
2315 diff_flush(&diff_opts);
2319 * The blobs of origin and porigin exactly match, so everything
2320 * origin is suspected for can be blamed on the parent.
2322 static void pass_whole_blame(struct blame_scoreboard *sb,
2323 struct blame_origin *origin, struct blame_origin *porigin)
2325 struct blame_entry *e, *suspects;
2327 if (!porigin->file.ptr && origin->file.ptr) {
2328 /* Steal its file */
2329 porigin->file = origin->file;
2330 origin->file.ptr = NULL;
2332 suspects = origin->suspects;
2333 origin->suspects = NULL;
2334 for (e = suspects; e; e = e->next) {
2335 blame_origin_incref(porigin);
2336 blame_origin_decref(e->suspect);
2337 e->suspect = porigin;
2339 queue_blames(sb, porigin, suspects);
2343 * We pass blame from the current commit to its parents. We keep saying
2344 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2345 * exonerate ourselves.
2347 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
2348 int reverse)
2350 if (!reverse) {
2351 if (revs->first_parent_only &&
2352 commit->parents &&
2353 commit->parents->next) {
2354 free_commit_list(commit->parents->next);
2355 commit->parents->next = NULL;
2357 return commit->parents;
2359 return lookup_decoration(&revs->children, &commit->object);
2362 static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
2364 struct commit_list *l = first_scapegoat(revs, commit, reverse);
2365 return commit_list_count(l);
2368 /* Distribute collected unsorted blames to the respected sorted lists
2369 * in the various origins.
2371 static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
2373 sort_blame_entries(&blamed, compare_blame_suspect);
2374 while (blamed)
2376 struct blame_origin *porigin = blamed->suspect;
2377 struct blame_entry *suspects = NULL;
2378 do {
2379 struct blame_entry *next = blamed->next;
2380 blamed->next = suspects;
2381 suspects = blamed;
2382 blamed = next;
2383 } while (blamed && blamed->suspect == porigin);
2384 suspects = reverse_blame(suspects, NULL);
2385 queue_blames(sb, porigin, suspects);
2389 #define MAXSG 16
2391 typedef struct blame_origin *(*blame_find_alg)(struct repository *,
2392 struct commit *,
2393 struct blame_origin *,
2394 struct blame_bloom_data *);
2396 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
2398 struct rev_info *revs = sb->revs;
2399 int i, pass, num_sg;
2400 struct commit *commit = origin->commit;
2401 struct commit_list *sg;
2402 struct blame_origin *sg_buf[MAXSG];
2403 struct blame_origin *porigin, **sg_origin = sg_buf;
2404 struct blame_entry *toosmall = NULL;
2405 struct blame_entry *blames, **blametail = &blames;
2407 num_sg = num_scapegoats(revs, commit, sb->reverse);
2408 if (!num_sg)
2409 goto finish;
2410 else if (num_sg < ARRAY_SIZE(sg_buf))
2411 memset(sg_buf, 0, sizeof(sg_buf));
2412 else
2413 CALLOC_ARRAY(sg_origin, num_sg);
2416 * The first pass looks for unrenamed path to optimize for
2417 * common cases, then we look for renames in the second pass.
2419 for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
2420 blame_find_alg find = pass ? find_rename : find_origin;
2422 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2423 i < num_sg && sg;
2424 sg = sg->next, i++) {
2425 struct commit *p = sg->item;
2426 int j, same;
2428 if (sg_origin[i])
2429 continue;
2430 if (parse_commit(p))
2431 continue;
2432 porigin = find(sb->repo, p, origin, sb->bloom_data);
2433 if (!porigin)
2434 continue;
2435 if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
2436 pass_whole_blame(sb, origin, porigin);
2437 blame_origin_decref(porigin);
2438 goto finish;
2440 for (j = same = 0; j < i; j++)
2441 if (sg_origin[j] &&
2442 oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
2443 same = 1;
2444 break;
2446 if (!same)
2447 sg_origin[i] = porigin;
2448 else
2449 blame_origin_decref(porigin);
2453 sb->num_commits++;
2454 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2455 i < num_sg && sg;
2456 sg = sg->next, i++) {
2457 struct blame_origin *porigin = sg_origin[i];
2458 if (!porigin)
2459 continue;
2460 if (!origin->previous) {
2461 blame_origin_incref(porigin);
2462 origin->previous = porigin;
2464 pass_blame_to_parent(sb, origin, porigin, 0);
2465 if (!origin->suspects)
2466 goto finish;
2470 * Pass remaining suspects for ignored commits to their parents.
2472 if (oidset_contains(&sb->ignore_list, &commit->object.oid)) {
2473 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2474 i < num_sg && sg;
2475 sg = sg->next, i++) {
2476 struct blame_origin *porigin = sg_origin[i];
2478 if (!porigin)
2479 continue;
2480 pass_blame_to_parent(sb, origin, porigin, 1);
2482 * Preemptively drop porigin so we can refresh the
2483 * fingerprints if we use the parent again, which can
2484 * occur if you ignore back-to-back commits.
2486 drop_origin_blob(porigin);
2487 if (!origin->suspects)
2488 goto finish;
2493 * Optionally find moves in parents' files.
2495 if (opt & PICKAXE_BLAME_MOVE) {
2496 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
2497 if (origin->suspects) {
2498 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2499 i < num_sg && sg;
2500 sg = sg->next, i++) {
2501 struct blame_origin *porigin = sg_origin[i];
2502 if (!porigin)
2503 continue;
2504 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
2505 if (!origin->suspects)
2506 break;
2512 * Optionally find copies from parents' files.
2514 if (opt & PICKAXE_BLAME_COPY) {
2515 if (sb->copy_score > sb->move_score)
2516 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2517 else if (sb->copy_score < sb->move_score) {
2518 origin->suspects = blame_merge(origin->suspects, toosmall);
2519 toosmall = NULL;
2520 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2522 if (!origin->suspects)
2523 goto finish;
2525 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2526 i < num_sg && sg;
2527 sg = sg->next, i++) {
2528 struct blame_origin *porigin = sg_origin[i];
2529 find_copy_in_parent(sb, &blametail, &toosmall,
2530 origin, sg->item, porigin, opt);
2531 if (!origin->suspects)
2532 goto finish;
2536 finish:
2537 *blametail = NULL;
2538 distribute_blame(sb, blames);
2540 * prepend toosmall to origin->suspects
2542 * There is no point in sorting: this ends up on a big
2543 * unsorted list in the caller anyway.
2545 if (toosmall) {
2546 struct blame_entry **tail = &toosmall;
2547 while (*tail)
2548 tail = &(*tail)->next;
2549 *tail = origin->suspects;
2550 origin->suspects = toosmall;
2552 for (i = 0; i < num_sg; i++) {
2553 if (sg_origin[i]) {
2554 if (!sg_origin[i]->suspects)
2555 drop_origin_blob(sg_origin[i]);
2556 blame_origin_decref(sg_origin[i]);
2559 drop_origin_blob(origin);
2560 if (sg_buf != sg_origin)
2561 free(sg_origin);
2565 * The main loop -- while we have blobs with lines whose true origin
2566 * is still unknown, pick one blob, and allow its lines to pass blames
2567 * to its parents. */
2568 void assign_blame(struct blame_scoreboard *sb, int opt)
2570 struct rev_info *revs = sb->revs;
2571 struct commit *commit = prio_queue_get(&sb->commits);
2573 while (commit) {
2574 struct blame_entry *ent;
2575 struct blame_origin *suspect = get_blame_suspects(commit);
2577 /* find one suspect to break down */
2578 while (suspect && !suspect->suspects)
2579 suspect = suspect->next;
2581 if (!suspect) {
2582 commit = prio_queue_get(&sb->commits);
2583 continue;
2586 assert(commit == suspect->commit);
2589 * We will use this suspect later in the loop,
2590 * so hold onto it in the meantime.
2592 blame_origin_incref(suspect);
2593 parse_commit(commit);
2594 if (sb->reverse ||
2595 (!(commit->object.flags & UNINTERESTING) &&
2596 !(revs->max_age != -1 && commit->date < revs->max_age)))
2597 pass_blame(sb, suspect, opt);
2598 else {
2599 commit->object.flags |= UNINTERESTING;
2600 if (commit->object.parsed)
2601 mark_parents_uninteresting(sb->revs, commit);
2603 /* treat root commit as boundary */
2604 if (!commit->parents && !sb->show_root)
2605 commit->object.flags |= UNINTERESTING;
2607 /* Take responsibility for the remaining entries */
2608 ent = suspect->suspects;
2609 if (ent) {
2610 suspect->guilty = 1;
2611 for (;;) {
2612 struct blame_entry *next = ent->next;
2613 if (sb->found_guilty_entry)
2614 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
2615 if (next) {
2616 ent = next;
2617 continue;
2619 ent->next = sb->ent;
2620 sb->ent = suspect->suspects;
2621 suspect->suspects = NULL;
2622 break;
2625 blame_origin_decref(suspect);
2627 if (sb->debug) /* sanity */
2628 sanity_check_refcnt(sb);
2633 * To allow quick access to the contents of nth line in the
2634 * final image, prepare an index in the scoreboard.
2636 static int prepare_lines(struct blame_scoreboard *sb)
2638 sb->num_lines = find_line_starts(&sb->lineno, sb->final_buf,
2639 sb->final_buf_size);
2640 return sb->num_lines;
2643 static struct commit *find_single_final(struct rev_info *revs,
2644 const char **name_p)
2646 int i;
2647 struct commit *found = NULL;
2648 const char *name = NULL;
2650 for (i = 0; i < revs->pending.nr; i++) {
2651 struct object *obj = revs->pending.objects[i].item;
2652 if (obj->flags & UNINTERESTING)
2653 continue;
2654 obj = deref_tag(revs->repo, obj, NULL, 0);
2655 if (!obj || obj->type != OBJ_COMMIT)
2656 die("Non commit %s?", revs->pending.objects[i].name);
2657 if (found)
2658 die("More than one commit to dig from %s and %s?",
2659 revs->pending.objects[i].name, name);
2660 found = (struct commit *)obj;
2661 name = revs->pending.objects[i].name;
2663 if (name_p)
2664 *name_p = xstrdup_or_null(name);
2665 return found;
2668 static struct commit *dwim_reverse_initial(struct rev_info *revs,
2669 const char **name_p)
2672 * DWIM "git blame --reverse ONE -- PATH" as
2673 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2674 * when it makes sense.
2676 struct object *obj;
2677 struct commit *head_commit;
2678 struct object_id head_oid;
2680 if (revs->pending.nr != 1)
2681 return NULL;
2683 /* Is that sole rev a committish? */
2684 obj = revs->pending.objects[0].item;
2685 obj = deref_tag(revs->repo, obj, NULL, 0);
2686 if (!obj || obj->type != OBJ_COMMIT)
2687 return NULL;
2689 /* Do we have HEAD? */
2690 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
2691 return NULL;
2692 head_commit = lookup_commit_reference_gently(revs->repo,
2693 &head_oid, 1);
2694 if (!head_commit)
2695 return NULL;
2697 /* Turn "ONE" into "ONE..HEAD" then */
2698 obj->flags |= UNINTERESTING;
2699 add_pending_object(revs, &head_commit->object, "HEAD");
2701 if (name_p)
2702 *name_p = revs->pending.objects[0].name;
2703 return (struct commit *)obj;
2706 static struct commit *find_single_initial(struct rev_info *revs,
2707 const char **name_p)
2709 int i;
2710 struct commit *found = NULL;
2711 const char *name = NULL;
2714 * There must be one and only one negative commit, and it must be
2715 * the boundary.
2717 for (i = 0; i < revs->pending.nr; i++) {
2718 struct object *obj = revs->pending.objects[i].item;
2719 if (!(obj->flags & UNINTERESTING))
2720 continue;
2721 obj = deref_tag(revs->repo, obj, NULL, 0);
2722 if (!obj || obj->type != OBJ_COMMIT)
2723 die("Non commit %s?", revs->pending.objects[i].name);
2724 if (found)
2725 die("More than one commit to dig up from, %s and %s?",
2726 revs->pending.objects[i].name, name);
2727 found = (struct commit *) obj;
2728 name = revs->pending.objects[i].name;
2731 if (!name)
2732 found = dwim_reverse_initial(revs, &name);
2733 if (!name)
2734 die("No commit to dig up from?");
2736 if (name_p)
2737 *name_p = xstrdup(name);
2738 return found;
2741 void init_scoreboard(struct blame_scoreboard *sb)
2743 memset(sb, 0, sizeof(struct blame_scoreboard));
2744 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
2745 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
2748 void setup_scoreboard(struct blame_scoreboard *sb,
2749 struct blame_origin **orig)
2751 const char *final_commit_name = NULL;
2752 struct blame_origin *o;
2753 struct commit *final_commit = NULL;
2754 enum object_type type;
2756 init_blame_suspects(&blame_suspects);
2758 if (sb->reverse && sb->contents_from)
2759 die(_("--contents and --reverse do not blend well."));
2761 if (!sb->repo)
2762 BUG("repo is NULL");
2764 if (!sb->reverse) {
2765 sb->final = find_single_final(sb->revs, &final_commit_name);
2766 sb->commits.compare = compare_commits_by_commit_date;
2767 } else {
2768 sb->final = find_single_initial(sb->revs, &final_commit_name);
2769 sb->commits.compare = compare_commits_by_reverse_commit_date;
2772 if (sb->reverse && sb->revs->first_parent_only)
2773 sb->revs->children.name = NULL;
2775 if (sb->contents_from || !sb->final) {
2776 struct object_id head_oid, *parent_oid;
2779 * Build a fake commit at the top of the history, when
2780 * (1) "git blame [^A] --path", i.e. with no positive end
2781 * of the history range, in which case we build such
2782 * a fake commit on top of the HEAD to blame in-tree
2783 * modifications.
2784 * (2) "git blame --contents=file [A] -- path", with or
2785 * without positive end of the history range but with
2786 * --contents, in which case we pretend that there is
2787 * a fake commit on top of the positive end (defaulting to
2788 * HEAD) that has the given contents in the path.
2790 if (sb->final) {
2791 parent_oid = &sb->final->object.oid;
2792 } else {
2793 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
2794 die("no such ref: HEAD");
2795 parent_oid = &head_oid;
2798 setup_work_tree();
2799 sb->final = fake_working_tree_commit(sb->repo,
2800 &sb->revs->diffopt,
2801 sb->path, sb->contents_from,
2802 parent_oid);
2803 add_pending_object(sb->revs, &(sb->final->object), ":");
2806 if (sb->reverse && sb->revs->first_parent_only) {
2807 final_commit = find_single_final(sb->revs, NULL);
2808 if (!final_commit)
2809 die(_("--reverse and --first-parent together require specified latest commit"));
2813 * If we have bottom, this will mark the ancestors of the
2814 * bottom commits we would reach while traversing as
2815 * uninteresting.
2817 if (prepare_revision_walk(sb->revs))
2818 die(_("revision walk setup failed"));
2820 if (sb->reverse && sb->revs->first_parent_only) {
2821 struct commit *c = final_commit;
2823 sb->revs->children.name = "children";
2824 while (c->parents &&
2825 !oideq(&c->object.oid, &sb->final->object.oid)) {
2826 struct commit_list *l = xcalloc(1, sizeof(*l));
2828 l->item = c;
2829 if (add_decoration(&sb->revs->children,
2830 &c->parents->item->object, l))
2831 BUG("not unique item in first-parent chain");
2832 c = c->parents->item;
2835 if (!oideq(&c->object.oid, &sb->final->object.oid))
2836 die(_("--reverse --first-parent together require range along first-parent chain"));
2839 if (is_null_oid(&sb->final->object.oid)) {
2840 o = get_blame_suspects(sb->final);
2841 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
2842 sb->final_buf_size = o->file.size;
2844 else {
2845 o = get_origin(sb->final, sb->path);
2846 if (fill_blob_sha1_and_mode(sb->repo, o))
2847 die(_("no such path %s in %s"), sb->path, final_commit_name);
2849 if (sb->revs->diffopt.flags.allow_textconv &&
2850 textconv_object(sb->repo, sb->path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
2851 &sb->final_buf_size))
2853 else
2854 sb->final_buf = read_object_file(&o->blob_oid, &type,
2855 &sb->final_buf_size);
2857 if (!sb->final_buf)
2858 die(_("cannot read blob %s for path %s"),
2859 oid_to_hex(&o->blob_oid),
2860 sb->path);
2862 sb->num_read_blob++;
2863 prepare_lines(sb);
2865 if (orig)
2866 *orig = o;
2868 free((char *)final_commit_name);
2873 struct blame_entry *blame_entry_prepend(struct blame_entry *head,
2874 long start, long end,
2875 struct blame_origin *o)
2877 struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
2878 new_head->lno = start;
2879 new_head->num_lines = end - start;
2880 new_head->suspect = o;
2881 new_head->s_lno = start;
2882 new_head->next = head;
2883 blame_origin_incref(o);
2884 return new_head;
2887 void setup_blame_bloom_data(struct blame_scoreboard *sb)
2889 struct blame_bloom_data *bd;
2890 struct bloom_filter_settings *bs;
2892 if (!sb->repo->objects->commit_graph)
2893 return;
2895 bs = get_bloom_filter_settings(sb->repo);
2896 if (!bs)
2897 return;
2899 bd = xmalloc(sizeof(struct blame_bloom_data));
2901 bd->settings = bs;
2903 bd->alloc = 4;
2904 bd->nr = 0;
2905 ALLOC_ARRAY(bd->keys, bd->alloc);
2907 add_bloom_key(bd, sb->path);
2909 sb->bloom_data = bd;
2912 void cleanup_scoreboard(struct blame_scoreboard *sb)
2914 if (sb->bloom_data) {
2915 int i;
2916 for (i = 0; i < sb->bloom_data->nr; i++) {
2917 free(sb->bloom_data->keys[i]->hashes);
2918 free(sb->bloom_data->keys[i]);
2920 free(sb->bloom_data->keys);
2921 FREE_AND_NULL(sb->bloom_data);
2923 trace2_data_intmax("blame", sb->repo,
2924 "bloom/queries", bloom_count_queries);
2925 trace2_data_intmax("blame", sb->repo,
2926 "bloom/response-no", bloom_count_no);