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