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