1 #include "git-compat-util.h"
3 #include "object-store-ll.h"
4 #include "cache-tree.h"
13 #include "read-cache.h"
20 #include "commit-slab.h"
22 #include "commit-graph.h"
24 define_commit_slab(blame_suspects
, struct blame_origin
*);
25 static struct blame_suspects blame_suspects
;
27 struct blame_origin
*get_blame_suspects(struct commit
*commit
)
29 struct blame_origin
**result
;
31 result
= blame_suspects_peek(&blame_suspects
, commit
);
33 return result
? *result
: NULL
;
36 static void set_blame_suspects(struct commit
*commit
, struct blame_origin
*origin
)
38 *blame_suspects_at(&blame_suspects
, commit
) = origin
;
41 void blame_origin_decref(struct blame_origin
*o
)
43 if (o
&& --o
->refcnt
<= 0) {
44 struct blame_origin
*p
, *l
= NULL
;
46 blame_origin_decref(o
->previous
);
48 /* Should be present exactly once in commit chain */
49 for (p
= get_blame_suspects(o
->commit
); p
; l
= p
, p
= p
->next
) {
54 set_blame_suspects(o
->commit
, p
->next
);
59 die("internal error in blame_origin_decref");
64 * Given a commit and a path in it, create a new origin structure.
65 * The callers that add blame to the scoreboard should use
66 * get_origin() to obtain shared, refcounted copy instead of calling
67 * this function directly.
69 static struct blame_origin
*make_origin(struct commit
*commit
, const char *path
)
71 struct blame_origin
*o
;
72 FLEX_ALLOC_STR(o
, path
, path
);
75 o
->next
= get_blame_suspects(commit
);
76 set_blame_suspects(commit
, o
);
81 * Locate an existing origin or create a new one.
82 * This moves the origin to front position in the commit util list.
84 static struct blame_origin
*get_origin(struct commit
*commit
, const char *path
)
86 struct blame_origin
*o
, *l
;
88 for (o
= get_blame_suspects(commit
), l
= NULL
; o
; l
= o
, o
= o
->next
) {
89 if (!strcmp(o
->path
, path
)) {
93 o
->next
= get_blame_suspects(commit
);
94 set_blame_suspects(commit
, o
);
96 return blame_origin_incref(o
);
99 return make_origin(commit
, path
);
104 static void verify_working_tree_path(struct repository
*r
,
105 struct commit
*work_tree
, const char *path
)
107 struct commit_list
*parents
;
110 for (parents
= work_tree
->parents
; parents
; parents
= parents
->next
) {
111 const struct object_id
*commit_oid
= &parents
->item
->object
.oid
;
112 struct object_id blob_oid
;
115 if (!get_tree_entry(r
, commit_oid
, path
, &blob_oid
, &mode
) &&
116 oid_object_info(r
, &blob_oid
, NULL
) == OBJ_BLOB
)
120 pos
= index_name_pos(r
->index
, path
, strlen(path
));
122 ; /* path is in the index */
123 else if (-1 - pos
< r
->index
->cache_nr
&&
124 !strcmp(r
->index
->cache
[-1 - pos
]->name
, path
))
125 ; /* path is in the index, unmerged */
127 die("no such path '%s' in HEAD", path
);
130 static struct commit_list
**append_parent(struct repository
*r
,
131 struct commit_list
**tail
,
132 const struct object_id
*oid
)
134 struct commit
*parent
;
136 parent
= lookup_commit_reference(r
, oid
);
138 die("no such commit %s", oid_to_hex(oid
));
139 return &commit_list_insert(parent
, tail
)->next
;
142 static void append_merge_parents(struct repository
*r
,
143 struct commit_list
**tail
)
146 struct strbuf line
= STRBUF_INIT
;
148 merge_head
= open(git_path_merge_head(r
), O_RDONLY
);
149 if (merge_head
< 0) {
152 die("cannot open '%s' for reading",
153 git_path_merge_head(r
));
156 while (!strbuf_getwholeline_fd(&line
, merge_head
, '\n')) {
157 struct object_id oid
;
158 if (get_oid_hex(line
.buf
, &oid
))
159 die("unknown line in '%s': %s",
160 git_path_merge_head(r
), line
.buf
);
161 tail
= append_parent(r
, tail
, &oid
);
164 strbuf_release(&line
);
168 * This isn't as simple as passing sb->buf and sb->len, because we
169 * want to transfer ownership of the buffer to the commit (so we
172 static void set_commit_buffer_from_strbuf(struct repository
*r
,
177 void *buf
= strbuf_detach(sb
, &len
);
178 set_commit_buffer(r
, c
, buf
, len
);
182 * Prepare a dummy commit that represents the work tree (or staged) item.
183 * Note that annotating work tree item never works in the reverse.
185 static struct commit
*fake_working_tree_commit(struct repository
*r
,
186 struct diff_options
*opt
,
188 const char *contents_from
,
189 struct object_id
*oid
)
191 struct commit
*commit
;
192 struct blame_origin
*origin
;
193 struct commit_list
**parent_tail
, *parent
;
194 struct strbuf buf
= STRBUF_INIT
;
198 struct cache_entry
*ce
;
200 struct strbuf msg
= STRBUF_INIT
;
204 commit
= alloc_commit_node(r
);
205 commit
->object
.parsed
= 1;
207 parent_tail
= &commit
->parents
;
209 parent_tail
= append_parent(r
, parent_tail
, oid
);
210 append_merge_parents(r
, parent_tail
);
211 verify_working_tree_path(r
, commit
, path
);
213 origin
= make_origin(commit
, path
);
216 ident
= fmt_ident("External file (--contents)", "external.file",
217 WANT_BLANK_IDENT
, NULL
, 0);
219 ident
= fmt_ident("Not Committed Yet", "not.committed.yet",
220 WANT_BLANK_IDENT
, NULL
, 0);
221 strbuf_addstr(&msg
, "tree 0000000000000000000000000000000000000000\n");
222 for (parent
= commit
->parents
; parent
; parent
= parent
->next
)
223 strbuf_addf(&msg
, "parent %s\n",
224 oid_to_hex(&parent
->item
->object
.oid
));
228 "Version of %s from %s\n",
230 (!contents_from
? path
:
231 (!strcmp(contents_from
, "-") ? "standard input" : contents_from
)));
232 set_commit_buffer_from_strbuf(r
, commit
, &msg
);
234 if (!contents_from
|| strcmp("-", contents_from
)) {
236 const char *read_from
;
238 unsigned long buf_len
;
241 if (stat(contents_from
, &st
) < 0)
242 die_errno("Cannot stat '%s'", contents_from
);
243 read_from
= contents_from
;
246 if (lstat(path
, &st
) < 0)
247 die_errno("Cannot lstat '%s'", path
);
250 mode
= canon_mode(st
.st_mode
);
252 switch (st
.st_mode
& S_IFMT
) {
254 if (opt
->flags
.allow_textconv
&&
255 textconv_object(r
, read_from
, mode
, null_oid(), 0, &buf_ptr
, &buf_len
))
256 strbuf_attach(&buf
, buf_ptr
, buf_len
, buf_len
+ 1);
257 else if (strbuf_read_file(&buf
, read_from
, st
.st_size
) != st
.st_size
)
258 die_errno("cannot open or read '%s'", read_from
);
261 if (strbuf_readlink(&buf
, read_from
, st
.st_size
) < 0)
262 die_errno("cannot readlink '%s'", read_from
);
265 die("unsupported file type %s", read_from
);
269 /* Reading from stdin */
271 if (strbuf_read(&buf
, 0, 0) < 0)
272 die_errno("failed to read from stdin");
274 convert_to_git(r
->index
, path
, buf
.buf
, buf
.len
, &buf
, 0);
275 origin
->file
.ptr
= buf
.buf
;
276 origin
->file
.size
= buf
.len
;
277 pretend_object_file(buf
.buf
, buf
.len
, OBJ_BLOB
, &origin
->blob_oid
);
280 * Read the current index, replace the path entry with
281 * origin->blob_sha1 without mucking with its mode or type
282 * bits; we are not going to write this index out -- we just
283 * want to run "diff-index --cached".
285 discard_index(r
->index
);
290 int pos
= index_name_pos(r
->index
, path
, len
);
292 mode
= r
->index
->cache
[pos
]->ce_mode
;
294 /* Let's not bother reading from HEAD tree */
295 mode
= S_IFREG
| 0644;
297 ce
= make_empty_cache_entry(r
->index
, len
);
298 oidcpy(&ce
->oid
, &origin
->blob_oid
);
299 memcpy(ce
->name
, path
, len
);
300 ce
->ce_flags
= create_ce_flags(0);
301 ce
->ce_namelen
= len
;
302 ce
->ce_mode
= create_ce_mode(mode
);
303 add_index_entry(r
->index
, ce
,
304 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
306 cache_tree_invalidate_path(r
->index
, path
);
313 static int diff_hunks(mmfile_t
*file_a
, mmfile_t
*file_b
,
314 xdl_emit_hunk_consume_func_t hunk_func
, void *cb_data
, int xdl_opts
)
317 xdemitconf_t xecfg
= {0};
318 xdemitcb_t ecb
= {NULL
};
320 xpp
.flags
= xdl_opts
;
321 xecfg
.hunk_func
= hunk_func
;
323 return xdi_diff(file_a
, file_b
, &xpp
, &xecfg
, &ecb
);
326 static const char *get_next_line(const char *start
, const char *end
)
328 const char *nl
= memchr(start
, '\n', end
- start
);
330 return nl
? nl
+ 1 : end
;
333 static int find_line_starts(int **line_starts
, const char *buf
,
336 const char *end
= buf
+ len
;
341 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
344 ALLOC_ARRAY(*line_starts
, num
+ 1);
345 lineno
= *line_starts
;
347 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
355 struct fingerprint_entry
;
357 /* A fingerprint is intended to loosely represent a string, such that two
358 * fingerprints can be quickly compared to give an indication of the similarity
359 * of the strings that they represent.
361 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
362 * the string that it represents. Whitespace is added at each end of the
363 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
364 * For example, the string "Darth Radar" will be converted to the following
366 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
368 * The similarity between two fingerprints is the size of the intersection of
369 * their multisets, including repeated elements. See fingerprint_similarity for
372 * For ease of implementation, the fingerprint is implemented as a map
373 * of byte pairs to the count of that byte pair in the string, instead of
374 * allowing repeated elements in a set.
378 /* As we know the maximum number of entries in advance, it's
379 * convenient to store the entries in a single array instead of having
380 * the hashmap manage the memory.
382 struct fingerprint_entry
*entries
;
385 /* A byte pair in a fingerprint. Stores the number of times the byte pair
386 * occurs in the string that the fingerprint represents.
388 struct fingerprint_entry
{
389 /* The hashmap entry - the hash represents the byte pair in its
390 * entirety so we don't need to store the byte pair separately.
392 struct hashmap_entry entry
;
393 /* The number of times the byte pair occurs in the string that the
394 * fingerprint represents.
399 /* See `struct fingerprint` for an explanation of what a fingerprint is.
400 * \param result the fingerprint of the string is stored here. This must be
401 * freed later using free_fingerprint.
402 * \param line_begin the start of the string
403 * \param line_end the end of the string
405 static void get_fingerprint(struct fingerprint
*result
,
406 const char *line_begin
,
407 const char *line_end
)
409 unsigned int hash
, c0
= 0, c1
;
411 int max_map_entry_count
= 1 + line_end
- line_begin
;
412 struct fingerprint_entry
*entry
= xcalloc(max_map_entry_count
,
413 sizeof(struct fingerprint_entry
));
414 struct fingerprint_entry
*found_entry
;
416 hashmap_init(&result
->map
, NULL
, NULL
, max_map_entry_count
);
417 result
->entries
= entry
;
418 for (p
= line_begin
; p
<= line_end
; ++p
, c0
= c1
) {
419 /* Always terminate the string with whitespace.
420 * Normalise whitespace to 0, and normalise letters to
421 * lower case. This won't work for multibyte characters but at
422 * worst will match some unrelated characters.
424 if ((p
== line_end
) || isspace(*p
))
428 hash
= c0
| (c1
<< 8);
429 /* Ignore whitespace pairs */
432 hashmap_entry_init(&entry
->entry
, hash
);
434 found_entry
= hashmap_get_entry(&result
->map
, entry
,
435 /* member name */ entry
, NULL
);
437 found_entry
->count
+= 1;
440 hashmap_add(&result
->map
, &entry
->entry
);
446 static void free_fingerprint(struct fingerprint
*f
)
448 hashmap_clear(&f
->map
);
452 /* Calculates the similarity between two fingerprints as the size of the
453 * intersection of their multisets, including repeated elements. See
454 * `struct fingerprint` for an explanation of the fingerprint representation.
455 * The similarity between "cat mat" and "father rather" is 2 because "at" is
456 * present twice in both strings while the similarity between "tim" and "mit"
459 static int fingerprint_similarity(struct fingerprint
*a
, struct fingerprint
*b
)
461 int intersection
= 0;
462 struct hashmap_iter iter
;
463 const struct fingerprint_entry
*entry_a
, *entry_b
;
465 hashmap_for_each_entry(&b
->map
, &iter
, entry_b
,
466 entry
/* member name */) {
467 entry_a
= hashmap_get_entry(&a
->map
, entry_b
, entry
, NULL
);
469 intersection
+= entry_a
->count
< entry_b
->count
?
470 entry_a
->count
: entry_b
->count
;
476 /* Subtracts byte-pair elements in B from A, modifying A in place.
478 static void fingerprint_subtract(struct fingerprint
*a
, struct fingerprint
*b
)
480 struct hashmap_iter iter
;
481 struct fingerprint_entry
*entry_a
;
482 const struct fingerprint_entry
*entry_b
;
484 hashmap_iter_init(&b
->map
, &iter
);
486 hashmap_for_each_entry(&b
->map
, &iter
, entry_b
,
487 entry
/* member name */) {
488 entry_a
= hashmap_get_entry(&a
->map
, entry_b
, entry
, NULL
);
490 if (entry_a
->count
<= entry_b
->count
)
491 hashmap_remove(&a
->map
, &entry_b
->entry
, NULL
);
493 entry_a
->count
-= entry_b
->count
;
498 /* Calculate fingerprints for a series of lines.
499 * Puts the fingerprints in the fingerprints array, which must have been
500 * preallocated to allow storing line_count elements.
502 static void get_line_fingerprints(struct fingerprint
*fingerprints
,
503 const char *content
, const int *line_starts
,
504 long first_line
, long line_count
)
507 const char *linestart
, *lineend
;
509 line_starts
+= first_line
;
510 for (i
= 0; i
< line_count
; ++i
) {
511 linestart
= content
+ line_starts
[i
];
512 lineend
= content
+ line_starts
[i
+ 1];
513 get_fingerprint(fingerprints
+ i
, linestart
, lineend
);
517 static void free_line_fingerprints(struct fingerprint
*fingerprints
,
522 for (i
= 0; i
< nr_fingerprints
; i
++)
523 free_fingerprint(&fingerprints
[i
]);
526 /* This contains the data necessary to linearly map a line number in one half
527 * of a diff chunk to the line in the other half of the diff chunk that is
528 * closest in terms of its position as a fraction of the length of the chunk.
530 struct line_number_mapping
{
531 int destination_start
, destination_length
,
532 source_start
, source_length
;
535 /* Given a line number in one range, offset and scale it to map it onto the
537 * Essentially this mapping is a simple linear equation but the calculation is
538 * more complicated to allow performing it with integer operations.
539 * Another complication is that if a line could map onto many lines in the
540 * destination range then we want to choose the line at the center of those
542 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
543 * first 5 lines in B will map onto the first line in the A chunk, while the
544 * last 5 lines will all map onto the second line in the A chunk.
545 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
546 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
548 static int map_line_number(int line_number
,
549 const struct line_number_mapping
*mapping
)
551 return ((line_number
- mapping
->source_start
) * 2 + 1) *
552 mapping
->destination_length
/
553 (mapping
->source_length
* 2) +
554 mapping
->destination_start
;
557 /* Get a pointer to the element storing the similarity between a line in A
560 * The similarities are stored in a 2-dimensional array. Each "row" in the
561 * array contains the similarities for a line in B. The similarities stored in
562 * a row are the similarities between the line in B and the nearby lines in A.
563 * To keep the length of each row the same, it is padded out with values of -1
564 * where the search range extends beyond the lines in A.
565 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
572 * Then the similarity array will contain:
573 * [-1, -1, am, bm, cm,
574 * -1, an, bn, cn, dn,
575 * ao, bo, co, do, eo,
576 * bp, cp, dp, ep, -1,
577 * cq, dq, eq, -1, -1]
578 * Where similarities are denoted either by -1 for invalid, or the
579 * concatenation of the two lines in the diff being compared.
581 * \param similarities array of similarities between lines in A and B
582 * \param line_a the index of the line in A, in the same frame of reference as
584 * \param local_line_b the index of the line in B, relative to the first line
585 * in B that similarities represents.
586 * \param closest_line_a the index of the line in A that is deemed to be
587 * closest to local_line_b. This must be in the same
588 * frame of reference as line_a. This value defines
589 * where similarities is centered for the line in B.
590 * \param max_search_distance_a maximum distance in lines from the closest line
591 * in A for other lines in A for which
592 * similarities may be calculated.
594 static int *get_similarity(int *similarities
,
595 int line_a
, int local_line_b
,
596 int closest_line_a
, int max_search_distance_a
)
598 assert(abs(line_a
- closest_line_a
) <=
599 max_search_distance_a
);
600 return similarities
+ line_a
- closest_line_a
+
601 max_search_distance_a
+
602 local_line_b
* (max_search_distance_a
* 2 + 1);
605 #define CERTAIN_NOTHING_MATCHES -2
606 #define CERTAINTY_NOT_CALCULATED -1
608 /* Given a line in B, first calculate its similarities with nearby lines in A
609 * if not already calculated, then identify the most similar and second most
610 * similar lines. The "certainty" is calculated based on those two
613 * \param start_a the index of the first line of the chunk in A
614 * \param length_a the length in lines of the chunk in A
615 * \param local_line_b the index of the line in B, relative to the first line
617 * \param fingerprints_a array of fingerprints for the chunk in A
618 * \param fingerprints_b array of fingerprints for the chunk in B
619 * \param similarities 2-dimensional array of similarities between lines in A
620 * and B. See get_similarity() for more details.
621 * \param certainties array of values indicating how strongly a line in B is
622 * matched with some line in A.
623 * \param second_best_result array of absolute indices in A for the second
624 * closest match of a line in B.
625 * \param result array of absolute indices in A for the closest match of a line
627 * \param max_search_distance_a maximum distance in lines from the closest line
628 * in A for other lines in A for which
629 * similarities may be calculated.
630 * \param map_line_number_in_b_to_a parameter to map_line_number().
632 static void find_best_line_matches(
637 struct fingerprint
*fingerprints_a
,
638 struct fingerprint
*fingerprints_b
,
641 int *second_best_result
,
643 const int max_search_distance_a
,
644 const struct line_number_mapping
*map_line_number_in_b_to_a
)
647 int i
, search_start
, search_end
, closest_local_line_a
, *similarity
,
648 best_similarity
= 0, second_best_similarity
= 0,
649 best_similarity_index
= 0, second_best_similarity_index
= 0;
651 /* certainty has already been calculated so no need to redo the work */
652 if (certainties
[local_line_b
] != CERTAINTY_NOT_CALCULATED
)
655 closest_local_line_a
= map_line_number(
656 local_line_b
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
658 search_start
= closest_local_line_a
- max_search_distance_a
;
659 if (search_start
< 0)
662 search_end
= closest_local_line_a
+ max_search_distance_a
+ 1;
663 if (search_end
> length_a
)
664 search_end
= length_a
;
666 for (i
= search_start
; i
< search_end
; ++i
) {
667 similarity
= get_similarity(similarities
,
669 closest_local_line_a
,
670 max_search_distance_a
);
671 if (*similarity
== -1) {
672 /* This value will never exceed 10 but assert just in
675 assert(abs(i
- closest_local_line_a
) < 1000);
676 /* scale the similarity by (1000 - distance from
677 * closest line) to act as a tie break between lines
678 * that otherwise are equally similar.
680 *similarity
= fingerprint_similarity(
681 fingerprints_b
+ local_line_b
,
682 fingerprints_a
+ i
) *
683 (1000 - abs(i
- closest_local_line_a
));
685 if (*similarity
> best_similarity
) {
686 second_best_similarity
= best_similarity
;
687 second_best_similarity_index
= best_similarity_index
;
688 best_similarity
= *similarity
;
689 best_similarity_index
= i
;
690 } else if (*similarity
> second_best_similarity
) {
691 second_best_similarity
= *similarity
;
692 second_best_similarity_index
= i
;
696 if (best_similarity
== 0) {
697 /* this line definitely doesn't match with anything. Mark it
698 * with this special value so it doesn't get invalidated and
699 * won't be recalculated.
701 certainties
[local_line_b
] = CERTAIN_NOTHING_MATCHES
;
702 result
[local_line_b
] = -1;
704 /* Calculate the certainty with which this line matches.
705 * If the line matches well with two lines then that reduces
706 * the certainty. However we still want to prioritise matching
707 * a line that matches very well with two lines over matching a
708 * line that matches poorly with one line, hence doubling
710 * This means that if we have
711 * line X that matches only one line with a score of 3,
712 * line Y that matches two lines equally with a score of 5,
713 * and line Z that matches only one line with a score or 2,
714 * then the lines in order of certainty are X, Y, Z.
716 certainties
[local_line_b
] = best_similarity
* 2 -
717 second_best_similarity
;
719 /* We keep both the best and second best results to allow us to
720 * check at a later stage of the matching process whether the
721 * result needs to be invalidated.
723 result
[local_line_b
] = start_a
+ best_similarity_index
;
724 second_best_result
[local_line_b
] =
725 start_a
+ second_best_similarity_index
;
730 * This finds the line that we can match with the most confidence, and
731 * uses it as a partition. It then calls itself on the lines on either side of
732 * that partition. In this way we avoid lines appearing out of order, and
733 * retain a sensible line ordering.
734 * \param start_a index of the first line in A with which lines in B may be
736 * \param start_b index of the first line in B for which matching should be
738 * \param length_a number of lines in A with which lines in B may be compared.
739 * \param length_b number of lines in B for which matching should be done.
740 * \param fingerprints_a mutable array of fingerprints in A. The first element
741 * corresponds to the line at start_a.
742 * \param fingerprints_b array of fingerprints in B. The first element
743 * corresponds to the line at start_b.
744 * \param similarities 2-dimensional array of similarities between lines in A
745 * and B. See get_similarity() for more details.
746 * \param certainties array of values indicating how strongly a line in B is
747 * matched with some line in A.
748 * \param second_best_result array of absolute indices in A for the second
749 * closest match of a line in B.
750 * \param result array of absolute indices in A for the closest match of a line
752 * \param max_search_distance_a maximum distance in lines from the closest line
753 * in A for other lines in A for which
754 * similarities may be calculated.
755 * \param max_search_distance_b an upper bound on the greatest possible
756 * distance between lines in B such that they will
757 * both be compared with the same line in A
758 * according to max_search_distance_a.
759 * \param map_line_number_in_b_to_a parameter to map_line_number().
761 static void fuzzy_find_matching_lines_recurse(
762 int start_a
, int start_b
,
763 int length_a
, int length_b
,
764 struct fingerprint
*fingerprints_a
,
765 struct fingerprint
*fingerprints_b
,
768 int *second_best_result
,
770 int max_search_distance_a
,
771 int max_search_distance_b
,
772 const struct line_number_mapping
*map_line_number_in_b_to_a
)
774 int i
, invalidate_min
, invalidate_max
, offset_b
,
775 second_half_start_a
, second_half_start_b
,
776 second_half_length_a
, second_half_length_b
,
777 most_certain_line_a
, most_certain_local_line_b
= -1,
778 most_certain_line_certainty
= -1,
779 closest_local_line_a
;
781 for (i
= 0; i
< length_b
; ++i
) {
782 find_best_line_matches(start_a
,
792 max_search_distance_a
,
793 map_line_number_in_b_to_a
);
795 if (certainties
[i
] > most_certain_line_certainty
) {
796 most_certain_line_certainty
= certainties
[i
];
797 most_certain_local_line_b
= i
;
802 if (most_certain_local_line_b
== -1)
805 most_certain_line_a
= result
[most_certain_local_line_b
];
808 * Subtract the most certain line's fingerprint in B from the matched
809 * fingerprint in A. This means that other lines in B can't also match
810 * the same parts of the line in A.
812 fingerprint_subtract(fingerprints_a
+ most_certain_line_a
- start_a
,
813 fingerprints_b
+ most_certain_local_line_b
);
815 /* Invalidate results that may be affected by the choice of most
818 invalidate_min
= most_certain_local_line_b
- max_search_distance_b
;
819 invalidate_max
= most_certain_local_line_b
+ max_search_distance_b
+ 1;
820 if (invalidate_min
< 0)
822 if (invalidate_max
> length_b
)
823 invalidate_max
= length_b
;
825 /* As the fingerprint in A has changed, discard previously calculated
826 * similarity values with that fingerprint.
828 for (i
= invalidate_min
; i
< invalidate_max
; ++i
) {
829 closest_local_line_a
= map_line_number(
830 i
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
832 /* Check that the lines in A and B are close enough that there
833 * is a similarity value for them.
835 if (abs(most_certain_line_a
- start_a
- closest_local_line_a
) >
836 max_search_distance_a
) {
840 *get_similarity(similarities
, most_certain_line_a
- start_a
,
841 i
, closest_local_line_a
,
842 max_search_distance_a
) = -1;
845 /* More invalidating of results that may be affected by the choice of
847 * Discard the matches for lines in B that are currently matched with a
848 * line in A such that their ordering contradicts the ordering imposed
849 * by the choice of most certain line.
851 for (i
= most_certain_local_line_b
- 1; i
>= invalidate_min
; --i
) {
852 /* In this loop we discard results for lines in B that are
853 * before most-certain-line-B but are matched with a line in A
854 * that is after most-certain-line-A.
856 if (certainties
[i
] >= 0 &&
857 (result
[i
] >= most_certain_line_a
||
858 second_best_result
[i
] >= most_certain_line_a
)) {
859 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
862 for (i
= most_certain_local_line_b
+ 1; i
< invalidate_max
; ++i
) {
863 /* In this loop we discard results for lines in B that are
864 * after most-certain-line-B but are matched with a line in A
865 * that is before most-certain-line-A.
867 if (certainties
[i
] >= 0 &&
868 (result
[i
] <= most_certain_line_a
||
869 second_best_result
[i
] <= most_certain_line_a
)) {
870 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
874 /* Repeat the matching process for lines before the most certain line.
876 if (most_certain_local_line_b
> 0) {
877 fuzzy_find_matching_lines_recurse(
879 most_certain_line_a
+ 1 - start_a
,
880 most_certain_local_line_b
,
881 fingerprints_a
, fingerprints_b
, similarities
,
882 certainties
, second_best_result
, result
,
883 max_search_distance_a
,
884 max_search_distance_b
,
885 map_line_number_in_b_to_a
);
887 /* Repeat the matching process for lines after the most certain line.
889 if (most_certain_local_line_b
+ 1 < length_b
) {
890 second_half_start_a
= most_certain_line_a
;
891 offset_b
= most_certain_local_line_b
+ 1;
892 second_half_start_b
= start_b
+ offset_b
;
893 second_half_length_a
=
894 length_a
+ start_a
- second_half_start_a
;
895 second_half_length_b
=
896 length_b
+ start_b
- second_half_start_b
;
897 fuzzy_find_matching_lines_recurse(
898 second_half_start_a
, second_half_start_b
,
899 second_half_length_a
, second_half_length_b
,
900 fingerprints_a
+ second_half_start_a
- start_a
,
901 fingerprints_b
+ offset_b
,
903 offset_b
* (max_search_distance_a
* 2 + 1),
904 certainties
+ offset_b
,
905 second_best_result
+ offset_b
, result
+ offset_b
,
906 max_search_distance_a
,
907 max_search_distance_b
,
908 map_line_number_in_b_to_a
);
912 /* Find the lines in the parent line range that most closely match the lines in
913 * the target line range. This is accomplished by matching fingerprints in each
914 * blame_origin, and choosing the best matches that preserve the line ordering.
915 * See struct fingerprint for details of fingerprint matching, and
916 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
918 * The performance is believed to be O(n log n) in the typical case and O(n^2)
919 * in a pathological case, where n is the number of lines in the target range.
921 static int *fuzzy_find_matching_lines(struct blame_origin
*parent
,
922 struct blame_origin
*target
,
923 int tlno
, int parent_slno
, int same
,
926 /* We use the terminology "A" for the left hand side of the diff AKA
927 * parent, and "B" for the right hand side of the diff AKA target. */
928 int start_a
= parent_slno
;
929 int length_a
= parent_len
;
931 int length_b
= same
- tlno
;
933 struct line_number_mapping map_line_number_in_b_to_a
= {
934 start_a
, length_a
, start_b
, length_b
937 struct fingerprint
*fingerprints_a
= parent
->fingerprints
;
938 struct fingerprint
*fingerprints_b
= target
->fingerprints
;
940 int i
, *result
, *second_best_result
,
941 *certainties
, *similarities
, similarity_count
;
944 * max_search_distance_a means that given a line in B, compare it to
945 * the line in A that is closest to its position, and the lines in A
946 * that are no greater than max_search_distance_a lines away from the
949 * max_search_distance_b is an upper bound on the greatest possible
950 * distance between lines in B such that they will both be compared
951 * with the same line in A according to max_search_distance_a.
953 int max_search_distance_a
= 10, max_search_distance_b
;
958 if (max_search_distance_a
>= length_a
)
959 max_search_distance_a
= length_a
? length_a
- 1 : 0;
961 max_search_distance_b
= ((2 * max_search_distance_a
+ 1) * length_b
964 CALLOC_ARRAY(result
, length_b
);
965 CALLOC_ARRAY(second_best_result
, length_b
);
966 CALLOC_ARRAY(certainties
, length_b
);
968 /* See get_similarity() for details of similarities. */
969 similarity_count
= length_b
* (max_search_distance_a
* 2 + 1);
970 CALLOC_ARRAY(similarities
, similarity_count
);
972 for (i
= 0; i
< length_b
; ++i
) {
974 second_best_result
[i
] = -1;
975 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
978 for (i
= 0; i
< similarity_count
; ++i
)
979 similarities
[i
] = -1;
981 fuzzy_find_matching_lines_recurse(start_a
, start_b
,
983 fingerprints_a
+ start_a
,
984 fingerprints_b
+ start_b
,
989 max_search_distance_a
,
990 max_search_distance_b
,
991 &map_line_number_in_b_to_a
);
995 free(second_best_result
);
1000 static void fill_origin_fingerprints(struct blame_origin
*o
)
1004 if (o
->fingerprints
)
1006 o
->num_lines
= find_line_starts(&line_starts
, o
->file
.ptr
,
1008 CALLOC_ARRAY(o
->fingerprints
, o
->num_lines
);
1009 get_line_fingerprints(o
->fingerprints
, o
->file
.ptr
, line_starts
,
1014 static void drop_origin_fingerprints(struct blame_origin
*o
)
1016 if (o
->fingerprints
) {
1017 free_line_fingerprints(o
->fingerprints
, o
->num_lines
);
1019 FREE_AND_NULL(o
->fingerprints
);
1024 * Given an origin, prepare mmfile_t structure to be used by the
1027 static void fill_origin_blob(struct diff_options
*opt
,
1028 struct blame_origin
*o
, mmfile_t
*file
,
1029 int *num_read_blob
, int fill_fingerprints
)
1032 enum object_type type
;
1033 unsigned long file_size
;
1036 if (opt
->flags
.allow_textconv
&&
1037 textconv_object(opt
->repo
, o
->path
, o
->mode
,
1038 &o
->blob_oid
, 1, &file
->ptr
, &file_size
))
1041 file
->ptr
= repo_read_object_file(the_repository
,
1042 &o
->blob_oid
, &type
,
1044 file
->size
= file_size
;
1047 die("Cannot read blob %s for path %s",
1048 oid_to_hex(&o
->blob_oid
),
1054 if (fill_fingerprints
)
1055 fill_origin_fingerprints(o
);
1058 static void drop_origin_blob(struct blame_origin
*o
)
1060 FREE_AND_NULL(o
->file
.ptr
);
1061 drop_origin_fingerprints(o
);
1065 * Any merge of blames happens on lists of blames that arrived via
1066 * different parents in a single suspect. In this case, we want to
1067 * sort according to the suspect line numbers as opposed to the final
1068 * image line numbers. The function body is somewhat longish because
1069 * it avoids unnecessary writes.
1072 static struct blame_entry
*blame_merge(struct blame_entry
*list1
,
1073 struct blame_entry
*list2
)
1075 struct blame_entry
*p1
= list1
, *p2
= list2
,
1083 if (p1
->s_lno
<= p2
->s_lno
) {
1086 if (!(p1
= *tail
)) {
1090 } while (p1
->s_lno
<= p2
->s_lno
);
1096 if (!(p2
= *tail
)) {
1100 } while (p1
->s_lno
> p2
->s_lno
);
1104 if (!(p1
= *tail
)) {
1108 } while (p1
->s_lno
<= p2
->s_lno
);
1112 DEFINE_LIST_SORT(static, sort_blame_entries
, struct blame_entry
, next
);
1115 * Final image line numbers are all different, so we don't need a
1116 * three-way comparison here.
1119 static int compare_blame_final(const struct blame_entry
*e1
,
1120 const struct blame_entry
*e2
)
1122 return e1
->lno
> e2
->lno
? 1 : -1;
1125 static int compare_blame_suspect(const struct blame_entry
*s1
,
1126 const struct blame_entry
*s2
)
1129 * to allow for collating suspects, we sort according to the
1130 * respective pointer value as the primary sorting criterion.
1131 * The actual relation is pretty unimportant as long as it
1132 * establishes a total order. Comparing as integers gives us
1135 if (s1
->suspect
!= s2
->suspect
)
1136 return (intptr_t)s1
->suspect
> (intptr_t)s2
->suspect
? 1 : -1;
1137 if (s1
->s_lno
== s2
->s_lno
)
1139 return s1
->s_lno
> s2
->s_lno
? 1 : -1;
1142 void blame_sort_final(struct blame_scoreboard
*sb
)
1144 sort_blame_entries(&sb
->ent
, compare_blame_final
);
1147 static int compare_commits_by_reverse_commit_date(const void *a
,
1151 return -compare_commits_by_commit_date(a
, b
, c
);
1155 * For debugging -- origin is refcounted, and this asserts that
1156 * we do not underflow.
1158 static void sanity_check_refcnt(struct blame_scoreboard
*sb
)
1161 struct blame_entry
*ent
;
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",
1168 oid_to_hex(&ent
->suspect
->commit
->object
.oid
),
1169 ent
->suspect
->refcnt
);
1174 sb
->on_sanity_fail(sb
, baa
);
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.
1182 void blame_coalesce(struct blame_scoreboard
*sb
)
1184 struct blame_entry
*ent
, *next
;
1186 for (ent
= sb
->ent
; ent
&& (next
= ent
->next
); ent
= next
) {
1187 if (ent
->suspect
== next
->suspect
&&
1188 ent
->s_lno
+ ent
->num_lines
== next
->s_lno
&&
1189 ent
->lno
+ ent
->num_lines
== next
->lno
&&
1190 ent
->ignored
== next
->ignored
&&
1191 ent
->unblamable
== next
->unblamable
) {
1192 ent
->num_lines
+= next
->num_lines
;
1193 ent
->next
= next
->next
;
1194 blame_origin_decref(next
->suspect
);
1197 next
= ent
; /* again */
1201 if (sb
->debug
) /* sanity */
1202 sanity_check_refcnt(sb
);
1206 * Merge the given sorted list of blames into a preexisting origin.
1207 * If there were no previous blames to that commit, it is entered into
1208 * the commit priority queue of the score board.
1211 static void queue_blames(struct blame_scoreboard
*sb
, struct blame_origin
*porigin
,
1212 struct blame_entry
*sorted
)
1214 if (porigin
->suspects
)
1215 porigin
->suspects
= blame_merge(porigin
->suspects
, sorted
);
1217 struct blame_origin
*o
;
1218 for (o
= get_blame_suspects(porigin
->commit
); o
; o
= o
->next
) {
1220 porigin
->suspects
= sorted
;
1224 porigin
->suspects
= sorted
;
1225 prio_queue_put(&sb
->commits
, porigin
->commit
);
1230 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1231 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1232 * for an origin is also used to pass the blame for the entire file to
1233 * the parent to detect the case where a child's blob is identical to
1234 * that of its parent's.
1236 * This also fills origin->mode for corresponding tree path.
1238 static int fill_blob_sha1_and_mode(struct repository
*r
,
1239 struct blame_origin
*origin
)
1241 if (!is_null_oid(&origin
->blob_oid
))
1243 if (get_tree_entry(r
, &origin
->commit
->object
.oid
, origin
->path
, &origin
->blob_oid
, &origin
->mode
))
1245 if (oid_object_info(r
, &origin
->blob_oid
, NULL
) != OBJ_BLOB
)
1249 oidclr(&origin
->blob_oid
);
1250 origin
->mode
= S_IFINVALID
;
1254 struct blame_bloom_data
{
1256 * Changed-path Bloom filter keys. These can help prevent
1257 * computing diffs against first parents, but we need to
1258 * expand the list as code is moved or files are renamed.
1260 struct bloom_filter_settings
*settings
;
1261 struct bloom_key
**keys
;
1266 static int bloom_count_queries
= 0;
1267 static int bloom_count_no
= 0;
1268 static int maybe_changed_path(struct repository
*r
,
1269 struct blame_origin
*origin
,
1270 struct blame_bloom_data
*bd
)
1273 struct bloom_filter
*filter
;
1278 if (commit_graph_generation(origin
->commit
) == GENERATION_NUMBER_INFINITY
)
1281 filter
= get_bloom_filter(r
, origin
->commit
);
1286 bloom_count_queries
++;
1287 for (i
= 0; i
< bd
->nr
; i
++) {
1288 if (bloom_filter_contains(filter
,
1298 static void add_bloom_key(struct blame_bloom_data
*bd
,
1304 if (bd
->nr
>= bd
->alloc
) {
1306 REALLOC_ARRAY(bd
->keys
, bd
->alloc
);
1309 bd
->keys
[bd
->nr
] = xmalloc(sizeof(struct bloom_key
));
1310 fill_bloom_key(path
, strlen(path
), bd
->keys
[bd
->nr
], bd
->settings
);
1315 * We have an origin -- check if the same path exists in the
1316 * parent and return an origin structure to represent it.
1318 static struct blame_origin
*find_origin(struct repository
*r
,
1319 struct commit
*parent
,
1320 struct blame_origin
*origin
,
1321 struct blame_bloom_data
*bd
)
1323 struct blame_origin
*porigin
;
1324 struct diff_options diff_opts
;
1325 const char *paths
[2];
1327 /* First check any existing origins */
1328 for (porigin
= get_blame_suspects(parent
); porigin
; porigin
= porigin
->next
)
1329 if (!strcmp(porigin
->path
, origin
->path
)) {
1331 * The same path between origin and its parent
1332 * without renaming -- the most common case.
1334 return blame_origin_incref (porigin
);
1337 /* See if the origin->path is different between parent
1338 * and origin first. Most of the time they are the
1339 * same and diff-tree is fairly efficient about this.
1341 repo_diff_setup(r
, &diff_opts
);
1342 diff_opts
.flags
.recursive
= 1;
1343 diff_opts
.detect_rename
= 0;
1344 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1345 paths
[0] = origin
->path
;
1348 parse_pathspec(&diff_opts
.pathspec
,
1349 PATHSPEC_ALL_MAGIC
& ~PATHSPEC_LITERAL
,
1350 PATHSPEC_LITERAL_PATH
, "", paths
);
1351 diff_setup_done(&diff_opts
);
1353 if (is_null_oid(&origin
->commit
->object
.oid
))
1354 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1356 int compute_diff
= 1;
1357 if (origin
->commit
->parents
&&
1358 oideq(&parent
->object
.oid
,
1359 &origin
->commit
->parents
->item
->object
.oid
))
1360 compute_diff
= maybe_changed_path(r
, origin
, bd
);
1363 diff_tree_oid(get_commit_tree_oid(parent
),
1364 get_commit_tree_oid(origin
->commit
),
1367 diffcore_std(&diff_opts
);
1369 if (!diff_queued_diff
.nr
) {
1370 /* The path is the same as parent */
1371 porigin
= get_origin(parent
, origin
->path
);
1372 oidcpy(&porigin
->blob_oid
, &origin
->blob_oid
);
1373 porigin
->mode
= origin
->mode
;
1376 * Since origin->path is a pathspec, if the parent
1377 * commit had it as a directory, we will see a whole
1378 * bunch of deletion of files in the directory that we
1379 * do not care about.
1382 struct diff_filepair
*p
= NULL
;
1383 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1385 p
= diff_queued_diff
.queue
[i
];
1386 name
= p
->one
->path
? p
->one
->path
: p
->two
->path
;
1387 if (!strcmp(name
, origin
->path
))
1391 die("internal error in blame::find_origin");
1392 switch (p
->status
) {
1394 die("internal error in blame::find_origin (%c)",
1397 porigin
= get_origin(parent
, origin
->path
);
1398 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1399 porigin
->mode
= p
->one
->mode
;
1403 /* Did not exist in parent, or type changed */
1407 diff_flush(&diff_opts
);
1412 * We have an origin -- find the path that corresponds to it in its
1413 * parent and return an origin structure to represent it.
1415 static struct blame_origin
*find_rename(struct repository
*r
,
1416 struct commit
*parent
,
1417 struct blame_origin
*origin
,
1418 struct blame_bloom_data
*bd
)
1420 struct blame_origin
*porigin
= NULL
;
1421 struct diff_options diff_opts
;
1424 repo_diff_setup(r
, &diff_opts
);
1425 diff_opts
.flags
.recursive
= 1;
1426 diff_opts
.detect_rename
= DIFF_DETECT_RENAME
;
1427 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1428 diff_opts
.single_follow
= origin
->path
;
1429 diff_setup_done(&diff_opts
);
1431 if (is_null_oid(&origin
->commit
->object
.oid
))
1432 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1434 diff_tree_oid(get_commit_tree_oid(parent
),
1435 get_commit_tree_oid(origin
->commit
),
1437 diffcore_std(&diff_opts
);
1439 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1440 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
1441 if ((p
->status
== 'R' || p
->status
== 'C') &&
1442 !strcmp(p
->two
->path
, origin
->path
)) {
1443 add_bloom_key(bd
, p
->one
->path
);
1444 porigin
= get_origin(parent
, p
->one
->path
);
1445 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1446 porigin
->mode
= p
->one
->mode
;
1450 diff_flush(&diff_opts
);
1455 * Append a new blame entry to a given output queue.
1457 static void add_blame_entry(struct blame_entry
***queue
,
1458 const struct blame_entry
*src
)
1460 struct blame_entry
*e
= xmalloc(sizeof(*e
));
1461 memcpy(e
, src
, sizeof(*e
));
1462 blame_origin_incref(e
->suspect
);
1470 * src typically is on-stack; we want to copy the information in it to
1471 * a malloced blame_entry that gets added to the given queue. The
1472 * origin of dst loses a refcnt.
1474 static void dup_entry(struct blame_entry
***queue
,
1475 struct blame_entry
*dst
, struct blame_entry
*src
)
1477 blame_origin_incref(src
->suspect
);
1478 blame_origin_decref(dst
->suspect
);
1479 memcpy(dst
, src
, sizeof(*src
));
1480 dst
->next
= **queue
;
1482 *queue
= &dst
->next
;
1485 const char *blame_nth_line(struct blame_scoreboard
*sb
, long lno
)
1487 return sb
->final_buf
+ sb
->lineno
[lno
];
1491 * It is known that lines between tlno to same came from parent, and e
1492 * has an overlap with that range. it also is known that parent's
1493 * line plno corresponds to e's line tlno.
1499 * <------------------>
1501 * Split e into potentially three parts; before this chunk, the chunk
1502 * to be blamed for the parent, and after that portion.
1504 static void split_overlap(struct blame_entry
*split
,
1505 struct blame_entry
*e
,
1506 int tlno
, int plno
, int same
,
1507 struct blame_origin
*parent
)
1511 memset(split
, 0, sizeof(struct blame_entry
[3]));
1513 for (i
= 0; i
< 3; i
++) {
1514 split
[i
].ignored
= e
->ignored
;
1515 split
[i
].unblamable
= e
->unblamable
;
1518 if (e
->s_lno
< tlno
) {
1519 /* there is a pre-chunk part not blamed on parent */
1520 split
[0].suspect
= blame_origin_incref(e
->suspect
);
1521 split
[0].lno
= e
->lno
;
1522 split
[0].s_lno
= e
->s_lno
;
1523 split
[0].num_lines
= tlno
- e
->s_lno
;
1524 split
[1].lno
= e
->lno
+ tlno
- e
->s_lno
;
1525 split
[1].s_lno
= plno
;
1528 split
[1].lno
= e
->lno
;
1529 split
[1].s_lno
= plno
+ (e
->s_lno
- tlno
);
1532 if (same
< e
->s_lno
+ e
->num_lines
) {
1533 /* there is a post-chunk part not blamed on parent */
1534 split
[2].suspect
= blame_origin_incref(e
->suspect
);
1535 split
[2].lno
= e
->lno
+ (same
- e
->s_lno
);
1536 split
[2].s_lno
= e
->s_lno
+ (same
- e
->s_lno
);
1537 split
[2].num_lines
= e
->s_lno
+ e
->num_lines
- same
;
1538 chunk_end_lno
= split
[2].lno
;
1541 chunk_end_lno
= e
->lno
+ e
->num_lines
;
1542 split
[1].num_lines
= chunk_end_lno
- split
[1].lno
;
1545 * if it turns out there is nothing to blame the parent for,
1546 * forget about the splitting. !split[1].suspect signals this.
1548 if (split
[1].num_lines
< 1)
1550 split
[1].suspect
= blame_origin_incref(parent
);
1554 * split_overlap() divided an existing blame e into up to three parts
1555 * in split. Any assigned blame is moved to queue to
1556 * reflect the split.
1558 static void split_blame(struct blame_entry
***blamed
,
1559 struct blame_entry
***unblamed
,
1560 struct blame_entry
*split
,
1561 struct blame_entry
*e
)
1563 if (split
[0].suspect
&& split
[2].suspect
) {
1564 /* The first part (reuse storage for the existing entry e) */
1565 dup_entry(unblamed
, e
, &split
[0]);
1567 /* The last part -- me */
1568 add_blame_entry(unblamed
, &split
[2]);
1570 /* ... and the middle part -- parent */
1571 add_blame_entry(blamed
, &split
[1]);
1573 else if (!split
[0].suspect
&& !split
[2].suspect
)
1575 * The parent covers the entire area; reuse storage for
1576 * e and replace it with the parent.
1578 dup_entry(blamed
, e
, &split
[1]);
1579 else if (split
[0].suspect
) {
1580 /* me and then parent */
1581 dup_entry(unblamed
, e
, &split
[0]);
1582 add_blame_entry(blamed
, &split
[1]);
1585 /* parent and then me */
1586 dup_entry(blamed
, e
, &split
[1]);
1587 add_blame_entry(unblamed
, &split
[2]);
1592 * After splitting the blame, the origins used by the
1593 * on-stack blame_entry should lose one refcnt each.
1595 static void decref_split(struct blame_entry
*split
)
1599 for (i
= 0; i
< 3; i
++)
1600 blame_origin_decref(split
[i
].suspect
);
1604 * reverse_blame reverses the list given in head, appending tail.
1605 * That allows us to build lists in reverse order, then reverse them
1606 * afterwards. This can be faster than building the list in proper
1607 * order right away. The reason is that building in proper order
1608 * requires writing a link in the _previous_ element, while building
1609 * in reverse order just requires placing the list head into the
1610 * _current_ element.
1613 static struct blame_entry
*reverse_blame(struct blame_entry
*head
,
1614 struct blame_entry
*tail
)
1617 struct blame_entry
*next
= head
->next
;
1626 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1627 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1628 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1629 * e->num_lines). The caller needs to sort out the reference counting for the
1630 * new entry's suspect.
1632 static struct blame_entry
*split_blame_at(struct blame_entry
*e
, int len
,
1633 struct blame_origin
*new_suspect
)
1635 struct blame_entry
*n
= xcalloc(1, sizeof(struct blame_entry
));
1637 n
->suspect
= new_suspect
;
1638 n
->ignored
= e
->ignored
;
1639 n
->unblamable
= e
->unblamable
;
1640 n
->lno
= e
->lno
+ len
;
1641 n
->s_lno
= e
->s_lno
+ len
;
1642 n
->num_lines
= e
->num_lines
- len
;
1648 struct blame_line_tracker
{
1653 static int are_lines_adjacent(struct blame_line_tracker
*first
,
1654 struct blame_line_tracker
*second
)
1656 return first
->is_parent
== second
->is_parent
&&
1657 first
->s_lno
+ 1 == second
->s_lno
;
1660 static int scan_parent_range(struct fingerprint
*p_fps
,
1661 struct fingerprint
*t_fps
, int t_idx
,
1662 int from
, int nr_lines
)
1665 #define FINGERPRINT_FILE_THRESHOLD 10
1666 int best_sim_val
= FINGERPRINT_FILE_THRESHOLD
;
1667 int best_sim_idx
= -1;
1669 for (p_idx
= from
; p_idx
< from
+ nr_lines
; p_idx
++) {
1670 sim
= fingerprint_similarity(&t_fps
[t_idx
], &p_fps
[p_idx
]);
1671 if (sim
< best_sim_val
)
1673 /* Break ties with the closest-to-target line number */
1674 if (sim
== best_sim_val
&& best_sim_idx
!= -1 &&
1675 abs(best_sim_idx
- t_idx
) < abs(p_idx
- t_idx
))
1678 best_sim_idx
= p_idx
;
1680 return best_sim_idx
;
1684 * The first pass checks the blame entry (from the target) against the parent's
1685 * diff chunk. If that fails for a line, the second pass tries to match that
1686 * line to any part of parent file. That catches cases where a change was
1687 * broken into two chunks by 'context.'
1689 static void guess_line_blames(struct blame_origin
*parent
,
1690 struct blame_origin
*target
,
1691 int tlno
, int offset
, int same
, int parent_len
,
1692 struct blame_line_tracker
*line_blames
)
1694 int i
, best_idx
, target_idx
;
1695 int parent_slno
= tlno
+ offset
;
1698 fuzzy_matches
= fuzzy_find_matching_lines(parent
, target
,
1699 tlno
, parent_slno
, same
,
1701 for (i
= 0; i
< same
- tlno
; i
++) {
1702 target_idx
= tlno
+ i
;
1703 if (fuzzy_matches
&& fuzzy_matches
[i
] >= 0) {
1704 best_idx
= fuzzy_matches
[i
];
1706 best_idx
= scan_parent_range(parent
->fingerprints
,
1707 target
->fingerprints
,
1711 if (best_idx
>= 0) {
1712 line_blames
[i
].is_parent
= 1;
1713 line_blames
[i
].s_lno
= best_idx
;
1715 line_blames
[i
].is_parent
= 0;
1716 line_blames
[i
].s_lno
= target_idx
;
1719 free(fuzzy_matches
);
1723 * This decides which parts of a blame entry go to the parent (added to the
1724 * ignoredp list) and which stay with the target (added to the diffp list). The
1725 * actual decision was made in a separate heuristic function, and those answers
1726 * for the lines in 'e' are in line_blames. This consumes e, essentially
1727 * putting it on a list.
1729 * Note that the blame entries on the ignoredp list are not necessarily sorted
1730 * with respect to the parent's line numbers yet.
1732 static void ignore_blame_entry(struct blame_entry
*e
,
1733 struct blame_origin
*parent
,
1734 struct blame_entry
**diffp
,
1735 struct blame_entry
**ignoredp
,
1736 struct blame_line_tracker
*line_blames
)
1738 int entry_len
, nr_lines
, i
;
1741 * We carve new entries off the front of e. Each entry comes from a
1742 * contiguous chunk of lines: adjacent lines from the same origin
1743 * (either the parent or the target).
1746 nr_lines
= e
->num_lines
; /* e changes in the loop */
1747 for (i
= 0; i
< nr_lines
; i
++) {
1748 struct blame_entry
*next
= NULL
;
1751 * We are often adjacent to the next line - only split the blame
1752 * entry when we have to.
1754 if (i
+ 1 < nr_lines
) {
1755 if (are_lines_adjacent(&line_blames
[i
],
1756 &line_blames
[i
+ 1])) {
1760 next
= split_blame_at(e
, entry_len
,
1761 blame_origin_incref(e
->suspect
));
1763 if (line_blames
[i
].is_parent
) {
1765 blame_origin_decref(e
->suspect
);
1766 e
->suspect
= blame_origin_incref(parent
);
1767 e
->s_lno
= line_blames
[i
- entry_len
+ 1].s_lno
;
1768 e
->next
= *ignoredp
;
1772 /* e->s_lno is already in the target's address space. */
1776 assert(e
->num_lines
== entry_len
);
1784 * Process one hunk from the patch between the current suspect for
1785 * blame_entry e and its parent. This first blames any unfinished
1786 * entries before the chunk (which is where target and parent start
1787 * differing) on the parent, and then splits blame entries at the
1788 * start and at the end of the difference region. Since use of -M and
1789 * -C options may lead to overlapping/duplicate source line number
1790 * ranges, all we can rely on from sorting/merging is the order of the
1791 * first suspect line number.
1793 * tlno: line number in the target where this chunk begins
1794 * same: line number in the target where this chunk ends
1795 * offset: add to tlno to get the chunk starting point in the parent
1796 * parent_len: number of lines in the parent chunk
1798 static void blame_chunk(struct blame_entry
***dstq
, struct blame_entry
***srcq
,
1799 int tlno
, int offset
, int same
, int parent_len
,
1800 struct blame_origin
*parent
,
1801 struct blame_origin
*target
, int ignore_diffs
)
1803 struct blame_entry
*e
= **srcq
;
1804 struct blame_entry
*samep
= NULL
, *diffp
= NULL
, *ignoredp
= NULL
;
1805 struct blame_line_tracker
*line_blames
= NULL
;
1807 while (e
&& e
->s_lno
< tlno
) {
1808 struct blame_entry
*next
= e
->next
;
1810 * current record starts before differing portion. If
1811 * it reaches into it, we need to split it up and
1812 * examine the second part separately.
1814 if (e
->s_lno
+ e
->num_lines
> tlno
) {
1815 /* Move second half to a new record */
1816 struct blame_entry
*n
;
1818 n
= split_blame_at(e
, tlno
- e
->s_lno
, e
->suspect
);
1819 /* Push new record to diffp */
1823 blame_origin_decref(e
->suspect
);
1824 /* Pass blame for everything before the differing
1825 * chunk to the parent */
1826 e
->suspect
= blame_origin_incref(parent
);
1833 * As we don't know how much of a common stretch after this
1834 * diff will occur, the currently blamed parts are all that we
1835 * can assign to the parent for now.
1839 **dstq
= reverse_blame(samep
, **dstq
);
1840 *dstq
= &samep
->next
;
1843 * Prepend the split off portions: everything after e starts
1844 * after the blameable portion.
1846 e
= reverse_blame(diffp
, e
);
1849 * Now retain records on the target while parts are different
1855 if (ignore_diffs
&& same
- tlno
> 0) {
1856 CALLOC_ARRAY(line_blames
, same
- tlno
);
1857 guess_line_blames(parent
, target
, tlno
, offset
, same
,
1858 parent_len
, line_blames
);
1861 while (e
&& e
->s_lno
< same
) {
1862 struct blame_entry
*next
= e
->next
;
1865 * If current record extends into sameness, need to split.
1867 if (e
->s_lno
+ e
->num_lines
> same
) {
1869 * Move second half to a new record to be
1870 * processed by later chunks
1872 struct blame_entry
*n
;
1874 n
= split_blame_at(e
, same
- e
->s_lno
,
1875 blame_origin_incref(e
->suspect
));
1876 /* Push new record to samep */
1881 ignore_blame_entry(e
, parent
, &diffp
, &ignoredp
,
1882 line_blames
+ e
->s_lno
- tlno
);
1892 * Note ignoredp is not sorted yet, and thus neither is dstq.
1893 * That list must be sorted before we queue_blames(). We defer
1894 * sorting until after all diff hunks are processed, so that
1895 * guess_line_blames() can pick *any* line in the parent. The
1896 * slight drawback is that we end up sorting all blame entries
1897 * passed to the parent, including those that are unrelated to
1898 * changes made by the ignored commit.
1900 **dstq
= reverse_blame(ignoredp
, **dstq
);
1901 *dstq
= &ignoredp
->next
;
1903 **srcq
= reverse_blame(diffp
, reverse_blame(samep
, e
));
1904 /* Move across elements that are in the unblamable portion */
1906 *srcq
= &diffp
->next
;
1909 struct blame_chunk_cb_data
{
1910 struct blame_origin
*parent
;
1911 struct blame_origin
*target
;
1914 struct blame_entry
**dstq
;
1915 struct blame_entry
**srcq
;
1918 /* diff chunks are from parent to target */
1919 static int blame_chunk_cb(long start_a
, long count_a
,
1920 long start_b
, long count_b
, void *data
)
1922 struct blame_chunk_cb_data
*d
= data
;
1923 if (start_a
- start_b
!= d
->offset
)
1924 die("internal error in blame::blame_chunk_cb");
1925 blame_chunk(&d
->dstq
, &d
->srcq
, start_b
, start_a
- start_b
,
1926 start_b
+ count_b
, count_a
, d
->parent
, d
->target
,
1928 d
->offset
= start_a
+ count_a
- (start_b
+ count_b
);
1933 * We are looking at the origin 'target' and aiming to pass blame
1934 * for the lines it is suspected to its parent. Run diff to find
1935 * which lines came from parent and pass blame for them.
1937 static void pass_blame_to_parent(struct blame_scoreboard
*sb
,
1938 struct blame_origin
*target
,
1939 struct blame_origin
*parent
, int ignore_diffs
)
1941 mmfile_t file_p
, file_o
;
1942 struct blame_chunk_cb_data d
;
1943 struct blame_entry
*newdest
= NULL
;
1945 if (!target
->suspects
)
1946 return; /* nothing remains for this target */
1951 d
.ignore_diffs
= ignore_diffs
;
1952 d
.dstq
= &newdest
; d
.srcq
= &target
->suspects
;
1954 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
1955 &sb
->num_read_blob
, ignore_diffs
);
1956 fill_origin_blob(&sb
->revs
->diffopt
, target
, &file_o
,
1957 &sb
->num_read_blob
, ignore_diffs
);
1958 sb
->num_get_patch
++;
1960 if (diff_hunks(&file_p
, &file_o
, blame_chunk_cb
, &d
, sb
->xdl_opts
))
1961 die("unable to generate diff (%s -> %s)",
1962 oid_to_hex(&parent
->commit
->object
.oid
),
1963 oid_to_hex(&target
->commit
->object
.oid
));
1964 /* The rest are the same as the parent */
1965 blame_chunk(&d
.dstq
, &d
.srcq
, INT_MAX
, d
.offset
, INT_MAX
, 0,
1969 sort_blame_entries(&newdest
, compare_blame_suspect
);
1970 queue_blames(sb
, parent
, newdest
);
1976 * The lines in blame_entry after splitting blames many times can become
1977 * very small and trivial, and at some point it becomes pointless to
1978 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1979 * ordinary C program, and it is not worth to say it was copied from
1980 * totally unrelated file in the parent.
1982 * Compute how trivial the lines in the blame_entry are.
1984 unsigned blame_entry_score(struct blame_scoreboard
*sb
, struct blame_entry
*e
)
1987 const char *cp
, *ep
;
1993 cp
= blame_nth_line(sb
, e
->lno
);
1994 ep
= blame_nth_line(sb
, e
->lno
+ e
->num_lines
);
1996 unsigned ch
= *((unsigned char *)cp
);
2006 * best_so_far[] and potential[] are both a split of an existing blame_entry
2007 * that passes blame to the parent. Maintain best_so_far the best split so
2008 * far, by comparing potential and best_so_far and copying potential into
2009 * bst_so_far as needed.
2011 static void copy_split_if_better(struct blame_scoreboard
*sb
,
2012 struct blame_entry
*best_so_far
,
2013 struct blame_entry
*potential
)
2017 if (!potential
[1].suspect
)
2019 if (best_so_far
[1].suspect
) {
2020 if (blame_entry_score(sb
, &potential
[1]) <
2021 blame_entry_score(sb
, &best_so_far
[1]))
2025 for (i
= 0; i
< 3; i
++)
2026 blame_origin_incref(potential
[i
].suspect
);
2027 decref_split(best_so_far
);
2028 memcpy(best_so_far
, potential
, sizeof(struct blame_entry
[3]));
2032 * We are looking at a part of the final image represented by
2033 * ent (tlno and same are offset by ent->s_lno).
2034 * tlno is where we are looking at in the final image.
2035 * up to (but not including) same match preimage.
2036 * plno is where we are looking at in the preimage.
2038 * <-------------- final image ---------------------->
2041 * <---------preimage----->
2044 * All line numbers are 0-based.
2046 static void handle_split(struct blame_scoreboard
*sb
,
2047 struct blame_entry
*ent
,
2048 int tlno
, int plno
, int same
,
2049 struct blame_origin
*parent
,
2050 struct blame_entry
*split
)
2052 if (ent
->num_lines
<= tlno
)
2055 struct blame_entry potential
[3];
2058 split_overlap(potential
, ent
, tlno
, plno
, same
, parent
);
2059 copy_split_if_better(sb
, split
, potential
);
2060 decref_split(potential
);
2064 struct handle_split_cb_data
{
2065 struct blame_scoreboard
*sb
;
2066 struct blame_entry
*ent
;
2067 struct blame_origin
*parent
;
2068 struct blame_entry
*split
;
2073 static int handle_split_cb(long start_a
, long count_a
,
2074 long start_b
, long count_b
, void *data
)
2076 struct handle_split_cb_data
*d
= data
;
2077 handle_split(d
->sb
, d
->ent
, d
->tlno
, d
->plno
, start_b
, d
->parent
,
2079 d
->plno
= start_a
+ count_a
;
2080 d
->tlno
= start_b
+ count_b
;
2085 * Find the lines from parent that are the same as ent so that
2086 * we can pass blames to it. file_p has the blob contents for
2089 static void find_copy_in_blob(struct blame_scoreboard
*sb
,
2090 struct blame_entry
*ent
,
2091 struct blame_origin
*parent
,
2092 struct blame_entry
*split
,
2097 struct handle_split_cb_data d
;
2099 memset(&d
, 0, sizeof(d
));
2100 d
.sb
= sb
; d
.ent
= ent
; d
.parent
= parent
; d
.split
= split
;
2102 * Prepare mmfile that contains only the lines in ent.
2104 cp
= blame_nth_line(sb
, ent
->lno
);
2105 file_o
.ptr
= (char *) cp
;
2106 file_o
.size
= blame_nth_line(sb
, ent
->lno
+ ent
->num_lines
) - cp
;
2109 * file_o is a part of final image we are annotating.
2110 * file_p partially may match that image.
2112 memset(split
, 0, sizeof(struct blame_entry
[3]));
2113 if (diff_hunks(file_p
, &file_o
, handle_split_cb
, &d
, sb
->xdl_opts
))
2114 die("unable to generate diff (%s)",
2115 oid_to_hex(&parent
->commit
->object
.oid
));
2116 /* remainder, if any, all match the preimage */
2117 handle_split(sb
, ent
, d
.tlno
, d
.plno
, ent
->num_lines
, parent
, split
);
2120 /* Move all blame entries from list *source that have a score smaller
2121 * than score_min to the front of list *small.
2122 * Returns a pointer to the link pointing to the old head of the small list.
2125 static struct blame_entry
**filter_small(struct blame_scoreboard
*sb
,
2126 struct blame_entry
**small
,
2127 struct blame_entry
**source
,
2130 struct blame_entry
*p
= *source
;
2131 struct blame_entry
*oldsmall
= *small
;
2133 if (blame_entry_score(sb
, p
) <= score_min
) {
2149 * See if lines currently target is suspected for can be attributed to
2152 static void find_move_in_parent(struct blame_scoreboard
*sb
,
2153 struct blame_entry
***blamed
,
2154 struct blame_entry
**toosmall
,
2155 struct blame_origin
*target
,
2156 struct blame_origin
*parent
)
2158 struct blame_entry
*e
, split
[3];
2159 struct blame_entry
*unblamed
= target
->suspects
;
2160 struct blame_entry
*leftover
= NULL
;
2164 return; /* nothing remains for this target */
2166 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
2167 &sb
->num_read_blob
, 0);
2171 /* At each iteration, unblamed has a NULL-terminated list of
2172 * entries that have not yet been tested for blame. leftover
2173 * contains the reversed list of entries that have been tested
2174 * without being assignable to the parent.
2177 struct blame_entry
**unblamedtail
= &unblamed
;
2178 struct blame_entry
*next
;
2179 for (e
= unblamed
; e
; e
= next
) {
2181 find_copy_in_blob(sb
, e
, parent
, split
, &file_p
);
2182 if (split
[1].suspect
&&
2183 sb
->move_score
< blame_entry_score(sb
, &split
[1])) {
2184 split_blame(blamed
, &unblamedtail
, split
, e
);
2189 decref_split(split
);
2191 *unblamedtail
= NULL
;
2192 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->move_score
);
2194 target
->suspects
= reverse_blame(leftover
, NULL
);
2198 struct blame_entry
*ent
;
2199 struct blame_entry split
[3];
2203 * Count the number of entries the target is suspected for,
2204 * and prepare a list of entry and the best split.
2206 static struct blame_list
*setup_blame_list(struct blame_entry
*unblamed
,
2209 struct blame_entry
*e
;
2211 struct blame_list
*blame_list
= NULL
;
2213 for (e
= unblamed
, num_ents
= 0; e
; e
= e
->next
)
2216 CALLOC_ARRAY(blame_list
, num_ents
);
2217 for (e
= unblamed
, i
= 0; e
; e
= e
->next
)
2218 blame_list
[i
++].ent
= e
;
2220 *num_ents_p
= num_ents
;
2225 * For lines target is suspected for, see if we can find code movement
2226 * across file boundary from the parent commit. porigin is the path
2227 * in the parent we already tried.
2229 static void find_copy_in_parent(struct blame_scoreboard
*sb
,
2230 struct blame_entry
***blamed
,
2231 struct blame_entry
**toosmall
,
2232 struct blame_origin
*target
,
2233 struct commit
*parent
,
2234 struct blame_origin
*porigin
,
2237 struct diff_options diff_opts
;
2239 struct blame_list
*blame_list
;
2241 struct blame_entry
*unblamed
= target
->suspects
;
2242 struct blame_entry
*leftover
= NULL
;
2245 return; /* nothing remains for this target */
2247 repo_diff_setup(sb
->repo
, &diff_opts
);
2248 diff_opts
.flags
.recursive
= 1;
2249 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
2251 diff_setup_done(&diff_opts
);
2253 /* Try "find copies harder" on new path if requested;
2254 * we do not want to use diffcore_rename() actually to
2255 * match things up; find_copies_harder is set only to
2256 * force diff_tree_oid() to feed all filepairs to diff_queue,
2257 * and this code needs to be after diff_setup_done(), which
2258 * usually makes find-copies-harder imply copy detection.
2260 if ((opt
& PICKAXE_BLAME_COPY_HARDEST
)
2261 || ((opt
& PICKAXE_BLAME_COPY_HARDER
)
2262 && (!porigin
|| strcmp(target
->path
, porigin
->path
))))
2263 diff_opts
.flags
.find_copies_harder
= 1;
2265 if (is_null_oid(&target
->commit
->object
.oid
))
2266 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
2268 diff_tree_oid(get_commit_tree_oid(parent
),
2269 get_commit_tree_oid(target
->commit
),
2272 if (!diff_opts
.flags
.find_copies_harder
)
2273 diffcore_std(&diff_opts
);
2276 struct blame_entry
**unblamedtail
= &unblamed
;
2277 blame_list
= setup_blame_list(unblamed
, &num_ents
);
2279 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
2280 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
2281 struct blame_origin
*norigin
;
2283 struct blame_entry potential
[3];
2285 if (!DIFF_FILE_VALID(p
->one
))
2286 continue; /* does not exist in parent */
2287 if (S_ISGITLINK(p
->one
->mode
))
2288 continue; /* ignore git links */
2289 if (porigin
&& !strcmp(p
->one
->path
, porigin
->path
))
2290 /* find_move already dealt with this path */
2293 norigin
= get_origin(parent
, p
->one
->path
);
2294 oidcpy(&norigin
->blob_oid
, &p
->one
->oid
);
2295 norigin
->mode
= p
->one
->mode
;
2296 fill_origin_blob(&sb
->revs
->diffopt
, norigin
, &file_p
,
2297 &sb
->num_read_blob
, 0);
2301 for (j
= 0; j
< num_ents
; j
++) {
2302 find_copy_in_blob(sb
, blame_list
[j
].ent
,
2303 norigin
, potential
, &file_p
);
2304 copy_split_if_better(sb
, blame_list
[j
].split
,
2306 decref_split(potential
);
2308 blame_origin_decref(norigin
);
2311 for (j
= 0; j
< num_ents
; j
++) {
2312 struct blame_entry
*split
= blame_list
[j
].split
;
2313 if (split
[1].suspect
&&
2314 sb
->copy_score
< blame_entry_score(sb
, &split
[1])) {
2315 split_blame(blamed
, &unblamedtail
, split
,
2318 blame_list
[j
].ent
->next
= leftover
;
2319 leftover
= blame_list
[j
].ent
;
2321 decref_split(split
);
2324 *unblamedtail
= NULL
;
2325 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->copy_score
);
2327 target
->suspects
= reverse_blame(leftover
, NULL
);
2328 diff_flush(&diff_opts
);
2332 * The blobs of origin and porigin exactly match, so everything
2333 * origin is suspected for can be blamed on the parent.
2335 static void pass_whole_blame(struct blame_scoreboard
*sb
,
2336 struct blame_origin
*origin
, struct blame_origin
*porigin
)
2338 struct blame_entry
*e
, *suspects
;
2340 if (!porigin
->file
.ptr
&& origin
->file
.ptr
) {
2341 /* Steal its file */
2342 porigin
->file
= origin
->file
;
2343 origin
->file
.ptr
= NULL
;
2345 suspects
= origin
->suspects
;
2346 origin
->suspects
= NULL
;
2347 for (e
= suspects
; e
; e
= e
->next
) {
2348 blame_origin_incref(porigin
);
2349 blame_origin_decref(e
->suspect
);
2350 e
->suspect
= porigin
;
2352 queue_blames(sb
, porigin
, suspects
);
2356 * We pass blame from the current commit to its parents. We keep saying
2357 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2358 * exonerate ourselves.
2360 static struct commit_list
*first_scapegoat(struct rev_info
*revs
, struct commit
*commit
,
2364 if (revs
->first_parent_only
&&
2366 commit
->parents
->next
) {
2367 free_commit_list(commit
->parents
->next
);
2368 commit
->parents
->next
= NULL
;
2370 return commit
->parents
;
2372 return lookup_decoration(&revs
->children
, &commit
->object
);
2375 static int num_scapegoats(struct rev_info
*revs
, struct commit
*commit
, int reverse
)
2377 struct commit_list
*l
= first_scapegoat(revs
, commit
, reverse
);
2378 return commit_list_count(l
);
2381 /* Distribute collected unsorted blames to the respected sorted lists
2382 * in the various origins.
2384 static void distribute_blame(struct blame_scoreboard
*sb
, struct blame_entry
*blamed
)
2386 sort_blame_entries(&blamed
, compare_blame_suspect
);
2389 struct blame_origin
*porigin
= blamed
->suspect
;
2390 struct blame_entry
*suspects
= NULL
;
2392 struct blame_entry
*next
= blamed
->next
;
2393 blamed
->next
= suspects
;
2396 } while (blamed
&& blamed
->suspect
== porigin
);
2397 suspects
= reverse_blame(suspects
, NULL
);
2398 queue_blames(sb
, porigin
, suspects
);
2404 typedef struct blame_origin
*(*blame_find_alg
)(struct repository
*,
2406 struct blame_origin
*,
2407 struct blame_bloom_data
*);
2409 static void pass_blame(struct blame_scoreboard
*sb
, struct blame_origin
*origin
, int opt
)
2411 struct rev_info
*revs
= sb
->revs
;
2412 int i
, pass
, num_sg
;
2413 struct commit
*commit
= origin
->commit
;
2414 struct commit_list
*sg
;
2415 struct blame_origin
*sg_buf
[MAXSG
];
2416 struct blame_origin
*porigin
, **sg_origin
= sg_buf
;
2417 struct blame_entry
*toosmall
= NULL
;
2418 struct blame_entry
*blames
, **blametail
= &blames
;
2420 num_sg
= num_scapegoats(revs
, commit
, sb
->reverse
);
2423 else if (num_sg
< ARRAY_SIZE(sg_buf
))
2424 memset(sg_buf
, 0, sizeof(sg_buf
));
2426 CALLOC_ARRAY(sg_origin
, num_sg
);
2429 * The first pass looks for unrenamed path to optimize for
2430 * common cases, then we look for renames in the second pass.
2432 for (pass
= 0; pass
< 2 - sb
->no_whole_file_rename
; pass
++) {
2433 blame_find_alg find
= pass
? find_rename
: find_origin
;
2435 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2437 sg
= sg
->next
, i
++) {
2438 struct commit
*p
= sg
->item
;
2443 if (repo_parse_commit(the_repository
, p
))
2445 porigin
= find(sb
->repo
, p
, origin
, sb
->bloom_data
);
2448 if (oideq(&porigin
->blob_oid
, &origin
->blob_oid
)) {
2449 pass_whole_blame(sb
, origin
, porigin
);
2450 blame_origin_decref(porigin
);
2453 for (j
= same
= 0; j
< i
; j
++)
2455 oideq(&sg_origin
[j
]->blob_oid
, &porigin
->blob_oid
)) {
2460 sg_origin
[i
] = porigin
;
2462 blame_origin_decref(porigin
);
2467 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2469 sg
= sg
->next
, i
++) {
2470 struct blame_origin
*porigin
= sg_origin
[i
];
2473 if (!origin
->previous
) {
2474 blame_origin_incref(porigin
);
2475 origin
->previous
= porigin
;
2477 pass_blame_to_parent(sb
, origin
, porigin
, 0);
2478 if (!origin
->suspects
)
2483 * Pass remaining suspects for ignored commits to their parents.
2485 if (oidset_contains(&sb
->ignore_list
, &commit
->object
.oid
)) {
2486 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2488 sg
= sg
->next
, i
++) {
2489 struct blame_origin
*porigin
= sg_origin
[i
];
2493 pass_blame_to_parent(sb
, origin
, porigin
, 1);
2495 * Preemptively drop porigin so we can refresh the
2496 * fingerprints if we use the parent again, which can
2497 * occur if you ignore back-to-back commits.
2499 drop_origin_blob(porigin
);
2500 if (!origin
->suspects
)
2506 * Optionally find moves in parents' files.
2508 if (opt
& PICKAXE_BLAME_MOVE
) {
2509 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->move_score
);
2510 if (origin
->suspects
) {
2511 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2513 sg
= sg
->next
, i
++) {
2514 struct blame_origin
*porigin
= sg_origin
[i
];
2517 find_move_in_parent(sb
, &blametail
, &toosmall
, origin
, porigin
);
2518 if (!origin
->suspects
)
2525 * Optionally find copies from parents' files.
2527 if (opt
& PICKAXE_BLAME_COPY
) {
2528 if (sb
->copy_score
> sb
->move_score
)
2529 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2530 else if (sb
->copy_score
< sb
->move_score
) {
2531 origin
->suspects
= blame_merge(origin
->suspects
, toosmall
);
2533 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2535 if (!origin
->suspects
)
2538 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2540 sg
= sg
->next
, i
++) {
2541 struct blame_origin
*porigin
= sg_origin
[i
];
2542 find_copy_in_parent(sb
, &blametail
, &toosmall
,
2543 origin
, sg
->item
, porigin
, opt
);
2544 if (!origin
->suspects
)
2551 distribute_blame(sb
, blames
);
2553 * prepend toosmall to origin->suspects
2555 * There is no point in sorting: this ends up on a big
2556 * unsorted list in the caller anyway.
2559 struct blame_entry
**tail
= &toosmall
;
2561 tail
= &(*tail
)->next
;
2562 *tail
= origin
->suspects
;
2563 origin
->suspects
= toosmall
;
2565 for (i
= 0; i
< num_sg
; i
++) {
2567 if (!sg_origin
[i
]->suspects
)
2568 drop_origin_blob(sg_origin
[i
]);
2569 blame_origin_decref(sg_origin
[i
]);
2572 drop_origin_blob(origin
);
2573 if (sg_buf
!= sg_origin
)
2578 * The main loop -- while we have blobs with lines whose true origin
2579 * is still unknown, pick one blob, and allow its lines to pass blames
2580 * to its parents. */
2581 void assign_blame(struct blame_scoreboard
*sb
, int opt
)
2583 struct rev_info
*revs
= sb
->revs
;
2584 struct commit
*commit
= prio_queue_get(&sb
->commits
);
2587 struct blame_entry
*ent
;
2588 struct blame_origin
*suspect
= get_blame_suspects(commit
);
2590 /* find one suspect to break down */
2591 while (suspect
&& !suspect
->suspects
)
2592 suspect
= suspect
->next
;
2595 commit
= prio_queue_get(&sb
->commits
);
2599 assert(commit
== suspect
->commit
);
2602 * We will use this suspect later in the loop,
2603 * so hold onto it in the meantime.
2605 blame_origin_incref(suspect
);
2606 repo_parse_commit(the_repository
, commit
);
2608 (!(commit
->object
.flags
& UNINTERESTING
) &&
2609 !(revs
->max_age
!= -1 && commit
->date
< revs
->max_age
)))
2610 pass_blame(sb
, suspect
, opt
);
2612 commit
->object
.flags
|= UNINTERESTING
;
2613 if (commit
->object
.parsed
)
2614 mark_parents_uninteresting(sb
->revs
, commit
);
2616 /* treat root commit as boundary */
2617 if (!commit
->parents
&& !sb
->show_root
)
2618 commit
->object
.flags
|= UNINTERESTING
;
2620 /* Take responsibility for the remaining entries */
2621 ent
= suspect
->suspects
;
2623 suspect
->guilty
= 1;
2625 struct blame_entry
*next
= ent
->next
;
2626 if (sb
->found_guilty_entry
)
2627 sb
->found_guilty_entry(ent
, sb
->found_guilty_entry_data
);
2632 ent
->next
= sb
->ent
;
2633 sb
->ent
= suspect
->suspects
;
2634 suspect
->suspects
= NULL
;
2638 blame_origin_decref(suspect
);
2640 if (sb
->debug
) /* sanity */
2641 sanity_check_refcnt(sb
);
2646 * To allow quick access to the contents of nth line in the
2647 * final image, prepare an index in the scoreboard.
2649 static int prepare_lines(struct blame_scoreboard
*sb
)
2651 sb
->num_lines
= find_line_starts(&sb
->lineno
, sb
->final_buf
,
2652 sb
->final_buf_size
);
2653 return sb
->num_lines
;
2656 static struct commit
*find_single_final(struct rev_info
*revs
,
2657 const char **name_p
)
2660 struct commit
*found
= NULL
;
2661 const char *name
= NULL
;
2663 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2664 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2665 if (obj
->flags
& UNINTERESTING
)
2667 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2668 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2669 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2671 die("More than one commit to dig from %s and %s?",
2672 revs
->pending
.objects
[i
].name
, name
);
2673 found
= (struct commit
*)obj
;
2674 name
= revs
->pending
.objects
[i
].name
;
2677 *name_p
= xstrdup_or_null(name
);
2681 static struct commit
*dwim_reverse_initial(struct rev_info
*revs
,
2682 const char **name_p
)
2685 * DWIM "git blame --reverse ONE -- PATH" as
2686 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2687 * when it makes sense.
2690 struct commit
*head_commit
;
2691 struct object_id head_oid
;
2693 if (revs
->pending
.nr
!= 1)
2696 /* Is that sole rev a committish? */
2697 obj
= revs
->pending
.objects
[0].item
;
2698 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2699 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2702 /* Do we have HEAD? */
2703 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository
), "HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
2705 head_commit
= lookup_commit_reference_gently(revs
->repo
,
2710 /* Turn "ONE" into "ONE..HEAD" then */
2711 obj
->flags
|= UNINTERESTING
;
2712 add_pending_object(revs
, &head_commit
->object
, "HEAD");
2715 *name_p
= revs
->pending
.objects
[0].name
;
2716 return (struct commit
*)obj
;
2719 static struct commit
*find_single_initial(struct rev_info
*revs
,
2720 const char **name_p
)
2723 struct commit
*found
= NULL
;
2724 const char *name
= NULL
;
2727 * There must be one and only one negative commit, and it must be
2730 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2731 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2732 if (!(obj
->flags
& UNINTERESTING
))
2734 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2735 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2736 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2738 die("More than one commit to dig up from, %s and %s?",
2739 revs
->pending
.objects
[i
].name
, name
);
2740 found
= (struct commit
*) obj
;
2741 name
= revs
->pending
.objects
[i
].name
;
2745 found
= dwim_reverse_initial(revs
, &name
);
2747 die("No commit to dig up from?");
2750 *name_p
= xstrdup(name
);
2754 void init_scoreboard(struct blame_scoreboard
*sb
)
2756 memset(sb
, 0, sizeof(struct blame_scoreboard
));
2757 sb
->move_score
= BLAME_DEFAULT_MOVE_SCORE
;
2758 sb
->copy_score
= BLAME_DEFAULT_COPY_SCORE
;
2761 void setup_scoreboard(struct blame_scoreboard
*sb
,
2762 struct blame_origin
**orig
)
2764 const char *final_commit_name
= NULL
;
2765 struct blame_origin
*o
;
2766 struct commit
*final_commit
= NULL
;
2767 enum object_type type
;
2769 init_blame_suspects(&blame_suspects
);
2771 if (sb
->reverse
&& sb
->contents_from
)
2772 die(_("--contents and --reverse do not blend well."));
2775 BUG("repo is NULL");
2778 sb
->final
= find_single_final(sb
->revs
, &final_commit_name
);
2779 sb
->commits
.compare
= compare_commits_by_commit_date
;
2781 sb
->final
= find_single_initial(sb
->revs
, &final_commit_name
);
2782 sb
->commits
.compare
= compare_commits_by_reverse_commit_date
;
2785 if (sb
->reverse
&& sb
->revs
->first_parent_only
)
2786 sb
->revs
->children
.name
= NULL
;
2788 if (sb
->contents_from
|| !sb
->final
) {
2789 struct object_id head_oid
, *parent_oid
;
2792 * Build a fake commit at the top of the history, when
2793 * (1) "git blame [^A] --path", i.e. with no positive end
2794 * of the history range, in which case we build such
2795 * a fake commit on top of the HEAD to blame in-tree
2797 * (2) "git blame --contents=file [A] -- path", with or
2798 * without positive end of the history range but with
2799 * --contents, in which case we pretend that there is
2800 * a fake commit on top of the positive end (defaulting to
2801 * HEAD) that has the given contents in the path.
2804 parent_oid
= &sb
->final
->object
.oid
;
2806 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository
), "HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
2807 die("no such ref: HEAD");
2808 parent_oid
= &head_oid
;
2811 if (!sb
->contents_from
)
2814 sb
->final
= fake_working_tree_commit(sb
->repo
,
2816 sb
->path
, sb
->contents_from
,
2818 add_pending_object(sb
->revs
, &(sb
->final
->object
), ":");
2821 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2822 final_commit
= find_single_final(sb
->revs
, NULL
);
2824 die(_("--reverse and --first-parent together require specified latest commit"));
2828 * If we have bottom, this will mark the ancestors of the
2829 * bottom commits we would reach while traversing as
2832 if (prepare_revision_walk(sb
->revs
))
2833 die(_("revision walk setup failed"));
2835 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2836 struct commit
*c
= final_commit
;
2838 sb
->revs
->children
.name
= "children";
2839 while (c
->parents
&&
2840 !oideq(&c
->object
.oid
, &sb
->final
->object
.oid
)) {
2841 struct commit_list
*l
= xcalloc(1, sizeof(*l
));
2844 if (add_decoration(&sb
->revs
->children
,
2845 &c
->parents
->item
->object
, l
))
2846 BUG("not unique item in first-parent chain");
2847 c
= c
->parents
->item
;
2850 if (!oideq(&c
->object
.oid
, &sb
->final
->object
.oid
))
2851 die(_("--reverse --first-parent together require range along first-parent chain"));
2854 if (is_null_oid(&sb
->final
->object
.oid
)) {
2855 o
= get_blame_suspects(sb
->final
);
2856 sb
->final_buf
= xmemdupz(o
->file
.ptr
, o
->file
.size
);
2857 sb
->final_buf_size
= o
->file
.size
;
2860 o
= get_origin(sb
->final
, sb
->path
);
2861 if (fill_blob_sha1_and_mode(sb
->repo
, o
))
2862 die(_("no such path %s in %s"), sb
->path
, final_commit_name
);
2864 if (sb
->revs
->diffopt
.flags
.allow_textconv
&&
2865 textconv_object(sb
->repo
, sb
->path
, o
->mode
, &o
->blob_oid
, 1, (char **) &sb
->final_buf
,
2866 &sb
->final_buf_size
))
2869 sb
->final_buf
= repo_read_object_file(the_repository
,
2872 &sb
->final_buf_size
);
2875 die(_("cannot read blob %s for path %s"),
2876 oid_to_hex(&o
->blob_oid
),
2879 sb
->num_read_blob
++;
2885 free((char *)final_commit_name
);
2890 struct blame_entry
*blame_entry_prepend(struct blame_entry
*head
,
2891 long start
, long end
,
2892 struct blame_origin
*o
)
2894 struct blame_entry
*new_head
= xcalloc(1, sizeof(struct blame_entry
));
2895 new_head
->lno
= start
;
2896 new_head
->num_lines
= end
- start
;
2897 new_head
->suspect
= o
;
2898 new_head
->s_lno
= start
;
2899 new_head
->next
= head
;
2900 blame_origin_incref(o
);
2904 void setup_blame_bloom_data(struct blame_scoreboard
*sb
)
2906 struct blame_bloom_data
*bd
;
2907 struct bloom_filter_settings
*bs
;
2909 if (!sb
->repo
->objects
->commit_graph
)
2912 bs
= get_bloom_filter_settings(sb
->repo
);
2916 bd
= xmalloc(sizeof(struct blame_bloom_data
));
2922 ALLOC_ARRAY(bd
->keys
, bd
->alloc
);
2924 add_bloom_key(bd
, sb
->path
);
2926 sb
->bloom_data
= bd
;
2929 void cleanup_scoreboard(struct blame_scoreboard
*sb
)
2931 if (sb
->bloom_data
) {
2933 for (i
= 0; i
< sb
->bloom_data
->nr
; i
++) {
2934 free(sb
->bloom_data
->keys
[i
]->hashes
);
2935 free(sb
->bloom_data
->keys
[i
]);
2937 free(sb
->bloom_data
->keys
);
2938 FREE_AND_NULL(sb
->bloom_data
);
2940 trace2_data_intmax("blame", sb
->repo
,
2941 "bloom/queries", bloom_count_queries
);
2942 trace2_data_intmax("blame", sb
->repo
,
2943 "bloom/response-no", bloom_count_no
);