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