fast-export: factor out anonymized_entry creation
[git/debian.git] / blame.c
blobe45d8a3bf92a4a3aac39ed41226a01b870254a15
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)
182 struct commit *commit;
183 struct blame_origin *origin;
184 struct commit_list **parent_tail, *parent;
185 struct object_id head_oid;
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 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
202 die("no such ref: HEAD");
204 parent_tail = append_parent(r, parent_tail, &head_oid);
205 append_merge_parents(r, parent_tail);
206 verify_working_tree_path(r, commit, path);
208 origin = make_origin(commit, path);
210 ident = fmt_ident("Not Committed Yet", "not.committed.yet",
211 WANT_BLANK_IDENT, NULL, 0);
212 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
213 for (parent = commit->parents; parent; parent = parent->next)
214 strbuf_addf(&msg, "parent %s\n",
215 oid_to_hex(&parent->item->object.oid));
216 strbuf_addf(&msg,
217 "author %s\n"
218 "committer %s\n\n"
219 "Version of %s from %s\n",
220 ident, ident, path,
221 (!contents_from ? path :
222 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
223 set_commit_buffer_from_strbuf(r, commit, &msg);
225 if (!contents_from || strcmp("-", contents_from)) {
226 struct stat st;
227 const char *read_from;
228 char *buf_ptr;
229 unsigned long buf_len;
231 if (contents_from) {
232 if (stat(contents_from, &st) < 0)
233 die_errno("Cannot stat '%s'", contents_from);
234 read_from = contents_from;
236 else {
237 if (lstat(path, &st) < 0)
238 die_errno("Cannot lstat '%s'", path);
239 read_from = path;
241 mode = canon_mode(st.st_mode);
243 switch (st.st_mode & S_IFMT) {
244 case S_IFREG:
245 if (opt->flags.allow_textconv &&
246 textconv_object(r, read_from, mode, null_oid(), 0, &buf_ptr, &buf_len))
247 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
248 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
249 die_errno("cannot open or read '%s'", read_from);
250 break;
251 case S_IFLNK:
252 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
253 die_errno("cannot readlink '%s'", read_from);
254 break;
255 default:
256 die("unsupported file type %s", read_from);
259 else {
260 /* Reading from stdin */
261 mode = 0;
262 if (strbuf_read(&buf, 0, 0) < 0)
263 die_errno("failed to read from stdin");
265 convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
266 origin->file.ptr = buf.buf;
267 origin->file.size = buf.len;
268 pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
271 * Read the current index, replace the path entry with
272 * origin->blob_sha1 without mucking with its mode or type
273 * bits; we are not going to write this index out -- we just
274 * want to run "diff-index --cached".
276 discard_index(r->index);
277 repo_read_index(r);
279 len = strlen(path);
280 if (!mode) {
281 int pos = index_name_pos(r->index, path, len);
282 if (0 <= pos)
283 mode = r->index->cache[pos]->ce_mode;
284 else
285 /* Let's not bother reading from HEAD tree */
286 mode = S_IFREG | 0644;
288 ce = make_empty_cache_entry(r->index, len);
289 oidcpy(&ce->oid, &origin->blob_oid);
290 memcpy(ce->name, path, len);
291 ce->ce_flags = create_ce_flags(0);
292 ce->ce_namelen = len;
293 ce->ce_mode = create_ce_mode(mode);
294 add_index_entry(r->index, ce,
295 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
297 cache_tree_invalidate_path(r->index, path);
299 return commit;
304 static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
305 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
307 xpparam_t xpp = {0};
308 xdemitconf_t xecfg = {0};
309 xdemitcb_t ecb = {NULL};
311 xpp.flags = xdl_opts;
312 xecfg.hunk_func = hunk_func;
313 ecb.priv = cb_data;
314 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
317 static const char *get_next_line(const char *start, const char *end)
319 const char *nl = memchr(start, '\n', end - start);
321 return nl ? nl + 1 : end;
324 static int find_line_starts(int **line_starts, const char *buf,
325 unsigned long len)
327 const char *end = buf + len;
328 const char *p;
329 int *lineno;
330 int num = 0;
332 for (p = buf; p < end; p = get_next_line(p, end))
333 num++;
335 ALLOC_ARRAY(*line_starts, num + 1);
336 lineno = *line_starts;
338 for (p = buf; p < end; p = get_next_line(p, end))
339 *lineno++ = p - buf;
341 *lineno = len;
343 return num;
346 struct fingerprint_entry;
348 /* A fingerprint is intended to loosely represent a string, such that two
349 * fingerprints can be quickly compared to give an indication of the similarity
350 * of the strings that they represent.
352 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
353 * the string that it represents. Whitespace is added at each end of the
354 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
355 * For example, the string "Darth Radar" will be converted to the following
356 * fingerprint:
357 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
359 * The similarity between two fingerprints is the size of the intersection of
360 * their multisets, including repeated elements. See fingerprint_similarity for
361 * examples.
363 * For ease of implementation, the fingerprint is implemented as a map
364 * of byte pairs to the count of that byte pair in the string, instead of
365 * allowing repeated elements in a set.
367 struct fingerprint {
368 struct hashmap map;
369 /* As we know the maximum number of entries in advance, it's
370 * convenient to store the entries in a single array instead of having
371 * the hashmap manage the memory.
373 struct fingerprint_entry *entries;
376 /* A byte pair in a fingerprint. Stores the number of times the byte pair
377 * occurs in the string that the fingerprint represents.
379 struct fingerprint_entry {
380 /* The hashmap entry - the hash represents the byte pair in its
381 * entirety so we don't need to store the byte pair separately.
383 struct hashmap_entry entry;
384 /* The number of times the byte pair occurs in the string that the
385 * fingerprint represents.
387 int count;
390 /* See `struct fingerprint` for an explanation of what a fingerprint is.
391 * \param result the fingerprint of the string is stored here. This must be
392 * freed later using free_fingerprint.
393 * \param line_begin the start of the string
394 * \param line_end the end of the string
396 static void get_fingerprint(struct fingerprint *result,
397 const char *line_begin,
398 const char *line_end)
400 unsigned int hash, c0 = 0, c1;
401 const char *p;
402 int max_map_entry_count = 1 + line_end - line_begin;
403 struct fingerprint_entry *entry = xcalloc(max_map_entry_count,
404 sizeof(struct fingerprint_entry));
405 struct fingerprint_entry *found_entry;
407 hashmap_init(&result->map, NULL, NULL, max_map_entry_count);
408 result->entries = entry;
409 for (p = line_begin; p <= line_end; ++p, c0 = c1) {
410 /* Always terminate the string with whitespace.
411 * Normalise whitespace to 0, and normalise letters to
412 * lower case. This won't work for multibyte characters but at
413 * worst will match some unrelated characters.
415 if ((p == line_end) || isspace(*p))
416 c1 = 0;
417 else
418 c1 = tolower(*p);
419 hash = c0 | (c1 << 8);
420 /* Ignore whitespace pairs */
421 if (hash == 0)
422 continue;
423 hashmap_entry_init(&entry->entry, hash);
425 found_entry = hashmap_get_entry(&result->map, entry,
426 /* member name */ entry, NULL);
427 if (found_entry) {
428 found_entry->count += 1;
429 } else {
430 entry->count = 1;
431 hashmap_add(&result->map, &entry->entry);
432 ++entry;
437 static void free_fingerprint(struct fingerprint *f)
439 hashmap_clear(&f->map);
440 free(f->entries);
443 /* Calculates the similarity between two fingerprints as the size of the
444 * intersection of their multisets, including repeated elements. See
445 * `struct fingerprint` for an explanation of the fingerprint representation.
446 * The similarity between "cat mat" and "father rather" is 2 because "at" is
447 * present twice in both strings while the similarity between "tim" and "mit"
448 * is 0.
450 static int fingerprint_similarity(struct fingerprint *a, struct fingerprint *b)
452 int intersection = 0;
453 struct hashmap_iter iter;
454 const struct fingerprint_entry *entry_a, *entry_b;
456 hashmap_for_each_entry(&b->map, &iter, entry_b,
457 entry /* member name */) {
458 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
459 if (entry_a) {
460 intersection += entry_a->count < entry_b->count ?
461 entry_a->count : entry_b->count;
464 return intersection;
467 /* Subtracts byte-pair elements in B from A, modifying A in place.
469 static void fingerprint_subtract(struct fingerprint *a, struct fingerprint *b)
471 struct hashmap_iter iter;
472 struct fingerprint_entry *entry_a;
473 const struct fingerprint_entry *entry_b;
475 hashmap_iter_init(&b->map, &iter);
477 hashmap_for_each_entry(&b->map, &iter, entry_b,
478 entry /* member name */) {
479 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
480 if (entry_a) {
481 if (entry_a->count <= entry_b->count)
482 hashmap_remove(&a->map, &entry_b->entry, NULL);
483 else
484 entry_a->count -= entry_b->count;
489 /* Calculate fingerprints for a series of lines.
490 * Puts the fingerprints in the fingerprints array, which must have been
491 * preallocated to allow storing line_count elements.
493 static void get_line_fingerprints(struct fingerprint *fingerprints,
494 const char *content, const int *line_starts,
495 long first_line, long line_count)
497 int i;
498 const char *linestart, *lineend;
500 line_starts += first_line;
501 for (i = 0; i < line_count; ++i) {
502 linestart = content + line_starts[i];
503 lineend = content + line_starts[i + 1];
504 get_fingerprint(fingerprints + i, linestart, lineend);
508 static void free_line_fingerprints(struct fingerprint *fingerprints,
509 int nr_fingerprints)
511 int i;
513 for (i = 0; i < nr_fingerprints; i++)
514 free_fingerprint(&fingerprints[i]);
517 /* This contains the data necessary to linearly map a line number in one half
518 * of a diff chunk to the line in the other half of the diff chunk that is
519 * closest in terms of its position as a fraction of the length of the chunk.
521 struct line_number_mapping {
522 int destination_start, destination_length,
523 source_start, source_length;
526 /* Given a line number in one range, offset and scale it to map it onto the
527 * other range.
528 * Essentially this mapping is a simple linear equation but the calculation is
529 * more complicated to allow performing it with integer operations.
530 * Another complication is that if a line could map onto many lines in the
531 * destination range then we want to choose the line at the center of those
532 * possibilities.
533 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
534 * first 5 lines in B will map onto the first line in the A chunk, while the
535 * last 5 lines will all map onto the second line in the A chunk.
536 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
537 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
539 static int map_line_number(int line_number,
540 const struct line_number_mapping *mapping)
542 return ((line_number - mapping->source_start) * 2 + 1) *
543 mapping->destination_length /
544 (mapping->source_length * 2) +
545 mapping->destination_start;
548 /* Get a pointer to the element storing the similarity between a line in A
549 * and a line in B.
551 * The similarities are stored in a 2-dimensional array. Each "row" in the
552 * array contains the similarities for a line in B. The similarities stored in
553 * a row are the similarities between the line in B and the nearby lines in A.
554 * To keep the length of each row the same, it is padded out with values of -1
555 * where the search range extends beyond the lines in A.
556 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
557 * look like this:
558 * a | m
559 * b | n
560 * c | o
561 * d | p
562 * e | q
563 * Then the similarity array will contain:
564 * [-1, -1, am, bm, cm,
565 * -1, an, bn, cn, dn,
566 * ao, bo, co, do, eo,
567 * bp, cp, dp, ep, -1,
568 * cq, dq, eq, -1, -1]
569 * Where similarities are denoted either by -1 for invalid, or the
570 * concatenation of the two lines in the diff being compared.
572 * \param similarities array of similarities between lines in A and B
573 * \param line_a the index of the line in A, in the same frame of reference as
574 * closest_line_a.
575 * \param local_line_b the index of the line in B, relative to the first line
576 * in B that similarities represents.
577 * \param closest_line_a the index of the line in A that is deemed to be
578 * closest to local_line_b. This must be in the same
579 * frame of reference as line_a. This value defines
580 * where similarities is centered for the line in B.
581 * \param max_search_distance_a maximum distance in lines from the closest line
582 * in A for other lines in A for which
583 * similarities may be calculated.
585 static int *get_similarity(int *similarities,
586 int line_a, int local_line_b,
587 int closest_line_a, int max_search_distance_a)
589 assert(abs(line_a - closest_line_a) <=
590 max_search_distance_a);
591 return similarities + line_a - closest_line_a +
592 max_search_distance_a +
593 local_line_b * (max_search_distance_a * 2 + 1);
596 #define CERTAIN_NOTHING_MATCHES -2
597 #define CERTAINTY_NOT_CALCULATED -1
599 /* Given a line in B, first calculate its similarities with nearby lines in A
600 * if not already calculated, then identify the most similar and second most
601 * similar lines. The "certainty" is calculated based on those two
602 * similarities.
604 * \param start_a the index of the first line of the chunk in A
605 * \param length_a the length in lines of the chunk in A
606 * \param local_line_b the index of the line in B, relative to the first line
607 * in the chunk.
608 * \param fingerprints_a array of fingerprints for the chunk in A
609 * \param fingerprints_b array of fingerprints for the chunk in B
610 * \param similarities 2-dimensional array of similarities between lines in A
611 * and B. See get_similarity() for more details.
612 * \param certainties array of values indicating how strongly a line in B is
613 * matched with some line in A.
614 * \param second_best_result array of absolute indices in A for the second
615 * closest match of a line in B.
616 * \param result array of absolute indices in A for the closest match of a line
617 * in B.
618 * \param max_search_distance_a maximum distance in lines from the closest line
619 * in A for other lines in A for which
620 * similarities may be calculated.
621 * \param map_line_number_in_b_to_a parameter to map_line_number().
623 static void find_best_line_matches(
624 int start_a,
625 int length_a,
626 int start_b,
627 int local_line_b,
628 struct fingerprint *fingerprints_a,
629 struct fingerprint *fingerprints_b,
630 int *similarities,
631 int *certainties,
632 int *second_best_result,
633 int *result,
634 const int max_search_distance_a,
635 const struct line_number_mapping *map_line_number_in_b_to_a)
638 int i, search_start, search_end, closest_local_line_a, *similarity,
639 best_similarity = 0, second_best_similarity = 0,
640 best_similarity_index = 0, second_best_similarity_index = 0;
642 /* certainty has already been calculated so no need to redo the work */
643 if (certainties[local_line_b] != CERTAINTY_NOT_CALCULATED)
644 return;
646 closest_local_line_a = map_line_number(
647 local_line_b + start_b, map_line_number_in_b_to_a) - start_a;
649 search_start = closest_local_line_a - max_search_distance_a;
650 if (search_start < 0)
651 search_start = 0;
653 search_end = closest_local_line_a + max_search_distance_a + 1;
654 if (search_end > length_a)
655 search_end = length_a;
657 for (i = search_start; i < search_end; ++i) {
658 similarity = get_similarity(similarities,
659 i, local_line_b,
660 closest_local_line_a,
661 max_search_distance_a);
662 if (*similarity == -1) {
663 /* This value will never exceed 10 but assert just in
664 * case
666 assert(abs(i - closest_local_line_a) < 1000);
667 /* scale the similarity by (1000 - distance from
668 * closest line) to act as a tie break between lines
669 * that otherwise are equally similar.
671 *similarity = fingerprint_similarity(
672 fingerprints_b + local_line_b,
673 fingerprints_a + i) *
674 (1000 - abs(i - closest_local_line_a));
676 if (*similarity > best_similarity) {
677 second_best_similarity = best_similarity;
678 second_best_similarity_index = best_similarity_index;
679 best_similarity = *similarity;
680 best_similarity_index = i;
681 } else if (*similarity > second_best_similarity) {
682 second_best_similarity = *similarity;
683 second_best_similarity_index = i;
687 if (best_similarity == 0) {
688 /* this line definitely doesn't match with anything. Mark it
689 * with this special value so it doesn't get invalidated and
690 * won't be recalculated.
692 certainties[local_line_b] = CERTAIN_NOTHING_MATCHES;
693 result[local_line_b] = -1;
694 } else {
695 /* Calculate the certainty with which this line matches.
696 * If the line matches well with two lines then that reduces
697 * the certainty. However we still want to prioritise matching
698 * a line that matches very well with two lines over matching a
699 * line that matches poorly with one line, hence doubling
700 * best_similarity.
701 * This means that if we have
702 * line X that matches only one line with a score of 3,
703 * line Y that matches two lines equally with a score of 5,
704 * and line Z that matches only one line with a score or 2,
705 * then the lines in order of certainty are X, Y, Z.
707 certainties[local_line_b] = best_similarity * 2 -
708 second_best_similarity;
710 /* We keep both the best and second best results to allow us to
711 * check at a later stage of the matching process whether the
712 * result needs to be invalidated.
714 result[local_line_b] = start_a + best_similarity_index;
715 second_best_result[local_line_b] =
716 start_a + second_best_similarity_index;
721 * This finds the line that we can match with the most confidence, and
722 * uses it as a partition. It then calls itself on the lines on either side of
723 * that partition. In this way we avoid lines appearing out of order, and
724 * retain a sensible line ordering.
725 * \param start_a index of the first line in A with which lines in B may be
726 * compared.
727 * \param start_b index of the first line in B for which matching should be
728 * done.
729 * \param length_a number of lines in A with which lines in B may be compared.
730 * \param length_b number of lines in B for which matching should be done.
731 * \param fingerprints_a mutable array of fingerprints in A. The first element
732 * corresponds to the line at start_a.
733 * \param fingerprints_b array of fingerprints in B. The first element
734 * corresponds to the line at start_b.
735 * \param similarities 2-dimensional array of similarities between lines in A
736 * and B. See get_similarity() for more details.
737 * \param certainties array of values indicating how strongly a line in B is
738 * matched with some line in A.
739 * \param second_best_result array of absolute indices in A for the second
740 * closest match of a line in B.
741 * \param result array of absolute indices in A for the closest match of a line
742 * in B.
743 * \param max_search_distance_a maximum distance in lines from the closest line
744 * in A for other lines in A for which
745 * similarities may be calculated.
746 * \param max_search_distance_b an upper bound on the greatest possible
747 * distance between lines in B such that they will
748 * both be compared with the same line in A
749 * according to max_search_distance_a.
750 * \param map_line_number_in_b_to_a parameter to map_line_number().
752 static void fuzzy_find_matching_lines_recurse(
753 int start_a, int start_b,
754 int length_a, int length_b,
755 struct fingerprint *fingerprints_a,
756 struct fingerprint *fingerprints_b,
757 int *similarities,
758 int *certainties,
759 int *second_best_result,
760 int *result,
761 int max_search_distance_a,
762 int max_search_distance_b,
763 const struct line_number_mapping *map_line_number_in_b_to_a)
765 int i, invalidate_min, invalidate_max, offset_b,
766 second_half_start_a, second_half_start_b,
767 second_half_length_a, second_half_length_b,
768 most_certain_line_a, most_certain_local_line_b = -1,
769 most_certain_line_certainty = -1,
770 closest_local_line_a;
772 for (i = 0; i < length_b; ++i) {
773 find_best_line_matches(start_a,
774 length_a,
775 start_b,
777 fingerprints_a,
778 fingerprints_b,
779 similarities,
780 certainties,
781 second_best_result,
782 result,
783 max_search_distance_a,
784 map_line_number_in_b_to_a);
786 if (certainties[i] > most_certain_line_certainty) {
787 most_certain_line_certainty = certainties[i];
788 most_certain_local_line_b = i;
792 /* No matches. */
793 if (most_certain_local_line_b == -1)
794 return;
796 most_certain_line_a = result[most_certain_local_line_b];
799 * Subtract the most certain line's fingerprint in B from the matched
800 * fingerprint in A. This means that other lines in B can't also match
801 * the same parts of the line in A.
803 fingerprint_subtract(fingerprints_a + most_certain_line_a - start_a,
804 fingerprints_b + most_certain_local_line_b);
806 /* Invalidate results that may be affected by the choice of most
807 * certain line.
809 invalidate_min = most_certain_local_line_b - max_search_distance_b;
810 invalidate_max = most_certain_local_line_b + max_search_distance_b + 1;
811 if (invalidate_min < 0)
812 invalidate_min = 0;
813 if (invalidate_max > length_b)
814 invalidate_max = length_b;
816 /* As the fingerprint in A has changed, discard previously calculated
817 * similarity values with that fingerprint.
819 for (i = invalidate_min; i < invalidate_max; ++i) {
820 closest_local_line_a = map_line_number(
821 i + start_b, map_line_number_in_b_to_a) - start_a;
823 /* Check that the lines in A and B are close enough that there
824 * is a similarity value for them.
826 if (abs(most_certain_line_a - start_a - closest_local_line_a) >
827 max_search_distance_a) {
828 continue;
831 *get_similarity(similarities, most_certain_line_a - start_a,
832 i, closest_local_line_a,
833 max_search_distance_a) = -1;
836 /* More invalidating of results that may be affected by the choice of
837 * most certain line.
838 * Discard the matches for lines in B that are currently matched with a
839 * line in A such that their ordering contradicts the ordering imposed
840 * by the choice of most certain line.
842 for (i = most_certain_local_line_b - 1; i >= invalidate_min; --i) {
843 /* In this loop we discard results for lines in B that are
844 * before most-certain-line-B but are matched with a line in A
845 * that is after most-certain-line-A.
847 if (certainties[i] >= 0 &&
848 (result[i] >= most_certain_line_a ||
849 second_best_result[i] >= most_certain_line_a)) {
850 certainties[i] = CERTAINTY_NOT_CALCULATED;
853 for (i = most_certain_local_line_b + 1; i < invalidate_max; ++i) {
854 /* In this loop we discard results for lines in B that are
855 * after most-certain-line-B but are matched with a line in A
856 * that is before most-certain-line-A.
858 if (certainties[i] >= 0 &&
859 (result[i] <= most_certain_line_a ||
860 second_best_result[i] <= most_certain_line_a)) {
861 certainties[i] = CERTAINTY_NOT_CALCULATED;
865 /* Repeat the matching process for lines before the most certain line.
867 if (most_certain_local_line_b > 0) {
868 fuzzy_find_matching_lines_recurse(
869 start_a, start_b,
870 most_certain_line_a + 1 - start_a,
871 most_certain_local_line_b,
872 fingerprints_a, fingerprints_b, similarities,
873 certainties, second_best_result, result,
874 max_search_distance_a,
875 max_search_distance_b,
876 map_line_number_in_b_to_a);
878 /* Repeat the matching process for lines after the most certain line.
880 if (most_certain_local_line_b + 1 < length_b) {
881 second_half_start_a = most_certain_line_a;
882 offset_b = most_certain_local_line_b + 1;
883 second_half_start_b = start_b + offset_b;
884 second_half_length_a =
885 length_a + start_a - second_half_start_a;
886 second_half_length_b =
887 length_b + start_b - second_half_start_b;
888 fuzzy_find_matching_lines_recurse(
889 second_half_start_a, second_half_start_b,
890 second_half_length_a, second_half_length_b,
891 fingerprints_a + second_half_start_a - start_a,
892 fingerprints_b + offset_b,
893 similarities +
894 offset_b * (max_search_distance_a * 2 + 1),
895 certainties + offset_b,
896 second_best_result + offset_b, result + offset_b,
897 max_search_distance_a,
898 max_search_distance_b,
899 map_line_number_in_b_to_a);
903 /* Find the lines in the parent line range that most closely match the lines in
904 * the target line range. This is accomplished by matching fingerprints in each
905 * blame_origin, and choosing the best matches that preserve the line ordering.
906 * See struct fingerprint for details of fingerprint matching, and
907 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
909 * The performance is believed to be O(n log n) in the typical case and O(n^2)
910 * in a pathological case, where n is the number of lines in the target range.
912 static int *fuzzy_find_matching_lines(struct blame_origin *parent,
913 struct blame_origin *target,
914 int tlno, int parent_slno, int same,
915 int parent_len)
917 /* We use the terminology "A" for the left hand side of the diff AKA
918 * parent, and "B" for the right hand side of the diff AKA target. */
919 int start_a = parent_slno;
920 int length_a = parent_len;
921 int start_b = tlno;
922 int length_b = same - tlno;
924 struct line_number_mapping map_line_number_in_b_to_a = {
925 start_a, length_a, start_b, length_b
928 struct fingerprint *fingerprints_a = parent->fingerprints;
929 struct fingerprint *fingerprints_b = target->fingerprints;
931 int i, *result, *second_best_result,
932 *certainties, *similarities, similarity_count;
935 * max_search_distance_a means that given a line in B, compare it to
936 * the line in A that is closest to its position, and the lines in A
937 * that are no greater than max_search_distance_a lines away from the
938 * closest line in A.
940 * max_search_distance_b is an upper bound on the greatest possible
941 * distance between lines in B such that they will both be compared
942 * with the same line in A according to max_search_distance_a.
944 int max_search_distance_a = 10, max_search_distance_b;
946 if (length_a <= 0)
947 return NULL;
949 if (max_search_distance_a >= length_a)
950 max_search_distance_a = length_a ? length_a - 1 : 0;
952 max_search_distance_b = ((2 * max_search_distance_a + 1) * length_b
953 - 1) / length_a;
955 CALLOC_ARRAY(result, length_b);
956 CALLOC_ARRAY(second_best_result, length_b);
957 CALLOC_ARRAY(certainties, length_b);
959 /* See get_similarity() for details of similarities. */
960 similarity_count = length_b * (max_search_distance_a * 2 + 1);
961 CALLOC_ARRAY(similarities, similarity_count);
963 for (i = 0; i < length_b; ++i) {
964 result[i] = -1;
965 second_best_result[i] = -1;
966 certainties[i] = CERTAINTY_NOT_CALCULATED;
969 for (i = 0; i < similarity_count; ++i)
970 similarities[i] = -1;
972 fuzzy_find_matching_lines_recurse(start_a, start_b,
973 length_a, length_b,
974 fingerprints_a + start_a,
975 fingerprints_b + start_b,
976 similarities,
977 certainties,
978 second_best_result,
979 result,
980 max_search_distance_a,
981 max_search_distance_b,
982 &map_line_number_in_b_to_a);
984 free(similarities);
985 free(certainties);
986 free(second_best_result);
988 return result;
991 static void fill_origin_fingerprints(struct blame_origin *o)
993 int *line_starts;
995 if (o->fingerprints)
996 return;
997 o->num_lines = find_line_starts(&line_starts, o->file.ptr,
998 o->file.size);
999 CALLOC_ARRAY(o->fingerprints, o->num_lines);
1000 get_line_fingerprints(o->fingerprints, o->file.ptr, line_starts,
1001 0, o->num_lines);
1002 free(line_starts);
1005 static void drop_origin_fingerprints(struct blame_origin *o)
1007 if (o->fingerprints) {
1008 free_line_fingerprints(o->fingerprints, o->num_lines);
1009 o->num_lines = 0;
1010 FREE_AND_NULL(o->fingerprints);
1015 * Given an origin, prepare mmfile_t structure to be used by the
1016 * diff machinery
1018 static void fill_origin_blob(struct diff_options *opt,
1019 struct blame_origin *o, mmfile_t *file,
1020 int *num_read_blob, int fill_fingerprints)
1022 if (!o->file.ptr) {
1023 enum object_type type;
1024 unsigned long file_size;
1026 (*num_read_blob)++;
1027 if (opt->flags.allow_textconv &&
1028 textconv_object(opt->repo, o->path, o->mode,
1029 &o->blob_oid, 1, &file->ptr, &file_size))
1031 else
1032 file->ptr = read_object_file(&o->blob_oid, &type,
1033 &file_size);
1034 file->size = file_size;
1036 if (!file->ptr)
1037 die("Cannot read blob %s for path %s",
1038 oid_to_hex(&o->blob_oid),
1039 o->path);
1040 o->file = *file;
1042 else
1043 *file = o->file;
1044 if (fill_fingerprints)
1045 fill_origin_fingerprints(o);
1048 static void drop_origin_blob(struct blame_origin *o)
1050 FREE_AND_NULL(o->file.ptr);
1051 drop_origin_fingerprints(o);
1055 * Any merge of blames happens on lists of blames that arrived via
1056 * different parents in a single suspect. In this case, we want to
1057 * sort according to the suspect line numbers as opposed to the final
1058 * image line numbers. The function body is somewhat longish because
1059 * it avoids unnecessary writes.
1062 static struct blame_entry *blame_merge(struct blame_entry *list1,
1063 struct blame_entry *list2)
1065 struct blame_entry *p1 = list1, *p2 = list2,
1066 **tail = &list1;
1068 if (!p1)
1069 return p2;
1070 if (!p2)
1071 return p1;
1073 if (p1->s_lno <= p2->s_lno) {
1074 do {
1075 tail = &p1->next;
1076 if (!(p1 = *tail)) {
1077 *tail = p2;
1078 return list1;
1080 } while (p1->s_lno <= p2->s_lno);
1082 for (;;) {
1083 *tail = p2;
1084 do {
1085 tail = &p2->next;
1086 if (!(p2 = *tail)) {
1087 *tail = p1;
1088 return list1;
1090 } while (p1->s_lno > p2->s_lno);
1091 *tail = p1;
1092 do {
1093 tail = &p1->next;
1094 if (!(p1 = *tail)) {
1095 *tail = p2;
1096 return list1;
1098 } while (p1->s_lno <= p2->s_lno);
1102 DEFINE_LIST_SORT(static, sort_blame_entries, struct blame_entry, next);
1105 * Final image line numbers are all different, so we don't need a
1106 * three-way comparison here.
1109 static int compare_blame_final(const struct blame_entry *e1,
1110 const struct blame_entry *e2)
1112 return e1->lno > e2->lno ? 1 : -1;
1115 static int compare_blame_suspect(const struct blame_entry *s1,
1116 const struct blame_entry *s2)
1119 * to allow for collating suspects, we sort according to the
1120 * respective pointer value as the primary sorting criterion.
1121 * The actual relation is pretty unimportant as long as it
1122 * establishes a total order. Comparing as integers gives us
1123 * that.
1125 if (s1->suspect != s2->suspect)
1126 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
1127 if (s1->s_lno == s2->s_lno)
1128 return 0;
1129 return s1->s_lno > s2->s_lno ? 1 : -1;
1132 void blame_sort_final(struct blame_scoreboard *sb)
1134 sort_blame_entries(&sb->ent, compare_blame_final);
1137 static int compare_commits_by_reverse_commit_date(const void *a,
1138 const void *b,
1139 void *c)
1141 return -compare_commits_by_commit_date(a, b, c);
1145 * For debugging -- origin is refcounted, and this asserts that
1146 * we do not underflow.
1148 static void sanity_check_refcnt(struct blame_scoreboard *sb)
1150 int baa = 0;
1151 struct blame_entry *ent;
1153 for (ent = sb->ent; ent; ent = ent->next) {
1154 /* Nobody should have zero or negative refcnt */
1155 if (ent->suspect->refcnt <= 0) {
1156 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1157 ent->suspect->path,
1158 oid_to_hex(&ent->suspect->commit->object.oid),
1159 ent->suspect->refcnt);
1160 baa = 1;
1163 if (baa)
1164 sb->on_sanity_fail(sb, baa);
1168 * If two blame entries that are next to each other came from
1169 * contiguous lines in the same origin (i.e. <commit, path> pair),
1170 * merge them together.
1172 void blame_coalesce(struct blame_scoreboard *sb)
1174 struct blame_entry *ent, *next;
1176 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
1177 if (ent->suspect == next->suspect &&
1178 ent->s_lno + ent->num_lines == next->s_lno &&
1179 ent->lno + ent->num_lines == next->lno &&
1180 ent->ignored == next->ignored &&
1181 ent->unblamable == next->unblamable) {
1182 ent->num_lines += next->num_lines;
1183 ent->next = next->next;
1184 blame_origin_decref(next->suspect);
1185 free(next);
1186 ent->score = 0;
1187 next = ent; /* again */
1191 if (sb->debug) /* sanity */
1192 sanity_check_refcnt(sb);
1196 * Merge the given sorted list of blames into a preexisting origin.
1197 * If there were no previous blames to that commit, it is entered into
1198 * the commit priority queue of the score board.
1201 static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
1202 struct blame_entry *sorted)
1204 if (porigin->suspects)
1205 porigin->suspects = blame_merge(porigin->suspects, sorted);
1206 else {
1207 struct blame_origin *o;
1208 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
1209 if (o->suspects) {
1210 porigin->suspects = sorted;
1211 return;
1214 porigin->suspects = sorted;
1215 prio_queue_put(&sb->commits, porigin->commit);
1220 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1221 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1222 * for an origin is also used to pass the blame for the entire file to
1223 * the parent to detect the case where a child's blob is identical to
1224 * that of its parent's.
1226 * This also fills origin->mode for corresponding tree path.
1228 static int fill_blob_sha1_and_mode(struct repository *r,
1229 struct blame_origin *origin)
1231 if (!is_null_oid(&origin->blob_oid))
1232 return 0;
1233 if (get_tree_entry(r, &origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
1234 goto error_out;
1235 if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
1236 goto error_out;
1237 return 0;
1238 error_out:
1239 oidclr(&origin->blob_oid);
1240 origin->mode = S_IFINVALID;
1241 return -1;
1244 struct blame_bloom_data {
1246 * Changed-path Bloom filter keys. These can help prevent
1247 * computing diffs against first parents, but we need to
1248 * expand the list as code is moved or files are renamed.
1250 struct bloom_filter_settings *settings;
1251 struct bloom_key **keys;
1252 int nr;
1253 int alloc;
1256 static int bloom_count_queries = 0;
1257 static int bloom_count_no = 0;
1258 static int maybe_changed_path(struct repository *r,
1259 struct blame_origin *origin,
1260 struct blame_bloom_data *bd)
1262 int i;
1263 struct bloom_filter *filter;
1265 if (!bd)
1266 return 1;
1268 if (commit_graph_generation(origin->commit) == GENERATION_NUMBER_INFINITY)
1269 return 1;
1271 filter = get_bloom_filter(r, origin->commit);
1273 if (!filter)
1274 return 1;
1276 bloom_count_queries++;
1277 for (i = 0; i < bd->nr; i++) {
1278 if (bloom_filter_contains(filter,
1279 bd->keys[i],
1280 bd->settings))
1281 return 1;
1284 bloom_count_no++;
1285 return 0;
1288 static void add_bloom_key(struct blame_bloom_data *bd,
1289 const char *path)
1291 if (!bd)
1292 return;
1294 if (bd->nr >= bd->alloc) {
1295 bd->alloc *= 2;
1296 REALLOC_ARRAY(bd->keys, bd->alloc);
1299 bd->keys[bd->nr] = xmalloc(sizeof(struct bloom_key));
1300 fill_bloom_key(path, strlen(path), bd->keys[bd->nr], bd->settings);
1301 bd->nr++;
1305 * We have an origin -- check if the same path exists in the
1306 * parent and return an origin structure to represent it.
1308 static struct blame_origin *find_origin(struct repository *r,
1309 struct commit *parent,
1310 struct blame_origin *origin,
1311 struct blame_bloom_data *bd)
1313 struct blame_origin *porigin;
1314 struct diff_options diff_opts;
1315 const char *paths[2];
1317 /* First check any existing origins */
1318 for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
1319 if (!strcmp(porigin->path, origin->path)) {
1321 * The same path between origin and its parent
1322 * without renaming -- the most common case.
1324 return blame_origin_incref (porigin);
1327 /* See if the origin->path is different between parent
1328 * and origin first. Most of the time they are the
1329 * same and diff-tree is fairly efficient about this.
1331 repo_diff_setup(r, &diff_opts);
1332 diff_opts.flags.recursive = 1;
1333 diff_opts.detect_rename = 0;
1334 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1335 paths[0] = origin->path;
1336 paths[1] = NULL;
1338 parse_pathspec(&diff_opts.pathspec,
1339 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1340 PATHSPEC_LITERAL_PATH, "", paths);
1341 diff_setup_done(&diff_opts);
1343 if (is_null_oid(&origin->commit->object.oid))
1344 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1345 else {
1346 int compute_diff = 1;
1347 if (origin->commit->parents &&
1348 oideq(&parent->object.oid,
1349 &origin->commit->parents->item->object.oid))
1350 compute_diff = maybe_changed_path(r, origin, bd);
1352 if (compute_diff)
1353 diff_tree_oid(get_commit_tree_oid(parent),
1354 get_commit_tree_oid(origin->commit),
1355 "", &diff_opts);
1357 diffcore_std(&diff_opts);
1359 if (!diff_queued_diff.nr) {
1360 /* The path is the same as parent */
1361 porigin = get_origin(parent, origin->path);
1362 oidcpy(&porigin->blob_oid, &origin->blob_oid);
1363 porigin->mode = origin->mode;
1364 } else {
1366 * Since origin->path is a pathspec, if the parent
1367 * commit had it as a directory, we will see a whole
1368 * bunch of deletion of files in the directory that we
1369 * do not care about.
1371 int i;
1372 struct diff_filepair *p = NULL;
1373 for (i = 0; i < diff_queued_diff.nr; i++) {
1374 const char *name;
1375 p = diff_queued_diff.queue[i];
1376 name = p->one->path ? p->one->path : p->two->path;
1377 if (!strcmp(name, origin->path))
1378 break;
1380 if (!p)
1381 die("internal error in blame::find_origin");
1382 switch (p->status) {
1383 default:
1384 die("internal error in blame::find_origin (%c)",
1385 p->status);
1386 case 'M':
1387 porigin = get_origin(parent, origin->path);
1388 oidcpy(&porigin->blob_oid, &p->one->oid);
1389 porigin->mode = p->one->mode;
1390 break;
1391 case 'A':
1392 case 'T':
1393 /* Did not exist in parent, or type changed */
1394 break;
1397 diff_flush(&diff_opts);
1398 return porigin;
1402 * We have an origin -- find the path that corresponds to it in its
1403 * parent and return an origin structure to represent it.
1405 static struct blame_origin *find_rename(struct repository *r,
1406 struct commit *parent,
1407 struct blame_origin *origin,
1408 struct blame_bloom_data *bd)
1410 struct blame_origin *porigin = NULL;
1411 struct diff_options diff_opts;
1412 int i;
1414 repo_diff_setup(r, &diff_opts);
1415 diff_opts.flags.recursive = 1;
1416 diff_opts.detect_rename = DIFF_DETECT_RENAME;
1417 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1418 diff_opts.single_follow = origin->path;
1419 diff_setup_done(&diff_opts);
1421 if (is_null_oid(&origin->commit->object.oid))
1422 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
1423 else
1424 diff_tree_oid(get_commit_tree_oid(parent),
1425 get_commit_tree_oid(origin->commit),
1426 "", &diff_opts);
1427 diffcore_std(&diff_opts);
1429 for (i = 0; i < diff_queued_diff.nr; i++) {
1430 struct diff_filepair *p = diff_queued_diff.queue[i];
1431 if ((p->status == 'R' || p->status == 'C') &&
1432 !strcmp(p->two->path, origin->path)) {
1433 add_bloom_key(bd, p->one->path);
1434 porigin = get_origin(parent, p->one->path);
1435 oidcpy(&porigin->blob_oid, &p->one->oid);
1436 porigin->mode = p->one->mode;
1437 break;
1440 diff_flush(&diff_opts);
1441 return porigin;
1445 * Append a new blame entry to a given output queue.
1447 static void add_blame_entry(struct blame_entry ***queue,
1448 const struct blame_entry *src)
1450 struct blame_entry *e = xmalloc(sizeof(*e));
1451 memcpy(e, src, sizeof(*e));
1452 blame_origin_incref(e->suspect);
1454 e->next = **queue;
1455 **queue = e;
1456 *queue = &e->next;
1460 * src typically is on-stack; we want to copy the information in it to
1461 * a malloced blame_entry that gets added to the given queue. The
1462 * origin of dst loses a refcnt.
1464 static void dup_entry(struct blame_entry ***queue,
1465 struct blame_entry *dst, struct blame_entry *src)
1467 blame_origin_incref(src->suspect);
1468 blame_origin_decref(dst->suspect);
1469 memcpy(dst, src, sizeof(*src));
1470 dst->next = **queue;
1471 **queue = dst;
1472 *queue = &dst->next;
1475 const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
1477 return sb->final_buf + sb->lineno[lno];
1481 * It is known that lines between tlno to same came from parent, and e
1482 * has an overlap with that range. it also is known that parent's
1483 * line plno corresponds to e's line tlno.
1485 * <---- e ----->
1486 * <------>
1487 * <------------>
1488 * <------------>
1489 * <------------------>
1491 * Split e into potentially three parts; before this chunk, the chunk
1492 * to be blamed for the parent, and after that portion.
1494 static void split_overlap(struct blame_entry *split,
1495 struct blame_entry *e,
1496 int tlno, int plno, int same,
1497 struct blame_origin *parent)
1499 int chunk_end_lno;
1500 int i;
1501 memset(split, 0, sizeof(struct blame_entry [3]));
1503 for (i = 0; i < 3; i++) {
1504 split[i].ignored = e->ignored;
1505 split[i].unblamable = e->unblamable;
1508 if (e->s_lno < tlno) {
1509 /* there is a pre-chunk part not blamed on parent */
1510 split[0].suspect = blame_origin_incref(e->suspect);
1511 split[0].lno = e->lno;
1512 split[0].s_lno = e->s_lno;
1513 split[0].num_lines = tlno - e->s_lno;
1514 split[1].lno = e->lno + tlno - e->s_lno;
1515 split[1].s_lno = plno;
1517 else {
1518 split[1].lno = e->lno;
1519 split[1].s_lno = plno + (e->s_lno - tlno);
1522 if (same < e->s_lno + e->num_lines) {
1523 /* there is a post-chunk part not blamed on parent */
1524 split[2].suspect = blame_origin_incref(e->suspect);
1525 split[2].lno = e->lno + (same - e->s_lno);
1526 split[2].s_lno = e->s_lno + (same - e->s_lno);
1527 split[2].num_lines = e->s_lno + e->num_lines - same;
1528 chunk_end_lno = split[2].lno;
1530 else
1531 chunk_end_lno = e->lno + e->num_lines;
1532 split[1].num_lines = chunk_end_lno - split[1].lno;
1535 * if it turns out there is nothing to blame the parent for,
1536 * forget about the splitting. !split[1].suspect signals this.
1538 if (split[1].num_lines < 1)
1539 return;
1540 split[1].suspect = blame_origin_incref(parent);
1544 * split_overlap() divided an existing blame e into up to three parts
1545 * in split. Any assigned blame is moved to queue to
1546 * reflect the split.
1548 static void split_blame(struct blame_entry ***blamed,
1549 struct blame_entry ***unblamed,
1550 struct blame_entry *split,
1551 struct blame_entry *e)
1553 if (split[0].suspect && split[2].suspect) {
1554 /* The first part (reuse storage for the existing entry e) */
1555 dup_entry(unblamed, e, &split[0]);
1557 /* The last part -- me */
1558 add_blame_entry(unblamed, &split[2]);
1560 /* ... and the middle part -- parent */
1561 add_blame_entry(blamed, &split[1]);
1563 else if (!split[0].suspect && !split[2].suspect)
1565 * The parent covers the entire area; reuse storage for
1566 * e and replace it with the parent.
1568 dup_entry(blamed, e, &split[1]);
1569 else if (split[0].suspect) {
1570 /* me and then parent */
1571 dup_entry(unblamed, e, &split[0]);
1572 add_blame_entry(blamed, &split[1]);
1574 else {
1575 /* parent and then me */
1576 dup_entry(blamed, e, &split[1]);
1577 add_blame_entry(unblamed, &split[2]);
1582 * After splitting the blame, the origins used by the
1583 * on-stack blame_entry should lose one refcnt each.
1585 static void decref_split(struct blame_entry *split)
1587 int i;
1589 for (i = 0; i < 3; i++)
1590 blame_origin_decref(split[i].suspect);
1594 * reverse_blame reverses the list given in head, appending tail.
1595 * That allows us to build lists in reverse order, then reverse them
1596 * afterwards. This can be faster than building the list in proper
1597 * order right away. The reason is that building in proper order
1598 * requires writing a link in the _previous_ element, while building
1599 * in reverse order just requires placing the list head into the
1600 * _current_ element.
1603 static struct blame_entry *reverse_blame(struct blame_entry *head,
1604 struct blame_entry *tail)
1606 while (head) {
1607 struct blame_entry *next = head->next;
1608 head->next = tail;
1609 tail = head;
1610 head = next;
1612 return tail;
1616 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1617 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1618 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1619 * e->num_lines). The caller needs to sort out the reference counting for the
1620 * new entry's suspect.
1622 static struct blame_entry *split_blame_at(struct blame_entry *e, int len,
1623 struct blame_origin *new_suspect)
1625 struct blame_entry *n = xcalloc(1, sizeof(struct blame_entry));
1627 n->suspect = new_suspect;
1628 n->ignored = e->ignored;
1629 n->unblamable = e->unblamable;
1630 n->lno = e->lno + len;
1631 n->s_lno = e->s_lno + len;
1632 n->num_lines = e->num_lines - len;
1633 e->num_lines = len;
1634 e->score = 0;
1635 return n;
1638 struct blame_line_tracker {
1639 int is_parent;
1640 int s_lno;
1643 static int are_lines_adjacent(struct blame_line_tracker *first,
1644 struct blame_line_tracker *second)
1646 return first->is_parent == second->is_parent &&
1647 first->s_lno + 1 == second->s_lno;
1650 static int scan_parent_range(struct fingerprint *p_fps,
1651 struct fingerprint *t_fps, int t_idx,
1652 int from, int nr_lines)
1654 int sim, p_idx;
1655 #define FINGERPRINT_FILE_THRESHOLD 10
1656 int best_sim_val = FINGERPRINT_FILE_THRESHOLD;
1657 int best_sim_idx = -1;
1659 for (p_idx = from; p_idx < from + nr_lines; p_idx++) {
1660 sim = fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);
1661 if (sim < best_sim_val)
1662 continue;
1663 /* Break ties with the closest-to-target line number */
1664 if (sim == best_sim_val && best_sim_idx != -1 &&
1665 abs(best_sim_idx - t_idx) < abs(p_idx - t_idx))
1666 continue;
1667 best_sim_val = sim;
1668 best_sim_idx = p_idx;
1670 return best_sim_idx;
1674 * The first pass checks the blame entry (from the target) against the parent's
1675 * diff chunk. If that fails for a line, the second pass tries to match that
1676 * line to any part of parent file. That catches cases where a change was
1677 * broken into two chunks by 'context.'
1679 static void guess_line_blames(struct blame_origin *parent,
1680 struct blame_origin *target,
1681 int tlno, int offset, int same, int parent_len,
1682 struct blame_line_tracker *line_blames)
1684 int i, best_idx, target_idx;
1685 int parent_slno = tlno + offset;
1686 int *fuzzy_matches;
1688 fuzzy_matches = fuzzy_find_matching_lines(parent, target,
1689 tlno, parent_slno, same,
1690 parent_len);
1691 for (i = 0; i < same - tlno; i++) {
1692 target_idx = tlno + i;
1693 if (fuzzy_matches && fuzzy_matches[i] >= 0) {
1694 best_idx = fuzzy_matches[i];
1695 } else {
1696 best_idx = scan_parent_range(parent->fingerprints,
1697 target->fingerprints,
1698 target_idx, 0,
1699 parent->num_lines);
1701 if (best_idx >= 0) {
1702 line_blames[i].is_parent = 1;
1703 line_blames[i].s_lno = best_idx;
1704 } else {
1705 line_blames[i].is_parent = 0;
1706 line_blames[i].s_lno = target_idx;
1709 free(fuzzy_matches);
1713 * This decides which parts of a blame entry go to the parent (added to the
1714 * ignoredp list) and which stay with the target (added to the diffp list). The
1715 * actual decision was made in a separate heuristic function, and those answers
1716 * for the lines in 'e' are in line_blames. This consumes e, essentially
1717 * putting it on a list.
1719 * Note that the blame entries on the ignoredp list are not necessarily sorted
1720 * with respect to the parent's line numbers yet.
1722 static void ignore_blame_entry(struct blame_entry *e,
1723 struct blame_origin *parent,
1724 struct blame_entry **diffp,
1725 struct blame_entry **ignoredp,
1726 struct blame_line_tracker *line_blames)
1728 int entry_len, nr_lines, i;
1731 * We carve new entries off the front of e. Each entry comes from a
1732 * contiguous chunk of lines: adjacent lines from the same origin
1733 * (either the parent or the target).
1735 entry_len = 1;
1736 nr_lines = e->num_lines; /* e changes in the loop */
1737 for (i = 0; i < nr_lines; i++) {
1738 struct blame_entry *next = NULL;
1741 * We are often adjacent to the next line - only split the blame
1742 * entry when we have to.
1744 if (i + 1 < nr_lines) {
1745 if (are_lines_adjacent(&line_blames[i],
1746 &line_blames[i + 1])) {
1747 entry_len++;
1748 continue;
1750 next = split_blame_at(e, entry_len,
1751 blame_origin_incref(e->suspect));
1753 if (line_blames[i].is_parent) {
1754 e->ignored = 1;
1755 blame_origin_decref(e->suspect);
1756 e->suspect = blame_origin_incref(parent);
1757 e->s_lno = line_blames[i - entry_len + 1].s_lno;
1758 e->next = *ignoredp;
1759 *ignoredp = e;
1760 } else {
1761 e->unblamable = 1;
1762 /* e->s_lno is already in the target's address space. */
1763 e->next = *diffp;
1764 *diffp = e;
1766 assert(e->num_lines == entry_len);
1767 e = next;
1768 entry_len = 1;
1770 assert(!e);
1774 * Process one hunk from the patch between the current suspect for
1775 * blame_entry e and its parent. This first blames any unfinished
1776 * entries before the chunk (which is where target and parent start
1777 * differing) on the parent, and then splits blame entries at the
1778 * start and at the end of the difference region. Since use of -M and
1779 * -C options may lead to overlapping/duplicate source line number
1780 * ranges, all we can rely on from sorting/merging is the order of the
1781 * first suspect line number.
1783 * tlno: line number in the target where this chunk begins
1784 * same: line number in the target where this chunk ends
1785 * offset: add to tlno to get the chunk starting point in the parent
1786 * parent_len: number of lines in the parent chunk
1788 static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
1789 int tlno, int offset, int same, int parent_len,
1790 struct blame_origin *parent,
1791 struct blame_origin *target, int ignore_diffs)
1793 struct blame_entry *e = **srcq;
1794 struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;
1795 struct blame_line_tracker *line_blames = NULL;
1797 while (e && e->s_lno < tlno) {
1798 struct blame_entry *next = e->next;
1800 * current record starts before differing portion. If
1801 * it reaches into it, we need to split it up and
1802 * examine the second part separately.
1804 if (e->s_lno + e->num_lines > tlno) {
1805 /* Move second half to a new record */
1806 struct blame_entry *n;
1808 n = split_blame_at(e, tlno - e->s_lno, e->suspect);
1809 /* Push new record to diffp */
1810 n->next = diffp;
1811 diffp = n;
1812 } else
1813 blame_origin_decref(e->suspect);
1814 /* Pass blame for everything before the differing
1815 * chunk to the parent */
1816 e->suspect = blame_origin_incref(parent);
1817 e->s_lno += offset;
1818 e->next = samep;
1819 samep = e;
1820 e = next;
1823 * As we don't know how much of a common stretch after this
1824 * diff will occur, the currently blamed parts are all that we
1825 * can assign to the parent for now.
1828 if (samep) {
1829 **dstq = reverse_blame(samep, **dstq);
1830 *dstq = &samep->next;
1833 * Prepend the split off portions: everything after e starts
1834 * after the blameable portion.
1836 e = reverse_blame(diffp, e);
1839 * Now retain records on the target while parts are different
1840 * from the parent.
1842 samep = NULL;
1843 diffp = NULL;
1845 if (ignore_diffs && same - tlno > 0) {
1846 CALLOC_ARRAY(line_blames, same - tlno);
1847 guess_line_blames(parent, target, tlno, offset, same,
1848 parent_len, line_blames);
1851 while (e && e->s_lno < same) {
1852 struct blame_entry *next = e->next;
1855 * If current record extends into sameness, need to split.
1857 if (e->s_lno + e->num_lines > same) {
1859 * Move second half to a new record to be
1860 * processed by later chunks
1862 struct blame_entry *n;
1864 n = split_blame_at(e, same - e->s_lno,
1865 blame_origin_incref(e->suspect));
1866 /* Push new record to samep */
1867 n->next = samep;
1868 samep = n;
1870 if (ignore_diffs) {
1871 ignore_blame_entry(e, parent, &diffp, &ignoredp,
1872 line_blames + e->s_lno - tlno);
1873 } else {
1874 e->next = diffp;
1875 diffp = e;
1877 e = next;
1879 free(line_blames);
1880 if (ignoredp) {
1882 * Note ignoredp is not sorted yet, and thus neither is dstq.
1883 * That list must be sorted before we queue_blames(). We defer
1884 * sorting until after all diff hunks are processed, so that
1885 * guess_line_blames() can pick *any* line in the parent. The
1886 * slight drawback is that we end up sorting all blame entries
1887 * passed to the parent, including those that are unrelated to
1888 * changes made by the ignored commit.
1890 **dstq = reverse_blame(ignoredp, **dstq);
1891 *dstq = &ignoredp->next;
1893 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
1894 /* Move across elements that are in the unblamable portion */
1895 if (diffp)
1896 *srcq = &diffp->next;
1899 struct blame_chunk_cb_data {
1900 struct blame_origin *parent;
1901 struct blame_origin *target;
1902 long offset;
1903 int ignore_diffs;
1904 struct blame_entry **dstq;
1905 struct blame_entry **srcq;
1908 /* diff chunks are from parent to target */
1909 static int blame_chunk_cb(long start_a, long count_a,
1910 long start_b, long count_b, void *data)
1912 struct blame_chunk_cb_data *d = data;
1913 if (start_a - start_b != d->offset)
1914 die("internal error in blame::blame_chunk_cb");
1915 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
1916 start_b + count_b, count_a, d->parent, d->target,
1917 d->ignore_diffs);
1918 d->offset = start_a + count_a - (start_b + count_b);
1919 return 0;
1923 * We are looking at the origin 'target' and aiming to pass blame
1924 * for the lines it is suspected to its parent. Run diff to find
1925 * which lines came from parent and pass blame for them.
1927 static void pass_blame_to_parent(struct blame_scoreboard *sb,
1928 struct blame_origin *target,
1929 struct blame_origin *parent, int ignore_diffs)
1931 mmfile_t file_p, file_o;
1932 struct blame_chunk_cb_data d;
1933 struct blame_entry *newdest = NULL;
1935 if (!target->suspects)
1936 return; /* nothing remains for this target */
1938 d.parent = parent;
1939 d.target = target;
1940 d.offset = 0;
1941 d.ignore_diffs = ignore_diffs;
1942 d.dstq = &newdest; d.srcq = &target->suspects;
1944 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
1945 &sb->num_read_blob, ignore_diffs);
1946 fill_origin_blob(&sb->revs->diffopt, target, &file_o,
1947 &sb->num_read_blob, ignore_diffs);
1948 sb->num_get_patch++;
1950 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
1951 die("unable to generate diff (%s -> %s)",
1952 oid_to_hex(&parent->commit->object.oid),
1953 oid_to_hex(&target->commit->object.oid));
1954 /* The rest are the same as the parent */
1955 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, 0,
1956 parent, target, 0);
1957 *d.dstq = NULL;
1958 if (ignore_diffs)
1959 sort_blame_entries(&newdest, compare_blame_suspect);
1960 queue_blames(sb, parent, newdest);
1962 return;
1966 * The lines in blame_entry after splitting blames many times can become
1967 * very small and trivial, and at some point it becomes pointless to
1968 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1969 * ordinary C program, and it is not worth to say it was copied from
1970 * totally unrelated file in the parent.
1972 * Compute how trivial the lines in the blame_entry are.
1974 unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1976 unsigned score;
1977 const char *cp, *ep;
1979 if (e->score)
1980 return e->score;
1982 score = 1;
1983 cp = blame_nth_line(sb, e->lno);
1984 ep = blame_nth_line(sb, e->lno + e->num_lines);
1985 while (cp < ep) {
1986 unsigned ch = *((unsigned char *)cp);
1987 if (isalnum(ch))
1988 score++;
1989 cp++;
1991 e->score = score;
1992 return score;
1996 * best_so_far[] and potential[] are both a split of an existing blame_entry
1997 * that passes blame to the parent. Maintain best_so_far the best split so
1998 * far, by comparing potential and best_so_far and copying potential into
1999 * bst_so_far as needed.
2001 static void copy_split_if_better(struct blame_scoreboard *sb,
2002 struct blame_entry *best_so_far,
2003 struct blame_entry *potential)
2005 int i;
2007 if (!potential[1].suspect)
2008 return;
2009 if (best_so_far[1].suspect) {
2010 if (blame_entry_score(sb, &potential[1]) <
2011 blame_entry_score(sb, &best_so_far[1]))
2012 return;
2015 for (i = 0; i < 3; i++)
2016 blame_origin_incref(potential[i].suspect);
2017 decref_split(best_so_far);
2018 memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
2022 * We are looking at a part of the final image represented by
2023 * ent (tlno and same are offset by ent->s_lno).
2024 * tlno is where we are looking at in the final image.
2025 * up to (but not including) same match preimage.
2026 * plno is where we are looking at in the preimage.
2028 * <-------------- final image ---------------------->
2029 * <------ent------>
2030 * ^tlno ^same
2031 * <---------preimage----->
2032 * ^plno
2034 * All line numbers are 0-based.
2036 static void handle_split(struct blame_scoreboard *sb,
2037 struct blame_entry *ent,
2038 int tlno, int plno, int same,
2039 struct blame_origin *parent,
2040 struct blame_entry *split)
2042 if (ent->num_lines <= tlno)
2043 return;
2044 if (tlno < same) {
2045 struct blame_entry potential[3];
2046 tlno += ent->s_lno;
2047 same += ent->s_lno;
2048 split_overlap(potential, ent, tlno, plno, same, parent);
2049 copy_split_if_better(sb, split, potential);
2050 decref_split(potential);
2054 struct handle_split_cb_data {
2055 struct blame_scoreboard *sb;
2056 struct blame_entry *ent;
2057 struct blame_origin *parent;
2058 struct blame_entry *split;
2059 long plno;
2060 long tlno;
2063 static int handle_split_cb(long start_a, long count_a,
2064 long start_b, long count_b, void *data)
2066 struct handle_split_cb_data *d = data;
2067 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
2068 d->split);
2069 d->plno = start_a + count_a;
2070 d->tlno = start_b + count_b;
2071 return 0;
2075 * Find the lines from parent that are the same as ent so that
2076 * we can pass blames to it. file_p has the blob contents for
2077 * the parent.
2079 static void find_copy_in_blob(struct blame_scoreboard *sb,
2080 struct blame_entry *ent,
2081 struct blame_origin *parent,
2082 struct blame_entry *split,
2083 mmfile_t *file_p)
2085 const char *cp;
2086 mmfile_t file_o;
2087 struct handle_split_cb_data d;
2089 memset(&d, 0, sizeof(d));
2090 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
2092 * Prepare mmfile that contains only the lines in ent.
2094 cp = blame_nth_line(sb, ent->lno);
2095 file_o.ptr = (char *) cp;
2096 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
2099 * file_o is a part of final image we are annotating.
2100 * file_p partially may match that image.
2102 memset(split, 0, sizeof(struct blame_entry [3]));
2103 if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
2104 die("unable to generate diff (%s)",
2105 oid_to_hex(&parent->commit->object.oid));
2106 /* remainder, if any, all match the preimage */
2107 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
2110 /* Move all blame entries from list *source that have a score smaller
2111 * than score_min to the front of list *small.
2112 * Returns a pointer to the link pointing to the old head of the small list.
2115 static struct blame_entry **filter_small(struct blame_scoreboard *sb,
2116 struct blame_entry **small,
2117 struct blame_entry **source,
2118 unsigned score_min)
2120 struct blame_entry *p = *source;
2121 struct blame_entry *oldsmall = *small;
2122 while (p) {
2123 if (blame_entry_score(sb, p) <= score_min) {
2124 *small = p;
2125 small = &p->next;
2126 p = *small;
2127 } else {
2128 *source = p;
2129 source = &p->next;
2130 p = *source;
2133 *small = oldsmall;
2134 *source = NULL;
2135 return small;
2139 * See if lines currently target is suspected for can be attributed to
2140 * parent.
2142 static void find_move_in_parent(struct blame_scoreboard *sb,
2143 struct blame_entry ***blamed,
2144 struct blame_entry **toosmall,
2145 struct blame_origin *target,
2146 struct blame_origin *parent)
2148 struct blame_entry *e, split[3];
2149 struct blame_entry *unblamed = target->suspects;
2150 struct blame_entry *leftover = NULL;
2151 mmfile_t file_p;
2153 if (!unblamed)
2154 return; /* nothing remains for this target */
2156 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
2157 &sb->num_read_blob, 0);
2158 if (!file_p.ptr)
2159 return;
2161 /* At each iteration, unblamed has a NULL-terminated list of
2162 * entries that have not yet been tested for blame. leftover
2163 * contains the reversed list of entries that have been tested
2164 * without being assignable to the parent.
2166 do {
2167 struct blame_entry **unblamedtail = &unblamed;
2168 struct blame_entry *next;
2169 for (e = unblamed; e; e = next) {
2170 next = e->next;
2171 find_copy_in_blob(sb, e, parent, split, &file_p);
2172 if (split[1].suspect &&
2173 sb->move_score < blame_entry_score(sb, &split[1])) {
2174 split_blame(blamed, &unblamedtail, split, e);
2175 } else {
2176 e->next = leftover;
2177 leftover = e;
2179 decref_split(split);
2181 *unblamedtail = NULL;
2182 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
2183 } while (unblamed);
2184 target->suspects = reverse_blame(leftover, NULL);
2187 struct blame_list {
2188 struct blame_entry *ent;
2189 struct blame_entry split[3];
2193 * Count the number of entries the target is suspected for,
2194 * and prepare a list of entry and the best split.
2196 static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
2197 int *num_ents_p)
2199 struct blame_entry *e;
2200 int num_ents, i;
2201 struct blame_list *blame_list = NULL;
2203 for (e = unblamed, num_ents = 0; e; e = e->next)
2204 num_ents++;
2205 if (num_ents) {
2206 CALLOC_ARRAY(blame_list, num_ents);
2207 for (e = unblamed, i = 0; e; e = e->next)
2208 blame_list[i++].ent = e;
2210 *num_ents_p = num_ents;
2211 return blame_list;
2215 * For lines target is suspected for, see if we can find code movement
2216 * across file boundary from the parent commit. porigin is the path
2217 * in the parent we already tried.
2219 static void find_copy_in_parent(struct blame_scoreboard *sb,
2220 struct blame_entry ***blamed,
2221 struct blame_entry **toosmall,
2222 struct blame_origin *target,
2223 struct commit *parent,
2224 struct blame_origin *porigin,
2225 int opt)
2227 struct diff_options diff_opts;
2228 int i, j;
2229 struct blame_list *blame_list;
2230 int num_ents;
2231 struct blame_entry *unblamed = target->suspects;
2232 struct blame_entry *leftover = NULL;
2234 if (!unblamed)
2235 return; /* nothing remains for this target */
2237 repo_diff_setup(sb->repo, &diff_opts);
2238 diff_opts.flags.recursive = 1;
2239 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2241 diff_setup_done(&diff_opts);
2243 /* Try "find copies harder" on new path if requested;
2244 * we do not want to use diffcore_rename() actually to
2245 * match things up; find_copies_harder is set only to
2246 * force diff_tree_oid() to feed all filepairs to diff_queue,
2247 * and this code needs to be after diff_setup_done(), which
2248 * usually makes find-copies-harder imply copy detection.
2250 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
2251 || ((opt & PICKAXE_BLAME_COPY_HARDER)
2252 && (!porigin || strcmp(target->path, porigin->path))))
2253 diff_opts.flags.find_copies_harder = 1;
2255 if (is_null_oid(&target->commit->object.oid))
2256 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
2257 else
2258 diff_tree_oid(get_commit_tree_oid(parent),
2259 get_commit_tree_oid(target->commit),
2260 "", &diff_opts);
2262 if (!diff_opts.flags.find_copies_harder)
2263 diffcore_std(&diff_opts);
2265 do {
2266 struct blame_entry **unblamedtail = &unblamed;
2267 blame_list = setup_blame_list(unblamed, &num_ents);
2269 for (i = 0; i < diff_queued_diff.nr; i++) {
2270 struct diff_filepair *p = diff_queued_diff.queue[i];
2271 struct blame_origin *norigin;
2272 mmfile_t file_p;
2273 struct blame_entry potential[3];
2275 if (!DIFF_FILE_VALID(p->one))
2276 continue; /* does not exist in parent */
2277 if (S_ISGITLINK(p->one->mode))
2278 continue; /* ignore git links */
2279 if (porigin && !strcmp(p->one->path, porigin->path))
2280 /* find_move already dealt with this path */
2281 continue;
2283 norigin = get_origin(parent, p->one->path);
2284 oidcpy(&norigin->blob_oid, &p->one->oid);
2285 norigin->mode = p->one->mode;
2286 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,
2287 &sb->num_read_blob, 0);
2288 if (!file_p.ptr)
2289 continue;
2291 for (j = 0; j < num_ents; j++) {
2292 find_copy_in_blob(sb, blame_list[j].ent,
2293 norigin, potential, &file_p);
2294 copy_split_if_better(sb, blame_list[j].split,
2295 potential);
2296 decref_split(potential);
2298 blame_origin_decref(norigin);
2301 for (j = 0; j < num_ents; j++) {
2302 struct blame_entry *split = blame_list[j].split;
2303 if (split[1].suspect &&
2304 sb->copy_score < blame_entry_score(sb, &split[1])) {
2305 split_blame(blamed, &unblamedtail, split,
2306 blame_list[j].ent);
2307 } else {
2308 blame_list[j].ent->next = leftover;
2309 leftover = blame_list[j].ent;
2311 decref_split(split);
2313 free(blame_list);
2314 *unblamedtail = NULL;
2315 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
2316 } while (unblamed);
2317 target->suspects = reverse_blame(leftover, NULL);
2318 diff_flush(&diff_opts);
2322 * The blobs of origin and porigin exactly match, so everything
2323 * origin is suspected for can be blamed on the parent.
2325 static void pass_whole_blame(struct blame_scoreboard *sb,
2326 struct blame_origin *origin, struct blame_origin *porigin)
2328 struct blame_entry *e, *suspects;
2330 if (!porigin->file.ptr && origin->file.ptr) {
2331 /* Steal its file */
2332 porigin->file = origin->file;
2333 origin->file.ptr = NULL;
2335 suspects = origin->suspects;
2336 origin->suspects = NULL;
2337 for (e = suspects; e; e = e->next) {
2338 blame_origin_incref(porigin);
2339 blame_origin_decref(e->suspect);
2340 e->suspect = porigin;
2342 queue_blames(sb, porigin, suspects);
2346 * We pass blame from the current commit to its parents. We keep saying
2347 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2348 * exonerate ourselves.
2350 static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
2351 int reverse)
2353 if (!reverse) {
2354 if (revs->first_parent_only &&
2355 commit->parents &&
2356 commit->parents->next) {
2357 free_commit_list(commit->parents->next);
2358 commit->parents->next = NULL;
2360 return commit->parents;
2362 return lookup_decoration(&revs->children, &commit->object);
2365 static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
2367 struct commit_list *l = first_scapegoat(revs, commit, reverse);
2368 return commit_list_count(l);
2371 /* Distribute collected unsorted blames to the respected sorted lists
2372 * in the various origins.
2374 static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
2376 sort_blame_entries(&blamed, compare_blame_suspect);
2377 while (blamed)
2379 struct blame_origin *porigin = blamed->suspect;
2380 struct blame_entry *suspects = NULL;
2381 do {
2382 struct blame_entry *next = blamed->next;
2383 blamed->next = suspects;
2384 suspects = blamed;
2385 blamed = next;
2386 } while (blamed && blamed->suspect == porigin);
2387 suspects = reverse_blame(suspects, NULL);
2388 queue_blames(sb, porigin, suspects);
2392 #define MAXSG 16
2394 typedef struct blame_origin *(*blame_find_alg)(struct repository *,
2395 struct commit *,
2396 struct blame_origin *,
2397 struct blame_bloom_data *);
2399 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
2401 struct rev_info *revs = sb->revs;
2402 int i, pass, num_sg;
2403 struct commit *commit = origin->commit;
2404 struct commit_list *sg;
2405 struct blame_origin *sg_buf[MAXSG];
2406 struct blame_origin *porigin, **sg_origin = sg_buf;
2407 struct blame_entry *toosmall = NULL;
2408 struct blame_entry *blames, **blametail = &blames;
2410 num_sg = num_scapegoats(revs, commit, sb->reverse);
2411 if (!num_sg)
2412 goto finish;
2413 else if (num_sg < ARRAY_SIZE(sg_buf))
2414 memset(sg_buf, 0, sizeof(sg_buf));
2415 else
2416 CALLOC_ARRAY(sg_origin, num_sg);
2419 * The first pass looks for unrenamed path to optimize for
2420 * common cases, then we look for renames in the second pass.
2422 for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
2423 blame_find_alg find = pass ? find_rename : find_origin;
2425 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2426 i < num_sg && sg;
2427 sg = sg->next, i++) {
2428 struct commit *p = sg->item;
2429 int j, same;
2431 if (sg_origin[i])
2432 continue;
2433 if (parse_commit(p))
2434 continue;
2435 porigin = find(sb->repo, p, origin, sb->bloom_data);
2436 if (!porigin)
2437 continue;
2438 if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
2439 pass_whole_blame(sb, origin, porigin);
2440 blame_origin_decref(porigin);
2441 goto finish;
2443 for (j = same = 0; j < i; j++)
2444 if (sg_origin[j] &&
2445 oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
2446 same = 1;
2447 break;
2449 if (!same)
2450 sg_origin[i] = porigin;
2451 else
2452 blame_origin_decref(porigin);
2456 sb->num_commits++;
2457 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2458 i < num_sg && sg;
2459 sg = sg->next, i++) {
2460 struct blame_origin *porigin = sg_origin[i];
2461 if (!porigin)
2462 continue;
2463 if (!origin->previous) {
2464 blame_origin_incref(porigin);
2465 origin->previous = porigin;
2467 pass_blame_to_parent(sb, origin, porigin, 0);
2468 if (!origin->suspects)
2469 goto finish;
2473 * Pass remaining suspects for ignored commits to their parents.
2475 if (oidset_contains(&sb->ignore_list, &commit->object.oid)) {
2476 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2477 i < num_sg && sg;
2478 sg = sg->next, i++) {
2479 struct blame_origin *porigin = sg_origin[i];
2481 if (!porigin)
2482 continue;
2483 pass_blame_to_parent(sb, origin, porigin, 1);
2485 * Preemptively drop porigin so we can refresh the
2486 * fingerprints if we use the parent again, which can
2487 * occur if you ignore back-to-back commits.
2489 drop_origin_blob(porigin);
2490 if (!origin->suspects)
2491 goto finish;
2496 * Optionally find moves in parents' files.
2498 if (opt & PICKAXE_BLAME_MOVE) {
2499 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
2500 if (origin->suspects) {
2501 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2502 i < num_sg && sg;
2503 sg = sg->next, i++) {
2504 struct blame_origin *porigin = sg_origin[i];
2505 if (!porigin)
2506 continue;
2507 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
2508 if (!origin->suspects)
2509 break;
2515 * Optionally find copies from parents' files.
2517 if (opt & PICKAXE_BLAME_COPY) {
2518 if (sb->copy_score > sb->move_score)
2519 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2520 else if (sb->copy_score < sb->move_score) {
2521 origin->suspects = blame_merge(origin->suspects, toosmall);
2522 toosmall = NULL;
2523 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2525 if (!origin->suspects)
2526 goto finish;
2528 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2529 i < num_sg && sg;
2530 sg = sg->next, i++) {
2531 struct blame_origin *porigin = sg_origin[i];
2532 find_copy_in_parent(sb, &blametail, &toosmall,
2533 origin, sg->item, porigin, opt);
2534 if (!origin->suspects)
2535 goto finish;
2539 finish:
2540 *blametail = NULL;
2541 distribute_blame(sb, blames);
2543 * prepend toosmall to origin->suspects
2545 * There is no point in sorting: this ends up on a big
2546 * unsorted list in the caller anyway.
2548 if (toosmall) {
2549 struct blame_entry **tail = &toosmall;
2550 while (*tail)
2551 tail = &(*tail)->next;
2552 *tail = origin->suspects;
2553 origin->suspects = toosmall;
2555 for (i = 0; i < num_sg; i++) {
2556 if (sg_origin[i]) {
2557 if (!sg_origin[i]->suspects)
2558 drop_origin_blob(sg_origin[i]);
2559 blame_origin_decref(sg_origin[i]);
2562 drop_origin_blob(origin);
2563 if (sg_buf != sg_origin)
2564 free(sg_origin);
2568 * The main loop -- while we have blobs with lines whose true origin
2569 * is still unknown, pick one blob, and allow its lines to pass blames
2570 * to its parents. */
2571 void assign_blame(struct blame_scoreboard *sb, int opt)
2573 struct rev_info *revs = sb->revs;
2574 struct commit *commit = prio_queue_get(&sb->commits);
2576 while (commit) {
2577 struct blame_entry *ent;
2578 struct blame_origin *suspect = get_blame_suspects(commit);
2580 /* find one suspect to break down */
2581 while (suspect && !suspect->suspects)
2582 suspect = suspect->next;
2584 if (!suspect) {
2585 commit = prio_queue_get(&sb->commits);
2586 continue;
2589 assert(commit == suspect->commit);
2592 * We will use this suspect later in the loop,
2593 * so hold onto it in the meantime.
2595 blame_origin_incref(suspect);
2596 parse_commit(commit);
2597 if (sb->reverse ||
2598 (!(commit->object.flags & UNINTERESTING) &&
2599 !(revs->max_age != -1 && commit->date < revs->max_age)))
2600 pass_blame(sb, suspect, opt);
2601 else {
2602 commit->object.flags |= UNINTERESTING;
2603 if (commit->object.parsed)
2604 mark_parents_uninteresting(sb->revs, commit);
2606 /* treat root commit as boundary */
2607 if (!commit->parents && !sb->show_root)
2608 commit->object.flags |= UNINTERESTING;
2610 /* Take responsibility for the remaining entries */
2611 ent = suspect->suspects;
2612 if (ent) {
2613 suspect->guilty = 1;
2614 for (;;) {
2615 struct blame_entry *next = ent->next;
2616 if (sb->found_guilty_entry)
2617 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
2618 if (next) {
2619 ent = next;
2620 continue;
2622 ent->next = sb->ent;
2623 sb->ent = suspect->suspects;
2624 suspect->suspects = NULL;
2625 break;
2628 blame_origin_decref(suspect);
2630 if (sb->debug) /* sanity */
2631 sanity_check_refcnt(sb);
2636 * To allow quick access to the contents of nth line in the
2637 * final image, prepare an index in the scoreboard.
2639 static int prepare_lines(struct blame_scoreboard *sb)
2641 sb->num_lines = find_line_starts(&sb->lineno, sb->final_buf,
2642 sb->final_buf_size);
2643 return sb->num_lines;
2646 static struct commit *find_single_final(struct rev_info *revs,
2647 const char **name_p)
2649 int i;
2650 struct commit *found = NULL;
2651 const char *name = NULL;
2653 for (i = 0; i < revs->pending.nr; i++) {
2654 struct object *obj = revs->pending.objects[i].item;
2655 if (obj->flags & UNINTERESTING)
2656 continue;
2657 obj = deref_tag(revs->repo, obj, NULL, 0);
2658 if (!obj || obj->type != OBJ_COMMIT)
2659 die("Non commit %s?", revs->pending.objects[i].name);
2660 if (found)
2661 die("More than one commit to dig from %s and %s?",
2662 revs->pending.objects[i].name, name);
2663 found = (struct commit *)obj;
2664 name = revs->pending.objects[i].name;
2666 if (name_p)
2667 *name_p = xstrdup_or_null(name);
2668 return found;
2671 static struct commit *dwim_reverse_initial(struct rev_info *revs,
2672 const char **name_p)
2675 * DWIM "git blame --reverse ONE -- PATH" as
2676 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2677 * when it makes sense.
2679 struct object *obj;
2680 struct commit *head_commit;
2681 struct object_id head_oid;
2683 if (revs->pending.nr != 1)
2684 return NULL;
2686 /* Is that sole rev a committish? */
2687 obj = revs->pending.objects[0].item;
2688 obj = deref_tag(revs->repo, obj, NULL, 0);
2689 if (!obj || obj->type != OBJ_COMMIT)
2690 return NULL;
2692 /* Do we have HEAD? */
2693 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
2694 return NULL;
2695 head_commit = lookup_commit_reference_gently(revs->repo,
2696 &head_oid, 1);
2697 if (!head_commit)
2698 return NULL;
2700 /* Turn "ONE" into "ONE..HEAD" then */
2701 obj->flags |= UNINTERESTING;
2702 add_pending_object(revs, &head_commit->object, "HEAD");
2704 if (name_p)
2705 *name_p = revs->pending.objects[0].name;
2706 return (struct commit *)obj;
2709 static struct commit *find_single_initial(struct rev_info *revs,
2710 const char **name_p)
2712 int i;
2713 struct commit *found = NULL;
2714 const char *name = NULL;
2717 * There must be one and only one negative commit, and it must be
2718 * the boundary.
2720 for (i = 0; i < revs->pending.nr; i++) {
2721 struct object *obj = revs->pending.objects[i].item;
2722 if (!(obj->flags & UNINTERESTING))
2723 continue;
2724 obj = deref_tag(revs->repo, obj, NULL, 0);
2725 if (!obj || obj->type != OBJ_COMMIT)
2726 die("Non commit %s?", revs->pending.objects[i].name);
2727 if (found)
2728 die("More than one commit to dig up from, %s and %s?",
2729 revs->pending.objects[i].name, name);
2730 found = (struct commit *) obj;
2731 name = revs->pending.objects[i].name;
2734 if (!name)
2735 found = dwim_reverse_initial(revs, &name);
2736 if (!name)
2737 die("No commit to dig up from?");
2739 if (name_p)
2740 *name_p = xstrdup(name);
2741 return found;
2744 void init_scoreboard(struct blame_scoreboard *sb)
2746 memset(sb, 0, sizeof(struct blame_scoreboard));
2747 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
2748 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
2751 void setup_scoreboard(struct blame_scoreboard *sb,
2752 struct blame_origin **orig)
2754 const char *final_commit_name = NULL;
2755 struct blame_origin *o;
2756 struct commit *final_commit = NULL;
2757 enum object_type type;
2759 init_blame_suspects(&blame_suspects);
2761 if (sb->reverse && sb->contents_from)
2762 die(_("--contents and --reverse do not blend well."));
2764 if (!sb->repo)
2765 BUG("repo is NULL");
2767 if (!sb->reverse) {
2768 sb->final = find_single_final(sb->revs, &final_commit_name);
2769 sb->commits.compare = compare_commits_by_commit_date;
2770 } else {
2771 sb->final = find_single_initial(sb->revs, &final_commit_name);
2772 sb->commits.compare = compare_commits_by_reverse_commit_date;
2775 if (sb->final && sb->contents_from)
2776 die(_("cannot use --contents with final commit object name"));
2778 if (sb->reverse && sb->revs->first_parent_only)
2779 sb->revs->children.name = NULL;
2781 if (!sb->final) {
2783 * "--not A B -- path" without anything positive;
2784 * do not default to HEAD, but use the working tree
2785 * or "--contents".
2787 setup_work_tree();
2788 sb->final = fake_working_tree_commit(sb->repo,
2789 &sb->revs->diffopt,
2790 sb->path, sb->contents_from);
2791 add_pending_object(sb->revs, &(sb->final->object), ":");
2794 if (sb->reverse && sb->revs->first_parent_only) {
2795 final_commit = find_single_final(sb->revs, NULL);
2796 if (!final_commit)
2797 die(_("--reverse and --first-parent together require specified latest commit"));
2801 * If we have bottom, this will mark the ancestors of the
2802 * bottom commits we would reach while traversing as
2803 * uninteresting.
2805 if (prepare_revision_walk(sb->revs))
2806 die(_("revision walk setup failed"));
2808 if (sb->reverse && sb->revs->first_parent_only) {
2809 struct commit *c = final_commit;
2811 sb->revs->children.name = "children";
2812 while (c->parents &&
2813 !oideq(&c->object.oid, &sb->final->object.oid)) {
2814 struct commit_list *l = xcalloc(1, sizeof(*l));
2816 l->item = c;
2817 if (add_decoration(&sb->revs->children,
2818 &c->parents->item->object, l))
2819 BUG("not unique item in first-parent chain");
2820 c = c->parents->item;
2823 if (!oideq(&c->object.oid, &sb->final->object.oid))
2824 die(_("--reverse --first-parent together require range along first-parent chain"));
2827 if (is_null_oid(&sb->final->object.oid)) {
2828 o = get_blame_suspects(sb->final);
2829 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
2830 sb->final_buf_size = o->file.size;
2832 else {
2833 o = get_origin(sb->final, sb->path);
2834 if (fill_blob_sha1_and_mode(sb->repo, o))
2835 die(_("no such path %s in %s"), sb->path, final_commit_name);
2837 if (sb->revs->diffopt.flags.allow_textconv &&
2838 textconv_object(sb->repo, sb->path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
2839 &sb->final_buf_size))
2841 else
2842 sb->final_buf = read_object_file(&o->blob_oid, &type,
2843 &sb->final_buf_size);
2845 if (!sb->final_buf)
2846 die(_("cannot read blob %s for path %s"),
2847 oid_to_hex(&o->blob_oid),
2848 sb->path);
2850 sb->num_read_blob++;
2851 prepare_lines(sb);
2853 if (orig)
2854 *orig = o;
2856 free((char *)final_commit_name);
2861 struct blame_entry *blame_entry_prepend(struct blame_entry *head,
2862 long start, long end,
2863 struct blame_origin *o)
2865 struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
2866 new_head->lno = start;
2867 new_head->num_lines = end - start;
2868 new_head->suspect = o;
2869 new_head->s_lno = start;
2870 new_head->next = head;
2871 blame_origin_incref(o);
2872 return new_head;
2875 void setup_blame_bloom_data(struct blame_scoreboard *sb)
2877 struct blame_bloom_data *bd;
2878 struct bloom_filter_settings *bs;
2880 if (!sb->repo->objects->commit_graph)
2881 return;
2883 bs = get_bloom_filter_settings(sb->repo);
2884 if (!bs)
2885 return;
2887 bd = xmalloc(sizeof(struct blame_bloom_data));
2889 bd->settings = bs;
2891 bd->alloc = 4;
2892 bd->nr = 0;
2893 ALLOC_ARRAY(bd->keys, bd->alloc);
2895 add_bloom_key(bd, sb->path);
2897 sb->bloom_data = bd;
2900 void cleanup_scoreboard(struct blame_scoreboard *sb)
2902 if (sb->bloom_data) {
2903 int i;
2904 for (i = 0; i < sb->bloom_data->nr; i++) {
2905 free(sb->bloom_data->keys[i]->hashes);
2906 free(sb->bloom_data->keys[i]);
2908 free(sb->bloom_data->keys);
2909 FREE_AND_NULL(sb->bloom_data);
2911 trace2_data_intmax("blame", sb->repo,
2912 "bloom/queries", bloom_count_queries);
2913 trace2_data_intmax("blame", sb->repo,
2914 "bloom/response-no", bloom_count_no);