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