treewide: be explicit about dependence on advice.h
[alt-git.git] / blame.c
blob3455f6a5ea35153dd30cc21073784a177e78bcfa
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 "gettext.h"
9 #include "hex.h"
10 #include "setup.h"
11 #include "tag.h"
12 #include "trace2.h"
13 #include "blame.h"
14 #include "alloc.h"
15 #include "commit-slab.h"
16 #include "bloom.h"
17 #include "commit-graph.h"
19 define_commit_slab(blame_suspects, struct blame_origin *);
20 static struct blame_suspects blame_suspects;
22 struct blame_origin *get_blame_suspects(struct commit *commit)
24 struct blame_origin **result;
26 result = blame_suspects_peek(&blame_suspects, commit);
28 return result ? *result : NULL;
31 static void set_blame_suspects(struct commit *commit, struct blame_origin *origin)
33 *blame_suspects_at(&blame_suspects, commit) = origin;
36 void blame_origin_decref(struct blame_origin *o)
38 if (o && --o->refcnt <= 0) {
39 struct blame_origin *p, *l = NULL;
40 if (o->previous)
41 blame_origin_decref(o->previous);
42 free(o->file.ptr);
43 /* Should be present exactly once in commit chain */
44 for (p = get_blame_suspects(o->commit); p; l = p, p = p->next) {
45 if (p == o) {
46 if (l)
47 l->next = p->next;
48 else
49 set_blame_suspects(o->commit, p->next);
50 free(o);
51 return;
54 die("internal error in blame_origin_decref");
59 * Given a commit and a path in it, create a new origin structure.
60 * The callers that add blame to the scoreboard should use
61 * get_origin() to obtain shared, refcounted copy instead of calling
62 * this function directly.
64 static struct blame_origin *make_origin(struct commit *commit, const char *path)
66 struct blame_origin *o;
67 FLEX_ALLOC_STR(o, path, path);
68 o->commit = commit;
69 o->refcnt = 1;
70 o->next = get_blame_suspects(commit);
71 set_blame_suspects(commit, o);
72 return o;
76 * Locate an existing origin or create a new one.
77 * This moves the origin to front position in the commit util list.
79 static struct blame_origin *get_origin(struct commit *commit, const char *path)
81 struct blame_origin *o, *l;
83 for (o = get_blame_suspects(commit), l = NULL; o; l = o, o = o->next) {
84 if (!strcmp(o->path, path)) {
85 /* bump to front */
86 if (l) {
87 l->next = o->next;
88 o->next = get_blame_suspects(commit);
89 set_blame_suspects(commit, o);
91 return blame_origin_incref(o);
94 return make_origin(commit, path);
99 static void verify_working_tree_path(struct repository *r,
100 struct commit *work_tree, const char *path)
102 struct commit_list *parents;
103 int pos;
105 for (parents = work_tree->parents; parents; parents = parents->next) {
106 const struct object_id *commit_oid = &parents->item->object.oid;
107 struct object_id blob_oid;
108 unsigned short mode;
110 if (!get_tree_entry(r, commit_oid, path, &blob_oid, &mode) &&
111 oid_object_info(r, &blob_oid, NULL) == OBJ_BLOB)
112 return;
115 pos = index_name_pos(r->index, path, strlen(path));
116 if (pos >= 0)
117 ; /* path is in the index */
118 else if (-1 - pos < r->index->cache_nr &&
119 !strcmp(r->index->cache[-1 - pos]->name, path))
120 ; /* path is in the index, unmerged */
121 else
122 die("no such path '%s' in HEAD", path);
125 static struct commit_list **append_parent(struct repository *r,
126 struct commit_list **tail,
127 const struct object_id *oid)
129 struct commit *parent;
131 parent = lookup_commit_reference(r, oid);
132 if (!parent)
133 die("no such commit %s", oid_to_hex(oid));
134 return &commit_list_insert(parent, tail)->next;
137 static void append_merge_parents(struct repository *r,
138 struct commit_list **tail)
140 int merge_head;
141 struct strbuf line = STRBUF_INIT;
143 merge_head = open(git_path_merge_head(r), O_RDONLY);
144 if (merge_head < 0) {
145 if (errno == ENOENT)
146 return;
147 die("cannot open '%s' for reading",
148 git_path_merge_head(r));
151 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
152 struct object_id oid;
153 if (get_oid_hex(line.buf, &oid))
154 die("unknown line in '%s': %s",
155 git_path_merge_head(r), line.buf);
156 tail = append_parent(r, tail, &oid);
158 close(merge_head);
159 strbuf_release(&line);
163 * This isn't as simple as passing sb->buf and sb->len, because we
164 * want to transfer ownership of the buffer to the commit (so we
165 * must use detach).
167 static void set_commit_buffer_from_strbuf(struct repository *r,
168 struct commit *c,
169 struct strbuf *sb)
171 size_t len;
172 void *buf = strbuf_detach(sb, &len);
173 set_commit_buffer(r, c, buf, len);
177 * Prepare a dummy commit that represents the work tree (or staged) item.
178 * Note that annotating work tree item never works in the reverse.
180 static struct commit *fake_working_tree_commit(struct repository *r,
181 struct diff_options *opt,
182 const char *path,
183 const char *contents_from)
185 struct commit *commit;
186 struct blame_origin *origin;
187 struct commit_list **parent_tail, *parent;
188 struct object_id head_oid;
189 struct strbuf buf = STRBUF_INIT;
190 const char *ident;
191 time_t now;
192 int len;
193 struct cache_entry *ce;
194 unsigned mode;
195 struct strbuf msg = STRBUF_INIT;
197 repo_read_index(r);
198 time(&now);
199 commit = alloc_commit_node(r);
200 commit->object.parsed = 1;
201 commit->date = now;
202 parent_tail = &commit->parents;
204 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
205 die("no such ref: HEAD");
207 parent_tail = append_parent(r, parent_tail, &head_oid);
208 append_merge_parents(r, parent_tail);
209 verify_working_tree_path(r, commit, path);
211 origin = make_origin(commit, path);
213 ident = fmt_ident("Not Committed Yet", "not.committed.yet",
214 WANT_BLANK_IDENT, NULL, 0);
215 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
216 for (parent = commit->parents; parent; parent = parent->next)
217 strbuf_addf(&msg, "parent %s\n",
218 oid_to_hex(&parent->item->object.oid));
219 strbuf_addf(&msg,
220 "author %s\n"
221 "committer %s\n\n"
222 "Version of %s from %s\n",
223 ident, ident, path,
224 (!contents_from ? path :
225 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
226 set_commit_buffer_from_strbuf(r, commit, &msg);
228 if (!contents_from || strcmp("-", contents_from)) {
229 struct stat st;
230 const char *read_from;
231 char *buf_ptr;
232 unsigned long buf_len;
234 if (contents_from) {
235 if (stat(contents_from, &st) < 0)
236 die_errno("Cannot stat '%s'", contents_from);
237 read_from = contents_from;
239 else {
240 if (lstat(path, &st) < 0)
241 die_errno("Cannot lstat '%s'", path);
242 read_from = path;
244 mode = canon_mode(st.st_mode);
246 switch (st.st_mode & S_IFMT) {
247 case S_IFREG:
248 if (opt->flags.allow_textconv &&
249 textconv_object(r, read_from, mode, null_oid(), 0, &buf_ptr, &buf_len))
250 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
251 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
252 die_errno("cannot open or read '%s'", read_from);
253 break;
254 case S_IFLNK:
255 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
256 die_errno("cannot readlink '%s'", read_from);
257 break;
258 default:
259 die("unsupported file type %s", read_from);
262 else {
263 /* Reading from stdin */
264 mode = 0;
265 if (strbuf_read(&buf, 0, 0) < 0)
266 die_errno("failed to read from stdin");
268 convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
269 origin->file.ptr = buf.buf;
270 origin->file.size = buf.len;
271 pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
274 * Read the current index, replace the path entry with
275 * origin->blob_sha1 without mucking with its mode or type
276 * bits; we are not going to write this index out -- we just
277 * want to run "diff-index --cached".
279 discard_index(r->index);
280 repo_read_index(r);
282 len = strlen(path);
283 if (!mode) {
284 int pos = index_name_pos(r->index, path, len);
285 if (0 <= pos)
286 mode = r->index->cache[pos]->ce_mode;
287 else
288 /* Let's not bother reading from HEAD tree */
289 mode = S_IFREG | 0644;
291 ce = make_empty_cache_entry(r->index, len);
292 oidcpy(&ce->oid, &origin->blob_oid);
293 memcpy(ce->name, path, len);
294 ce->ce_flags = create_ce_flags(0);
295 ce->ce_namelen = len;
296 ce->ce_mode = create_ce_mode(mode);
297 add_index_entry(r->index, ce,
298 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
300 cache_tree_invalidate_path(r->index, path);
302 return commit;
307 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
308 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
310 xpparam_t xpp = {0};
311 xdemitconf_t xecfg = {0};
312 xdemitcb_t ecb = {NULL};
314 xpp.flags = xdl_opts;
315 xecfg.hunk_func = hunk_func;
316 ecb.priv = cb_data;
317 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
320 static const char *get_next_line(const char *start, const char *end)
322 const char *nl = memchr(start, '\n', end - start);
324 return nl ? nl + 1 : end;
327 static int find_line_starts(int **line_starts, const char *buf,
328 unsigned long len)
330 const char *end = buf + len;
331 const char *p;
332 int *lineno;
333 int num = 0;
335 for (p = buf; p < end; p = get_next_line(p, end))
336 num++;
338 ALLOC_ARRAY(*line_starts, num + 1);
339 lineno = *line_starts;
341 for (p = buf; p < end; p = get_next_line(p, end))
342 *lineno++ = p - buf;
344 *lineno = len;
346 return num;
349 struct fingerprint_entry;
351 /* A fingerprint is intended to loosely represent a string, such that two
352 * fingerprints can be quickly compared to give an indication of the similarity
353 * of the strings that they represent.
355 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
356 * the string that it represents. Whitespace is added at each end of the
357 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
358 * For example, the string "Darth Radar" will be converted to the following
359 * fingerprint:
360 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
362 * The similarity between two fingerprints is the size of the intersection of
363 * their multisets, including repeated elements. See fingerprint_similarity for
364 * examples.
366 * For ease of implementation, the fingerprint is implemented as a map
367 * of byte pairs to the count of that byte pair in the string, instead of
368 * allowing repeated elements in a set.
370 struct fingerprint {
371 struct hashmap map;
372 /* As we know the maximum number of entries in advance, it's
373 * convenient to store the entries in a single array instead of having
374 * the hashmap manage the memory.
376 struct fingerprint_entry *entries;
379 /* A byte pair in a fingerprint. Stores the number of times the byte pair
380 * occurs in the string that the fingerprint represents.
382 struct fingerprint_entry {
383 /* The hashmap entry - the hash represents the byte pair in its
384 * entirety so we don't need to store the byte pair separately.
386 struct hashmap_entry entry;
387 /* The number of times the byte pair occurs in the string that the
388 * fingerprint represents.
390 int count;
393 /* See `struct fingerprint` for an explanation of what a fingerprint is.
394 * \param result the fingerprint of the string is stored here. This must be
395 * freed later using free_fingerprint.
396 * \param line_begin the start of the string
397 * \param line_end the end of the string
399 static void get_fingerprint(struct fingerprint *result,
400 const char *line_begin,
401 const char *line_end)
403 unsigned int hash, c0 = 0, c1;
404 const char *p;
405 int max_map_entry_count = 1 + line_end - line_begin;
406 struct fingerprint_entry *entry = xcalloc(max_map_entry_count,
407 sizeof(struct fingerprint_entry));
408 struct fingerprint_entry *found_entry;
410 hashmap_init(&result->map, NULL, NULL, max_map_entry_count);
411 result->entries = entry;
412 for (p = line_begin; p <= line_end; ++p, c0 = c1) {
413 /* Always terminate the string with whitespace.
414 * Normalise whitespace to 0, and normalise letters to
415 * lower case. This won't work for multibyte characters but at
416 * worst will match some unrelated characters.
418 if ((p == line_end) || isspace(*p))
419 c1 = 0;
420 else
421 c1 = tolower(*p);
422 hash = c0 | (c1 << 8);
423 /* Ignore whitespace pairs */
424 if (hash == 0)
425 continue;
426 hashmap_entry_init(&entry->entry, hash);
428 found_entry = hashmap_get_entry(&result->map, entry,
429 /* member name */ entry, NULL);
430 if (found_entry) {
431 found_entry->count += 1;
432 } else {
433 entry->count = 1;
434 hashmap_add(&result->map, &entry->entry);
435 ++entry;
440 static void free_fingerprint(struct fingerprint *f)
442 hashmap_clear(&f->map);
443 free(f->entries);
446 /* Calculates the similarity between two fingerprints as the size of the
447 * intersection of their multisets, including repeated elements. See
448 * `struct fingerprint` for an explanation of the fingerprint representation.
449 * The similarity between "cat mat" and "father rather" is 2 because "at" is
450 * present twice in both strings while the similarity between "tim" and "mit"
451 * is 0.
453 static int fingerprint_similarity(struct fingerprint *a, struct fingerprint *b)
455 int intersection = 0;
456 struct hashmap_iter iter;
457 const struct fingerprint_entry *entry_a, *entry_b;
459 hashmap_for_each_entry(&b->map, &iter, entry_b,
460 entry /* member name */) {
461 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
462 if (entry_a) {
463 intersection += entry_a->count < entry_b->count ?
464 entry_a->count : entry_b->count;
467 return intersection;
470 /* Subtracts byte-pair elements in B from A, modifying A in place.
472 static void fingerprint_subtract(struct fingerprint *a, struct fingerprint *b)
474 struct hashmap_iter iter;
475 struct fingerprint_entry *entry_a;
476 const struct fingerprint_entry *entry_b;
478 hashmap_iter_init(&b->map, &iter);
480 hashmap_for_each_entry(&b->map, &iter, entry_b,
481 entry /* member name */) {
482 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
483 if (entry_a) {
484 if (entry_a->count <= entry_b->count)
485 hashmap_remove(&a->map, &entry_b->entry, NULL);
486 else
487 entry_a->count -= entry_b->count;
492 /* Calculate fingerprints for a series of lines.
493 * Puts the fingerprints in the fingerprints array, which must have been
494 * preallocated to allow storing line_count elements.
496 static void get_line_fingerprints(struct fingerprint *fingerprints,
497 const char *content, const int *line_starts,
498 long first_line, long line_count)
500 int i;
501 const char *linestart, *lineend;
503 line_starts += first_line;
504 for (i = 0; i < line_count; ++i) {
505 linestart = content + line_starts[i];
506 lineend = content + line_starts[i + 1];
507 get_fingerprint(fingerprints + i, linestart, lineend);
511 static void free_line_fingerprints(struct fingerprint *fingerprints,
512 int nr_fingerprints)
514 int i;
516 for (i = 0; i < nr_fingerprints; i++)
517 free_fingerprint(&fingerprints[i]);
520 /* This contains the data necessary to linearly map a line number in one half
521 * of a diff chunk to the line in the other half of the diff chunk that is
522 * closest in terms of its position as a fraction of the length of the chunk.
524 struct line_number_mapping {
525 int destination_start, destination_length,
526 source_start, source_length;
529 /* Given a line number in one range, offset and scale it to map it onto the
530 * other range.
531 * Essentially this mapping is a simple linear equation but the calculation is
532 * more complicated to allow performing it with integer operations.
533 * Another complication is that if a line could map onto many lines in the
534 * destination range then we want to choose the line at the center of those
535 * possibilities.
536 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
537 * first 5 lines in B will map onto the first line in the A chunk, while the
538 * last 5 lines will all map onto the second line in the A chunk.
539 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
540 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
542 static int map_line_number(int line_number,
543 const struct line_number_mapping *mapping)
545 return ((line_number - mapping->source_start) * 2 + 1) *
546 mapping->destination_length /
547 (mapping->source_length * 2) +
548 mapping->destination_start;
551 /* Get a pointer to the element storing the similarity between a line in A
552 * and a line in B.
554 * The similarities are stored in a 2-dimensional array. Each "row" in the
555 * array contains the similarities for a line in B. The similarities stored in
556 * a row are the similarities between the line in B and the nearby lines in A.
557 * To keep the length of each row the same, it is padded out with values of -1
558 * where the search range extends beyond the lines in A.
559 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
560 * look like this:
561 * a | m
562 * b | n
563 * c | o
564 * d | p
565 * e | q
566 * Then the similarity array will contain:
567 * [-1, -1, am, bm, cm,
568 * -1, an, bn, cn, dn,
569 * ao, bo, co, do, eo,
570 * bp, cp, dp, ep, -1,
571 * cq, dq, eq, -1, -1]
572 * Where similarities are denoted either by -1 for invalid, or the
573 * concatenation of the two lines in the diff being compared.
575 * \param similarities array of similarities between lines in A and B
576 * \param line_a the index of the line in A, in the same frame of reference as
577 * closest_line_a.
578 * \param local_line_b the index of the line in B, relative to the first line
579 * in B that similarities represents.
580 * \param closest_line_a the index of the line in A that is deemed to be
581 * closest to local_line_b. This must be in the same
582 * frame of reference as line_a. This value defines
583 * where similarities is centered for the line in B.
584 * \param max_search_distance_a maximum distance in lines from the closest line
585 * in A for other lines in A for which
586 * similarities may be calculated.
588 static int *get_similarity(int *similarities,
589 int line_a, int local_line_b,
590 int closest_line_a, int max_search_distance_a)
592 assert(abs(line_a - closest_line_a) <=
593 max_search_distance_a);
594 return similarities + line_a - closest_line_a +
595 max_search_distance_a +
596 local_line_b * (max_search_distance_a * 2 + 1);
599 #define CERTAIN_NOTHING_MATCHES -2
600 #define CERTAINTY_NOT_CALCULATED -1
602 /* Given a line in B, first calculate its similarities with nearby lines in A
603 * if not already calculated, then identify the most similar and second most
604 * similar lines. The "certainty" is calculated based on those two
605 * similarities.
607 * \param start_a the index of the first line of the chunk in A
608 * \param length_a the length in lines of the chunk in A
609 * \param local_line_b the index of the line in B, relative to the first line
610 * in the chunk.
611 * \param fingerprints_a array of fingerprints for the chunk in A
612 * \param fingerprints_b array of fingerprints for the chunk in B
613 * \param similarities 2-dimensional array of similarities between lines in A
614 * and B. See get_similarity() for more details.
615 * \param certainties array of values indicating how strongly a line in B is
616 * matched with some line in A.
617 * \param second_best_result array of absolute indices in A for the second
618 * closest match of a line in B.
619 * \param result array of absolute indices in A for the closest match of a line
620 * in B.
621 * \param max_search_distance_a maximum distance in lines from the closest line
622 * in A for other lines in A for which
623 * similarities may be calculated.
624 * \param map_line_number_in_b_to_a parameter to map_line_number().
626 static void find_best_line_matches(
627 int start_a,
628 int length_a,
629 int start_b,
630 int local_line_b,
631 struct fingerprint *fingerprints_a,
632 struct fingerprint *fingerprints_b,
633 int *similarities,
634 int *certainties,
635 int *second_best_result,
636 int *result,
637 const int max_search_distance_a,
638 const struct line_number_mapping *map_line_number_in_b_to_a)
641 int i, search_start, search_end, closest_local_line_a, *similarity,
642 best_similarity = 0, second_best_similarity = 0,
643 best_similarity_index = 0, second_best_similarity_index = 0;
645 /* certainty has already been calculated so no need to redo the work */
646 if (certainties[local_line_b] != CERTAINTY_NOT_CALCULATED)
647 return;
649 closest_local_line_a = map_line_number(
650 local_line_b + start_b, map_line_number_in_b_to_a) - start_a;
652 search_start = closest_local_line_a - max_search_distance_a;
653 if (search_start < 0)
654 search_start = 0;
656 search_end = closest_local_line_a + max_search_distance_a + 1;
657 if (search_end > length_a)
658 search_end = length_a;
660 for (i = search_start; i < search_end; ++i) {
661 similarity = get_similarity(similarities,
662 i, local_line_b,
663 closest_local_line_a,
664 max_search_distance_a);
665 if (*similarity == -1) {
666 /* This value will never exceed 10 but assert just in
667 * case
669 assert(abs(i - closest_local_line_a) < 1000);
670 /* scale the similarity by (1000 - distance from
671 * closest line) to act as a tie break between lines
672 * that otherwise are equally similar.
674 *similarity = fingerprint_similarity(
675 fingerprints_b + local_line_b,
676 fingerprints_a + i) *
677 (1000 - abs(i - closest_local_line_a));
679 if (*similarity > best_similarity) {
680 second_best_similarity = best_similarity;
681 second_best_similarity_index = best_similarity_index;
682 best_similarity = *similarity;
683 best_similarity_index = i;
684 } else if (*similarity > second_best_similarity) {
685 second_best_similarity = *similarity;
686 second_best_similarity_index = i;
690 if (best_similarity == 0) {
691 /* this line definitely doesn't match with anything. Mark it
692 * with this special value so it doesn't get invalidated and
693 * won't be recalculated.
695 certainties[local_line_b] = CERTAIN_NOTHING_MATCHES;
696 result[local_line_b] = -1;
697 } else {
698 /* Calculate the certainty with which this line matches.
699 * If the line matches well with two lines then that reduces
700 * the certainty. However we still want to prioritise matching
701 * a line that matches very well with two lines over matching a
702 * line that matches poorly with one line, hence doubling
703 * best_similarity.
704 * This means that if we have
705 * line X that matches only one line with a score of 3,
706 * line Y that matches two lines equally with a score of 5,
707 * and line Z that matches only one line with a score or 2,
708 * then the lines in order of certainty are X, Y, Z.
710 certainties[local_line_b] = best_similarity * 2 -
711 second_best_similarity;
713 /* We keep both the best and second best results to allow us to
714 * check at a later stage of the matching process whether the
715 * result needs to be invalidated.
717 result[local_line_b] = start_a + best_similarity_index;
718 second_best_result[local_line_b] =
719 start_a + second_best_similarity_index;
724 * This finds the line that we can match with the most confidence, and
725 * uses it as a partition. It then calls itself on the lines on either side of
726 * that partition. In this way we avoid lines appearing out of order, and
727 * retain a sensible line ordering.
728 * \param start_a index of the first line in A with which lines in B may be
729 * compared.
730 * \param start_b index of the first line in B for which matching should be
731 * done.
732 * \param length_a number of lines in A with which lines in B may be compared.
733 * \param length_b number of lines in B for which matching should be done.
734 * \param fingerprints_a mutable array of fingerprints in A. The first element
735 * corresponds to the line at start_a.
736 * \param fingerprints_b array of fingerprints in B. The first element
737 * corresponds to the line at start_b.
738 * \param similarities 2-dimensional array of similarities between lines in A
739 * and B. See get_similarity() for more details.
740 * \param certainties array of values indicating how strongly a line in B is
741 * matched with some line in A.
742 * \param second_best_result array of absolute indices in A for the second
743 * closest match of a line in B.
744 * \param result array of absolute indices in A for the closest match of a line
745 * in B.
746 * \param max_search_distance_a maximum distance in lines from the closest line
747 * in A for other lines in A for which
748 * similarities may be calculated.
749 * \param max_search_distance_b an upper bound on the greatest possible
750 * distance between lines in B such that they will
751 * both be compared with the same line in A
752 * according to max_search_distance_a.
753 * \param map_line_number_in_b_to_a parameter to map_line_number().
755 static void fuzzy_find_matching_lines_recurse(
756 int start_a, int start_b,
757 int length_a, int length_b,
758 struct fingerprint *fingerprints_a,
759 struct fingerprint *fingerprints_b,
760 int *similarities,
761 int *certainties,
762 int *second_best_result,
763 int *result,
764 int max_search_distance_a,
765 int max_search_distance_b,
766 const struct line_number_mapping *map_line_number_in_b_to_a)
768 int i, invalidate_min, invalidate_max, offset_b,
769 second_half_start_a, second_half_start_b,
770 second_half_length_a, second_half_length_b,
771 most_certain_line_a, most_certain_local_line_b = -1,
772 most_certain_line_certainty = -1,
773 closest_local_line_a;
775 for (i = 0; i < length_b; ++i) {
776 find_best_line_matches(start_a,
777 length_a,
778 start_b,
780 fingerprints_a,
781 fingerprints_b,
782 similarities,
783 certainties,
784 second_best_result,
785 result,
786 max_search_distance_a,
787 map_line_number_in_b_to_a);
789 if (certainties[i] > most_certain_line_certainty) {
790 most_certain_line_certainty = certainties[i];
791 most_certain_local_line_b = i;
795 /* No matches. */
796 if (most_certain_local_line_b == -1)
797 return;
799 most_certain_line_a = result[most_certain_local_line_b];
802 * Subtract the most certain line's fingerprint in B from the matched
803 * fingerprint in A. This means that other lines in B can't also match
804 * the same parts of the line in A.
806 fingerprint_subtract(fingerprints_a + most_certain_line_a - start_a,
807 fingerprints_b + most_certain_local_line_b);
809 /* Invalidate results that may be affected by the choice of most
810 * certain line.
812 invalidate_min = most_certain_local_line_b - max_search_distance_b;
813 invalidate_max = most_certain_local_line_b + max_search_distance_b + 1;
814 if (invalidate_min < 0)
815 invalidate_min = 0;
816 if (invalidate_max > length_b)
817 invalidate_max = length_b;
819 /* As the fingerprint in A has changed, discard previously calculated
820 * similarity values with that fingerprint.
822 for (i = invalidate_min; i < invalidate_max; ++i) {
823 closest_local_line_a = map_line_number(
824 i + start_b, map_line_number_in_b_to_a) - start_a;
826 /* Check that the lines in A and B are close enough that there
827 * is a similarity value for them.
829 if (abs(most_certain_line_a - start_a - closest_local_line_a) >
830 max_search_distance_a) {
831 continue;
834 *get_similarity(similarities, most_certain_line_a - start_a,
835 i, closest_local_line_a,
836 max_search_distance_a) = -1;
839 /* More invalidating of results that may be affected by the choice of
840 * most certain line.
841 * Discard the matches for lines in B that are currently matched with a
842 * line in A such that their ordering contradicts the ordering imposed
843 * by the choice of most certain line.
845 for (i = most_certain_local_line_b - 1; i >= invalidate_min; --i) {
846 /* In this loop we discard results for lines in B that are
847 * before most-certain-line-B but are matched with a line in A
848 * that is after most-certain-line-A.
850 if (certainties[i] >= 0 &&
851 (result[i] >= most_certain_line_a ||
852 second_best_result[i] >= most_certain_line_a)) {
853 certainties[i] = CERTAINTY_NOT_CALCULATED;
856 for (i = most_certain_local_line_b + 1; i < invalidate_max; ++i) {
857 /* In this loop we discard results for lines in B that are
858 * after most-certain-line-B but are matched with a line in A
859 * that is before most-certain-line-A.
861 if (certainties[i] >= 0 &&
862 (result[i] <= most_certain_line_a ||
863 second_best_result[i] <= most_certain_line_a)) {
864 certainties[i] = CERTAINTY_NOT_CALCULATED;
868 /* Repeat the matching process for lines before the most certain line.
870 if (most_certain_local_line_b > 0) {
871 fuzzy_find_matching_lines_recurse(
872 start_a, start_b,
873 most_certain_line_a + 1 - start_a,
874 most_certain_local_line_b,
875 fingerprints_a, fingerprints_b, similarities,
876 certainties, second_best_result, result,
877 max_search_distance_a,
878 max_search_distance_b,
879 map_line_number_in_b_to_a);
881 /* Repeat the matching process for lines after the most certain line.
883 if (most_certain_local_line_b + 1 < length_b) {
884 second_half_start_a = most_certain_line_a;
885 offset_b = most_certain_local_line_b + 1;
886 second_half_start_b = start_b + offset_b;
887 second_half_length_a =
888 length_a + start_a - second_half_start_a;
889 second_half_length_b =
890 length_b + start_b - second_half_start_b;
891 fuzzy_find_matching_lines_recurse(
892 second_half_start_a, second_half_start_b,
893 second_half_length_a, second_half_length_b,
894 fingerprints_a + second_half_start_a - start_a,
895 fingerprints_b + offset_b,
896 similarities +
897 offset_b * (max_search_distance_a * 2 + 1),
898 certainties + offset_b,
899 second_best_result + offset_b, result + offset_b,
900 max_search_distance_a,
901 max_search_distance_b,
902 map_line_number_in_b_to_a);
906 /* Find the lines in the parent line range that most closely match the lines in
907 * the target line range. This is accomplished by matching fingerprints in each
908 * blame_origin, and choosing the best matches that preserve the line ordering.
909 * See struct fingerprint for details of fingerprint matching, and
910 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
912 * The performance is believed to be O(n log n) in the typical case and O(n^2)
913 * in a pathological case, where n is the number of lines in the target range.
915 static int *fuzzy_find_matching_lines(struct blame_origin *parent,
916 struct blame_origin *target,
917 int tlno, int parent_slno, int same,
918 int parent_len)
920 /* We use the terminology "A" for the left hand side of the diff AKA
921 * parent, and "B" for the right hand side of the diff AKA target. */
922 int start_a = parent_slno;
923 int length_a = parent_len;
924 int start_b = tlno;
925 int length_b = same - tlno;
927 struct line_number_mapping map_line_number_in_b_to_a = {
928 start_a, length_a, start_b, length_b
931 struct fingerprint *fingerprints_a = parent->fingerprints;
932 struct fingerprint *fingerprints_b = target->fingerprints;
934 int i, *result, *second_best_result,
935 *certainties, *similarities, similarity_count;
938 * max_search_distance_a means that given a line in B, compare it to
939 * the line in A that is closest to its position, and the lines in A
940 * that are no greater than max_search_distance_a lines away from the
941 * closest line in A.
943 * max_search_distance_b is an upper bound on the greatest possible
944 * distance between lines in B such that they will both be compared
945 * with the same line in A according to max_search_distance_a.
947 int max_search_distance_a = 10, max_search_distance_b;
949 if (length_a <= 0)
950 return NULL;
952 if (max_search_distance_a >= length_a)
953 max_search_distance_a = length_a ? length_a - 1 : 0;
955 max_search_distance_b = ((2 * max_search_distance_a + 1) * length_b
956 - 1) / length_a;
958 CALLOC_ARRAY(result, length_b);
959 CALLOC_ARRAY(second_best_result, length_b);
960 CALLOC_ARRAY(certainties, length_b);
962 /* See get_similarity() for details of similarities. */
963 similarity_count = length_b * (max_search_distance_a * 2 + 1);
964 CALLOC_ARRAY(similarities, similarity_count);
966 for (i = 0; i < length_b; ++i) {
967 result[i] = -1;
968 second_best_result[i] = -1;
969 certainties[i] = CERTAINTY_NOT_CALCULATED;
972 for (i = 0; i < similarity_count; ++i)
973 similarities[i] = -1;
975 fuzzy_find_matching_lines_recurse(start_a, start_b,
976 length_a, length_b,
977 fingerprints_a + start_a,
978 fingerprints_b + start_b,
979 similarities,
980 certainties,
981 second_best_result,
982 result,
983 max_search_distance_a,
984 max_search_distance_b,
985 &map_line_number_in_b_to_a);
987 free(similarities);
988 free(certainties);
989 free(second_best_result);
991 return result;
994 static void fill_origin_fingerprints(struct blame_origin *o)
996 int *line_starts;
998 if (o->fingerprints)
999 return;
1000 o->num_lines = find_line_starts(&line_starts, o->file.ptr,
1001 o->file.size);
1002 CALLOC_ARRAY(o->fingerprints, o->num_lines);
1003 get_line_fingerprints(o->fingerprints, o->file.ptr, line_starts,
1004 0, o->num_lines);
1005 free(line_starts);
1008 static void drop_origin_fingerprints(struct blame_origin *o)
1010 if (o->fingerprints) {
1011 free_line_fingerprints(o->fingerprints, o->num_lines);
1012 o->num_lines = 0;
1013 FREE_AND_NULL(o->fingerprints);
1018 * Given an origin, prepare mmfile_t structure to be used by the
1019 * diff machinery
1021 static void fill_origin_blob(struct diff_options *opt,
1022 struct blame_origin *o, mmfile_t *file,
1023 int *num_read_blob, int fill_fingerprints)
1025 if (!o->file.ptr) {
1026 enum object_type type;
1027 unsigned long file_size;
1029 (*num_read_blob)++;
1030 if (opt->flags.allow_textconv &&
1031 textconv_object(opt->repo, o->path, o->mode,
1032 &o->blob_oid, 1, &file->ptr, &file_size))
1034 else
1035 file->ptr = repo_read_object_file(the_repository,
1036 &o->blob_oid, &type,
1037 &file_size);
1038 file->size = file_size;
1040 if (!file->ptr)
1041 die("Cannot read blob %s for path %s",
1042 oid_to_hex(&o->blob_oid),
1043 o->path);
1044 o->file = *file;
1046 else
1047 *file = o->file;
1048 if (fill_fingerprints)
1049 fill_origin_fingerprints(o);
1052 static void drop_origin_blob(struct blame_origin *o)
1054 FREE_AND_NULL(o->file.ptr);
1055 drop_origin_fingerprints(o);
1059 * Any merge of blames happens on lists of blames that arrived via
1060 * different parents in a single suspect. In this case, we want to
1061 * sort according to the suspect line numbers as opposed to the final
1062 * image line numbers. The function body is somewhat longish because
1063 * it avoids unnecessary writes.
1066 static struct blame_entry *blame_merge(struct blame_entry *list1,
1067 struct blame_entry *list2)
1069 struct blame_entry *p1 = list1, *p2 = list2,
1070 **tail = &list1;
1072 if (!p1)
1073 return p2;
1074 if (!p2)
1075 return p1;
1077 if (p1->s_lno <= p2->s_lno) {
1078 do {
1079 tail = &p1->next;
1080 if (!(p1 = *tail)) {
1081 *tail = p2;
1082 return list1;
1084 } while (p1->s_lno <= p2->s_lno);
1086 for (;;) {
1087 *tail = p2;
1088 do {
1089 tail = &p2->next;
1090 if (!(p2 = *tail)) {
1091 *tail = p1;
1092 return list1;
1094 } while (p1->s_lno > p2->s_lno);
1095 *tail = p1;
1096 do {
1097 tail = &p1->next;
1098 if (!(p1 = *tail)) {
1099 *tail = p2;
1100 return list1;
1102 } while (p1->s_lno <= p2->s_lno);
1106 DEFINE_LIST_SORT(static, sort_blame_entries, struct blame_entry, next);
1109 * Final image line numbers are all different, so we don't need a
1110 * three-way comparison here.
1113 static int compare_blame_final(const struct blame_entry *e1,
1114 const struct blame_entry *e2)
1116 return e1->lno > e2->lno ? 1 : -1;
1119 static int compare_blame_suspect(const struct blame_entry *s1,
1120 const struct blame_entry *s2)
1123 * to allow for collating suspects, we sort according to the
1124 * respective pointer value as the primary sorting criterion.
1125 * The actual relation is pretty unimportant as long as it
1126 * establishes a total order. Comparing as integers gives us
1127 * that.
1129 if (s1->suspect != s2->suspect)
1130 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
1131 if (s1->s_lno == s2->s_lno)
1132 return 0;
1133 return s1->s_lno > s2->s_lno ? 1 : -1;
1136 void blame_sort_final(struct blame_scoreboard *sb)
1138 sort_blame_entries(&sb->ent, compare_blame_final);
1141 static int compare_commits_by_reverse_commit_date(const void *a,
1142 const void *b,
1143 void *c)
1145 return -compare_commits_by_commit_date(a, b, c);
1149 * For debugging -- origin is refcounted, and this asserts that
1150 * we do not underflow.
1152 static void sanity_check_refcnt(struct blame_scoreboard *sb)
1154 int baa = 0;
1155 struct blame_entry *ent;
1157 for (ent = sb->ent; ent; ent = ent->next) {
1158 /* Nobody should have zero or negative refcnt */
1159 if (ent->suspect->refcnt <= 0) {
1160 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1161 ent->suspect->path,
1162 oid_to_hex(&ent->suspect->commit->object.oid),
1163 ent->suspect->refcnt);
1164 baa = 1;
1167 if (baa)
1168 sb->on_sanity_fail(sb, baa);
1172 * If two blame entries that are next to each other came from
1173 * contiguous lines in the same origin (i.e. <commit, path> pair),
1174 * merge them together.
1176 void blame_coalesce(struct blame_scoreboard *sb)
1178 struct blame_entry *ent, *next;
1180 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
1181 if (ent->suspect == next->suspect &&
1182 ent->s_lno + ent->num_lines == next->s_lno &&
1183 ent->lno + ent->num_lines == next->lno &&
1184 ent->ignored == next->ignored &&
1185 ent->unblamable == next->unblamable) {
1186 ent->num_lines += next->num_lines;
1187 ent->next = next->next;
1188 blame_origin_decref(next->suspect);
1189 free(next);
1190 ent->score = 0;
1191 next = ent; /* again */
1195 if (sb->debug) /* sanity */
1196 sanity_check_refcnt(sb);
1200 * Merge the given sorted list of blames into a preexisting origin.
1201 * If there were no previous blames to that commit, it is entered into
1202 * the commit priority queue of the score board.
1205 static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
1206 struct blame_entry *sorted)
1208 if (porigin->suspects)
1209 porigin->suspects = blame_merge(porigin->suspects, sorted);
1210 else {
1211 struct blame_origin *o;
1212 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
1213 if (o->suspects) {
1214 porigin->suspects = sorted;
1215 return;
1218 porigin->suspects = sorted;
1219 prio_queue_put(&sb->commits, porigin->commit);
1224 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1225 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1226 * for an origin is also used to pass the blame for the entire file to
1227 * the parent to detect the case where a child's blob is identical to
1228 * that of its parent's.
1230 * This also fills origin->mode for corresponding tree path.
1232 static int fill_blob_sha1_and_mode(struct repository *r,
1233 struct blame_origin *origin)
1235 if (!is_null_oid(&origin->blob_oid))
1236 return 0;
1237 if (get_tree_entry(r, &origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
1238 goto error_out;
1239 if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
1240 goto error_out;
1241 return 0;
1242 error_out:
1243 oidclr(&origin->blob_oid);
1244 origin->mode = S_IFINVALID;
1245 return -1;
1248 struct blame_bloom_data {
1250 * Changed-path Bloom filter keys. These can help prevent
1251 * computing diffs against first parents, but we need to
1252 * expand the list as code is moved or files are renamed.
1254 struct bloom_filter_settings *settings;
1255 struct bloom_key **keys;
1256 int nr;
1257 int alloc;
1260 static int bloom_count_queries = 0;
1261 static int bloom_count_no = 0;
1262 static int maybe_changed_path(struct repository *r,
1263 struct blame_origin *origin,
1264 struct blame_bloom_data *bd)
1266 int i;
1267 struct bloom_filter *filter;
1269 if (!bd)
1270 return 1;
1272 if (commit_graph_generation(origin->commit) == GENERATION_NUMBER_INFINITY)
1273 return 1;
1275 filter = get_bloom_filter(r, origin->commit);
1277 if (!filter)
1278 return 1;
1280 bloom_count_queries++;
1281 for (i = 0; i < bd->nr; i++) {
1282 if (bloom_filter_contains(filter,
1283 bd->keys[i],
1284 bd->settings))
1285 return 1;
1288 bloom_count_no++;
1289 return 0;
1292 static void add_bloom_key(struct blame_bloom_data *bd,
1293 const char *path)
1295 if (!bd)
1296 return;
1298 if (bd->nr >= bd->alloc) {
1299 bd->alloc *= 2;
1300 REALLOC_ARRAY(bd->keys, bd->alloc);
1303 bd->keys[bd->nr] = xmalloc(sizeof(struct bloom_key));
1304 fill_bloom_key(path, strlen(path), bd->keys[bd->nr], bd->settings);
1305 bd->nr++;
1309 * We have an origin -- check if the same path exists in the
1310 * parent and return an origin structure to represent it.
1312 static struct blame_origin *find_origin(struct repository *r,
1313 struct commit *parent,
1314 struct blame_origin *origin,
1315 struct blame_bloom_data *bd)
1317 struct blame_origin *porigin;
1318 struct diff_options diff_opts;
1319 const char *paths[2];
1321 /* First check any existing origins */
1322 for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
1323 if (!strcmp(porigin->path, origin->path)) {
1325 * The same path between origin and its parent
1326 * without renaming -- the most common case.
1328 return blame_origin_incref (porigin);
1331 /* See if the origin->path is different between parent
1332 * and origin first. Most of the time they are the
1333 * same and diff-tree is fairly efficient about this.
1335 repo_diff_setup(r, &diff_opts);
1336 diff_opts.flags.recursive = 1;
1337 diff_opts.detect_rename = 0;
1338 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1339 paths[0] = origin->path;
1340 paths[1] = NULL;
1342 parse_pathspec(&diff_opts.pathspec,
1343 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1344 PATHSPEC_LITERAL_PATH, "", paths);
1345 diff_setup_done(&diff_opts);
1347 if (is_null_oid(&origin->commit->object.oid))
1348 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1349 else {
1350 int compute_diff = 1;
1351 if (origin->commit->parents &&
1352 oideq(&parent->object.oid,
1353 &origin->commit->parents->item->object.oid))
1354 compute_diff = maybe_changed_path(r, origin, bd);
1356 if (compute_diff)
1357 diff_tree_oid(get_commit_tree_oid(parent),
1358 get_commit_tree_oid(origin->commit),
1359 "", &diff_opts);
1361 diffcore_std(&diff_opts);
1363 if (!diff_queued_diff.nr) {
1364 /* The path is the same as parent */
1365 porigin = get_origin(parent, origin->path);
1366 oidcpy(&porigin->blob_oid, &origin->blob_oid);
1367 porigin->mode = origin->mode;
1368 } else {
1370 * Since origin->path is a pathspec, if the parent
1371 * commit had it as a directory, we will see a whole
1372 * bunch of deletion of files in the directory that we
1373 * do not care about.
1375 int i;
1376 struct diff_filepair *p = NULL;
1377 for (i = 0; i < diff_queued_diff.nr; i++) {
1378 const char *name;
1379 p = diff_queued_diff.queue[i];
1380 name = p->one->path ? p->one->path : p->two->path;
1381 if (!strcmp(name, origin->path))
1382 break;
1384 if (!p)
1385 die("internal error in blame::find_origin");
1386 switch (p->status) {
1387 default:
1388 die("internal error in blame::find_origin (%c)",
1389 p->status);
1390 case 'M':
1391 porigin = get_origin(parent, origin->path);
1392 oidcpy(&porigin->blob_oid, &p->one->oid);
1393 porigin->mode = p->one->mode;
1394 break;
1395 case 'A':
1396 case 'T':
1397 /* Did not exist in parent, or type changed */
1398 break;
1401 diff_flush(&diff_opts);
1402 return porigin;
1406 * We have an origin -- find the path that corresponds to it in its
1407 * parent and return an origin structure to represent it.
1409 static struct blame_origin *find_rename(struct repository *r,
1410 struct commit *parent,
1411 struct blame_origin *origin,
1412 struct blame_bloom_data *bd)
1414 struct blame_origin *porigin = NULL;
1415 struct diff_options diff_opts;
1416 int i;
1418 repo_diff_setup(r, &diff_opts);
1419 diff_opts.flags.recursive = 1;
1420 diff_opts.detect_rename = DIFF_DETECT_RENAME;
1421 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1422 diff_opts.single_follow = origin->path;
1423 diff_setup_done(&diff_opts);
1425 if (is_null_oid(&origin->commit->object.oid))
1426 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1427 else
1428 diff_tree_oid(get_commit_tree_oid(parent),
1429 get_commit_tree_oid(origin->commit),
1430 "", &diff_opts);
1431 diffcore_std(&diff_opts);
1433 for (i = 0; i < diff_queued_diff.nr; i++) {
1434 struct diff_filepair *p = diff_queued_diff.queue[i];
1435 if ((p->status == 'R' || p->status == 'C') &&
1436 !strcmp(p->two->path, origin->path)) {
1437 add_bloom_key(bd, p->one->path);
1438 porigin = get_origin(parent, p->one->path);
1439 oidcpy(&porigin->blob_oid, &p->one->oid);
1440 porigin->mode = p->one->mode;
1441 break;
1444 diff_flush(&diff_opts);
1445 return porigin;
1449 * Append a new blame entry to a given output queue.
1451 static void add_blame_entry(struct blame_entry ***queue,
1452 const struct blame_entry *src)
1454 struct blame_entry *e = xmalloc(sizeof(*e));
1455 memcpy(e, src, sizeof(*e));
1456 blame_origin_incref(e->suspect);
1458 e->next = **queue;
1459 **queue = e;
1460 *queue = &e->next;
1464 * src typically is on-stack; we want to copy the information in it to
1465 * a malloced blame_entry that gets added to the given queue. The
1466 * origin of dst loses a refcnt.
1468 static void dup_entry(struct blame_entry ***queue,
1469 struct blame_entry *dst, struct blame_entry *src)
1471 blame_origin_incref(src->suspect);
1472 blame_origin_decref(dst->suspect);
1473 memcpy(dst, src, sizeof(*src));
1474 dst->next = **queue;
1475 **queue = dst;
1476 *queue = &dst->next;
1479 const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
1481 return sb->final_buf + sb->lineno[lno];
1485 * It is known that lines between tlno to same came from parent, and e
1486 * has an overlap with that range. it also is known that parent's
1487 * line plno corresponds to e's line tlno.
1489 * <---- e ----->
1490 * <------>
1491 * <------------>
1492 * <------------>
1493 * <------------------>
1495 * Split e into potentially three parts; before this chunk, the chunk
1496 * to be blamed for the parent, and after that portion.
1498 static void split_overlap(struct blame_entry *split,
1499 struct blame_entry *e,
1500 int tlno, int plno, int same,
1501 struct blame_origin *parent)
1503 int chunk_end_lno;
1504 int i;
1505 memset(split, 0, sizeof(struct blame_entry [3]));
1507 for (i = 0; i < 3; i++) {
1508 split[i].ignored = e->ignored;
1509 split[i].unblamable = e->unblamable;
1512 if (e->s_lno < tlno) {
1513 /* there is a pre-chunk part not blamed on parent */
1514 split[0].suspect = blame_origin_incref(e->suspect);
1515 split[0].lno = e->lno;
1516 split[0].s_lno = e->s_lno;
1517 split[0].num_lines = tlno - e->s_lno;
1518 split[1].lno = e->lno + tlno - e->s_lno;
1519 split[1].s_lno = plno;
1521 else {
1522 split[1].lno = e->lno;
1523 split[1].s_lno = plno + (e->s_lno - tlno);
1526 if (same < e->s_lno + e->num_lines) {
1527 /* there is a post-chunk part not blamed on parent */
1528 split[2].suspect = blame_origin_incref(e->suspect);
1529 split[2].lno = e->lno + (same - e->s_lno);
1530 split[2].s_lno = e->s_lno + (same - e->s_lno);
1531 split[2].num_lines = e->s_lno + e->num_lines - same;
1532 chunk_end_lno = split[2].lno;
1534 else
1535 chunk_end_lno = e->lno + e->num_lines;
1536 split[1].num_lines = chunk_end_lno - split[1].lno;
1539 * if it turns out there is nothing to blame the parent for,
1540 * forget about the splitting. !split[1].suspect signals this.
1542 if (split[1].num_lines < 1)
1543 return;
1544 split[1].suspect = blame_origin_incref(parent);
1548 * split_overlap() divided an existing blame e into up to three parts
1549 * in split. Any assigned blame is moved to queue to
1550 * reflect the split.
1552 static void split_blame(struct blame_entry ***blamed,
1553 struct blame_entry ***unblamed,
1554 struct blame_entry *split,
1555 struct blame_entry *e)
1557 if (split[0].suspect && split[2].suspect) {
1558 /* The first part (reuse storage for the existing entry e) */
1559 dup_entry(unblamed, e, &split[0]);
1561 /* The last part -- me */
1562 add_blame_entry(unblamed, &split[2]);
1564 /* ... and the middle part -- parent */
1565 add_blame_entry(blamed, &split[1]);
1567 else if (!split[0].suspect && !split[2].suspect)
1569 * The parent covers the entire area; reuse storage for
1570 * e and replace it with the parent.
1572 dup_entry(blamed, e, &split[1]);
1573 else if (split[0].suspect) {
1574 /* me and then parent */
1575 dup_entry(unblamed, e, &split[0]);
1576 add_blame_entry(blamed, &split[1]);
1578 else {
1579 /* parent and then me */
1580 dup_entry(blamed, e, &split[1]);
1581 add_blame_entry(unblamed, &split[2]);
1586 * After splitting the blame, the origins used by the
1587 * on-stack blame_entry should lose one refcnt each.
1589 static void decref_split(struct blame_entry *split)
1591 int i;
1593 for (i = 0; i < 3; i++)
1594 blame_origin_decref(split[i].suspect);
1598 * reverse_blame reverses the list given in head, appending tail.
1599 * That allows us to build lists in reverse order, then reverse them
1600 * afterwards. This can be faster than building the list in proper
1601 * order right away. The reason is that building in proper order
1602 * requires writing a link in the _previous_ element, while building
1603 * in reverse order just requires placing the list head into the
1604 * _current_ element.
1607 static struct blame_entry *reverse_blame(struct blame_entry *head,
1608 struct blame_entry *tail)
1610 while (head) {
1611 struct blame_entry *next = head->next;
1612 head->next = tail;
1613 tail = head;
1614 head = next;
1616 return tail;
1620 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1621 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1622 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1623 * e->num_lines). The caller needs to sort out the reference counting for the
1624 * new entry's suspect.
1626 static struct blame_entry *split_blame_at(struct blame_entry *e, int len,
1627 struct blame_origin *new_suspect)
1629 struct blame_entry *n = xcalloc(1, sizeof(struct blame_entry));
1631 n->suspect = new_suspect;
1632 n->ignored = e->ignored;
1633 n->unblamable = e->unblamable;
1634 n->lno = e->lno + len;
1635 n->s_lno = e->s_lno + len;
1636 n->num_lines = e->num_lines - len;
1637 e->num_lines = len;
1638 e->score = 0;
1639 return n;
1642 struct blame_line_tracker {
1643 int is_parent;
1644 int s_lno;
1647 static int are_lines_adjacent(struct blame_line_tracker *first,
1648 struct blame_line_tracker *second)
1650 return first->is_parent == second->is_parent &&
1651 first->s_lno + 1 == second->s_lno;
1654 static int scan_parent_range(struct fingerprint *p_fps,
1655 struct fingerprint *t_fps, int t_idx,
1656 int from, int nr_lines)
1658 int sim, p_idx;
1659 #define FINGERPRINT_FILE_THRESHOLD 10
1660 int best_sim_val = FINGERPRINT_FILE_THRESHOLD;
1661 int best_sim_idx = -1;
1663 for (p_idx = from; p_idx < from + nr_lines; p_idx++) {
1664 sim = fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);
1665 if (sim < best_sim_val)
1666 continue;
1667 /* Break ties with the closest-to-target line number */
1668 if (sim == best_sim_val && best_sim_idx != -1 &&
1669 abs(best_sim_idx - t_idx) < abs(p_idx - t_idx))
1670 continue;
1671 best_sim_val = sim;
1672 best_sim_idx = p_idx;
1674 return best_sim_idx;
1678 * The first pass checks the blame entry (from the target) against the parent's
1679 * diff chunk. If that fails for a line, the second pass tries to match that
1680 * line to any part of parent file. That catches cases where a change was
1681 * broken into two chunks by 'context.'
1683 static void guess_line_blames(struct blame_origin *parent,
1684 struct blame_origin *target,
1685 int tlno, int offset, int same, int parent_len,
1686 struct blame_line_tracker *line_blames)
1688 int i, best_idx, target_idx;
1689 int parent_slno = tlno + offset;
1690 int *fuzzy_matches;
1692 fuzzy_matches = fuzzy_find_matching_lines(parent, target,
1693 tlno, parent_slno, same,
1694 parent_len);
1695 for (i = 0; i < same - tlno; i++) {
1696 target_idx = tlno + i;
1697 if (fuzzy_matches && fuzzy_matches[i] >= 0) {
1698 best_idx = fuzzy_matches[i];
1699 } else {
1700 best_idx = scan_parent_range(parent->fingerprints,
1701 target->fingerprints,
1702 target_idx, 0,
1703 parent->num_lines);
1705 if (best_idx >= 0) {
1706 line_blames[i].is_parent = 1;
1707 line_blames[i].s_lno = best_idx;
1708 } else {
1709 line_blames[i].is_parent = 0;
1710 line_blames[i].s_lno = target_idx;
1713 free(fuzzy_matches);
1717 * This decides which parts of a blame entry go to the parent (added to the
1718 * ignoredp list) and which stay with the target (added to the diffp list). The
1719 * actual decision was made in a separate heuristic function, and those answers
1720 * for the lines in 'e' are in line_blames. This consumes e, essentially
1721 * putting it on a list.
1723 * Note that the blame entries on the ignoredp list are not necessarily sorted
1724 * with respect to the parent's line numbers yet.
1726 static void ignore_blame_entry(struct blame_entry *e,
1727 struct blame_origin *parent,
1728 struct blame_entry **diffp,
1729 struct blame_entry **ignoredp,
1730 struct blame_line_tracker *line_blames)
1732 int entry_len, nr_lines, i;
1735 * We carve new entries off the front of e. Each entry comes from a
1736 * contiguous chunk of lines: adjacent lines from the same origin
1737 * (either the parent or the target).
1739 entry_len = 1;
1740 nr_lines = e->num_lines; /* e changes in the loop */
1741 for (i = 0; i < nr_lines; i++) {
1742 struct blame_entry *next = NULL;
1745 * We are often adjacent to the next line - only split the blame
1746 * entry when we have to.
1748 if (i + 1 < nr_lines) {
1749 if (are_lines_adjacent(&line_blames[i],
1750 &line_blames[i + 1])) {
1751 entry_len++;
1752 continue;
1754 next = split_blame_at(e, entry_len,
1755 blame_origin_incref(e->suspect));
1757 if (line_blames[i].is_parent) {
1758 e->ignored = 1;
1759 blame_origin_decref(e->suspect);
1760 e->suspect = blame_origin_incref(parent);
1761 e->s_lno = line_blames[i - entry_len + 1].s_lno;
1762 e->next = *ignoredp;
1763 *ignoredp = e;
1764 } else {
1765 e->unblamable = 1;
1766 /* e->s_lno is already in the target's address space. */
1767 e->next = *diffp;
1768 *diffp = e;
1770 assert(e->num_lines == entry_len);
1771 e = next;
1772 entry_len = 1;
1774 assert(!e);
1778 * Process one hunk from the patch between the current suspect for
1779 * blame_entry e and its parent. This first blames any unfinished
1780 * entries before the chunk (which is where target and parent start
1781 * differing) on the parent, and then splits blame entries at the
1782 * start and at the end of the difference region. Since use of -M and
1783 * -C options may lead to overlapping/duplicate source line number
1784 * ranges, all we can rely on from sorting/merging is the order of the
1785 * first suspect line number.
1787 * tlno: line number in the target where this chunk begins
1788 * same: line number in the target where this chunk ends
1789 * offset: add to tlno to get the chunk starting point in the parent
1790 * parent_len: number of lines in the parent chunk
1792 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
1793 int tlno, int offset, int same, int parent_len,
1794 struct blame_origin *parent,
1795 struct blame_origin *target, int ignore_diffs)
1797 struct blame_entry *e = **srcq;
1798 struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;
1799 struct blame_line_tracker *line_blames = NULL;
1801 while (e && e->s_lno < tlno) {
1802 struct blame_entry *next = e->next;
1804 * current record starts before differing portion. If
1805 * it reaches into it, we need to split it up and
1806 * examine the second part separately.
1808 if (e->s_lno + e->num_lines > tlno) {
1809 /* Move second half to a new record */
1810 struct blame_entry *n;
1812 n = split_blame_at(e, tlno - e->s_lno, e->suspect);
1813 /* Push new record to diffp */
1814 n->next = diffp;
1815 diffp = n;
1816 } else
1817 blame_origin_decref(e->suspect);
1818 /* Pass blame for everything before the differing
1819 * chunk to the parent */
1820 e->suspect = blame_origin_incref(parent);
1821 e->s_lno += offset;
1822 e->next = samep;
1823 samep = e;
1824 e = next;
1827 * As we don't know how much of a common stretch after this
1828 * diff will occur, the currently blamed parts are all that we
1829 * can assign to the parent for now.
1832 if (samep) {
1833 **dstq = reverse_blame(samep, **dstq);
1834 *dstq = &samep->next;
1837 * Prepend the split off portions: everything after e starts
1838 * after the blameable portion.
1840 e = reverse_blame(diffp, e);
1843 * Now retain records on the target while parts are different
1844 * from the parent.
1846 samep = NULL;
1847 diffp = NULL;
1849 if (ignore_diffs && same - tlno > 0) {
1850 CALLOC_ARRAY(line_blames, same - tlno);
1851 guess_line_blames(parent, target, tlno, offset, same,
1852 parent_len, line_blames);
1855 while (e && e->s_lno < same) {
1856 struct blame_entry *next = e->next;
1859 * If current record extends into sameness, need to split.
1861 if (e->s_lno + e->num_lines > same) {
1863 * Move second half to a new record to be
1864 * processed by later chunks
1866 struct blame_entry *n;
1868 n = split_blame_at(e, same - e->s_lno,
1869 blame_origin_incref(e->suspect));
1870 /* Push new record to samep */
1871 n->next = samep;
1872 samep = n;
1874 if (ignore_diffs) {
1875 ignore_blame_entry(e, parent, &diffp, &ignoredp,
1876 line_blames + e->s_lno - tlno);
1877 } else {
1878 e->next = diffp;
1879 diffp = e;
1881 e = next;
1883 free(line_blames);
1884 if (ignoredp) {
1886 * Note ignoredp is not sorted yet, and thus neither is dstq.
1887 * That list must be sorted before we queue_blames(). We defer
1888 * sorting until after all diff hunks are processed, so that
1889 * guess_line_blames() can pick *any* line in the parent. The
1890 * slight drawback is that we end up sorting all blame entries
1891 * passed to the parent, including those that are unrelated to
1892 * changes made by the ignored commit.
1894 **dstq = reverse_blame(ignoredp, **dstq);
1895 *dstq = &ignoredp->next;
1897 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
1898 /* Move across elements that are in the unblamable portion */
1899 if (diffp)
1900 *srcq = &diffp->next;
1903 struct blame_chunk_cb_data {
1904 struct blame_origin *parent;
1905 struct blame_origin *target;
1906 long offset;
1907 int ignore_diffs;
1908 struct blame_entry **dstq;
1909 struct blame_entry **srcq;
1912 /* diff chunks are from parent to target */
1913 static int blame_chunk_cb(long start_a, long count_a,
1914 long start_b, long count_b, void *data)
1916 struct blame_chunk_cb_data *d = data;
1917 if (start_a - start_b != d->offset)
1918 die("internal error in blame::blame_chunk_cb");
1919 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
1920 start_b + count_b, count_a, d->parent, d->target,
1921 d->ignore_diffs);
1922 d->offset = start_a + count_a - (start_b + count_b);
1923 return 0;
1927 * We are looking at the origin 'target' and aiming to pass blame
1928 * for the lines it is suspected to its parent. Run diff to find
1929 * which lines came from parent and pass blame for them.
1931 static void pass_blame_to_parent(struct blame_scoreboard *sb,
1932 struct blame_origin *target,
1933 struct blame_origin *parent, int ignore_diffs)
1935 mmfile_t file_p, file_o;
1936 struct blame_chunk_cb_data d;
1937 struct blame_entry *newdest = NULL;
1939 if (!target->suspects)
1940 return; /* nothing remains for this target */
1942 d.parent = parent;
1943 d.target = target;
1944 d.offset = 0;
1945 d.ignore_diffs = ignore_diffs;
1946 d.dstq = &newdest; d.srcq = &target->suspects;
1948 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
1949 &sb->num_read_blob, ignore_diffs);
1950 fill_origin_blob(&sb->revs->diffopt, target, &file_o,
1951 &sb->num_read_blob, ignore_diffs);
1952 sb->num_get_patch++;
1954 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
1955 die("unable to generate diff (%s -> %s)",
1956 oid_to_hex(&parent->commit->object.oid),
1957 oid_to_hex(&target->commit->object.oid));
1958 /* The rest are the same as the parent */
1959 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, 0,
1960 parent, target, 0);
1961 *d.dstq = NULL;
1962 if (ignore_diffs)
1963 sort_blame_entries(&newdest, compare_blame_suspect);
1964 queue_blames(sb, parent, newdest);
1966 return;
1970 * The lines in blame_entry after splitting blames many times can become
1971 * very small and trivial, and at some point it becomes pointless to
1972 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1973 * ordinary C program, and it is not worth to say it was copied from
1974 * totally unrelated file in the parent.
1976 * Compute how trivial the lines in the blame_entry are.
1978 unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1980 unsigned score;
1981 const char *cp, *ep;
1983 if (e->score)
1984 return e->score;
1986 score = 1;
1987 cp = blame_nth_line(sb, e->lno);
1988 ep = blame_nth_line(sb, e->lno + e->num_lines);
1989 while (cp < ep) {
1990 unsigned ch = *((unsigned char *)cp);
1991 if (isalnum(ch))
1992 score++;
1993 cp++;
1995 e->score = score;
1996 return score;
2000 * best_so_far[] and potential[] are both a split of an existing blame_entry
2001 * that passes blame to the parent. Maintain best_so_far the best split so
2002 * far, by comparing potential and best_so_far and copying potential into
2003 * bst_so_far as needed.
2005 static void copy_split_if_better(struct blame_scoreboard *sb,
2006 struct blame_entry *best_so_far,
2007 struct blame_entry *potential)
2009 int i;
2011 if (!potential[1].suspect)
2012 return;
2013 if (best_so_far[1].suspect) {
2014 if (blame_entry_score(sb, &potential[1]) <
2015 blame_entry_score(sb, &best_so_far[1]))
2016 return;
2019 for (i = 0; i < 3; i++)
2020 blame_origin_incref(potential[i].suspect);
2021 decref_split(best_so_far);
2022 memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
2026 * We are looking at a part of the final image represented by
2027 * ent (tlno and same are offset by ent->s_lno).
2028 * tlno is where we are looking at in the final image.
2029 * up to (but not including) same match preimage.
2030 * plno is where we are looking at in the preimage.
2032 * <-------------- final image ---------------------->
2033 * <------ent------>
2034 * ^tlno ^same
2035 * <---------preimage----->
2036 * ^plno
2038 * All line numbers are 0-based.
2040 static void handle_split(struct blame_scoreboard *sb,
2041 struct blame_entry *ent,
2042 int tlno, int plno, int same,
2043 struct blame_origin *parent,
2044 struct blame_entry *split)
2046 if (ent->num_lines <= tlno)
2047 return;
2048 if (tlno < same) {
2049 struct blame_entry potential[3];
2050 tlno += ent->s_lno;
2051 same += ent->s_lno;
2052 split_overlap(potential, ent, tlno, plno, same, parent);
2053 copy_split_if_better(sb, split, potential);
2054 decref_split(potential);
2058 struct handle_split_cb_data {
2059 struct blame_scoreboard *sb;
2060 struct blame_entry *ent;
2061 struct blame_origin *parent;
2062 struct blame_entry *split;
2063 long plno;
2064 long tlno;
2067 static int handle_split_cb(long start_a, long count_a,
2068 long start_b, long count_b, void *data)
2070 struct handle_split_cb_data *d = data;
2071 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
2072 d->split);
2073 d->plno = start_a + count_a;
2074 d->tlno = start_b + count_b;
2075 return 0;
2079 * Find the lines from parent that are the same as ent so that
2080 * we can pass blames to it. file_p has the blob contents for
2081 * the parent.
2083 static void find_copy_in_blob(struct blame_scoreboard *sb,
2084 struct blame_entry *ent,
2085 struct blame_origin *parent,
2086 struct blame_entry *split,
2087 mmfile_t *file_p)
2089 const char *cp;
2090 mmfile_t file_o;
2091 struct handle_split_cb_data d;
2093 memset(&d, 0, sizeof(d));
2094 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
2096 * Prepare mmfile that contains only the lines in ent.
2098 cp = blame_nth_line(sb, ent->lno);
2099 file_o.ptr = (char *) cp;
2100 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
2103 * file_o is a part of final image we are annotating.
2104 * file_p partially may match that image.
2106 memset(split, 0, sizeof(struct blame_entry [3]));
2107 if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
2108 die("unable to generate diff (%s)",
2109 oid_to_hex(&parent->commit->object.oid));
2110 /* remainder, if any, all match the preimage */
2111 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
2114 /* Move all blame entries from list *source that have a score smaller
2115 * than score_min to the front of list *small.
2116 * Returns a pointer to the link pointing to the old head of the small list.
2119 static struct blame_entry **filter_small(struct blame_scoreboard *sb,
2120 struct blame_entry **small,
2121 struct blame_entry **source,
2122 unsigned score_min)
2124 struct blame_entry *p = *source;
2125 struct blame_entry *oldsmall = *small;
2126 while (p) {
2127 if (blame_entry_score(sb, p) <= score_min) {
2128 *small = p;
2129 small = &p->next;
2130 p = *small;
2131 } else {
2132 *source = p;
2133 source = &p->next;
2134 p = *source;
2137 *small = oldsmall;
2138 *source = NULL;
2139 return small;
2143 * See if lines currently target is suspected for can be attributed to
2144 * parent.
2146 static void find_move_in_parent(struct blame_scoreboard *sb,
2147 struct blame_entry ***blamed,
2148 struct blame_entry **toosmall,
2149 struct blame_origin *target,
2150 struct blame_origin *parent)
2152 struct blame_entry *e, split[3];
2153 struct blame_entry *unblamed = target->suspects;
2154 struct blame_entry *leftover = NULL;
2155 mmfile_t file_p;
2157 if (!unblamed)
2158 return; /* nothing remains for this target */
2160 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
2161 &sb->num_read_blob, 0);
2162 if (!file_p.ptr)
2163 return;
2165 /* At each iteration, unblamed has a NULL-terminated list of
2166 * entries that have not yet been tested for blame. leftover
2167 * contains the reversed list of entries that have been tested
2168 * without being assignable to the parent.
2170 do {
2171 struct blame_entry **unblamedtail = &unblamed;
2172 struct blame_entry *next;
2173 for (e = unblamed; e; e = next) {
2174 next = e->next;
2175 find_copy_in_blob(sb, e, parent, split, &file_p);
2176 if (split[1].suspect &&
2177 sb->move_score < blame_entry_score(sb, &split[1])) {
2178 split_blame(blamed, &unblamedtail, split, e);
2179 } else {
2180 e->next = leftover;
2181 leftover = e;
2183 decref_split(split);
2185 *unblamedtail = NULL;
2186 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
2187 } while (unblamed);
2188 target->suspects = reverse_blame(leftover, NULL);
2191 struct blame_list {
2192 struct blame_entry *ent;
2193 struct blame_entry split[3];
2197 * Count the number of entries the target is suspected for,
2198 * and prepare a list of entry and the best split.
2200 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
2201 int *num_ents_p)
2203 struct blame_entry *e;
2204 int num_ents, i;
2205 struct blame_list *blame_list = NULL;
2207 for (e = unblamed, num_ents = 0; e; e = e->next)
2208 num_ents++;
2209 if (num_ents) {
2210 CALLOC_ARRAY(blame_list, num_ents);
2211 for (e = unblamed, i = 0; e; e = e->next)
2212 blame_list[i++].ent = e;
2214 *num_ents_p = num_ents;
2215 return blame_list;
2219 * For lines target is suspected for, see if we can find code movement
2220 * across file boundary from the parent commit. porigin is the path
2221 * in the parent we already tried.
2223 static void find_copy_in_parent(struct blame_scoreboard *sb,
2224 struct blame_entry ***blamed,
2225 struct blame_entry **toosmall,
2226 struct blame_origin *target,
2227 struct commit *parent,
2228 struct blame_origin *porigin,
2229 int opt)
2231 struct diff_options diff_opts;
2232 int i, j;
2233 struct blame_list *blame_list;
2234 int num_ents;
2235 struct blame_entry *unblamed = target->suspects;
2236 struct blame_entry *leftover = NULL;
2238 if (!unblamed)
2239 return; /* nothing remains for this target */
2241 repo_diff_setup(sb->repo, &diff_opts);
2242 diff_opts.flags.recursive = 1;
2243 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2245 diff_setup_done(&diff_opts);
2247 /* Try "find copies harder" on new path if requested;
2248 * we do not want to use diffcore_rename() actually to
2249 * match things up; find_copies_harder is set only to
2250 * force diff_tree_oid() to feed all filepairs to diff_queue,
2251 * and this code needs to be after diff_setup_done(), which
2252 * usually makes find-copies-harder imply copy detection.
2254 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
2255 || ((opt & PICKAXE_BLAME_COPY_HARDER)
2256 && (!porigin || strcmp(target->path, porigin->path))))
2257 diff_opts.flags.find_copies_harder = 1;
2259 if (is_null_oid(&target->commit->object.oid))
2260 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
2261 else
2262 diff_tree_oid(get_commit_tree_oid(parent),
2263 get_commit_tree_oid(target->commit),
2264 "", &diff_opts);
2266 if (!diff_opts.flags.find_copies_harder)
2267 diffcore_std(&diff_opts);
2269 do {
2270 struct blame_entry **unblamedtail = &unblamed;
2271 blame_list = setup_blame_list(unblamed, &num_ents);
2273 for (i = 0; i < diff_queued_diff.nr; i++) {
2274 struct diff_filepair *p = diff_queued_diff.queue[i];
2275 struct blame_origin *norigin;
2276 mmfile_t file_p;
2277 struct blame_entry potential[3];
2279 if (!DIFF_FILE_VALID(p->one))
2280 continue; /* does not exist in parent */
2281 if (S_ISGITLINK(p->one->mode))
2282 continue; /* ignore git links */
2283 if (porigin && !strcmp(p->one->path, porigin->path))
2284 /* find_move already dealt with this path */
2285 continue;
2287 norigin = get_origin(parent, p->one->path);
2288 oidcpy(&norigin->blob_oid, &p->one->oid);
2289 norigin->mode = p->one->mode;
2290 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,
2291 &sb->num_read_blob, 0);
2292 if (!file_p.ptr)
2293 continue;
2295 for (j = 0; j < num_ents; j++) {
2296 find_copy_in_blob(sb, blame_list[j].ent,
2297 norigin, potential, &file_p);
2298 copy_split_if_better(sb, blame_list[j].split,
2299 potential);
2300 decref_split(potential);
2302 blame_origin_decref(norigin);
2305 for (j = 0; j < num_ents; j++) {
2306 struct blame_entry *split = blame_list[j].split;
2307 if (split[1].suspect &&
2308 sb->copy_score < blame_entry_score(sb, &split[1])) {
2309 split_blame(blamed, &unblamedtail, split,
2310 blame_list[j].ent);
2311 } else {
2312 blame_list[j].ent->next = leftover;
2313 leftover = blame_list[j].ent;
2315 decref_split(split);
2317 free(blame_list);
2318 *unblamedtail = NULL;
2319 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
2320 } while (unblamed);
2321 target->suspects = reverse_blame(leftover, NULL);
2322 diff_flush(&diff_opts);
2326 * The blobs of origin and porigin exactly match, so everything
2327 * origin is suspected for can be blamed on the parent.
2329 static void pass_whole_blame(struct blame_scoreboard *sb,
2330 struct blame_origin *origin, struct blame_origin *porigin)
2332 struct blame_entry *e, *suspects;
2334 if (!porigin->file.ptr && origin->file.ptr) {
2335 /* Steal its file */
2336 porigin->file = origin->file;
2337 origin->file.ptr = NULL;
2339 suspects = origin->suspects;
2340 origin->suspects = NULL;
2341 for (e = suspects; e; e = e->next) {
2342 blame_origin_incref(porigin);
2343 blame_origin_decref(e->suspect);
2344 e->suspect = porigin;
2346 queue_blames(sb, porigin, suspects);
2350 * We pass blame from the current commit to its parents. We keep saying
2351 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2352 * exonerate ourselves.
2354 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
2355 int reverse)
2357 if (!reverse) {
2358 if (revs->first_parent_only &&
2359 commit->parents &&
2360 commit->parents->next) {
2361 free_commit_list(commit->parents->next);
2362 commit->parents->next = NULL;
2364 return commit->parents;
2366 return lookup_decoration(&revs->children, &commit->object);
2369 static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
2371 struct commit_list *l = first_scapegoat(revs, commit, reverse);
2372 return commit_list_count(l);
2375 /* Distribute collected unsorted blames to the respected sorted lists
2376 * in the various origins.
2378 static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
2380 sort_blame_entries(&blamed, compare_blame_suspect);
2381 while (blamed)
2383 struct blame_origin *porigin = blamed->suspect;
2384 struct blame_entry *suspects = NULL;
2385 do {
2386 struct blame_entry *next = blamed->next;
2387 blamed->next = suspects;
2388 suspects = blamed;
2389 blamed = next;
2390 } while (blamed && blamed->suspect == porigin);
2391 suspects = reverse_blame(suspects, NULL);
2392 queue_blames(sb, porigin, suspects);
2396 #define MAXSG 16
2398 typedef struct blame_origin *(*blame_find_alg)(struct repository *,
2399 struct commit *,
2400 struct blame_origin *,
2401 struct blame_bloom_data *);
2403 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
2405 struct rev_info *revs = sb->revs;
2406 int i, pass, num_sg;
2407 struct commit *commit = origin->commit;
2408 struct commit_list *sg;
2409 struct blame_origin *sg_buf[MAXSG];
2410 struct blame_origin *porigin, **sg_origin = sg_buf;
2411 struct blame_entry *toosmall = NULL;
2412 struct blame_entry *blames, **blametail = &blames;
2414 num_sg = num_scapegoats(revs, commit, sb->reverse);
2415 if (!num_sg)
2416 goto finish;
2417 else if (num_sg < ARRAY_SIZE(sg_buf))
2418 memset(sg_buf, 0, sizeof(sg_buf));
2419 else
2420 CALLOC_ARRAY(sg_origin, num_sg);
2423 * The first pass looks for unrenamed path to optimize for
2424 * common cases, then we look for renames in the second pass.
2426 for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
2427 blame_find_alg find = pass ? find_rename : find_origin;
2429 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2430 i < num_sg && sg;
2431 sg = sg->next, i++) {
2432 struct commit *p = sg->item;
2433 int j, same;
2435 if (sg_origin[i])
2436 continue;
2437 if (repo_parse_commit(the_repository, p))
2438 continue;
2439 porigin = find(sb->repo, p, origin, sb->bloom_data);
2440 if (!porigin)
2441 continue;
2442 if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
2443 pass_whole_blame(sb, origin, porigin);
2444 blame_origin_decref(porigin);
2445 goto finish;
2447 for (j = same = 0; j < i; j++)
2448 if (sg_origin[j] &&
2449 oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
2450 same = 1;
2451 break;
2453 if (!same)
2454 sg_origin[i] = porigin;
2455 else
2456 blame_origin_decref(porigin);
2460 sb->num_commits++;
2461 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2462 i < num_sg && sg;
2463 sg = sg->next, i++) {
2464 struct blame_origin *porigin = sg_origin[i];
2465 if (!porigin)
2466 continue;
2467 if (!origin->previous) {
2468 blame_origin_incref(porigin);
2469 origin->previous = porigin;
2471 pass_blame_to_parent(sb, origin, porigin, 0);
2472 if (!origin->suspects)
2473 goto finish;
2477 * Pass remaining suspects for ignored commits to their parents.
2479 if (oidset_contains(&sb->ignore_list, &commit->object.oid)) {
2480 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2481 i < num_sg && sg;
2482 sg = sg->next, i++) {
2483 struct blame_origin *porigin = sg_origin[i];
2485 if (!porigin)
2486 continue;
2487 pass_blame_to_parent(sb, origin, porigin, 1);
2489 * Preemptively drop porigin so we can refresh the
2490 * fingerprints if we use the parent again, which can
2491 * occur if you ignore back-to-back commits.
2493 drop_origin_blob(porigin);
2494 if (!origin->suspects)
2495 goto finish;
2500 * Optionally find moves in parents' files.
2502 if (opt & PICKAXE_BLAME_MOVE) {
2503 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
2504 if (origin->suspects) {
2505 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2506 i < num_sg && sg;
2507 sg = sg->next, i++) {
2508 struct blame_origin *porigin = sg_origin[i];
2509 if (!porigin)
2510 continue;
2511 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
2512 if (!origin->suspects)
2513 break;
2519 * Optionally find copies from parents' files.
2521 if (opt & PICKAXE_BLAME_COPY) {
2522 if (sb->copy_score > sb->move_score)
2523 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2524 else if (sb->copy_score < sb->move_score) {
2525 origin->suspects = blame_merge(origin->suspects, toosmall);
2526 toosmall = NULL;
2527 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2529 if (!origin->suspects)
2530 goto finish;
2532 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2533 i < num_sg && sg;
2534 sg = sg->next, i++) {
2535 struct blame_origin *porigin = sg_origin[i];
2536 find_copy_in_parent(sb, &blametail, &toosmall,
2537 origin, sg->item, porigin, opt);
2538 if (!origin->suspects)
2539 goto finish;
2543 finish:
2544 *blametail = NULL;
2545 distribute_blame(sb, blames);
2547 * prepend toosmall to origin->suspects
2549 * There is no point in sorting: this ends up on a big
2550 * unsorted list in the caller anyway.
2552 if (toosmall) {
2553 struct blame_entry **tail = &toosmall;
2554 while (*tail)
2555 tail = &(*tail)->next;
2556 *tail = origin->suspects;
2557 origin->suspects = toosmall;
2559 for (i = 0; i < num_sg; i++) {
2560 if (sg_origin[i]) {
2561 if (!sg_origin[i]->suspects)
2562 drop_origin_blob(sg_origin[i]);
2563 blame_origin_decref(sg_origin[i]);
2566 drop_origin_blob(origin);
2567 if (sg_buf != sg_origin)
2568 free(sg_origin);
2572 * The main loop -- while we have blobs with lines whose true origin
2573 * is still unknown, pick one blob, and allow its lines to pass blames
2574 * to its parents. */
2575 void assign_blame(struct blame_scoreboard *sb, int opt)
2577 struct rev_info *revs = sb->revs;
2578 struct commit *commit = prio_queue_get(&sb->commits);
2580 while (commit) {
2581 struct blame_entry *ent;
2582 struct blame_origin *suspect = get_blame_suspects(commit);
2584 /* find one suspect to break down */
2585 while (suspect && !suspect->suspects)
2586 suspect = suspect->next;
2588 if (!suspect) {
2589 commit = prio_queue_get(&sb->commits);
2590 continue;
2593 assert(commit == suspect->commit);
2596 * We will use this suspect later in the loop,
2597 * so hold onto it in the meantime.
2599 blame_origin_incref(suspect);
2600 repo_parse_commit(the_repository, commit);
2601 if (sb->reverse ||
2602 (!(commit->object.flags & UNINTERESTING) &&
2603 !(revs->max_age != -1 && commit->date < revs->max_age)))
2604 pass_blame(sb, suspect, opt);
2605 else {
2606 commit->object.flags |= UNINTERESTING;
2607 if (commit->object.parsed)
2608 mark_parents_uninteresting(sb->revs, commit);
2610 /* treat root commit as boundary */
2611 if (!commit->parents && !sb->show_root)
2612 commit->object.flags |= UNINTERESTING;
2614 /* Take responsibility for the remaining entries */
2615 ent = suspect->suspects;
2616 if (ent) {
2617 suspect->guilty = 1;
2618 for (;;) {
2619 struct blame_entry *next = ent->next;
2620 if (sb->found_guilty_entry)
2621 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
2622 if (next) {
2623 ent = next;
2624 continue;
2626 ent->next = sb->ent;
2627 sb->ent = suspect->suspects;
2628 suspect->suspects = NULL;
2629 break;
2632 blame_origin_decref(suspect);
2634 if (sb->debug) /* sanity */
2635 sanity_check_refcnt(sb);
2640 * To allow quick access to the contents of nth line in the
2641 * final image, prepare an index in the scoreboard.
2643 static int prepare_lines(struct blame_scoreboard *sb)
2645 sb->num_lines = find_line_starts(&sb->lineno, sb->final_buf,
2646 sb->final_buf_size);
2647 return sb->num_lines;
2650 static struct commit *find_single_final(struct rev_info *revs,
2651 const char **name_p)
2653 int i;
2654 struct commit *found = NULL;
2655 const char *name = NULL;
2657 for (i = 0; i < revs->pending.nr; i++) {
2658 struct object *obj = revs->pending.objects[i].item;
2659 if (obj->flags & UNINTERESTING)
2660 continue;
2661 obj = deref_tag(revs->repo, obj, NULL, 0);
2662 if (!obj || obj->type != OBJ_COMMIT)
2663 die("Non commit %s?", revs->pending.objects[i].name);
2664 if (found)
2665 die("More than one commit to dig from %s and %s?",
2666 revs->pending.objects[i].name, name);
2667 found = (struct commit *)obj;
2668 name = revs->pending.objects[i].name;
2670 if (name_p)
2671 *name_p = xstrdup_or_null(name);
2672 return found;
2675 static struct commit *dwim_reverse_initial(struct rev_info *revs,
2676 const char **name_p)
2679 * DWIM "git blame --reverse ONE -- PATH" as
2680 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2681 * when it makes sense.
2683 struct object *obj;
2684 struct commit *head_commit;
2685 struct object_id head_oid;
2687 if (revs->pending.nr != 1)
2688 return NULL;
2690 /* Is that sole rev a committish? */
2691 obj = revs->pending.objects[0].item;
2692 obj = deref_tag(revs->repo, obj, NULL, 0);
2693 if (!obj || obj->type != OBJ_COMMIT)
2694 return NULL;
2696 /* Do we have HEAD? */
2697 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
2698 return NULL;
2699 head_commit = lookup_commit_reference_gently(revs->repo,
2700 &head_oid, 1);
2701 if (!head_commit)
2702 return NULL;
2704 /* Turn "ONE" into "ONE..HEAD" then */
2705 obj->flags |= UNINTERESTING;
2706 add_pending_object(revs, &head_commit->object, "HEAD");
2708 if (name_p)
2709 *name_p = revs->pending.objects[0].name;
2710 return (struct commit *)obj;
2713 static struct commit *find_single_initial(struct rev_info *revs,
2714 const char **name_p)
2716 int i;
2717 struct commit *found = NULL;
2718 const char *name = NULL;
2721 * There must be one and only one negative commit, and it must be
2722 * the boundary.
2724 for (i = 0; i < revs->pending.nr; i++) {
2725 struct object *obj = revs->pending.objects[i].item;
2726 if (!(obj->flags & UNINTERESTING))
2727 continue;
2728 obj = deref_tag(revs->repo, obj, NULL, 0);
2729 if (!obj || obj->type != OBJ_COMMIT)
2730 die("Non commit %s?", revs->pending.objects[i].name);
2731 if (found)
2732 die("More than one commit to dig up from, %s and %s?",
2733 revs->pending.objects[i].name, name);
2734 found = (struct commit *) obj;
2735 name = revs->pending.objects[i].name;
2738 if (!name)
2739 found = dwim_reverse_initial(revs, &name);
2740 if (!name)
2741 die("No commit to dig up from?");
2743 if (name_p)
2744 *name_p = xstrdup(name);
2745 return found;
2748 void init_scoreboard(struct blame_scoreboard *sb)
2750 memset(sb, 0, sizeof(struct blame_scoreboard));
2751 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
2752 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
2755 void setup_scoreboard(struct blame_scoreboard *sb,
2756 struct blame_origin **orig)
2758 const char *final_commit_name = NULL;
2759 struct blame_origin *o;
2760 struct commit *final_commit = NULL;
2761 enum object_type type;
2763 init_blame_suspects(&blame_suspects);
2765 if (sb->reverse && sb->contents_from)
2766 die(_("--contents and --reverse do not blend well."));
2768 if (!sb->repo)
2769 BUG("repo is NULL");
2771 if (!sb->reverse) {
2772 sb->final = find_single_final(sb->revs, &final_commit_name);
2773 sb->commits.compare = compare_commits_by_commit_date;
2774 } else {
2775 sb->final = find_single_initial(sb->revs, &final_commit_name);
2776 sb->commits.compare = compare_commits_by_reverse_commit_date;
2779 if (sb->final && sb->contents_from)
2780 die(_("cannot use --contents with final commit object name"));
2782 if (sb->reverse && sb->revs->first_parent_only)
2783 sb->revs->children.name = NULL;
2785 if (!sb->final) {
2787 * "--not A B -- path" without anything positive;
2788 * do not default to HEAD, but use the working tree
2789 * or "--contents".
2791 setup_work_tree();
2792 sb->final = fake_working_tree_commit(sb->repo,
2793 &sb->revs->diffopt,
2794 sb->path, sb->contents_from);
2795 add_pending_object(sb->revs, &(sb->final->object), ":");
2798 if (sb->reverse && sb->revs->first_parent_only) {
2799 final_commit = find_single_final(sb->revs, NULL);
2800 if (!final_commit)
2801 die(_("--reverse and --first-parent together require specified latest commit"));
2805 * If we have bottom, this will mark the ancestors of the
2806 * bottom commits we would reach while traversing as
2807 * uninteresting.
2809 if (prepare_revision_walk(sb->revs))
2810 die(_("revision walk setup failed"));
2812 if (sb->reverse && sb->revs->first_parent_only) {
2813 struct commit *c = final_commit;
2815 sb->revs->children.name = "children";
2816 while (c->parents &&
2817 !oideq(&c->object.oid, &sb->final->object.oid)) {
2818 struct commit_list *l = xcalloc(1, sizeof(*l));
2820 l->item = c;
2821 if (add_decoration(&sb->revs->children,
2822 &c->parents->item->object, l))
2823 BUG("not unique item in first-parent chain");
2824 c = c->parents->item;
2827 if (!oideq(&c->object.oid, &sb->final->object.oid))
2828 die(_("--reverse --first-parent together require range along first-parent chain"));
2831 if (is_null_oid(&sb->final->object.oid)) {
2832 o = get_blame_suspects(sb->final);
2833 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
2834 sb->final_buf_size = o->file.size;
2836 else {
2837 o = get_origin(sb->final, sb->path);
2838 if (fill_blob_sha1_and_mode(sb->repo, o))
2839 die(_("no such path %s in %s"), sb->path, final_commit_name);
2841 if (sb->revs->diffopt.flags.allow_textconv &&
2842 textconv_object(sb->repo, sb->path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
2843 &sb->final_buf_size))
2845 else
2846 sb->final_buf = repo_read_object_file(the_repository,
2847 &o->blob_oid,
2848 &type,
2849 &sb->final_buf_size);
2851 if (!sb->final_buf)
2852 die(_("cannot read blob %s for path %s"),
2853 oid_to_hex(&o->blob_oid),
2854 sb->path);
2856 sb->num_read_blob++;
2857 prepare_lines(sb);
2859 if (orig)
2860 *orig = o;
2862 free((char *)final_commit_name);
2867 struct blame_entry *blame_entry_prepend(struct blame_entry *head,
2868 long start, long end,
2869 struct blame_origin *o)
2871 struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
2872 new_head->lno = start;
2873 new_head->num_lines = end - start;
2874 new_head->suspect = o;
2875 new_head->s_lno = start;
2876 new_head->next = head;
2877 blame_origin_incref(o);
2878 return new_head;
2881 void setup_blame_bloom_data(struct blame_scoreboard *sb)
2883 struct blame_bloom_data *bd;
2884 struct bloom_filter_settings *bs;
2886 if (!sb->repo->objects->commit_graph)
2887 return;
2889 bs = get_bloom_filter_settings(sb->repo);
2890 if (!bs)
2891 return;
2893 bd = xmalloc(sizeof(struct blame_bloom_data));
2895 bd->settings = bs;
2897 bd->alloc = 4;
2898 bd->nr = 0;
2899 ALLOC_ARRAY(bd->keys, bd->alloc);
2901 add_bloom_key(bd, sb->path);
2903 sb->bloom_data = bd;
2906 void cleanup_scoreboard(struct blame_scoreboard *sb)
2908 if (sb->bloom_data) {
2909 int i;
2910 for (i = 0; i < sb->bloom_data->nr; i++) {
2911 free(sb->bloom_data->keys[i]->hashes);
2912 free(sb->bloom_data->keys[i]);
2914 free(sb->bloom_data->keys);
2915 FREE_AND_NULL(sb->bloom_data);
2917 trace2_data_intmax("blame", sb->repo,
2918 "bloom/queries", bloom_count_queries);
2919 trace2_data_intmax("blame", sb->repo,
2920 "bloom/response-no", bloom_count_no);