]> git.ipfire.org Git - thirdparty/git.git/blame - blame.c
treewide: remove cache.h inclusion due to environment.h changes
[thirdparty/git.git] / blame.c
CommitLineData
072bf432
JS
1#include "cache.h"
2#include "refs.h"
cbd53a21 3#include "object-store.h"
072bf432 4#include "cache-tree.h"
b543bb1c
JS
5#include "mergesort.h"
6#include "diff.h"
7#include "diffcore.h"
f394e093 8#include "gettext.h"
41771fa4 9#include "hex.h"
09002f1b 10#include "tag.h"
f5dd754c 11#include "blame.h"
14ba97f8 12#include "alloc.h"
4e0df4e6 13#include "commit-slab.h"
0906ac2b
DS
14#include "bloom.h"
15#include "commit-graph.h"
4e0df4e6
NTND
16
17define_commit_slab(blame_suspects, struct blame_origin *);
18static struct blame_suspects blame_suspects;
19
20struct blame_origin *get_blame_suspects(struct commit *commit)
21{
22 struct blame_origin **result;
23
24 result = blame_suspects_peek(&blame_suspects, commit);
25
26 return result ? *result : NULL;
27}
28
29static void set_blame_suspects(struct commit *commit, struct blame_origin *origin)
30{
31 *blame_suspects_at(&blame_suspects, commit) = origin;
32}
f5dd754c
JS
33
34void blame_origin_decref(struct blame_origin *o)
35{
36 if (o && --o->refcnt <= 0) {
37 struct blame_origin *p, *l = NULL;
38 if (o->previous)
39 blame_origin_decref(o->previous);
40 free(o->file.ptr);
41 /* Should be present exactly once in commit chain */
4e0df4e6 42 for (p = get_blame_suspects(o->commit); p; l = p, p = p->next) {
f5dd754c
JS
43 if (p == o) {
44 if (l)
45 l->next = p->next;
46 else
4e0df4e6 47 set_blame_suspects(o->commit, p->next);
f5dd754c
JS
48 free(o);
49 return;
50 }
51 }
52 die("internal error in blame_origin_decref");
53 }
54}
55
56/*
57 * Given a commit and a path in it, create a new origin structure.
58 * The callers that add blame to the scoreboard should use
59 * get_origin() to obtain shared, refcounted copy instead of calling
60 * this function directly.
61 */
072bf432 62static struct blame_origin *make_origin(struct commit *commit, const char *path)
f5dd754c
JS
63{
64 struct blame_origin *o;
65 FLEX_ALLOC_STR(o, path, path);
66 o->commit = commit;
67 o->refcnt = 1;
4e0df4e6
NTND
68 o->next = get_blame_suspects(commit);
69 set_blame_suspects(commit, o);
f5dd754c
JS
70 return o;
71}
72
73/*
74 * Locate an existing origin or create a new one.
75 * This moves the origin to front position in the commit util list.
76 */
09002f1b 77static struct blame_origin *get_origin(struct commit *commit, const char *path)
f5dd754c
JS
78{
79 struct blame_origin *o, *l;
80
4e0df4e6 81 for (o = get_blame_suspects(commit), l = NULL; o; l = o, o = o->next) {
f5dd754c
JS
82 if (!strcmp(o->path, path)) {
83 /* bump to front */
84 if (l) {
85 l->next = o->next;
4e0df4e6
NTND
86 o->next = get_blame_suspects(commit);
87 set_blame_suspects(commit, o);
f5dd754c
JS
88 }
89 return blame_origin_incref(o);
90 }
91 }
92 return make_origin(commit, path);
93}
072bf432
JS
94
95
96
a470beea 97static void verify_working_tree_path(struct repository *r,
ecbbc0a5 98 struct commit *work_tree, const char *path)
072bf432
JS
99{
100 struct commit_list *parents;
101 int pos;
102
103 for (parents = work_tree->parents; parents; parents = parents->next) {
104 const struct object_id *commit_oid = &parents->item->object.oid;
105 struct object_id blob_oid;
5ec1e728 106 unsigned short mode;
072bf432 107
50ddb089 108 if (!get_tree_entry(r, commit_oid, path, &blob_oid, &mode) &&
a470beea 109 oid_object_info(r, &blob_oid, NULL) == OBJ_BLOB)
072bf432
JS
110 return;
111 }
112
a470beea 113 pos = index_name_pos(r->index, path, strlen(path));
072bf432
JS
114 if (pos >= 0)
115 ; /* path is in the index */
a470beea
NTND
116 else if (-1 - pos < r->index->cache_nr &&
117 !strcmp(r->index->cache[-1 - pos]->name, path))
072bf432
JS
118 ; /* path is in the index, unmerged */
119 else
120 die("no such path '%s' in HEAD", path);
121}
122
fb998eae
NTND
123static struct commit_list **append_parent(struct repository *r,
124 struct commit_list **tail,
125 const struct object_id *oid)
072bf432
JS
126{
127 struct commit *parent;
128
fb998eae 129 parent = lookup_commit_reference(r, oid);
072bf432
JS
130 if (!parent)
131 die("no such commit %s", oid_to_hex(oid));
132 return &commit_list_insert(parent, tail)->next;
133}
134
fb998eae
NTND
135static void append_merge_parents(struct repository *r,
136 struct commit_list **tail)
072bf432
JS
137{
138 int merge_head;
139 struct strbuf line = STRBUF_INIT;
140
fb998eae 141 merge_head = open(git_path_merge_head(r), O_RDONLY);
072bf432
JS
142 if (merge_head < 0) {
143 if (errno == ENOENT)
144 return;
102de880 145 die("cannot open '%s' for reading",
fb998eae 146 git_path_merge_head(r));
072bf432
JS
147 }
148
149 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
150 struct object_id oid;
fee49308 151 if (get_oid_hex(line.buf, &oid))
102de880 152 die("unknown line in '%s': %s",
fb998eae
NTND
153 git_path_merge_head(r), line.buf);
154 tail = append_parent(r, tail, &oid);
072bf432
JS
155 }
156 close(merge_head);
157 strbuf_release(&line);
158}
159
160/*
161 * This isn't as simple as passing sb->buf and sb->len, because we
162 * want to transfer ownership of the buffer to the commit (so we
163 * must use detach).
164 */
fb998eae
NTND
165static void set_commit_buffer_from_strbuf(struct repository *r,
166 struct commit *c,
167 struct strbuf *sb)
072bf432
JS
168{
169 size_t len;
170 void *buf = strbuf_detach(sb, &len);
fb998eae 171 set_commit_buffer(r, c, buf, len);
072bf432
JS
172}
173
174/*
175 * Prepare a dummy commit that represents the work tree (or staged) item.
176 * Note that annotating work tree item never works in the reverse.
177 */
a470beea 178static struct commit *fake_working_tree_commit(struct repository *r,
ecbbc0a5 179 struct diff_options *opt,
09002f1b
JS
180 const char *path,
181 const char *contents_from)
072bf432
JS
182{
183 struct commit *commit;
184 struct blame_origin *origin;
185 struct commit_list **parent_tail, *parent;
186 struct object_id head_oid;
187 struct strbuf buf = STRBUF_INIT;
188 const char *ident;
189 time_t now;
a849735b 190 int len;
072bf432
JS
191 struct cache_entry *ce;
192 unsigned mode;
193 struct strbuf msg = STRBUF_INIT;
194
e1ff0a32 195 repo_read_index(r);
072bf432 196 time(&now);
fb998eae 197 commit = alloc_commit_node(r);
072bf432
JS
198 commit->object.parsed = 1;
199 commit->date = now;
200 parent_tail = &commit->parents;
201
49e61479 202 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
072bf432
JS
203 die("no such ref: HEAD");
204
fb998eae
NTND
205 parent_tail = append_parent(r, parent_tail, &head_oid);
206 append_merge_parents(r, parent_tail);
a470beea 207 verify_working_tree_path(r, commit, path);
072bf432
JS
208
209 origin = make_origin(commit, path);
210
39ab4d09
WH
211 ident = fmt_ident("Not Committed Yet", "not.committed.yet",
212 WANT_BLANK_IDENT, NULL, 0);
072bf432
JS
213 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
214 for (parent = commit->parents; parent; parent = parent->next)
215 strbuf_addf(&msg, "parent %s\n",
216 oid_to_hex(&parent->item->object.oid));
217 strbuf_addf(&msg,
218 "author %s\n"
219 "committer %s\n\n"
220 "Version of %s from %s\n",
221 ident, ident, path,
222 (!contents_from ? path :
223 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
fb998eae 224 set_commit_buffer_from_strbuf(r, commit, &msg);
072bf432
JS
225
226 if (!contents_from || strcmp("-", contents_from)) {
227 struct stat st;
228 const char *read_from;
229 char *buf_ptr;
230 unsigned long buf_len;
231
232 if (contents_from) {
233 if (stat(contents_from, &st) < 0)
234 die_errno("Cannot stat '%s'", contents_from);
235 read_from = contents_from;
236 }
237 else {
238 if (lstat(path, &st) < 0)
239 die_errno("Cannot lstat '%s'", path);
240 read_from = path;
241 }
242 mode = canon_mode(st.st_mode);
243
244 switch (st.st_mode & S_IFMT) {
245 case S_IFREG:
0d1e0e78 246 if (opt->flags.allow_textconv &&
14228447 247 textconv_object(r, read_from, mode, null_oid(), 0, &buf_ptr, &buf_len))
072bf432
JS
248 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
249 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
250 die_errno("cannot open or read '%s'", read_from);
251 break;
252 case S_IFLNK:
253 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
254 die_errno("cannot readlink '%s'", read_from);
255 break;
256 default:
257 die("unsupported file type %s", read_from);
258 }
259 }
260 else {
261 /* Reading from stdin */
262 mode = 0;
263 if (strbuf_read(&buf, 0, 0) < 0)
264 die_errno("failed to read from stdin");
265 }
a470beea 266 convert_to_git(r->index, path, buf.buf, buf.len, &buf, 0);
072bf432
JS
267 origin->file.ptr = buf.buf;
268 origin->file.size = buf.len;
829e5c3b 269 pretend_object_file(buf.buf, buf.len, OBJ_BLOB, &origin->blob_oid);
072bf432
JS
270
271 /*
272 * Read the current index, replace the path entry with
273 * origin->blob_sha1 without mucking with its mode or type
274 * bits; we are not going to write this index out -- we just
275 * want to run "diff-index --cached".
276 */
a470beea 277 discard_index(r->index);
e1ff0a32 278 repo_read_index(r);
072bf432
JS
279
280 len = strlen(path);
281 if (!mode) {
a470beea 282 int pos = index_name_pos(r->index, path, len);
072bf432 283 if (0 <= pos)
a470beea 284 mode = r->index->cache[pos]->ce_mode;
072bf432
JS
285 else
286 /* Let's not bother reading from HEAD tree */
287 mode = S_IFREG | 0644;
288 }
a470beea 289 ce = make_empty_cache_entry(r->index, len);
072bf432
JS
290 oidcpy(&ce->oid, &origin->blob_oid);
291 memcpy(ce->name, path, len);
292 ce->ce_flags = create_ce_flags(0);
293 ce->ce_namelen = len;
294 ce->ce_mode = create_ce_mode(mode);
a470beea 295 add_index_entry(r->index, ce,
ecbbc0a5 296 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
072bf432 297
a470beea 298 cache_tree_invalidate_path(r->index, path);
072bf432
JS
299
300 return commit;
301}
b543bb1c
JS
302
303
304
305static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
306 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data, int xdl_opts)
307{
308 xpparam_t xpp = {0};
309 xdemitconf_t xecfg = {0};
310 xdemitcb_t ecb = {NULL};
311
312 xpp.flags = xdl_opts;
313 xecfg.hunk_func = hunk_func;
314 ecb.priv = cb_data;
315 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
316}
317
1fc73384
BR
318static const char *get_next_line(const char *start, const char *end)
319{
320 const char *nl = memchr(start, '\n', end - start);
321
322 return nl ? nl + 1 : end;
323}
324
325static int find_line_starts(int **line_starts, const char *buf,
326 unsigned long len)
327{
328 const char *end = buf + len;
329 const char *p;
330 int *lineno;
331 int num = 0;
332
333 for (p = buf; p < end; p = get_next_line(p, end))
334 num++;
335
336 ALLOC_ARRAY(*line_starts, num + 1);
337 lineno = *line_starts;
338
339 for (p = buf; p < end; p = get_next_line(p, end))
340 *lineno++ = p - buf;
341
342 *lineno = len;
343
344 return num;
345}
346
1d028dc6
MP
347struct fingerprint_entry;
348
349/* A fingerprint is intended to loosely represent a string, such that two
350 * fingerprints can be quickly compared to give an indication of the similarity
351 * of the strings that they represent.
352 *
353 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
354 * the string that it represents. Whitespace is added at each end of the
355 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
356 * For example, the string "Darth Radar" will be converted to the following
357 * fingerprint:
358 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
359 *
360 * The similarity between two fingerprints is the size of the intersection of
361 * their multisets, including repeated elements. See fingerprint_similarity for
362 * examples.
363 *
364 * For ease of implementation, the fingerprint is implemented as a map
365 * of byte pairs to the count of that byte pair in the string, instead of
366 * allowing repeated elements in a set.
367 */
368struct fingerprint {
369 struct hashmap map;
370 /* As we know the maximum number of entries in advance, it's
371 * convenient to store the entries in a single array instead of having
372 * the hashmap manage the memory.
373 */
374 struct fingerprint_entry *entries;
375};
376
377/* A byte pair in a fingerprint. Stores the number of times the byte pair
378 * occurs in the string that the fingerprint represents.
379 */
380struct fingerprint_entry {
381 /* The hashmap entry - the hash represents the byte pair in its
382 * entirety so we don't need to store the byte pair separately.
383 */
384 struct hashmap_entry entry;
385 /* The number of times the byte pair occurs in the string that the
386 * fingerprint represents.
387 */
388 int count;
389};
390
391/* See `struct fingerprint` for an explanation of what a fingerprint is.
392 * \param result the fingerprint of the string is stored here. This must be
393 * freed later using free_fingerprint.
394 * \param line_begin the start of the string
395 * \param line_end the end of the string
396 */
397static void get_fingerprint(struct fingerprint *result,
398 const char *line_begin,
399 const char *line_end)
400{
401 unsigned int hash, c0 = 0, c1;
402 const char *p;
403 int max_map_entry_count = 1 + line_end - line_begin;
404 struct fingerprint_entry *entry = xcalloc(max_map_entry_count,
405 sizeof(struct fingerprint_entry));
406 struct fingerprint_entry *found_entry;
407
408 hashmap_init(&result->map, NULL, NULL, max_map_entry_count);
409 result->entries = entry;
410 for (p = line_begin; p <= line_end; ++p, c0 = c1) {
411 /* Always terminate the string with whitespace.
412 * Normalise whitespace to 0, and normalise letters to
413 * lower case. This won't work for multibyte characters but at
414 * worst will match some unrelated characters.
415 */
416 if ((p == line_end) || isspace(*p))
417 c1 = 0;
418 else
419 c1 = tolower(*p);
420 hash = c0 | (c1 << 8);
421 /* Ignore whitespace pairs */
422 if (hash == 0)
423 continue;
d22245a2 424 hashmap_entry_init(&entry->entry, hash);
1d028dc6 425
404ab78e
EW
426 found_entry = hashmap_get_entry(&result->map, entry,
427 /* member name */ entry, NULL);
1d028dc6
MP
428 if (found_entry) {
429 found_entry->count += 1;
430 } else {
431 entry->count = 1;
b94e5c1d 432 hashmap_add(&result->map, &entry->entry);
1d028dc6
MP
433 ++entry;
434 }
435 }
436}
437
438static void free_fingerprint(struct fingerprint *f)
439{
6da1a258 440 hashmap_clear(&f->map);
1d028dc6
MP
441 free(f->entries);
442}
443
444/* Calculates the similarity between two fingerprints as the size of the
445 * intersection of their multisets, including repeated elements. See
446 * `struct fingerprint` for an explanation of the fingerprint representation.
447 * The similarity between "cat mat" and "father rather" is 2 because "at" is
448 * present twice in both strings while the similarity between "tim" and "mit"
449 * is 0.
450 */
451static int fingerprint_similarity(struct fingerprint *a, struct fingerprint *b)
452{
453 int intersection = 0;
454 struct hashmap_iter iter;
455 const struct fingerprint_entry *entry_a, *entry_b;
456
87571c3f 457 hashmap_for_each_entry(&b->map, &iter, entry_b,
87571c3f 458 entry /* member name */) {
404ab78e 459 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
f23a4651 460 if (entry_a) {
1d028dc6
MP
461 intersection += entry_a->count < entry_b->count ?
462 entry_a->count : entry_b->count;
463 }
464 }
465 return intersection;
466}
467
468/* Subtracts byte-pair elements in B from A, modifying A in place.
469 */
470static void fingerprint_subtract(struct fingerprint *a, struct fingerprint *b)
471{
472 struct hashmap_iter iter;
473 struct fingerprint_entry *entry_a;
474 const struct fingerprint_entry *entry_b;
475
476 hashmap_iter_init(&b->map, &iter);
477
87571c3f 478 hashmap_for_each_entry(&b->map, &iter, entry_b,
87571c3f 479 entry /* member name */) {
404ab78e 480 entry_a = hashmap_get_entry(&a->map, entry_b, entry, NULL);
f23a4651 481 if (entry_a) {
1d028dc6 482 if (entry_a->count <= entry_b->count)
28ee7941 483 hashmap_remove(&a->map, &entry_b->entry, NULL);
1d028dc6
MP
484 else
485 entry_a->count -= entry_b->count;
486 }
487 }
488}
489
490/* Calculate fingerprints for a series of lines.
491 * Puts the fingerprints in the fingerprints array, which must have been
492 * preallocated to allow storing line_count elements.
493 */
494static void get_line_fingerprints(struct fingerprint *fingerprints,
495 const char *content, const int *line_starts,
496 long first_line, long line_count)
497{
498 int i;
499 const char *linestart, *lineend;
500
501 line_starts += first_line;
502 for (i = 0; i < line_count; ++i) {
503 linestart = content + line_starts[i];
504 lineend = content + line_starts[i + 1];
505 get_fingerprint(fingerprints + i, linestart, lineend);
506 }
507}
508
509static void free_line_fingerprints(struct fingerprint *fingerprints,
510 int nr_fingerprints)
511{
512 int i;
513
514 for (i = 0; i < nr_fingerprints; i++)
515 free_fingerprint(&fingerprints[i]);
516}
517
518/* This contains the data necessary to linearly map a line number in one half
519 * of a diff chunk to the line in the other half of the diff chunk that is
520 * closest in terms of its position as a fraction of the length of the chunk.
521 */
522struct line_number_mapping {
523 int destination_start, destination_length,
524 source_start, source_length;
525};
526
527/* Given a line number in one range, offset and scale it to map it onto the
528 * other range.
529 * Essentially this mapping is a simple linear equation but the calculation is
530 * more complicated to allow performing it with integer operations.
531 * Another complication is that if a line could map onto many lines in the
532 * destination range then we want to choose the line at the center of those
533 * possibilities.
534 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
535 * first 5 lines in B will map onto the first line in the A chunk, while the
536 * last 5 lines will all map onto the second line in the A chunk.
537 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
538 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
539 */
540static int map_line_number(int line_number,
541 const struct line_number_mapping *mapping)
542{
543 return ((line_number - mapping->source_start) * 2 + 1) *
544 mapping->destination_length /
545 (mapping->source_length * 2) +
546 mapping->destination_start;
547}
548
549/* Get a pointer to the element storing the similarity between a line in A
550 * and a line in B.
551 *
552 * The similarities are stored in a 2-dimensional array. Each "row" in the
553 * array contains the similarities for a line in B. The similarities stored in
554 * a row are the similarities between the line in B and the nearby lines in A.
555 * To keep the length of each row the same, it is padded out with values of -1
556 * where the search range extends beyond the lines in A.
557 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
558 * look like this:
559 * a | m
560 * b | n
561 * c | o
562 * d | p
563 * e | q
564 * Then the similarity array will contain:
565 * [-1, -1, am, bm, cm,
566 * -1, an, bn, cn, dn,
567 * ao, bo, co, do, eo,
568 * bp, cp, dp, ep, -1,
569 * cq, dq, eq, -1, -1]
570 * Where similarities are denoted either by -1 for invalid, or the
571 * concatenation of the two lines in the diff being compared.
572 *
573 * \param similarities array of similarities between lines in A and B
574 * \param line_a the index of the line in A, in the same frame of reference as
575 * closest_line_a.
576 * \param local_line_b the index of the line in B, relative to the first line
577 * in B that similarities represents.
578 * \param closest_line_a the index of the line in A that is deemed to be
579 * closest to local_line_b. This must be in the same
580 * frame of reference as line_a. This value defines
581 * where similarities is centered for the line in B.
582 * \param max_search_distance_a maximum distance in lines from the closest line
583 * in A for other lines in A for which
584 * similarities may be calculated.
585 */
586static int *get_similarity(int *similarities,
587 int line_a, int local_line_b,
588 int closest_line_a, int max_search_distance_a)
589{
590 assert(abs(line_a - closest_line_a) <=
591 max_search_distance_a);
592 return similarities + line_a - closest_line_a +
593 max_search_distance_a +
594 local_line_b * (max_search_distance_a * 2 + 1);
595}
596
597#define CERTAIN_NOTHING_MATCHES -2
598#define CERTAINTY_NOT_CALCULATED -1
599
600/* Given a line in B, first calculate its similarities with nearby lines in A
601 * if not already calculated, then identify the most similar and second most
602 * similar lines. The "certainty" is calculated based on those two
603 * similarities.
604 *
605 * \param start_a the index of the first line of the chunk in A
606 * \param length_a the length in lines of the chunk in A
607 * \param local_line_b the index of the line in B, relative to the first line
608 * in the chunk.
609 * \param fingerprints_a array of fingerprints for the chunk in A
610 * \param fingerprints_b array of fingerprints for the chunk in B
611 * \param similarities 2-dimensional array of similarities between lines in A
612 * and B. See get_similarity() for more details.
613 * \param certainties array of values indicating how strongly a line in B is
614 * matched with some line in A.
615 * \param second_best_result array of absolute indices in A for the second
616 * closest match of a line in B.
617 * \param result array of absolute indices in A for the closest match of a line
618 * in B.
619 * \param max_search_distance_a maximum distance in lines from the closest line
620 * in A for other lines in A for which
621 * similarities may be calculated.
622 * \param map_line_number_in_b_to_a parameter to map_line_number().
623 */
624static void find_best_line_matches(
625 int start_a,
626 int length_a,
627 int start_b,
628 int local_line_b,
629 struct fingerprint *fingerprints_a,
630 struct fingerprint *fingerprints_b,
631 int *similarities,
632 int *certainties,
633 int *second_best_result,
634 int *result,
635 const int max_search_distance_a,
636 const struct line_number_mapping *map_line_number_in_b_to_a)
637{
638
639 int i, search_start, search_end, closest_local_line_a, *similarity,
640 best_similarity = 0, second_best_similarity = 0,
641 best_similarity_index = 0, second_best_similarity_index = 0;
642
643 /* certainty has already been calculated so no need to redo the work */
644 if (certainties[local_line_b] != CERTAINTY_NOT_CALCULATED)
645 return;
646
647 closest_local_line_a = map_line_number(
648 local_line_b + start_b, map_line_number_in_b_to_a) - start_a;
649
650 search_start = closest_local_line_a - max_search_distance_a;
651 if (search_start < 0)
652 search_start = 0;
653
654 search_end = closest_local_line_a + max_search_distance_a + 1;
655 if (search_end > length_a)
656 search_end = length_a;
657
658 for (i = search_start; i < search_end; ++i) {
659 similarity = get_similarity(similarities,
660 i, local_line_b,
661 closest_local_line_a,
662 max_search_distance_a);
663 if (*similarity == -1) {
664 /* This value will never exceed 10 but assert just in
665 * case
666 */
667 assert(abs(i - closest_local_line_a) < 1000);
668 /* scale the similarity by (1000 - distance from
669 * closest line) to act as a tie break between lines
670 * that otherwise are equally similar.
671 */
672 *similarity = fingerprint_similarity(
673 fingerprints_b + local_line_b,
674 fingerprints_a + i) *
675 (1000 - abs(i - closest_local_line_a));
676 }
677 if (*similarity > best_similarity) {
678 second_best_similarity = best_similarity;
679 second_best_similarity_index = best_similarity_index;
680 best_similarity = *similarity;
681 best_similarity_index = i;
682 } else if (*similarity > second_best_similarity) {
683 second_best_similarity = *similarity;
684 second_best_similarity_index = i;
685 }
686 }
687
688 if (best_similarity == 0) {
689 /* this line definitely doesn't match with anything. Mark it
690 * with this special value so it doesn't get invalidated and
691 * won't be recalculated.
692 */
693 certainties[local_line_b] = CERTAIN_NOTHING_MATCHES;
694 result[local_line_b] = -1;
695 } else {
696 /* Calculate the certainty with which this line matches.
697 * If the line matches well with two lines then that reduces
698 * the certainty. However we still want to prioritise matching
699 * a line that matches very well with two lines over matching a
700 * line that matches poorly with one line, hence doubling
701 * best_similarity.
702 * This means that if we have
703 * line X that matches only one line with a score of 3,
704 * line Y that matches two lines equally with a score of 5,
705 * and line Z that matches only one line with a score or 2,
706 * then the lines in order of certainty are X, Y, Z.
707 */
708 certainties[local_line_b] = best_similarity * 2 -
709 second_best_similarity;
710
711 /* We keep both the best and second best results to allow us to
712 * check at a later stage of the matching process whether the
713 * result needs to be invalidated.
714 */
715 result[local_line_b] = start_a + best_similarity_index;
716 second_best_result[local_line_b] =
717 start_a + second_best_similarity_index;
718 }
719}
720
721/*
722 * This finds the line that we can match with the most confidence, and
723 * uses it as a partition. It then calls itself on the lines on either side of
724 * that partition. In this way we avoid lines appearing out of order, and
725 * retain a sensible line ordering.
726 * \param start_a index of the first line in A with which lines in B may be
727 * compared.
728 * \param start_b index of the first line in B for which matching should be
729 * done.
730 * \param length_a number of lines in A with which lines in B may be compared.
731 * \param length_b number of lines in B for which matching should be done.
732 * \param fingerprints_a mutable array of fingerprints in A. The first element
733 * corresponds to the line at start_a.
734 * \param fingerprints_b array of fingerprints in B. The first element
735 * corresponds to the line at start_b.
736 * \param similarities 2-dimensional array of similarities between lines in A
737 * and B. See get_similarity() for more details.
738 * \param certainties array of values indicating how strongly a line in B is
739 * matched with some line in A.
740 * \param second_best_result array of absolute indices in A for the second
741 * closest match of a line in B.
742 * \param result array of absolute indices in A for the closest match of a line
743 * in B.
744 * \param max_search_distance_a maximum distance in lines from the closest line
745 * in A for other lines in A for which
746 * similarities may be calculated.
747 * \param max_search_distance_b an upper bound on the greatest possible
748 * distance between lines in B such that they will
749 * both be compared with the same line in A
750 * according to max_search_distance_a.
751 * \param map_line_number_in_b_to_a parameter to map_line_number().
752 */
753static void fuzzy_find_matching_lines_recurse(
754 int start_a, int start_b,
755 int length_a, int length_b,
756 struct fingerprint *fingerprints_a,
757 struct fingerprint *fingerprints_b,
758 int *similarities,
759 int *certainties,
760 int *second_best_result,
761 int *result,
762 int max_search_distance_a,
763 int max_search_distance_b,
764 const struct line_number_mapping *map_line_number_in_b_to_a)
765{
766 int i, invalidate_min, invalidate_max, offset_b,
767 second_half_start_a, second_half_start_b,
768 second_half_length_a, second_half_length_b,
769 most_certain_line_a, most_certain_local_line_b = -1,
770 most_certain_line_certainty = -1,
771 closest_local_line_a;
772
773 for (i = 0; i < length_b; ++i) {
774 find_best_line_matches(start_a,
775 length_a,
776 start_b,
777 i,
778 fingerprints_a,
779 fingerprints_b,
780 similarities,
781 certainties,
782 second_best_result,
783 result,
784 max_search_distance_a,
785 map_line_number_in_b_to_a);
786
787 if (certainties[i] > most_certain_line_certainty) {
788 most_certain_line_certainty = certainties[i];
789 most_certain_local_line_b = i;
790 }
791 }
792
793 /* No matches. */
794 if (most_certain_local_line_b == -1)
795 return;
796
797 most_certain_line_a = result[most_certain_local_line_b];
798
799 /*
800 * Subtract the most certain line's fingerprint in B from the matched
801 * fingerprint in A. This means that other lines in B can't also match
802 * the same parts of the line in A.
803 */
804 fingerprint_subtract(fingerprints_a + most_certain_line_a - start_a,
805 fingerprints_b + most_certain_local_line_b);
806
807 /* Invalidate results that may be affected by the choice of most
808 * certain line.
809 */
810 invalidate_min = most_certain_local_line_b - max_search_distance_b;
811 invalidate_max = most_certain_local_line_b + max_search_distance_b + 1;
812 if (invalidate_min < 0)
813 invalidate_min = 0;
814 if (invalidate_max > length_b)
815 invalidate_max = length_b;
816
817 /* As the fingerprint in A has changed, discard previously calculated
818 * similarity values with that fingerprint.
819 */
820 for (i = invalidate_min; i < invalidate_max; ++i) {
821 closest_local_line_a = map_line_number(
822 i + start_b, map_line_number_in_b_to_a) - start_a;
823
824 /* Check that the lines in A and B are close enough that there
825 * is a similarity value for them.
826 */
827 if (abs(most_certain_line_a - start_a - closest_local_line_a) >
828 max_search_distance_a) {
829 continue;
830 }
831
832 *get_similarity(similarities, most_certain_line_a - start_a,
833 i, closest_local_line_a,
834 max_search_distance_a) = -1;
835 }
836
837 /* More invalidating of results that may be affected by the choice of
838 * most certain line.
839 * Discard the matches for lines in B that are currently matched with a
840 * line in A such that their ordering contradicts the ordering imposed
841 * by the choice of most certain line.
842 */
843 for (i = most_certain_local_line_b - 1; i >= invalidate_min; --i) {
844 /* In this loop we discard results for lines in B that are
845 * before most-certain-line-B but are matched with a line in A
846 * that is after most-certain-line-A.
847 */
848 if (certainties[i] >= 0 &&
849 (result[i] >= most_certain_line_a ||
850 second_best_result[i] >= most_certain_line_a)) {
851 certainties[i] = CERTAINTY_NOT_CALCULATED;
852 }
853 }
854 for (i = most_certain_local_line_b + 1; i < invalidate_max; ++i) {
855 /* In this loop we discard results for lines in B that are
856 * after most-certain-line-B but are matched with a line in A
857 * that is before most-certain-line-A.
858 */
859 if (certainties[i] >= 0 &&
860 (result[i] <= most_certain_line_a ||
861 second_best_result[i] <= most_certain_line_a)) {
862 certainties[i] = CERTAINTY_NOT_CALCULATED;
863 }
864 }
865
866 /* Repeat the matching process for lines before the most certain line.
867 */
868 if (most_certain_local_line_b > 0) {
869 fuzzy_find_matching_lines_recurse(
870 start_a, start_b,
871 most_certain_line_a + 1 - start_a,
872 most_certain_local_line_b,
873 fingerprints_a, fingerprints_b, similarities,
874 certainties, second_best_result, result,
875 max_search_distance_a,
876 max_search_distance_b,
877 map_line_number_in_b_to_a);
878 }
879 /* Repeat the matching process for lines after the most certain line.
880 */
881 if (most_certain_local_line_b + 1 < length_b) {
882 second_half_start_a = most_certain_line_a;
883 offset_b = most_certain_local_line_b + 1;
884 second_half_start_b = start_b + offset_b;
885 second_half_length_a =
886 length_a + start_a - second_half_start_a;
887 second_half_length_b =
888 length_b + start_b - second_half_start_b;
889 fuzzy_find_matching_lines_recurse(
890 second_half_start_a, second_half_start_b,
891 second_half_length_a, second_half_length_b,
892 fingerprints_a + second_half_start_a - start_a,
893 fingerprints_b + offset_b,
894 similarities +
895 offset_b * (max_search_distance_a * 2 + 1),
896 certainties + offset_b,
897 second_best_result + offset_b, result + offset_b,
898 max_search_distance_a,
899 max_search_distance_b,
900 map_line_number_in_b_to_a);
901 }
902}
903
904/* Find the lines in the parent line range that most closely match the lines in
905 * the target line range. This is accomplished by matching fingerprints in each
906 * blame_origin, and choosing the best matches that preserve the line ordering.
907 * See struct fingerprint for details of fingerprint matching, and
908 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
909 *
910 * The performance is believed to be O(n log n) in the typical case and O(n^2)
911 * in a pathological case, where n is the number of lines in the target range.
912 */
913static int *fuzzy_find_matching_lines(struct blame_origin *parent,
914 struct blame_origin *target,
915 int tlno, int parent_slno, int same,
916 int parent_len)
917{
918 /* We use the terminology "A" for the left hand side of the diff AKA
919 * parent, and "B" for the right hand side of the diff AKA target. */
920 int start_a = parent_slno;
921 int length_a = parent_len;
922 int start_b = tlno;
923 int length_b = same - tlno;
924
925 struct line_number_mapping map_line_number_in_b_to_a = {
926 start_a, length_a, start_b, length_b
927 };
928
929 struct fingerprint *fingerprints_a = parent->fingerprints;
930 struct fingerprint *fingerprints_b = target->fingerprints;
931
932 int i, *result, *second_best_result,
933 *certainties, *similarities, similarity_count;
934
935 /*
936 * max_search_distance_a means that given a line in B, compare it to
937 * the line in A that is closest to its position, and the lines in A
938 * that are no greater than max_search_distance_a lines away from the
939 * closest line in A.
940 *
941 * max_search_distance_b is an upper bound on the greatest possible
942 * distance between lines in B such that they will both be compared
943 * with the same line in A according to max_search_distance_a.
944 */
945 int max_search_distance_a = 10, max_search_distance_b;
946
947 if (length_a <= 0)
948 return NULL;
949
950 if (max_search_distance_a >= length_a)
951 max_search_distance_a = length_a ? length_a - 1 : 0;
952
953 max_search_distance_b = ((2 * max_search_distance_a + 1) * length_b
954 - 1) / length_a;
955
ca56dadb
RS
956 CALLOC_ARRAY(result, length_b);
957 CALLOC_ARRAY(second_best_result, length_b);
958 CALLOC_ARRAY(certainties, length_b);
1d028dc6
MP
959
960 /* See get_similarity() for details of similarities. */
961 similarity_count = length_b * (max_search_distance_a * 2 + 1);
ca56dadb 962 CALLOC_ARRAY(similarities, similarity_count);
1d028dc6
MP
963
964 for (i = 0; i < length_b; ++i) {
965 result[i] = -1;
966 second_best_result[i] = -1;
967 certainties[i] = CERTAINTY_NOT_CALCULATED;
968 }
969
970 for (i = 0; i < similarity_count; ++i)
971 similarities[i] = -1;
972
973 fuzzy_find_matching_lines_recurse(start_a, start_b,
974 length_a, length_b,
975 fingerprints_a + start_a,
976 fingerprints_b + start_b,
977 similarities,
978 certainties,
979 second_best_result,
980 result,
981 max_search_distance_a,
982 max_search_distance_b,
983 &map_line_number_in_b_to_a);
984
985 free(similarities);
986 free(certainties);
987 free(second_best_result);
988
989 return result;
990}
991
07a54dc3 992static void fill_origin_fingerprints(struct blame_origin *o)
1fc73384
BR
993{
994 int *line_starts;
995
996 if (o->fingerprints)
997 return;
998 o->num_lines = find_line_starts(&line_starts, o->file.ptr,
999 o->file.size);
ca56dadb 1000 CALLOC_ARRAY(o->fingerprints, o->num_lines);
a07a9776
BR
1001 get_line_fingerprints(o->fingerprints, o->file.ptr, line_starts,
1002 0, o->num_lines);
1fc73384
BR
1003 free(line_starts);
1004}
1005
1006static void drop_origin_fingerprints(struct blame_origin *o)
1007{
a07a9776
BR
1008 if (o->fingerprints) {
1009 free_line_fingerprints(o->fingerprints, o->num_lines);
1010 o->num_lines = 0;
1011 FREE_AND_NULL(o->fingerprints);
1012 }
1fc73384
BR
1013}
1014
b543bb1c
JS
1015/*
1016 * Given an origin, prepare mmfile_t structure to be used by the
1017 * diff machinery
1018 */
1019static void fill_origin_blob(struct diff_options *opt,
1fc73384
BR
1020 struct blame_origin *o, mmfile_t *file,
1021 int *num_read_blob, int fill_fingerprints)
b543bb1c
JS
1022{
1023 if (!o->file.ptr) {
1024 enum object_type type;
1025 unsigned long file_size;
1026
1027 (*num_read_blob)++;
0d1e0e78 1028 if (opt->flags.allow_textconv &&
6afaf807
NTND
1029 textconv_object(opt->repo, o->path, o->mode,
1030 &o->blob_oid, 1, &file->ptr, &file_size))
b543bb1c
JS
1031 ;
1032 else
b4f5aca4 1033 file->ptr = read_object_file(&o->blob_oid, &type,
1034 &file_size);
b543bb1c
JS
1035 file->size = file_size;
1036
1037 if (!file->ptr)
1038 die("Cannot read blob %s for path %s",
1039 oid_to_hex(&o->blob_oid),
1040 o->path);
1041 o->file = *file;
1042 }
1043 else
1044 *file = o->file;
1fc73384 1045 if (fill_fingerprints)
07a54dc3 1046 fill_origin_fingerprints(o);
b543bb1c
JS
1047}
1048
1049static void drop_origin_blob(struct blame_origin *o)
1050{
ce528de0 1051 FREE_AND_NULL(o->file.ptr);
1fc73384 1052 drop_origin_fingerprints(o);
b543bb1c
JS
1053}
1054
1055/*
1056 * Any merge of blames happens on lists of blames that arrived via
1057 * different parents in a single suspect. In this case, we want to
1058 * sort according to the suspect line numbers as opposed to the final
1059 * image line numbers. The function body is somewhat longish because
1060 * it avoids unnecessary writes.
1061 */
1062
1063static struct blame_entry *blame_merge(struct blame_entry *list1,
1064 struct blame_entry *list2)
1065{
1066 struct blame_entry *p1 = list1, *p2 = list2,
1067 **tail = &list1;
1068
1069 if (!p1)
1070 return p2;
1071 if (!p2)
1072 return p1;
1073
1074 if (p1->s_lno <= p2->s_lno) {
1075 do {
1076 tail = &p1->next;
afe8a907 1077 if (!(p1 = *tail)) {
b543bb1c
JS
1078 *tail = p2;
1079 return list1;
1080 }
1081 } while (p1->s_lno <= p2->s_lno);
1082 }
1083 for (;;) {
1084 *tail = p2;
1085 do {
1086 tail = &p2->next;
afe8a907 1087 if (!(p2 = *tail)) {
b543bb1c
JS
1088 *tail = p1;
1089 return list1;
1090 }
1091 } while (p1->s_lno > p2->s_lno);
1092 *tail = p1;
1093 do {
1094 tail = &p1->next;
afe8a907 1095 if (!(p1 = *tail)) {
b543bb1c
JS
1096 *tail = p2;
1097 return list1;
1098 }
1099 } while (p1->s_lno <= p2->s_lno);
1100 }
1101}
1102
47c30f7d 1103DEFINE_LIST_SORT(static, sort_blame_entries, struct blame_entry, next);
b543bb1c
JS
1104
1105/*
1106 * Final image line numbers are all different, so we don't need a
1107 * three-way comparison here.
1108 */
1109
47c30f7d
RS
1110static int compare_blame_final(const struct blame_entry *e1,
1111 const struct blame_entry *e2)
b543bb1c 1112{
47c30f7d 1113 return e1->lno > e2->lno ? 1 : -1;
b543bb1c
JS
1114}
1115
47c30f7d
RS
1116static int compare_blame_suspect(const struct blame_entry *s1,
1117 const struct blame_entry *s2)
b543bb1c 1118{
b543bb1c
JS
1119 /*
1120 * to allow for collating suspects, we sort according to the
1121 * respective pointer value as the primary sorting criterion.
1122 * The actual relation is pretty unimportant as long as it
1123 * establishes a total order. Comparing as integers gives us
1124 * that.
1125 */
1126 if (s1->suspect != s2->suspect)
1127 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
1128 if (s1->s_lno == s2->s_lno)
1129 return 0;
1130 return s1->s_lno > s2->s_lno ? 1 : -1;
1131}
1132
1133void blame_sort_final(struct blame_scoreboard *sb)
1134{
47c30f7d 1135 sort_blame_entries(&sb->ent, compare_blame_final);
b543bb1c
JS
1136}
1137
09002f1b
JS
1138static int compare_commits_by_reverse_commit_date(const void *a,
1139 const void *b,
1140 void *c)
1141{
1142 return -compare_commits_by_commit_date(a, b, c);
1143}
1144
b543bb1c
JS
1145/*
1146 * For debugging -- origin is refcounted, and this asserts that
1147 * we do not underflow.
1148 */
1149static void sanity_check_refcnt(struct blame_scoreboard *sb)
1150{
1151 int baa = 0;
1152 struct blame_entry *ent;
1153
1154 for (ent = sb->ent; ent; ent = ent->next) {
1155 /* Nobody should have zero or negative refcnt */
1156 if (ent->suspect->refcnt <= 0) {
1157 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1158 ent->suspect->path,
1159 oid_to_hex(&ent->suspect->commit->object.oid),
1160 ent->suspect->refcnt);
1161 baa = 1;
1162 }
1163 }
1164 if (baa)
1165 sb->on_sanity_fail(sb, baa);
1166}
1167
1168/*
1169 * If two blame entries that are next to each other came from
1170 * contiguous lines in the same origin (i.e. <commit, path> pair),
1171 * merge them together.
1172 */
1173void blame_coalesce(struct blame_scoreboard *sb)
1174{
1175 struct blame_entry *ent, *next;
1176
1177 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
1178 if (ent->suspect == next->suspect &&
8934ac8c 1179 ent->s_lno + ent->num_lines == next->s_lno &&
c2ebaa27 1180 ent->lno + ent->num_lines == next->lno &&
8934ac8c
BR
1181 ent->ignored == next->ignored &&
1182 ent->unblamable == next->unblamable) {
b543bb1c
JS
1183 ent->num_lines += next->num_lines;
1184 ent->next = next->next;
1185 blame_origin_decref(next->suspect);
1186 free(next);
1187 ent->score = 0;
1188 next = ent; /* again */
1189 }
1190 }
1191
1192 if (sb->debug) /* sanity */
1193 sanity_check_refcnt(sb);
1194}
1195
1196/*
1197 * Merge the given sorted list of blames into a preexisting origin.
1198 * If there were no previous blames to that commit, it is entered into
1199 * the commit priority queue of the score board.
1200 */
1201
1202static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porigin,
1203 struct blame_entry *sorted)
1204{
1205 if (porigin->suspects)
1206 porigin->suspects = blame_merge(porigin->suspects, sorted);
1207 else {
1208 struct blame_origin *o;
4e0df4e6 1209 for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
b543bb1c
JS
1210 if (o->suspects) {
1211 porigin->suspects = sorted;
1212 return;
1213 }
1214 }
1215 porigin->suspects = sorted;
1216 prio_queue_put(&sb->commits, porigin->commit);
1217 }
1218}
1219
09002f1b
JS
1220/*
1221 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1222 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1223 * for an origin is also used to pass the blame for the entire file to
1224 * the parent to detect the case where a child's blob is identical to
1225 * that of its parent's.
1226 *
1227 * This also fills origin->mode for corresponding tree path.
1228 */
a470beea 1229static int fill_blob_sha1_and_mode(struct repository *r,
ecbbc0a5 1230 struct blame_origin *origin)
09002f1b
JS
1231{
1232 if (!is_null_oid(&origin->blob_oid))
1233 return 0;
50ddb089 1234 if (get_tree_entry(r, &origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
09002f1b 1235 goto error_out;
a470beea 1236 if (oid_object_info(r, &origin->blob_oid, NULL) != OBJ_BLOB)
09002f1b
JS
1237 goto error_out;
1238 return 0;
1239 error_out:
1240 oidclr(&origin->blob_oid);
1241 origin->mode = S_IFINVALID;
1242 return -1;
1243}
1244
0906ac2b
DS
1245struct blame_bloom_data {
1246 /*
1247 * Changed-path Bloom filter keys. These can help prevent
1248 * computing diffs against first parents, but we need to
1249 * expand the list as code is moved or files are renamed.
1250 */
1251 struct bloom_filter_settings *settings;
1252 struct bloom_key **keys;
1253 int nr;
1254 int alloc;
1255};
1256
1257static int bloom_count_queries = 0;
1258static int bloom_count_no = 0;
1259static int maybe_changed_path(struct repository *r,
0906ac2b
DS
1260 struct blame_origin *origin,
1261 struct blame_bloom_data *bd)
1262{
1263 int i;
1264 struct bloom_filter *filter;
1265
1266 if (!bd)
1267 return 1;
1268
c49c82aa 1269 if (commit_graph_generation(origin->commit) == GENERATION_NUMBER_INFINITY)
0906ac2b
DS
1270 return 1;
1271
312cff52 1272 filter = get_bloom_filter(r, origin->commit);
0906ac2b
DS
1273
1274 if (!filter)
1275 return 1;
1276
1277 bloom_count_queries++;
1278 for (i = 0; i < bd->nr; i++) {
1279 if (bloom_filter_contains(filter,
1280 bd->keys[i],
1281 bd->settings))
1282 return 1;
1283 }
1284
1285 bloom_count_no++;
1286 return 0;
1287}
1288
1289static void add_bloom_key(struct blame_bloom_data *bd,
1290 const char *path)
1291{
1292 if (!bd)
1293 return;
1294
1295 if (bd->nr >= bd->alloc) {
1296 bd->alloc *= 2;
1297 REALLOC_ARRAY(bd->keys, bd->alloc);
1298 }
1299
1300 bd->keys[bd->nr] = xmalloc(sizeof(struct bloom_key));
1301 fill_bloom_key(path, strlen(path), bd->keys[bd->nr], bd->settings);
1302 bd->nr++;
1303}
1304
b543bb1c
JS
1305/*
1306 * We have an origin -- check if the same path exists in the
1307 * parent and return an origin structure to represent it.
1308 */
e6757652
NTND
1309static struct blame_origin *find_origin(struct repository *r,
1310 struct commit *parent,
0906ac2b
DS
1311 struct blame_origin *origin,
1312 struct blame_bloom_data *bd)
b543bb1c
JS
1313{
1314 struct blame_origin *porigin;
1315 struct diff_options diff_opts;
1316 const char *paths[2];
1317
1318 /* First check any existing origins */
4e0df4e6 1319 for (porigin = get_blame_suspects(parent); porigin; porigin = porigin->next)
b543bb1c
JS
1320 if (!strcmp(porigin->path, origin->path)) {
1321 /*
1322 * The same path between origin and its parent
1323 * without renaming -- the most common case.
1324 */
1325 return blame_origin_incref (porigin);
1326 }
1327
1328 /* See if the origin->path is different between parent
1329 * and origin first. Most of the time they are the
1330 * same and diff-tree is fairly efficient about this.
1331 */
e6757652 1332 repo_diff_setup(r, &diff_opts);
0d1e0e78 1333 diff_opts.flags.recursive = 1;
b543bb1c
JS
1334 diff_opts.detect_rename = 0;
1335 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1336 paths[0] = origin->path;
1337 paths[1] = NULL;
1338
1339 parse_pathspec(&diff_opts.pathspec,
1340 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
1341 PATHSPEC_LITERAL_PATH, "", paths);
1342 diff_setup_done(&diff_opts);
1343
1344 if (is_null_oid(&origin->commit->object.oid))
2e27bd77 1345 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
0906ac2b
DS
1346 else {
1347 int compute_diff = 1;
1348 if (origin->commit->parents &&
1302badd
ECA
1349 oideq(&parent->object.oid,
1350 &origin->commit->parents->item->object.oid))
fe88f9f9 1351 compute_diff = maybe_changed_path(r, origin, bd);
0906ac2b
DS
1352
1353 if (compute_diff)
1354 diff_tree_oid(get_commit_tree_oid(parent),
1355 get_commit_tree_oid(origin->commit),
1356 "", &diff_opts);
1357 }
b543bb1c
JS
1358 diffcore_std(&diff_opts);
1359
1360 if (!diff_queued_diff.nr) {
1361 /* The path is the same as parent */
1362 porigin = get_origin(parent, origin->path);
1363 oidcpy(&porigin->blob_oid, &origin->blob_oid);
1364 porigin->mode = origin->mode;
1365 } else {
1366 /*
1367 * Since origin->path is a pathspec, if the parent
1368 * commit had it as a directory, we will see a whole
1369 * bunch of deletion of files in the directory that we
1370 * do not care about.
1371 */
1372 int i;
1373 struct diff_filepair *p = NULL;
1374 for (i = 0; i < diff_queued_diff.nr; i++) {
1375 const char *name;
1376 p = diff_queued_diff.queue[i];
1377 name = p->one->path ? p->one->path : p->two->path;
1378 if (!strcmp(name, origin->path))
1379 break;
1380 }
1381 if (!p)
1382 die("internal error in blame::find_origin");
1383 switch (p->status) {
1384 default:
1385 die("internal error in blame::find_origin (%c)",
1386 p->status);
1387 case 'M':
1388 porigin = get_origin(parent, origin->path);
1389 oidcpy(&porigin->blob_oid, &p->one->oid);
1390 porigin->mode = p->one->mode;
1391 break;
1392 case 'A':
1393 case 'T':
1394 /* Did not exist in parent, or type changed */
1395 break;
1396 }
1397 }
1398 diff_flush(&diff_opts);
b543bb1c
JS
1399 return porigin;
1400}
1401
1402/*
1403 * We have an origin -- find the path that corresponds to it in its
1404 * parent and return an origin structure to represent it.
1405 */
e6757652
NTND
1406static struct blame_origin *find_rename(struct repository *r,
1407 struct commit *parent,
0906ac2b
DS
1408 struct blame_origin *origin,
1409 struct blame_bloom_data *bd)
b543bb1c
JS
1410{
1411 struct blame_origin *porigin = NULL;
1412 struct diff_options diff_opts;
1413 int i;
1414
e6757652 1415 repo_diff_setup(r, &diff_opts);
0d1e0e78 1416 diff_opts.flags.recursive = 1;
b543bb1c
JS
1417 diff_opts.detect_rename = DIFF_DETECT_RENAME;
1418 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1419 diff_opts.single_follow = origin->path;
1420 diff_setup_done(&diff_opts);
1421
1422 if (is_null_oid(&origin->commit->object.oid))
2e27bd77 1423 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
b543bb1c 1424 else
2e27bd77
DS
1425 diff_tree_oid(get_commit_tree_oid(parent),
1426 get_commit_tree_oid(origin->commit),
a6f38c10 1427 "", &diff_opts);
b543bb1c
JS
1428 diffcore_std(&diff_opts);
1429
1430 for (i = 0; i < diff_queued_diff.nr; i++) {
1431 struct diff_filepair *p = diff_queued_diff.queue[i];
1432 if ((p->status == 'R' || p->status == 'C') &&
1433 !strcmp(p->two->path, origin->path)) {
0906ac2b 1434 add_bloom_key(bd, p->one->path);
b543bb1c
JS
1435 porigin = get_origin(parent, p->one->path);
1436 oidcpy(&porigin->blob_oid, &p->one->oid);
1437 porigin->mode = p->one->mode;
1438 break;
1439 }
1440 }
1441 diff_flush(&diff_opts);
b543bb1c
JS
1442 return porigin;
1443}
1444
1445/*
1446 * Append a new blame entry to a given output queue.
1447 */
1448static void add_blame_entry(struct blame_entry ***queue,
1449 const struct blame_entry *src)
1450{
1451 struct blame_entry *e = xmalloc(sizeof(*e));
1452 memcpy(e, src, sizeof(*e));
1453 blame_origin_incref(e->suspect);
1454
1455 e->next = **queue;
1456 **queue = e;
1457 *queue = &e->next;
1458}
1459
1460/*
1461 * src typically is on-stack; we want to copy the information in it to
1462 * a malloced blame_entry that gets added to the given queue. The
1463 * origin of dst loses a refcnt.
1464 */
1465static void dup_entry(struct blame_entry ***queue,
1466 struct blame_entry *dst, struct blame_entry *src)
1467{
1468 blame_origin_incref(src->suspect);
1469 blame_origin_decref(dst->suspect);
1470 memcpy(dst, src, sizeof(*src));
1471 dst->next = **queue;
1472 **queue = dst;
1473 *queue = &dst->next;
1474}
1475
1476const char *blame_nth_line(struct blame_scoreboard *sb, long lno)
1477{
1478 return sb->final_buf + sb->lineno[lno];
1479}
1480
1481/*
1482 * It is known that lines between tlno to same came from parent, and e
1483 * has an overlap with that range. it also is known that parent's
1484 * line plno corresponds to e's line tlno.
1485 *
1486 * <---- e ----->
1487 * <------>
1488 * <------------>
1489 * <------------>
1490 * <------------------>
1491 *
1492 * Split e into potentially three parts; before this chunk, the chunk
1493 * to be blamed for the parent, and after that portion.
1494 */
1495static void split_overlap(struct blame_entry *split,
1496 struct blame_entry *e,
1497 int tlno, int plno, int same,
1498 struct blame_origin *parent)
1499{
1500 int chunk_end_lno;
8934ac8c 1501 int i;
b543bb1c
JS
1502 memset(split, 0, sizeof(struct blame_entry [3]));
1503
8934ac8c
BR
1504 for (i = 0; i < 3; i++) {
1505 split[i].ignored = e->ignored;
1506 split[i].unblamable = e->unblamable;
1507 }
1508
b543bb1c
JS
1509 if (e->s_lno < tlno) {
1510 /* there is a pre-chunk part not blamed on parent */
1511 split[0].suspect = blame_origin_incref(e->suspect);
1512 split[0].lno = e->lno;
1513 split[0].s_lno = e->s_lno;
1514 split[0].num_lines = tlno - e->s_lno;
1515 split[1].lno = e->lno + tlno - e->s_lno;
1516 split[1].s_lno = plno;
1517 }
1518 else {
1519 split[1].lno = e->lno;
1520 split[1].s_lno = plno + (e->s_lno - tlno);
1521 }
1522
1523 if (same < e->s_lno + e->num_lines) {
1524 /* there is a post-chunk part not blamed on parent */
1525 split[2].suspect = blame_origin_incref(e->suspect);
1526 split[2].lno = e->lno + (same - e->s_lno);
1527 split[2].s_lno = e->s_lno + (same - e->s_lno);
1528 split[2].num_lines = e->s_lno + e->num_lines - same;
1529 chunk_end_lno = split[2].lno;
1530 }
1531 else
1532 chunk_end_lno = e->lno + e->num_lines;
1533 split[1].num_lines = chunk_end_lno - split[1].lno;
1534
1535 /*
1536 * if it turns out there is nothing to blame the parent for,
1537 * forget about the splitting. !split[1].suspect signals this.
1538 */
1539 if (split[1].num_lines < 1)
1540 return;
1541 split[1].suspect = blame_origin_incref(parent);
1542}
1543
1544/*
1545 * split_overlap() divided an existing blame e into up to three parts
1546 * in split. Any assigned blame is moved to queue to
1547 * reflect the split.
1548 */
1549static void split_blame(struct blame_entry ***blamed,
1550 struct blame_entry ***unblamed,
1551 struct blame_entry *split,
1552 struct blame_entry *e)
1553{
1554 if (split[0].suspect && split[2].suspect) {
1555 /* The first part (reuse storage for the existing entry e) */
1556 dup_entry(unblamed, e, &split[0]);
1557
1558 /* The last part -- me */
1559 add_blame_entry(unblamed, &split[2]);
1560
1561 /* ... and the middle part -- parent */
1562 add_blame_entry(blamed, &split[1]);
1563 }
1564 else if (!split[0].suspect && !split[2].suspect)
1565 /*
1566 * The parent covers the entire area; reuse storage for
1567 * e and replace it with the parent.
1568 */
1569 dup_entry(blamed, e, &split[1]);
1570 else if (split[0].suspect) {
1571 /* me and then parent */
1572 dup_entry(unblamed, e, &split[0]);
1573 add_blame_entry(blamed, &split[1]);
1574 }
1575 else {
1576 /* parent and then me */
1577 dup_entry(blamed, e, &split[1]);
1578 add_blame_entry(unblamed, &split[2]);
1579 }
1580}
1581
1582/*
1583 * After splitting the blame, the origins used by the
1584 * on-stack blame_entry should lose one refcnt each.
1585 */
1586static void decref_split(struct blame_entry *split)
1587{
1588 int i;
1589
1590 for (i = 0; i < 3; i++)
1591 blame_origin_decref(split[i].suspect);
1592}
1593
1594/*
1595 * reverse_blame reverses the list given in head, appending tail.
1596 * That allows us to build lists in reverse order, then reverse them
1597 * afterwards. This can be faster than building the list in proper
1598 * order right away. The reason is that building in proper order
1599 * requires writing a link in the _previous_ element, while building
1600 * in reverse order just requires placing the list head into the
1601 * _current_ element.
1602 */
1603
1604static struct blame_entry *reverse_blame(struct blame_entry *head,
1605 struct blame_entry *tail)
1606{
1607 while (head) {
1608 struct blame_entry *next = head->next;
1609 head->next = tail;
1610 tail = head;
1611 head = next;
1612 }
1613 return tail;
1614}
1615
55f808fb
BR
1616/*
1617 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1618 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1619 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1620 * e->num_lines). The caller needs to sort out the reference counting for the
1621 * new entry's suspect.
1622 */
1623static struct blame_entry *split_blame_at(struct blame_entry *e, int len,
1624 struct blame_origin *new_suspect)
1625{
1626 struct blame_entry *n = xcalloc(1, sizeof(struct blame_entry));
1627
1628 n->suspect = new_suspect;
8934ac8c
BR
1629 n->ignored = e->ignored;
1630 n->unblamable = e->unblamable;
55f808fb
BR
1631 n->lno = e->lno + len;
1632 n->s_lno = e->s_lno + len;
1633 n->num_lines = e->num_lines - len;
1634 e->num_lines = len;
1635 e->score = 0;
1636 return n;
1637}
1638
ae3f36de
BR
1639struct blame_line_tracker {
1640 int is_parent;
1641 int s_lno;
1642};
1643
1644static int are_lines_adjacent(struct blame_line_tracker *first,
1645 struct blame_line_tracker *second)
1646{
1647 return first->is_parent == second->is_parent &&
1648 first->s_lno + 1 == second->s_lno;
1649}
1650
a07a9776
BR
1651static int scan_parent_range(struct fingerprint *p_fps,
1652 struct fingerprint *t_fps, int t_idx,
1653 int from, int nr_lines)
1654{
1655 int sim, p_idx;
1656 #define FINGERPRINT_FILE_THRESHOLD 10
1657 int best_sim_val = FINGERPRINT_FILE_THRESHOLD;
1658 int best_sim_idx = -1;
1659
1660 for (p_idx = from; p_idx < from + nr_lines; p_idx++) {
1661 sim = fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);
1662 if (sim < best_sim_val)
1663 continue;
1664 /* Break ties with the closest-to-target line number */
1665 if (sim == best_sim_val && best_sim_idx != -1 &&
1666 abs(best_sim_idx - t_idx) < abs(p_idx - t_idx))
1667 continue;
1668 best_sim_val = sim;
1669 best_sim_idx = p_idx;
1670 }
1671 return best_sim_idx;
1672}
1673
ae3f36de 1674/*
a07a9776
BR
1675 * The first pass checks the blame entry (from the target) against the parent's
1676 * diff chunk. If that fails for a line, the second pass tries to match that
1677 * line to any part of parent file. That catches cases where a change was
1678 * broken into two chunks by 'context.'
ae3f36de
BR
1679 */
1680static void guess_line_blames(struct blame_origin *parent,
1681 struct blame_origin *target,
1682 int tlno, int offset, int same, int parent_len,
1683 struct blame_line_tracker *line_blames)
1684{
1685 int i, best_idx, target_idx;
1686 int parent_slno = tlno + offset;
a07a9776 1687 int *fuzzy_matches;
ae3f36de 1688
a07a9776
BR
1689 fuzzy_matches = fuzzy_find_matching_lines(parent, target,
1690 tlno, parent_slno, same,
1691 parent_len);
ae3f36de
BR
1692 for (i = 0; i < same - tlno; i++) {
1693 target_idx = tlno + i;
a07a9776
BR
1694 if (fuzzy_matches && fuzzy_matches[i] >= 0) {
1695 best_idx = fuzzy_matches[i];
1696 } else {
1697 best_idx = scan_parent_range(parent->fingerprints,
1698 target->fingerprints,
1699 target_idx, 0,
1700 parent->num_lines);
1701 }
1702 if (best_idx >= 0) {
ae3f36de
BR
1703 line_blames[i].is_parent = 1;
1704 line_blames[i].s_lno = best_idx;
1705 } else {
1706 line_blames[i].is_parent = 0;
1707 line_blames[i].s_lno = target_idx;
1708 }
1709 }
a07a9776 1710 free(fuzzy_matches);
ae3f36de
BR
1711}
1712
1713/*
1714 * This decides which parts of a blame entry go to the parent (added to the
1715 * ignoredp list) and which stay with the target (added to the diffp list). The
1716 * actual decision was made in a separate heuristic function, and those answers
1717 * for the lines in 'e' are in line_blames. This consumes e, essentially
1718 * putting it on a list.
1719 *
1720 * Note that the blame entries on the ignoredp list are not necessarily sorted
1721 * with respect to the parent's line numbers yet.
1722 */
1723static void ignore_blame_entry(struct blame_entry *e,
1724 struct blame_origin *parent,
ae3f36de
BR
1725 struct blame_entry **diffp,
1726 struct blame_entry **ignoredp,
1727 struct blame_line_tracker *line_blames)
1728{
1729 int entry_len, nr_lines, i;
1730
1731 /*
1732 * We carve new entries off the front of e. Each entry comes from a
1733 * contiguous chunk of lines: adjacent lines from the same origin
1734 * (either the parent or the target).
1735 */
1736 entry_len = 1;
1737 nr_lines = e->num_lines; /* e changes in the loop */
1738 for (i = 0; i < nr_lines; i++) {
1739 struct blame_entry *next = NULL;
1740
1741 /*
1742 * We are often adjacent to the next line - only split the blame
1743 * entry when we have to.
1744 */
1745 if (i + 1 < nr_lines) {
1746 if (are_lines_adjacent(&line_blames[i],
1747 &line_blames[i + 1])) {
1748 entry_len++;
1749 continue;
1750 }
1751 next = split_blame_at(e, entry_len,
1752 blame_origin_incref(e->suspect));
1753 }
1754 if (line_blames[i].is_parent) {
8934ac8c 1755 e->ignored = 1;
ae3f36de
BR
1756 blame_origin_decref(e->suspect);
1757 e->suspect = blame_origin_incref(parent);
1758 e->s_lno = line_blames[i - entry_len + 1].s_lno;
1759 e->next = *ignoredp;
1760 *ignoredp = e;
1761 } else {
8934ac8c 1762 e->unblamable = 1;
ae3f36de
BR
1763 /* e->s_lno is already in the target's address space. */
1764 e->next = *diffp;
1765 *diffp = e;
1766 }
1767 assert(e->num_lines == entry_len);
1768 e = next;
1769 entry_len = 1;
1770 }
1771 assert(!e);
1772}
1773
b543bb1c
JS
1774/*
1775 * Process one hunk from the patch between the current suspect for
1776 * blame_entry e and its parent. This first blames any unfinished
1777 * entries before the chunk (which is where target and parent start
1778 * differing) on the parent, and then splits blame entries at the
1779 * start and at the end of the difference region. Since use of -M and
1780 * -C options may lead to overlapping/duplicate source line number
1781 * ranges, all we can rely on from sorting/merging is the order of the
1782 * first suspect line number.
ae3f36de
BR
1783 *
1784 * tlno: line number in the target where this chunk begins
1785 * same: line number in the target where this chunk ends
1786 * offset: add to tlno to get the chunk starting point in the parent
1787 * parent_len: number of lines in the parent chunk
b543bb1c
JS
1788 */
1789static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
ae3f36de
BR
1790 int tlno, int offset, int same, int parent_len,
1791 struct blame_origin *parent,
1792 struct blame_origin *target, int ignore_diffs)
b543bb1c
JS
1793{
1794 struct blame_entry *e = **srcq;
ae3f36de
BR
1795 struct blame_entry *samep = NULL, *diffp = NULL, *ignoredp = NULL;
1796 struct blame_line_tracker *line_blames = NULL;
b543bb1c
JS
1797
1798 while (e && e->s_lno < tlno) {
1799 struct blame_entry *next = e->next;
1800 /*
1801 * current record starts before differing portion. If
1802 * it reaches into it, we need to split it up and
1803 * examine the second part separately.
1804 */
1805 if (e->s_lno + e->num_lines > tlno) {
1806 /* Move second half to a new record */
55f808fb
BR
1807 struct blame_entry *n;
1808
1809 n = split_blame_at(e, tlno - e->s_lno, e->suspect);
b543bb1c
JS
1810 /* Push new record to diffp */
1811 n->next = diffp;
1812 diffp = n;
1813 } else
1814 blame_origin_decref(e->suspect);
1815 /* Pass blame for everything before the differing
1816 * chunk to the parent */
1817 e->suspect = blame_origin_incref(parent);
1818 e->s_lno += offset;
1819 e->next = samep;
1820 samep = e;
1821 e = next;
1822 }
1823 /*
1824 * As we don't know how much of a common stretch after this
1825 * diff will occur, the currently blamed parts are all that we
1826 * can assign to the parent for now.
1827 */
1828
1829 if (samep) {
1830 **dstq = reverse_blame(samep, **dstq);
1831 *dstq = &samep->next;
1832 }
1833 /*
1834 * Prepend the split off portions: everything after e starts
1835 * after the blameable portion.
1836 */
1837 e = reverse_blame(diffp, e);
1838
1839 /*
1840 * Now retain records on the target while parts are different
1841 * from the parent.
1842 */
1843 samep = NULL;
1844 diffp = NULL;
ae3f36de
BR
1845
1846 if (ignore_diffs && same - tlno > 0) {
ca56dadb 1847 CALLOC_ARRAY(line_blames, same - tlno);
ae3f36de
BR
1848 guess_line_blames(parent, target, tlno, offset, same,
1849 parent_len, line_blames);
1850 }
1851
b543bb1c
JS
1852 while (e && e->s_lno < same) {
1853 struct blame_entry *next = e->next;
1854
1855 /*
1856 * If current record extends into sameness, need to split.
1857 */
1858 if (e->s_lno + e->num_lines > same) {
1859 /*
1860 * Move second half to a new record to be
1861 * processed by later chunks
1862 */
55f808fb
BR
1863 struct blame_entry *n;
1864
1865 n = split_blame_at(e, same - e->s_lno,
1866 blame_origin_incref(e->suspect));
b543bb1c
JS
1867 /* Push new record to samep */
1868 n->next = samep;
1869 samep = n;
1870 }
ae3f36de 1871 if (ignore_diffs) {
07a54dc3 1872 ignore_blame_entry(e, parent, &diffp, &ignoredp,
ae3f36de
BR
1873 line_blames + e->s_lno - tlno);
1874 } else {
1875 e->next = diffp;
1876 diffp = e;
1877 }
b543bb1c
JS
1878 e = next;
1879 }
ae3f36de
BR
1880 free(line_blames);
1881 if (ignoredp) {
1882 /*
1883 * Note ignoredp is not sorted yet, and thus neither is dstq.
1884 * That list must be sorted before we queue_blames(). We defer
1885 * sorting until after all diff hunks are processed, so that
1886 * guess_line_blames() can pick *any* line in the parent. The
1887 * slight drawback is that we end up sorting all blame entries
1888 * passed to the parent, including those that are unrelated to
1889 * changes made by the ignored commit.
1890 */
1891 **dstq = reverse_blame(ignoredp, **dstq);
1892 *dstq = &ignoredp->next;
1893 }
b543bb1c
JS
1894 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
1895 /* Move across elements that are in the unblamable portion */
1896 if (diffp)
1897 *srcq = &diffp->next;
1898}
1899
1900struct blame_chunk_cb_data {
1901 struct blame_origin *parent;
ae3f36de 1902 struct blame_origin *target;
b543bb1c 1903 long offset;
ae3f36de 1904 int ignore_diffs;
b543bb1c
JS
1905 struct blame_entry **dstq;
1906 struct blame_entry **srcq;
1907};
1908
1909/* diff chunks are from parent to target */
1910static int blame_chunk_cb(long start_a, long count_a,
1911 long start_b, long count_b, void *data)
1912{
1913 struct blame_chunk_cb_data *d = data;
1914 if (start_a - start_b != d->offset)
1915 die("internal error in blame::blame_chunk_cb");
1916 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
ae3f36de
BR
1917 start_b + count_b, count_a, d->parent, d->target,
1918 d->ignore_diffs);
b543bb1c
JS
1919 d->offset = start_a + count_a - (start_b + count_b);
1920 return 0;
1921}
1922
1923/*
1924 * We are looking at the origin 'target' and aiming to pass blame
1925 * for the lines it is suspected to its parent. Run diff to find
1926 * which lines came from parent and pass blame for them.
1927 */
1928static void pass_blame_to_parent(struct blame_scoreboard *sb,
1929 struct blame_origin *target,
ae3f36de 1930 struct blame_origin *parent, int ignore_diffs)
b543bb1c
JS
1931{
1932 mmfile_t file_p, file_o;
1933 struct blame_chunk_cb_data d;
1934 struct blame_entry *newdest = NULL;
1935
1936 if (!target->suspects)
1937 return; /* nothing remains for this target */
1938
1939 d.parent = parent;
ae3f36de 1940 d.target = target;
b543bb1c 1941 d.offset = 0;
ae3f36de 1942 d.ignore_diffs = ignore_diffs;
b543bb1c
JS
1943 d.dstq = &newdest; d.srcq = &target->suspects;
1944
1fc73384
BR
1945 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
1946 &sb->num_read_blob, ignore_diffs);
1947 fill_origin_blob(&sb->revs->diffopt, target, &file_o,
1948 &sb->num_read_blob, ignore_diffs);
b543bb1c
JS
1949 sb->num_get_patch++;
1950
1951 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, sb->xdl_opts))
1952 die("unable to generate diff (%s -> %s)",
1953 oid_to_hex(&parent->commit->object.oid),
1954 oid_to_hex(&target->commit->object.oid));
1955 /* The rest are the same as the parent */
ae3f36de
BR
1956 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, 0,
1957 parent, target, 0);
b543bb1c 1958 *d.dstq = NULL;
ae3f36de 1959 if (ignore_diffs)
47c30f7d 1960 sort_blame_entries(&newdest, compare_blame_suspect);
b543bb1c
JS
1961 queue_blames(sb, parent, newdest);
1962
1963 return;
1964}
1965
1966/*
1967 * The lines in blame_entry after splitting blames many times can become
1968 * very small and trivial, and at some point it becomes pointless to
1969 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1970 * ordinary C program, and it is not worth to say it was copied from
1971 * totally unrelated file in the parent.
1972 *
1973 * Compute how trivial the lines in the blame_entry are.
1974 */
1975unsigned blame_entry_score(struct blame_scoreboard *sb, struct blame_entry *e)
1976{
1977 unsigned score;
1978 const char *cp, *ep;
1979
1980 if (e->score)
1981 return e->score;
1982
1983 score = 1;
1984 cp = blame_nth_line(sb, e->lno);
1985 ep = blame_nth_line(sb, e->lno + e->num_lines);
1986 while (cp < ep) {
1987 unsigned ch = *((unsigned char *)cp);
1988 if (isalnum(ch))
1989 score++;
1990 cp++;
1991 }
1992 e->score = score;
1993 return score;
1994}
1995
1996/*
abeacb25
BW
1997 * best_so_far[] and potential[] are both a split of an existing blame_entry
1998 * that passes blame to the parent. Maintain best_so_far the best split so
1999 * far, by comparing potential and best_so_far and copying potential into
b543bb1c
JS
2000 * bst_so_far as needed.
2001 */
2002static void copy_split_if_better(struct blame_scoreboard *sb,
2003 struct blame_entry *best_so_far,
abeacb25 2004 struct blame_entry *potential)
b543bb1c
JS
2005{
2006 int i;
2007
abeacb25 2008 if (!potential[1].suspect)
b543bb1c
JS
2009 return;
2010 if (best_so_far[1].suspect) {
abeacb25
BW
2011 if (blame_entry_score(sb, &potential[1]) <
2012 blame_entry_score(sb, &best_so_far[1]))
b543bb1c
JS
2013 return;
2014 }
2015
2016 for (i = 0; i < 3; i++)
abeacb25 2017 blame_origin_incref(potential[i].suspect);
b543bb1c 2018 decref_split(best_so_far);
abeacb25 2019 memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
b543bb1c
JS
2020}
2021
2022/*
2023 * We are looking at a part of the final image represented by
2024 * ent (tlno and same are offset by ent->s_lno).
2025 * tlno is where we are looking at in the final image.
2026 * up to (but not including) same match preimage.
2027 * plno is where we are looking at in the preimage.
2028 *
2029 * <-------------- final image ---------------------->
2030 * <------ent------>
2031 * ^tlno ^same
2032 * <---------preimage----->
2033 * ^plno
2034 *
2035 * All line numbers are 0-based.
2036 */
2037static void handle_split(struct blame_scoreboard *sb,
2038 struct blame_entry *ent,
2039 int tlno, int plno, int same,
2040 struct blame_origin *parent,
2041 struct blame_entry *split)
2042{
2043 if (ent->num_lines <= tlno)
2044 return;
2045 if (tlno < same) {
abeacb25 2046 struct blame_entry potential[3];
b543bb1c
JS
2047 tlno += ent->s_lno;
2048 same += ent->s_lno;
abeacb25
BW
2049 split_overlap(potential, ent, tlno, plno, same, parent);
2050 copy_split_if_better(sb, split, potential);
2051 decref_split(potential);
b543bb1c
JS
2052 }
2053}
2054
2055struct handle_split_cb_data {
2056 struct blame_scoreboard *sb;
2057 struct blame_entry *ent;
2058 struct blame_origin *parent;
2059 struct blame_entry *split;
2060 long plno;
2061 long tlno;
2062};
2063
2064static int handle_split_cb(long start_a, long count_a,
2065 long start_b, long count_b, void *data)
2066{
2067 struct handle_split_cb_data *d = data;
2068 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
2069 d->split);
2070 d->plno = start_a + count_a;
2071 d->tlno = start_b + count_b;
2072 return 0;
2073}
2074
2075/*
2076 * Find the lines from parent that are the same as ent so that
2077 * we can pass blames to it. file_p has the blob contents for
2078 * the parent.
2079 */
2080static void find_copy_in_blob(struct blame_scoreboard *sb,
2081 struct blame_entry *ent,
2082 struct blame_origin *parent,
2083 struct blame_entry *split,
2084 mmfile_t *file_p)
2085{
2086 const char *cp;
2087 mmfile_t file_o;
2088 struct handle_split_cb_data d;
2089
2090 memset(&d, 0, sizeof(d));
2091 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
2092 /*
2093 * Prepare mmfile that contains only the lines in ent.
2094 */
2095 cp = blame_nth_line(sb, ent->lno);
2096 file_o.ptr = (char *) cp;
2097 file_o.size = blame_nth_line(sb, ent->lno + ent->num_lines) - cp;
2098
2099 /*
2100 * file_o is a part of final image we are annotating.
2101 * file_p partially may match that image.
2102 */
2103 memset(split, 0, sizeof(struct blame_entry [3]));
2104 if (diff_hunks(file_p, &file_o, handle_split_cb, &d, sb->xdl_opts))
2105 die("unable to generate diff (%s)",
2106 oid_to_hex(&parent->commit->object.oid));
2107 /* remainder, if any, all match the preimage */
2108 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
2109}
2110
2111/* Move all blame entries from list *source that have a score smaller
2112 * than score_min to the front of list *small.
2113 * Returns a pointer to the link pointing to the old head of the small list.
2114 */
2115
2116static struct blame_entry **filter_small(struct blame_scoreboard *sb,
2117 struct blame_entry **small,
2118 struct blame_entry **source,
2119 unsigned score_min)
2120{
2121 struct blame_entry *p = *source;
2122 struct blame_entry *oldsmall = *small;
2123 while (p) {
2124 if (blame_entry_score(sb, p) <= score_min) {
2125 *small = p;
2126 small = &p->next;
2127 p = *small;
2128 } else {
2129 *source = p;
2130 source = &p->next;
2131 p = *source;
2132 }
2133 }
2134 *small = oldsmall;
2135 *source = NULL;
2136 return small;
2137}
2138
2139/*
2140 * See if lines currently target is suspected for can be attributed to
2141 * parent.
2142 */
2143static void find_move_in_parent(struct blame_scoreboard *sb,
2144 struct blame_entry ***blamed,
2145 struct blame_entry **toosmall,
2146 struct blame_origin *target,
2147 struct blame_origin *parent)
2148{
2149 struct blame_entry *e, split[3];
2150 struct blame_entry *unblamed = target->suspects;
2151 struct blame_entry *leftover = NULL;
2152 mmfile_t file_p;
2153
2154 if (!unblamed)
2155 return; /* nothing remains for this target */
2156
1fc73384
BR
2157 fill_origin_blob(&sb->revs->diffopt, parent, &file_p,
2158 &sb->num_read_blob, 0);
b543bb1c
JS
2159 if (!file_p.ptr)
2160 return;
2161
2162 /* At each iteration, unblamed has a NULL-terminated list of
2163 * entries that have not yet been tested for blame. leftover
2164 * contains the reversed list of entries that have been tested
2165 * without being assignable to the parent.
2166 */
2167 do {
2168 struct blame_entry **unblamedtail = &unblamed;
2169 struct blame_entry *next;
2170 for (e = unblamed; e; e = next) {
2171 next = e->next;
2172 find_copy_in_blob(sb, e, parent, split, &file_p);
2173 if (split[1].suspect &&
2174 sb->move_score < blame_entry_score(sb, &split[1])) {
2175 split_blame(blamed, &unblamedtail, split, e);
2176 } else {
2177 e->next = leftover;
2178 leftover = e;
2179 }
2180 decref_split(split);
2181 }
2182 *unblamedtail = NULL;
2183 toosmall = filter_small(sb, toosmall, &unblamed, sb->move_score);
2184 } while (unblamed);
2185 target->suspects = reverse_blame(leftover, NULL);
2186}
2187
2188struct blame_list {
2189 struct blame_entry *ent;
2190 struct blame_entry split[3];
2191};
2192
2193/*
2194 * Count the number of entries the target is suspected for,
2195 * and prepare a list of entry and the best split.
2196 */
2197static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
2198 int *num_ents_p)
2199{
2200 struct blame_entry *e;
2201 int num_ents, i;
2202 struct blame_list *blame_list = NULL;
2203
2204 for (e = unblamed, num_ents = 0; e; e = e->next)
2205 num_ents++;
2206 if (num_ents) {
ca56dadb 2207 CALLOC_ARRAY(blame_list, num_ents);
b543bb1c
JS
2208 for (e = unblamed, i = 0; e; e = e->next)
2209 blame_list[i++].ent = e;
2210 }
2211 *num_ents_p = num_ents;
2212 return blame_list;
2213}
2214
2215/*
2216 * For lines target is suspected for, see if we can find code movement
2217 * across file boundary from the parent commit. porigin is the path
2218 * in the parent we already tried.
2219 */
2220static void find_copy_in_parent(struct blame_scoreboard *sb,
2221 struct blame_entry ***blamed,
2222 struct blame_entry **toosmall,
2223 struct blame_origin *target,
2224 struct commit *parent,
2225 struct blame_origin *porigin,
2226 int opt)
2227{
2228 struct diff_options diff_opts;
2229 int i, j;
2230 struct blame_list *blame_list;
2231 int num_ents;
2232 struct blame_entry *unblamed = target->suspects;
2233 struct blame_entry *leftover = NULL;
2234
2235 if (!unblamed)
2236 return; /* nothing remains for this target */
2237
e6757652 2238 repo_diff_setup(sb->repo, &diff_opts);
0d1e0e78 2239 diff_opts.flags.recursive = 1;
b543bb1c
JS
2240 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2241
2242 diff_setup_done(&diff_opts);
2243
2244 /* Try "find copies harder" on new path if requested;
2245 * we do not want to use diffcore_rename() actually to
2246 * match things up; find_copies_harder is set only to
a6f38c10 2247 * force diff_tree_oid() to feed all filepairs to diff_queue,
b543bb1c
JS
2248 * and this code needs to be after diff_setup_done(), which
2249 * usually makes find-copies-harder imply copy detection.
2250 */
2251 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
2252 || ((opt & PICKAXE_BLAME_COPY_HARDER)
2253 && (!porigin || strcmp(target->path, porigin->path))))
0d1e0e78 2254 diff_opts.flags.find_copies_harder = 1;
b543bb1c
JS
2255
2256 if (is_null_oid(&target->commit->object.oid))
2e27bd77 2257 do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
b543bb1c 2258 else
2e27bd77
DS
2259 diff_tree_oid(get_commit_tree_oid(parent),
2260 get_commit_tree_oid(target->commit),
a6f38c10 2261 "", &diff_opts);
b543bb1c 2262
0d1e0e78 2263 if (!diff_opts.flags.find_copies_harder)
b543bb1c
JS
2264 diffcore_std(&diff_opts);
2265
2266 do {
2267 struct blame_entry **unblamedtail = &unblamed;
2268 blame_list = setup_blame_list(unblamed, &num_ents);
2269
2270 for (i = 0; i < diff_queued_diff.nr; i++) {
2271 struct diff_filepair *p = diff_queued_diff.queue[i];
2272 struct blame_origin *norigin;
2273 mmfile_t file_p;
abeacb25 2274 struct blame_entry potential[3];
b543bb1c
JS
2275
2276 if (!DIFF_FILE_VALID(p->one))
2277 continue; /* does not exist in parent */
2278 if (S_ISGITLINK(p->one->mode))
2279 continue; /* ignore git links */
2280 if (porigin && !strcmp(p->one->path, porigin->path))
2281 /* find_move already dealt with this path */
2282 continue;
2283
2284 norigin = get_origin(parent, p->one->path);
2285 oidcpy(&norigin->blob_oid, &p->one->oid);
2286 norigin->mode = p->one->mode;
1fc73384
BR
2287 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p,
2288 &sb->num_read_blob, 0);
b543bb1c
JS
2289 if (!file_p.ptr)
2290 continue;
2291
2292 for (j = 0; j < num_ents; j++) {
2293 find_copy_in_blob(sb, blame_list[j].ent,
abeacb25 2294 norigin, potential, &file_p);
b543bb1c 2295 copy_split_if_better(sb, blame_list[j].split,
abeacb25
BW
2296 potential);
2297 decref_split(potential);
b543bb1c
JS
2298 }
2299 blame_origin_decref(norigin);
2300 }
2301
2302 for (j = 0; j < num_ents; j++) {
2303 struct blame_entry *split = blame_list[j].split;
2304 if (split[1].suspect &&
2305 sb->copy_score < blame_entry_score(sb, &split[1])) {
2306 split_blame(blamed, &unblamedtail, split,
2307 blame_list[j].ent);
2308 } else {
2309 blame_list[j].ent->next = leftover;
2310 leftover = blame_list[j].ent;
2311 }
2312 decref_split(split);
2313 }
2314 free(blame_list);
2315 *unblamedtail = NULL;
2316 toosmall = filter_small(sb, toosmall, &unblamed, sb->copy_score);
2317 } while (unblamed);
2318 target->suspects = reverse_blame(leftover, NULL);
2319 diff_flush(&diff_opts);
b543bb1c
JS
2320}
2321
2322/*
2323 * The blobs of origin and porigin exactly match, so everything
2324 * origin is suspected for can be blamed on the parent.
2325 */
2326static void pass_whole_blame(struct blame_scoreboard *sb,
2327 struct blame_origin *origin, struct blame_origin *porigin)
2328{
2329 struct blame_entry *e, *suspects;
2330
2331 if (!porigin->file.ptr && origin->file.ptr) {
2332 /* Steal its file */
2333 porigin->file = origin->file;
2334 origin->file.ptr = NULL;
2335 }
2336 suspects = origin->suspects;
2337 origin->suspects = NULL;
2338 for (e = suspects; e; e = e->next) {
2339 blame_origin_incref(porigin);
2340 blame_origin_decref(e->suspect);
2341 e->suspect = porigin;
2342 }
2343 queue_blames(sb, porigin, suspects);
2344}
2345
2346/*
2347 * We pass blame from the current commit to its parents. We keep saying
2348 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2349 * exonerate ourselves.
2350 */
2351static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit,
2352 int reverse)
2353{
2354 if (!reverse) {
2355 if (revs->first_parent_only &&
2356 commit->parents &&
2357 commit->parents->next) {
2358 free_commit_list(commit->parents->next);
2359 commit->parents->next = NULL;
2360 }
2361 return commit->parents;
2362 }
2363 return lookup_decoration(&revs->children, &commit->object);
2364}
2365
2366static int num_scapegoats(struct rev_info *revs, struct commit *commit, int reverse)
2367{
2368 struct commit_list *l = first_scapegoat(revs, commit, reverse);
2369 return commit_list_count(l);
2370}
2371
2372/* Distribute collected unsorted blames to the respected sorted lists
2373 * in the various origins.
2374 */
2375static void distribute_blame(struct blame_scoreboard *sb, struct blame_entry *blamed)
2376{
47c30f7d 2377 sort_blame_entries(&blamed, compare_blame_suspect);
b543bb1c
JS
2378 while (blamed)
2379 {
2380 struct blame_origin *porigin = blamed->suspect;
2381 struct blame_entry *suspects = NULL;
2382 do {
2383 struct blame_entry *next = blamed->next;
2384 blamed->next = suspects;
2385 suspects = blamed;
2386 blamed = next;
2387 } while (blamed && blamed->suspect == porigin);
2388 suspects = reverse_blame(suspects, NULL);
2389 queue_blames(sb, porigin, suspects);
2390 }
2391}
2392
2393#define MAXSG 16
2394
0906ac2b
DS
2395typedef struct blame_origin *(*blame_find_alg)(struct repository *,
2396 struct commit *,
2397 struct blame_origin *,
2398 struct blame_bloom_data *);
2399
b543bb1c
JS
2400static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
2401{
2402 struct rev_info *revs = sb->revs;
2403 int i, pass, num_sg;
2404 struct commit *commit = origin->commit;
2405 struct commit_list *sg;
2406 struct blame_origin *sg_buf[MAXSG];
2407 struct blame_origin *porigin, **sg_origin = sg_buf;
2408 struct blame_entry *toosmall = NULL;
2409 struct blame_entry *blames, **blametail = &blames;
2410
2411 num_sg = num_scapegoats(revs, commit, sb->reverse);
2412 if (!num_sg)
2413 goto finish;
2414 else if (num_sg < ARRAY_SIZE(sg_buf))
2415 memset(sg_buf, 0, sizeof(sg_buf));
2416 else
ca56dadb 2417 CALLOC_ARRAY(sg_origin, num_sg);
b543bb1c
JS
2418
2419 /*
2420 * The first pass looks for unrenamed path to optimize for
2421 * common cases, then we look for renames in the second pass.
2422 */
2423 for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
0906ac2b 2424 blame_find_alg find = pass ? find_rename : find_origin;
b543bb1c
JS
2425
2426 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2427 i < num_sg && sg;
2428 sg = sg->next, i++) {
2429 struct commit *p = sg->item;
2430 int j, same;
2431
2432 if (sg_origin[i])
2433 continue;
2434 if (parse_commit(p))
2435 continue;
0906ac2b 2436 porigin = find(sb->repo, p, origin, sb->bloom_data);
b543bb1c
JS
2437 if (!porigin)
2438 continue;
4a7e27e9 2439 if (oideq(&porigin->blob_oid, &origin->blob_oid)) {
b543bb1c
JS
2440 pass_whole_blame(sb, origin, porigin);
2441 blame_origin_decref(porigin);
2442 goto finish;
2443 }
2444 for (j = same = 0; j < i; j++)
2445 if (sg_origin[j] &&
4a7e27e9 2446 oideq(&sg_origin[j]->blob_oid, &porigin->blob_oid)) {
b543bb1c
JS
2447 same = 1;
2448 break;
2449 }
2450 if (!same)
2451 sg_origin[i] = porigin;
2452 else
2453 blame_origin_decref(porigin);
2454 }
2455 }
2456
2457 sb->num_commits++;
2458 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2459 i < num_sg && sg;
2460 sg = sg->next, i++) {
2461 struct blame_origin *porigin = sg_origin[i];
2462 if (!porigin)
2463 continue;
2464 if (!origin->previous) {
2465 blame_origin_incref(porigin);
2466 origin->previous = porigin;
2467 }
ae3f36de 2468 pass_blame_to_parent(sb, origin, porigin, 0);
b543bb1c
JS
2469 if (!origin->suspects)
2470 goto finish;
2471 }
2472
ae3f36de
BR
2473 /*
2474 * Pass remaining suspects for ignored commits to their parents.
2475 */
2476 if (oidset_contains(&sb->ignore_list, &commit->object.oid)) {
2477 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2478 i < num_sg && sg;
2479 sg = sg->next, i++) {
2480 struct blame_origin *porigin = sg_origin[i];
2481
2482 if (!porigin)
2483 continue;
2484 pass_blame_to_parent(sb, origin, porigin, 1);
a07a9776
BR
2485 /*
2486 * Preemptively drop porigin so we can refresh the
2487 * fingerprints if we use the parent again, which can
2488 * occur if you ignore back-to-back commits.
2489 */
2490 drop_origin_blob(porigin);
ae3f36de
BR
2491 if (!origin->suspects)
2492 goto finish;
2493 }
2494 }
2495
b543bb1c
JS
2496 /*
2497 * Optionally find moves in parents' files.
2498 */
2499 if (opt & PICKAXE_BLAME_MOVE) {
2500 filter_small(sb, &toosmall, &origin->suspects, sb->move_score);
2501 if (origin->suspects) {
2502 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2503 i < num_sg && sg;
2504 sg = sg->next, i++) {
2505 struct blame_origin *porigin = sg_origin[i];
2506 if (!porigin)
2507 continue;
2508 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
2509 if (!origin->suspects)
2510 break;
2511 }
2512 }
2513 }
2514
2515 /*
2516 * Optionally find copies from parents' files.
2517 */
2518 if (opt & PICKAXE_BLAME_COPY) {
2519 if (sb->copy_score > sb->move_score)
2520 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2521 else if (sb->copy_score < sb->move_score) {
2522 origin->suspects = blame_merge(origin->suspects, toosmall);
2523 toosmall = NULL;
2524 filter_small(sb, &toosmall, &origin->suspects, sb->copy_score);
2525 }
2526 if (!origin->suspects)
2527 goto finish;
2528
2529 for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
2530 i < num_sg && sg;
2531 sg = sg->next, i++) {
2532 struct blame_origin *porigin = sg_origin[i];
2533 find_copy_in_parent(sb, &blametail, &toosmall,
2534 origin, sg->item, porigin, opt);
2535 if (!origin->suspects)
2536 goto finish;
2537 }
2538 }
2539
2540finish:
2541 *blametail = NULL;
2542 distribute_blame(sb, blames);
2543 /*
2544 * prepend toosmall to origin->suspects
2545 *
2546 * There is no point in sorting: this ends up on a big
2547 * unsorted list in the caller anyway.
2548 */
2549 if (toosmall) {
2550 struct blame_entry **tail = &toosmall;
2551 while (*tail)
2552 tail = &(*tail)->next;
2553 *tail = origin->suspects;
2554 origin->suspects = toosmall;
2555 }
2556 for (i = 0; i < num_sg; i++) {
2557 if (sg_origin[i]) {
f8920149
DK
2558 if (!sg_origin[i]->suspects)
2559 drop_origin_blob(sg_origin[i]);
b543bb1c
JS
2560 blame_origin_decref(sg_origin[i]);
2561 }
2562 }
2563 drop_origin_blob(origin);
2564 if (sg_buf != sg_origin)
2565 free(sg_origin);
2566}
2567
2568/*
2569 * The main loop -- while we have blobs with lines whose true origin
2570 * is still unknown, pick one blob, and allow its lines to pass blames
2571 * to its parents. */
2572void assign_blame(struct blame_scoreboard *sb, int opt)
2573{
2574 struct rev_info *revs = sb->revs;
2575 struct commit *commit = prio_queue_get(&sb->commits);
2576
2577 while (commit) {
2578 struct blame_entry *ent;
4e0df4e6 2579 struct blame_origin *suspect = get_blame_suspects(commit);
b543bb1c
JS
2580
2581 /* find one suspect to break down */
2582 while (suspect && !suspect->suspects)
2583 suspect = suspect->next;
2584
2585 if (!suspect) {
2586 commit = prio_queue_get(&sb->commits);
2587 continue;
2588 }
2589
2590 assert(commit == suspect->commit);
2591
2592 /*
2593 * We will use this suspect later in the loop,
2594 * so hold onto it in the meantime.
2595 */
2596 blame_origin_incref(suspect);
2597 parse_commit(commit);
2598 if (sb->reverse ||
2599 (!(commit->object.flags & UNINTERESTING) &&
2600 !(revs->max_age != -1 && commit->date < revs->max_age)))
2601 pass_blame(sb, suspect, opt);
2602 else {
2603 commit->object.flags |= UNINTERESTING;
2604 if (commit->object.parsed)
9d505b7b 2605 mark_parents_uninteresting(sb->revs, commit);
b543bb1c
JS
2606 }
2607 /* treat root commit as boundary */
2608 if (!commit->parents && !sb->show_root)
2609 commit->object.flags |= UNINTERESTING;
2610
2611 /* Take responsibility for the remaining entries */
2612 ent = suspect->suspects;
2613 if (ent) {
2614 suspect->guilty = 1;
2615 for (;;) {
2616 struct blame_entry *next = ent->next;
2617 if (sb->found_guilty_entry)
2618 sb->found_guilty_entry(ent, sb->found_guilty_entry_data);
2619 if (next) {
2620 ent = next;
2621 continue;
2622 }
2623 ent->next = sb->ent;
2624 sb->ent = suspect->suspects;
2625 suspect->suspects = NULL;
2626 break;
2627 }
2628 }
2629 blame_origin_decref(suspect);
2630
2631 if (sb->debug) /* sanity */
2632 sanity_check_refcnt(sb);
2633 }
2634}
09002f1b 2635
09002f1b
JS
2636/*
2637 * To allow quick access to the contents of nth line in the
2638 * final image, prepare an index in the scoreboard.
2639 */
2640static int prepare_lines(struct blame_scoreboard *sb)
2641{
1fc73384
BR
2642 sb->num_lines = find_line_starts(&sb->lineno, sb->final_buf,
2643 sb->final_buf_size);
09002f1b
JS
2644 return sb->num_lines;
2645}
2646
2647static struct commit *find_single_final(struct rev_info *revs,
2648 const char **name_p)
2649{
2650 int i;
2651 struct commit *found = NULL;
2652 const char *name = NULL;
2653
2654 for (i = 0; i < revs->pending.nr; i++) {
2655 struct object *obj = revs->pending.objects[i].item;
2656 if (obj->flags & UNINTERESTING)
2657 continue;
fb998eae 2658 obj = deref_tag(revs->repo, obj, NULL, 0);
db7d07f6 2659 if (!obj || obj->type != OBJ_COMMIT)
09002f1b
JS
2660 die("Non commit %s?", revs->pending.objects[i].name);
2661 if (found)
2662 die("More than one commit to dig from %s and %s?",
2663 revs->pending.objects[i].name, name);
2664 found = (struct commit *)obj;
2665 name = revs->pending.objects[i].name;
2666 }
2667 if (name_p)
9e7d8a9b 2668 *name_p = xstrdup_or_null(name);
09002f1b
JS
2669 return found;
2670}
2671
2672static struct commit *dwim_reverse_initial(struct rev_info *revs,
2673 const char **name_p)
2674{
2675 /*
2676 * DWIM "git blame --reverse ONE -- PATH" as
2677 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2678 * when it makes sense.
2679 */
2680 struct object *obj;
2681 struct commit *head_commit;
583c6a22 2682 struct object_id head_oid;
09002f1b
JS
2683
2684 if (revs->pending.nr != 1)
2685 return NULL;
2686
2687 /* Is that sole rev a committish? */
2688 obj = revs->pending.objects[0].item;
fb998eae 2689 obj = deref_tag(revs->repo, obj, NULL, 0);
db7d07f6 2690 if (!obj || obj->type != OBJ_COMMIT)
09002f1b
JS
2691 return NULL;
2692
2693 /* Do we have HEAD? */
49e61479 2694 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
09002f1b 2695 return NULL;
fb998eae 2696 head_commit = lookup_commit_reference_gently(revs->repo,
21e1ee8f 2697 &head_oid, 1);
09002f1b
JS
2698 if (!head_commit)
2699 return NULL;
2700
2701 /* Turn "ONE" into "ONE..HEAD" then */
2702 obj->flags |= UNINTERESTING;
2703 add_pending_object(revs, &head_commit->object, "HEAD");
2704
2705 if (name_p)
2706 *name_p = revs->pending.objects[0].name;
2707 return (struct commit *)obj;
2708}
2709
2710static struct commit *find_single_initial(struct rev_info *revs,
2711 const char **name_p)
2712{
2713 int i;
2714 struct commit *found = NULL;
2715 const char *name = NULL;
2716
2717 /*
2718 * There must be one and only one negative commit, and it must be
2719 * the boundary.
2720 */
2721 for (i = 0; i < revs->pending.nr; i++) {
2722 struct object *obj = revs->pending.objects[i].item;
2723 if (!(obj->flags & UNINTERESTING))
2724 continue;
fb998eae 2725 obj = deref_tag(revs->repo, obj, NULL, 0);
db7d07f6 2726 if (!obj || obj->type != OBJ_COMMIT)
09002f1b
JS
2727 die("Non commit %s?", revs->pending.objects[i].name);
2728 if (found)
2729 die("More than one commit to dig up from, %s and %s?",
2730 revs->pending.objects[i].name, name);
2731 found = (struct commit *) obj;
2732 name = revs->pending.objects[i].name;
2733 }
2734
2735 if (!name)
2736 found = dwim_reverse_initial(revs, &name);
2737 if (!name)
2738 die("No commit to dig up from?");
2739
2740 if (name_p)
9e7d8a9b 2741 *name_p = xstrdup(name);
09002f1b
JS
2742 return found;
2743}
2744
2745void init_scoreboard(struct blame_scoreboard *sb)
2746{
2747 memset(sb, 0, sizeof(struct blame_scoreboard));
2748 sb->move_score = BLAME_DEFAULT_MOVE_SCORE;
2749 sb->copy_score = BLAME_DEFAULT_COPY_SCORE;
2750}
2751
ecbbc0a5 2752void setup_scoreboard(struct blame_scoreboard *sb,
ecbbc0a5 2753 struct blame_origin **orig)
09002f1b
JS
2754{
2755 const char *final_commit_name = NULL;
2756 struct blame_origin *o;
2757 struct commit *final_commit = NULL;
2758 enum object_type type;
2759
4e0df4e6
NTND
2760 init_blame_suspects(&blame_suspects);
2761
09002f1b
JS
2762 if (sb->reverse && sb->contents_from)
2763 die(_("--contents and --reverse do not blend well."));
2764
ecbbc0a5
NTND
2765 if (!sb->repo)
2766 BUG("repo is NULL");
2767
09002f1b
JS
2768 if (!sb->reverse) {
2769 sb->final = find_single_final(sb->revs, &final_commit_name);
2770 sb->commits.compare = compare_commits_by_commit_date;
2771 } else {
2772 sb->final = find_single_initial(sb->revs, &final_commit_name);
2773 sb->commits.compare = compare_commits_by_reverse_commit_date;
2774 }
2775
2776 if (sb->final && sb->contents_from)
2777 die(_("cannot use --contents with final commit object name"));
2778
2779 if (sb->reverse && sb->revs->first_parent_only)
2780 sb->revs->children.name = NULL;
2781
2782 if (!sb->final) {
2783 /*
2784 * "--not A B -- path" without anything positive;
2785 * do not default to HEAD, but use the working tree
2786 * or "--contents".
2787 */
2788 setup_work_tree();
ecbbc0a5
NTND
2789 sb->final = fake_working_tree_commit(sb->repo,
2790 &sb->revs->diffopt,
88894aae 2791 sb->path, sb->contents_from);
09002f1b
JS
2792 add_pending_object(sb->revs, &(sb->final->object), ":");
2793 }
2794
2795 if (sb->reverse && sb->revs->first_parent_only) {
2796 final_commit = find_single_final(sb->revs, NULL);
2797 if (!final_commit)
2798 die(_("--reverse and --first-parent together require specified latest commit"));
2799 }
2800
2801 /*
2802 * If we have bottom, this will mark the ancestors of the
2803 * bottom commits we would reach while traversing as
2804 * uninteresting.
2805 */
2806 if (prepare_revision_walk(sb->revs))
2807 die(_("revision walk setup failed"));
2808
2809 if (sb->reverse && sb->revs->first_parent_only) {
2810 struct commit *c = final_commit;
2811
2812 sb->revs->children.name = "children";
2813 while (c->parents &&
9001dc2a 2814 !oideq(&c->object.oid, &sb->final->object.oid)) {
09002f1b
JS
2815 struct commit_list *l = xcalloc(1, sizeof(*l));
2816
2817 l->item = c;
2818 if (add_decoration(&sb->revs->children,
2819 &c->parents->item->object, l))
033abf97 2820 BUG("not unique item in first-parent chain");
09002f1b
JS
2821 c = c->parents->item;
2822 }
2823
9001dc2a 2824 if (!oideq(&c->object.oid, &sb->final->object.oid))
09002f1b
JS
2825 die(_("--reverse --first-parent together require range along first-parent chain"));
2826 }
2827
2828 if (is_null_oid(&sb->final->object.oid)) {
4e0df4e6 2829 o = get_blame_suspects(sb->final);
09002f1b
JS
2830 sb->final_buf = xmemdupz(o->file.ptr, o->file.size);
2831 sb->final_buf_size = o->file.size;
2832 }
2833 else {
88894aae 2834 o = get_origin(sb->final, sb->path);
ecbbc0a5 2835 if (fill_blob_sha1_and_mode(sb->repo, o))
88894aae 2836 die(_("no such path %s in %s"), sb->path, final_commit_name);
09002f1b 2837
0d1e0e78 2838 if (sb->revs->diffopt.flags.allow_textconv &&
88894aae 2839 textconv_object(sb->repo, sb->path, o->mode, &o->blob_oid, 1, (char **) &sb->final_buf,
09002f1b
JS
2840 &sb->final_buf_size))
2841 ;
2842 else
b4f5aca4 2843 sb->final_buf = read_object_file(&o->blob_oid, &type,
2844 &sb->final_buf_size);
09002f1b
JS
2845
2846 if (!sb->final_buf)
2847 die(_("cannot read blob %s for path %s"),
2848 oid_to_hex(&o->blob_oid),
88894aae 2849 sb->path);
09002f1b
JS
2850 }
2851 sb->num_read_blob++;
2852 prepare_lines(sb);
2853
2854 if (orig)
2855 *orig = o;
9e7d8a9b
SG
2856
2857 free((char *)final_commit_name);
09002f1b 2858}
bd481de7
JS
2859
2860
2861
2862struct blame_entry *blame_entry_prepend(struct blame_entry *head,
2863 long start, long end,
2864 struct blame_origin *o)
2865{
2866 struct blame_entry *new_head = xcalloc(1, sizeof(struct blame_entry));
2867 new_head->lno = start;
2868 new_head->num_lines = end - start;
2869 new_head->suspect = o;
2870 new_head->s_lno = start;
2871 new_head->next = head;
2872 blame_origin_incref(o);
2873 return new_head;
2874}
0906ac2b 2875
3af31e87 2876void setup_blame_bloom_data(struct blame_scoreboard *sb)
0906ac2b
DS
2877{
2878 struct blame_bloom_data *bd;
4f364405 2879 struct bloom_filter_settings *bs;
0906ac2b
DS
2880
2881 if (!sb->repo->objects->commit_graph)
2882 return;
2883
4f364405
TB
2884 bs = get_bloom_filter_settings(sb->repo);
2885 if (!bs)
0906ac2b
DS
2886 return;
2887
2888 bd = xmalloc(sizeof(struct blame_bloom_data));
2889
4f364405 2890 bd->settings = bs;
0906ac2b
DS
2891
2892 bd->alloc = 4;
2893 bd->nr = 0;
2894 ALLOC_ARRAY(bd->keys, bd->alloc);
2895
3af31e87 2896 add_bloom_key(bd, sb->path);
0906ac2b
DS
2897
2898 sb->bloom_data = bd;
2899}
2900
2901void cleanup_scoreboard(struct blame_scoreboard *sb)
2902{
2903 if (sb->bloom_data) {
2904 int i;
2905 for (i = 0; i < sb->bloom_data->nr; i++) {
2906 free(sb->bloom_data->keys[i]->hashes);
2907 free(sb->bloom_data->keys[i]);
2908 }
2909 free(sb->bloom_data->keys);
2910 FREE_AND_NULL(sb->bloom_data);
2911
2912 trace2_data_intmax("blame", sb->repo,
2913 "bloom/queries", bloom_count_queries);
2914 trace2_data_intmax("blame", sb->repo,
2915 "bloom/response-no", bloom_count_no);
2916 }
2917}