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