3 #include "object-store.h"
4 #include "cache-tree.h"
11 #include "commit-slab.h"
13 #include "commit-graph.h"
15 define_commit_slab(blame_suspects
, struct blame_origin
*);
16 static struct blame_suspects blame_suspects
;
18 struct blame_origin
*get_blame_suspects(struct commit
*commit
)
20 struct blame_origin
**result
;
22 result
= blame_suspects_peek(&blame_suspects
, commit
);
24 return result
? *result
: NULL
;
27 static void set_blame_suspects(struct commit
*commit
, struct blame_origin
*origin
)
29 *blame_suspects_at(&blame_suspects
, commit
) = origin
;
32 void blame_origin_decref(struct blame_origin
*o
)
34 if (o
&& --o
->refcnt
<= 0) {
35 struct blame_origin
*p
, *l
= NULL
;
37 blame_origin_decref(o
->previous
);
39 /* Should be present exactly once in commit chain */
40 for (p
= get_blame_suspects(o
->commit
); p
; l
= p
, p
= p
->next
) {
45 set_blame_suspects(o
->commit
, p
->next
);
50 die("internal error in blame_origin_decref");
55 * Given a commit and a path in it, create a new origin structure.
56 * The callers that add blame to the scoreboard should use
57 * get_origin() to obtain shared, refcounted copy instead of calling
58 * this function directly.
60 static struct blame_origin
*make_origin(struct commit
*commit
, const char *path
)
62 struct blame_origin
*o
;
63 FLEX_ALLOC_STR(o
, path
, path
);
66 o
->next
= get_blame_suspects(commit
);
67 set_blame_suspects(commit
, o
);
72 * Locate an existing origin or create a new one.
73 * This moves the origin to front position in the commit util list.
75 static struct blame_origin
*get_origin(struct commit
*commit
, const char *path
)
77 struct blame_origin
*o
, *l
;
79 for (o
= get_blame_suspects(commit
), l
= NULL
; o
; l
= o
, o
= o
->next
) {
80 if (!strcmp(o
->path
, path
)) {
84 o
->next
= get_blame_suspects(commit
);
85 set_blame_suspects(commit
, o
);
87 return blame_origin_incref(o
);
90 return make_origin(commit
, path
);
95 static void verify_working_tree_path(struct repository
*r
,
96 struct commit
*work_tree
, const char *path
)
98 struct commit_list
*parents
;
101 for (parents
= work_tree
->parents
; parents
; parents
= parents
->next
) {
102 const struct object_id
*commit_oid
= &parents
->item
->object
.oid
;
103 struct object_id blob_oid
;
106 if (!get_tree_entry(r
, commit_oid
, path
, &blob_oid
, &mode
) &&
107 oid_object_info(r
, &blob_oid
, NULL
) == OBJ_BLOB
)
111 pos
= index_name_pos(r
->index
, path
, strlen(path
));
113 ; /* path is in the index */
114 else if (-1 - pos
< r
->index
->cache_nr
&&
115 !strcmp(r
->index
->cache
[-1 - pos
]->name
, path
))
116 ; /* path is in the index, unmerged */
118 die("no such path '%s' in HEAD", path
);
121 static struct commit_list
**append_parent(struct repository
*r
,
122 struct commit_list
**tail
,
123 const struct object_id
*oid
)
125 struct commit
*parent
;
127 parent
= lookup_commit_reference(r
, oid
);
129 die("no such commit %s", oid_to_hex(oid
));
130 return &commit_list_insert(parent
, tail
)->next
;
133 static void append_merge_parents(struct repository
*r
,
134 struct commit_list
**tail
)
137 struct strbuf line
= STRBUF_INIT
;
139 merge_head
= open(git_path_merge_head(r
), O_RDONLY
);
140 if (merge_head
< 0) {
143 die("cannot open '%s' for reading",
144 git_path_merge_head(r
));
147 while (!strbuf_getwholeline_fd(&line
, merge_head
, '\n')) {
148 struct object_id oid
;
149 if (get_oid_hex(line
.buf
, &oid
))
150 die("unknown line in '%s': %s",
151 git_path_merge_head(r
), line
.buf
);
152 tail
= append_parent(r
, tail
, &oid
);
155 strbuf_release(&line
);
159 * This isn't as simple as passing sb->buf and sb->len, because we
160 * want to transfer ownership of the buffer to the commit (so we
163 static void set_commit_buffer_from_strbuf(struct repository
*r
,
168 void *buf
= strbuf_detach(sb
, &len
);
169 set_commit_buffer(r
, c
, buf
, len
);
173 * Prepare a dummy commit that represents the work tree (or staged) item.
174 * Note that annotating work tree item never works in the reverse.
176 static struct commit
*fake_working_tree_commit(struct repository
*r
,
177 struct diff_options
*opt
,
179 const char *contents_from
)
181 struct commit
*commit
;
182 struct blame_origin
*origin
;
183 struct commit_list
**parent_tail
, *parent
;
184 struct object_id head_oid
;
185 struct strbuf buf
= STRBUF_INIT
;
189 struct cache_entry
*ce
;
191 struct strbuf msg
= STRBUF_INIT
;
195 commit
= alloc_commit_node(r
);
196 commit
->object
.parsed
= 1;
198 parent_tail
= &commit
->parents
;
200 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
201 die("no such ref: HEAD");
203 parent_tail
= append_parent(r
, parent_tail
, &head_oid
);
204 append_merge_parents(r
, parent_tail
);
205 verify_working_tree_path(r
, commit
, path
);
207 origin
= make_origin(commit
, path
);
209 ident
= fmt_ident("Not Committed Yet", "not.committed.yet",
210 WANT_BLANK_IDENT
, NULL
, 0);
211 strbuf_addstr(&msg
, "tree 0000000000000000000000000000000000000000\n");
212 for (parent
= commit
->parents
; parent
; parent
= parent
->next
)
213 strbuf_addf(&msg
, "parent %s\n",
214 oid_to_hex(&parent
->item
->object
.oid
));
218 "Version of %s from %s\n",
220 (!contents_from
? path
:
221 (!strcmp(contents_from
, "-") ? "standard input" : contents_from
)));
222 set_commit_buffer_from_strbuf(r
, commit
, &msg
);
224 if (!contents_from
|| strcmp("-", contents_from
)) {
226 const char *read_from
;
228 unsigned long buf_len
;
231 if (stat(contents_from
, &st
) < 0)
232 die_errno("Cannot stat '%s'", contents_from
);
233 read_from
= contents_from
;
236 if (lstat(path
, &st
) < 0)
237 die_errno("Cannot lstat '%s'", path
);
240 mode
= canon_mode(st
.st_mode
);
242 switch (st
.st_mode
& S_IFMT
) {
244 if (opt
->flags
.allow_textconv
&&
245 textconv_object(r
, read_from
, mode
, null_oid(), 0, &buf_ptr
, &buf_len
))
246 strbuf_attach(&buf
, buf_ptr
, buf_len
, buf_len
+ 1);
247 else if (strbuf_read_file(&buf
, read_from
, st
.st_size
) != st
.st_size
)
248 die_errno("cannot open or read '%s'", read_from
);
251 if (strbuf_readlink(&buf
, read_from
, st
.st_size
) < 0)
252 die_errno("cannot readlink '%s'", read_from
);
255 die("unsupported file type %s", read_from
);
259 /* Reading from stdin */
261 if (strbuf_read(&buf
, 0, 0) < 0)
262 die_errno("failed to read from stdin");
264 convert_to_git(r
->index
, path
, buf
.buf
, buf
.len
, &buf
, 0);
265 origin
->file
.ptr
= buf
.buf
;
266 origin
->file
.size
= buf
.len
;
267 pretend_object_file(buf
.buf
, buf
.len
, OBJ_BLOB
, &origin
->blob_oid
);
270 * Read the current index, replace the path entry with
271 * origin->blob_sha1 without mucking with its mode or type
272 * bits; we are not going to write this index out -- we just
273 * want to run "diff-index --cached".
275 discard_index(r
->index
);
280 int pos
= index_name_pos(r
->index
, path
, len
);
282 mode
= r
->index
->cache
[pos
]->ce_mode
;
284 /* Let's not bother reading from HEAD tree */
285 mode
= S_IFREG
| 0644;
287 ce
= make_empty_cache_entry(r
->index
, len
);
288 oidcpy(&ce
->oid
, &origin
->blob_oid
);
289 memcpy(ce
->name
, path
, len
);
290 ce
->ce_flags
= create_ce_flags(0);
291 ce
->ce_namelen
= len
;
292 ce
->ce_mode
= create_ce_mode(mode
);
293 add_index_entry(r
->index
, ce
,
294 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
296 cache_tree_invalidate_path(r
->index
, path
);
303 static int diff_hunks(mmfile_t
*file_a
, mmfile_t
*file_b
,
304 xdl_emit_hunk_consume_func_t hunk_func
, void *cb_data
, int xdl_opts
)
307 xdemitconf_t xecfg
= {0};
308 xdemitcb_t ecb
= {NULL
};
310 xpp
.flags
= xdl_opts
;
311 xecfg
.hunk_func
= hunk_func
;
313 return xdi_diff(file_a
, file_b
, &xpp
, &xecfg
, &ecb
);
316 static const char *get_next_line(const char *start
, const char *end
)
318 const char *nl
= memchr(start
, '\n', end
- start
);
320 return nl
? nl
+ 1 : end
;
323 static int find_line_starts(int **line_starts
, const char *buf
,
326 const char *end
= buf
+ len
;
331 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
334 ALLOC_ARRAY(*line_starts
, num
+ 1);
335 lineno
= *line_starts
;
337 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
345 struct fingerprint_entry
;
347 /* A fingerprint is intended to loosely represent a string, such that two
348 * fingerprints can be quickly compared to give an indication of the similarity
349 * of the strings that they represent.
351 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
352 * the string that it represents. Whitespace is added at each end of the
353 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
354 * For example, the string "Darth Radar" will be converted to the following
356 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
358 * The similarity between two fingerprints is the size of the intersection of
359 * their multisets, including repeated elements. See fingerprint_similarity for
362 * For ease of implementation, the fingerprint is implemented as a map
363 * of byte pairs to the count of that byte pair in the string, instead of
364 * allowing repeated elements in a set.
368 /* As we know the maximum number of entries in advance, it's
369 * convenient to store the entries in a single array instead of having
370 * the hashmap manage the memory.
372 struct fingerprint_entry
*entries
;
375 /* A byte pair in a fingerprint. Stores the number of times the byte pair
376 * occurs in the string that the fingerprint represents.
378 struct fingerprint_entry
{
379 /* The hashmap entry - the hash represents the byte pair in its
380 * entirety so we don't need to store the byte pair separately.
382 struct hashmap_entry entry
;
383 /* The number of times the byte pair occurs in the string that the
384 * fingerprint represents.
389 /* See `struct fingerprint` for an explanation of what a fingerprint is.
390 * \param result the fingerprint of the string is stored here. This must be
391 * freed later using free_fingerprint.
392 * \param line_begin the start of the string
393 * \param line_end the end of the string
395 static void get_fingerprint(struct fingerprint
*result
,
396 const char *line_begin
,
397 const char *line_end
)
399 unsigned int hash
, c0
= 0, c1
;
401 int max_map_entry_count
= 1 + line_end
- line_begin
;
402 struct fingerprint_entry
*entry
= xcalloc(max_map_entry_count
,
403 sizeof(struct fingerprint_entry
));
404 struct fingerprint_entry
*found_entry
;
406 hashmap_init(&result
->map
, NULL
, NULL
, max_map_entry_count
);
407 result
->entries
= entry
;
408 for (p
= line_begin
; p
<= line_end
; ++p
, c0
= c1
) {
409 /* Always terminate the string with whitespace.
410 * Normalise whitespace to 0, and normalise letters to
411 * lower case. This won't work for multibyte characters but at
412 * worst will match some unrelated characters.
414 if ((p
== line_end
) || isspace(*p
))
418 hash
= c0
| (c1
<< 8);
419 /* Ignore whitespace pairs */
422 hashmap_entry_init(&entry
->entry
, hash
);
424 found_entry
= hashmap_get_entry(&result
->map
, entry
,
425 /* member name */ entry
, NULL
);
427 found_entry
->count
+= 1;
430 hashmap_add(&result
->map
, &entry
->entry
);
436 static void free_fingerprint(struct fingerprint
*f
)
438 hashmap_clear(&f
->map
);
442 /* Calculates the similarity between two fingerprints as the size of the
443 * intersection of their multisets, including repeated elements. See
444 * `struct fingerprint` for an explanation of the fingerprint representation.
445 * The similarity between "cat mat" and "father rather" is 2 because "at" is
446 * present twice in both strings while the similarity between "tim" and "mit"
449 static int fingerprint_similarity(struct fingerprint
*a
, struct fingerprint
*b
)
451 int intersection
= 0;
452 struct hashmap_iter iter
;
453 const struct fingerprint_entry
*entry_a
, *entry_b
;
455 hashmap_for_each_entry(&b
->map
, &iter
, entry_b
,
456 entry
/* member name */) {
457 entry_a
= hashmap_get_entry(&a
->map
, entry_b
, entry
, NULL
);
459 intersection
+= entry_a
->count
< entry_b
->count
?
460 entry_a
->count
: entry_b
->count
;
466 /* Subtracts byte-pair elements in B from A, modifying A in place.
468 static void fingerprint_subtract(struct fingerprint
*a
, struct fingerprint
*b
)
470 struct hashmap_iter iter
;
471 struct fingerprint_entry
*entry_a
;
472 const struct fingerprint_entry
*entry_b
;
474 hashmap_iter_init(&b
->map
, &iter
);
476 hashmap_for_each_entry(&b
->map
, &iter
, entry_b
,
477 entry
/* member name */) {
478 entry_a
= hashmap_get_entry(&a
->map
, entry_b
, entry
, NULL
);
480 if (entry_a
->count
<= entry_b
->count
)
481 hashmap_remove(&a
->map
, &entry_b
->entry
, NULL
);
483 entry_a
->count
-= entry_b
->count
;
488 /* Calculate fingerprints for a series of lines.
489 * Puts the fingerprints in the fingerprints array, which must have been
490 * preallocated to allow storing line_count elements.
492 static void get_line_fingerprints(struct fingerprint
*fingerprints
,
493 const char *content
, const int *line_starts
,
494 long first_line
, long line_count
)
497 const char *linestart
, *lineend
;
499 line_starts
+= first_line
;
500 for (i
= 0; i
< line_count
; ++i
) {
501 linestart
= content
+ line_starts
[i
];
502 lineend
= content
+ line_starts
[i
+ 1];
503 get_fingerprint(fingerprints
+ i
, linestart
, lineend
);
507 static void free_line_fingerprints(struct fingerprint
*fingerprints
,
512 for (i
= 0; i
< nr_fingerprints
; i
++)
513 free_fingerprint(&fingerprints
[i
]);
516 /* This contains the data necessary to linearly map a line number in one half
517 * of a diff chunk to the line in the other half of the diff chunk that is
518 * closest in terms of its position as a fraction of the length of the chunk.
520 struct line_number_mapping
{
521 int destination_start
, destination_length
,
522 source_start
, source_length
;
525 /* Given a line number in one range, offset and scale it to map it onto the
527 * Essentially this mapping is a simple linear equation but the calculation is
528 * more complicated to allow performing it with integer operations.
529 * Another complication is that if a line could map onto many lines in the
530 * destination range then we want to choose the line at the center of those
532 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
533 * first 5 lines in B will map onto the first line in the A chunk, while the
534 * last 5 lines will all map onto the second line in the A chunk.
535 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
536 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
538 static int map_line_number(int line_number
,
539 const struct line_number_mapping
*mapping
)
541 return ((line_number
- mapping
->source_start
) * 2 + 1) *
542 mapping
->destination_length
/
543 (mapping
->source_length
* 2) +
544 mapping
->destination_start
;
547 /* Get a pointer to the element storing the similarity between a line in A
550 * The similarities are stored in a 2-dimensional array. Each "row" in the
551 * array contains the similarities for a line in B. The similarities stored in
552 * a row are the similarities between the line in B and the nearby lines in A.
553 * To keep the length of each row the same, it is padded out with values of -1
554 * where the search range extends beyond the lines in A.
555 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
562 * Then the similarity array will contain:
563 * [-1, -1, am, bm, cm,
564 * -1, an, bn, cn, dn,
565 * ao, bo, co, do, eo,
566 * bp, cp, dp, ep, -1,
567 * cq, dq, eq, -1, -1]
568 * Where similarities are denoted either by -1 for invalid, or the
569 * concatenation of the two lines in the diff being compared.
571 * \param similarities array of similarities between lines in A and B
572 * \param line_a the index of the line in A, in the same frame of reference as
574 * \param local_line_b the index of the line in B, relative to the first line
575 * in B that similarities represents.
576 * \param closest_line_a the index of the line in A that is deemed to be
577 * closest to local_line_b. This must be in the same
578 * frame of reference as line_a. This value defines
579 * where similarities is centered for the line in B.
580 * \param max_search_distance_a maximum distance in lines from the closest line
581 * in A for other lines in A for which
582 * similarities may be calculated.
584 static int *get_similarity(int *similarities
,
585 int line_a
, int local_line_b
,
586 int closest_line_a
, int max_search_distance_a
)
588 assert(abs(line_a
- closest_line_a
) <=
589 max_search_distance_a
);
590 return similarities
+ line_a
- closest_line_a
+
591 max_search_distance_a
+
592 local_line_b
* (max_search_distance_a
* 2 + 1);
595 #define CERTAIN_NOTHING_MATCHES -2
596 #define CERTAINTY_NOT_CALCULATED -1
598 /* Given a line in B, first calculate its similarities with nearby lines in A
599 * if not already calculated, then identify the most similar and second most
600 * similar lines. The "certainty" is calculated based on those two
603 * \param start_a the index of the first line of the chunk in A
604 * \param length_a the length in lines of the chunk in A
605 * \param local_line_b the index of the line in B, relative to the first line
607 * \param fingerprints_a array of fingerprints for the chunk in A
608 * \param fingerprints_b array of fingerprints for the chunk in B
609 * \param similarities 2-dimensional array of similarities between lines in A
610 * and B. See get_similarity() for more details.
611 * \param certainties array of values indicating how strongly a line in B is
612 * matched with some line in A.
613 * \param second_best_result array of absolute indices in A for the second
614 * closest match of a line in B.
615 * \param result array of absolute indices in A for the closest match of a line
617 * \param max_search_distance_a maximum distance in lines from the closest line
618 * in A for other lines in A for which
619 * similarities may be calculated.
620 * \param map_line_number_in_b_to_a parameter to map_line_number().
622 static void find_best_line_matches(
627 struct fingerprint
*fingerprints_a
,
628 struct fingerprint
*fingerprints_b
,
631 int *second_best_result
,
633 const int max_search_distance_a
,
634 const struct line_number_mapping
*map_line_number_in_b_to_a
)
637 int i
, search_start
, search_end
, closest_local_line_a
, *similarity
,
638 best_similarity
= 0, second_best_similarity
= 0,
639 best_similarity_index
= 0, second_best_similarity_index
= 0;
641 /* certainty has already been calculated so no need to redo the work */
642 if (certainties
[local_line_b
] != CERTAINTY_NOT_CALCULATED
)
645 closest_local_line_a
= map_line_number(
646 local_line_b
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
648 search_start
= closest_local_line_a
- max_search_distance_a
;
649 if (search_start
< 0)
652 search_end
= closest_local_line_a
+ max_search_distance_a
+ 1;
653 if (search_end
> length_a
)
654 search_end
= length_a
;
656 for (i
= search_start
; i
< search_end
; ++i
) {
657 similarity
= get_similarity(similarities
,
659 closest_local_line_a
,
660 max_search_distance_a
);
661 if (*similarity
== -1) {
662 /* This value will never exceed 10 but assert just in
665 assert(abs(i
- closest_local_line_a
) < 1000);
666 /* scale the similarity by (1000 - distance from
667 * closest line) to act as a tie break between lines
668 * that otherwise are equally similar.
670 *similarity
= fingerprint_similarity(
671 fingerprints_b
+ local_line_b
,
672 fingerprints_a
+ i
) *
673 (1000 - abs(i
- closest_local_line_a
));
675 if (*similarity
> best_similarity
) {
676 second_best_similarity
= best_similarity
;
677 second_best_similarity_index
= best_similarity_index
;
678 best_similarity
= *similarity
;
679 best_similarity_index
= i
;
680 } else if (*similarity
> second_best_similarity
) {
681 second_best_similarity
= *similarity
;
682 second_best_similarity_index
= i
;
686 if (best_similarity
== 0) {
687 /* this line definitely doesn't match with anything. Mark it
688 * with this special value so it doesn't get invalidated and
689 * won't be recalculated.
691 certainties
[local_line_b
] = CERTAIN_NOTHING_MATCHES
;
692 result
[local_line_b
] = -1;
694 /* Calculate the certainty with which this line matches.
695 * If the line matches well with two lines then that reduces
696 * the certainty. However we still want to prioritise matching
697 * a line that matches very well with two lines over matching a
698 * line that matches poorly with one line, hence doubling
700 * This means that if we have
701 * line X that matches only one line with a score of 3,
702 * line Y that matches two lines equally with a score of 5,
703 * and line Z that matches only one line with a score or 2,
704 * then the lines in order of certainty are X, Y, Z.
706 certainties
[local_line_b
] = best_similarity
* 2 -
707 second_best_similarity
;
709 /* We keep both the best and second best results to allow us to
710 * check at a later stage of the matching process whether the
711 * result needs to be invalidated.
713 result
[local_line_b
] = start_a
+ best_similarity_index
;
714 second_best_result
[local_line_b
] =
715 start_a
+ second_best_similarity_index
;
720 * This finds the line that we can match with the most confidence, and
721 * uses it as a partition. It then calls itself on the lines on either side of
722 * that partition. In this way we avoid lines appearing out of order, and
723 * retain a sensible line ordering.
724 * \param start_a index of the first line in A with which lines in B may be
726 * \param start_b index of the first line in B for which matching should be
728 * \param length_a number of lines in A with which lines in B may be compared.
729 * \param length_b number of lines in B for which matching should be done.
730 * \param fingerprints_a mutable array of fingerprints in A. The first element
731 * corresponds to the line at start_a.
732 * \param fingerprints_b array of fingerprints in B. The first element
733 * corresponds to the line at start_b.
734 * \param similarities 2-dimensional array of similarities between lines in A
735 * and B. See get_similarity() for more details.
736 * \param certainties array of values indicating how strongly a line in B is
737 * matched with some line in A.
738 * \param second_best_result array of absolute indices in A for the second
739 * closest match of a line in B.
740 * \param result array of absolute indices in A for the closest match of a line
742 * \param max_search_distance_a maximum distance in lines from the closest line
743 * in A for other lines in A for which
744 * similarities may be calculated.
745 * \param max_search_distance_b an upper bound on the greatest possible
746 * distance between lines in B such that they will
747 * both be compared with the same line in A
748 * according to max_search_distance_a.
749 * \param map_line_number_in_b_to_a parameter to map_line_number().
751 static void fuzzy_find_matching_lines_recurse(
752 int start_a
, int start_b
,
753 int length_a
, int length_b
,
754 struct fingerprint
*fingerprints_a
,
755 struct fingerprint
*fingerprints_b
,
758 int *second_best_result
,
760 int max_search_distance_a
,
761 int max_search_distance_b
,
762 const struct line_number_mapping
*map_line_number_in_b_to_a
)
764 int i
, invalidate_min
, invalidate_max
, offset_b
,
765 second_half_start_a
, second_half_start_b
,
766 second_half_length_a
, second_half_length_b
,
767 most_certain_line_a
, most_certain_local_line_b
= -1,
768 most_certain_line_certainty
= -1,
769 closest_local_line_a
;
771 for (i
= 0; i
< length_b
; ++i
) {
772 find_best_line_matches(start_a
,
782 max_search_distance_a
,
783 map_line_number_in_b_to_a
);
785 if (certainties
[i
] > most_certain_line_certainty
) {
786 most_certain_line_certainty
= certainties
[i
];
787 most_certain_local_line_b
= i
;
792 if (most_certain_local_line_b
== -1)
795 most_certain_line_a
= result
[most_certain_local_line_b
];
798 * Subtract the most certain line's fingerprint in B from the matched
799 * fingerprint in A. This means that other lines in B can't also match
800 * the same parts of the line in A.
802 fingerprint_subtract(fingerprints_a
+ most_certain_line_a
- start_a
,
803 fingerprints_b
+ most_certain_local_line_b
);
805 /* Invalidate results that may be affected by the choice of most
808 invalidate_min
= most_certain_local_line_b
- max_search_distance_b
;
809 invalidate_max
= most_certain_local_line_b
+ max_search_distance_b
+ 1;
810 if (invalidate_min
< 0)
812 if (invalidate_max
> length_b
)
813 invalidate_max
= length_b
;
815 /* As the fingerprint in A has changed, discard previously calculated
816 * similarity values with that fingerprint.
818 for (i
= invalidate_min
; i
< invalidate_max
; ++i
) {
819 closest_local_line_a
= map_line_number(
820 i
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
822 /* Check that the lines in A and B are close enough that there
823 * is a similarity value for them.
825 if (abs(most_certain_line_a
- start_a
- closest_local_line_a
) >
826 max_search_distance_a
) {
830 *get_similarity(similarities
, most_certain_line_a
- start_a
,
831 i
, closest_local_line_a
,
832 max_search_distance_a
) = -1;
835 /* More invalidating of results that may be affected by the choice of
837 * Discard the matches for lines in B that are currently matched with a
838 * line in A such that their ordering contradicts the ordering imposed
839 * by the choice of most certain line.
841 for (i
= most_certain_local_line_b
- 1; i
>= invalidate_min
; --i
) {
842 /* In this loop we discard results for lines in B that are
843 * before most-certain-line-B but are matched with a line in A
844 * that is after most-certain-line-A.
846 if (certainties
[i
] >= 0 &&
847 (result
[i
] >= most_certain_line_a
||
848 second_best_result
[i
] >= most_certain_line_a
)) {
849 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
852 for (i
= most_certain_local_line_b
+ 1; i
< invalidate_max
; ++i
) {
853 /* In this loop we discard results for lines in B that are
854 * after most-certain-line-B but are matched with a line in A
855 * that is before most-certain-line-A.
857 if (certainties
[i
] >= 0 &&
858 (result
[i
] <= most_certain_line_a
||
859 second_best_result
[i
] <= most_certain_line_a
)) {
860 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
864 /* Repeat the matching process for lines before the most certain line.
866 if (most_certain_local_line_b
> 0) {
867 fuzzy_find_matching_lines_recurse(
869 most_certain_line_a
+ 1 - start_a
,
870 most_certain_local_line_b
,
871 fingerprints_a
, fingerprints_b
, similarities
,
872 certainties
, second_best_result
, result
,
873 max_search_distance_a
,
874 max_search_distance_b
,
875 map_line_number_in_b_to_a
);
877 /* Repeat the matching process for lines after the most certain line.
879 if (most_certain_local_line_b
+ 1 < length_b
) {
880 second_half_start_a
= most_certain_line_a
;
881 offset_b
= most_certain_local_line_b
+ 1;
882 second_half_start_b
= start_b
+ offset_b
;
883 second_half_length_a
=
884 length_a
+ start_a
- second_half_start_a
;
885 second_half_length_b
=
886 length_b
+ start_b
- second_half_start_b
;
887 fuzzy_find_matching_lines_recurse(
888 second_half_start_a
, second_half_start_b
,
889 second_half_length_a
, second_half_length_b
,
890 fingerprints_a
+ second_half_start_a
- start_a
,
891 fingerprints_b
+ offset_b
,
893 offset_b
* (max_search_distance_a
* 2 + 1),
894 certainties
+ offset_b
,
895 second_best_result
+ offset_b
, result
+ offset_b
,
896 max_search_distance_a
,
897 max_search_distance_b
,
898 map_line_number_in_b_to_a
);
902 /* Find the lines in the parent line range that most closely match the lines in
903 * the target line range. This is accomplished by matching fingerprints in each
904 * blame_origin, and choosing the best matches that preserve the line ordering.
905 * See struct fingerprint for details of fingerprint matching, and
906 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
908 * The performance is believed to be O(n log n) in the typical case and O(n^2)
909 * in a pathological case, where n is the number of lines in the target range.
911 static int *fuzzy_find_matching_lines(struct blame_origin
*parent
,
912 struct blame_origin
*target
,
913 int tlno
, int parent_slno
, int same
,
916 /* We use the terminology "A" for the left hand side of the diff AKA
917 * parent, and "B" for the right hand side of the diff AKA target. */
918 int start_a
= parent_slno
;
919 int length_a
= parent_len
;
921 int length_b
= same
- tlno
;
923 struct line_number_mapping map_line_number_in_b_to_a
= {
924 start_a
, length_a
, start_b
, length_b
927 struct fingerprint
*fingerprints_a
= parent
->fingerprints
;
928 struct fingerprint
*fingerprints_b
= target
->fingerprints
;
930 int i
, *result
, *second_best_result
,
931 *certainties
, *similarities
, similarity_count
;
934 * max_search_distance_a means that given a line in B, compare it to
935 * the line in A that is closest to its position, and the lines in A
936 * that are no greater than max_search_distance_a lines away from the
939 * max_search_distance_b is an upper bound on the greatest possible
940 * distance between lines in B such that they will both be compared
941 * with the same line in A according to max_search_distance_a.
943 int max_search_distance_a
= 10, max_search_distance_b
;
948 if (max_search_distance_a
>= length_a
)
949 max_search_distance_a
= length_a
? length_a
- 1 : 0;
951 max_search_distance_b
= ((2 * max_search_distance_a
+ 1) * length_b
954 CALLOC_ARRAY(result
, length_b
);
955 CALLOC_ARRAY(second_best_result
, length_b
);
956 CALLOC_ARRAY(certainties
, length_b
);
958 /* See get_similarity() for details of similarities. */
959 similarity_count
= length_b
* (max_search_distance_a
* 2 + 1);
960 CALLOC_ARRAY(similarities
, similarity_count
);
962 for (i
= 0; i
< length_b
; ++i
) {
964 second_best_result
[i
] = -1;
965 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
968 for (i
= 0; i
< similarity_count
; ++i
)
969 similarities
[i
] = -1;
971 fuzzy_find_matching_lines_recurse(start_a
, start_b
,
973 fingerprints_a
+ start_a
,
974 fingerprints_b
+ start_b
,
979 max_search_distance_a
,
980 max_search_distance_b
,
981 &map_line_number_in_b_to_a
);
985 free(second_best_result
);
990 static void fill_origin_fingerprints(struct blame_origin
*o
)
996 o
->num_lines
= find_line_starts(&line_starts
, o
->file
.ptr
,
998 CALLOC_ARRAY(o
->fingerprints
, o
->num_lines
);
999 get_line_fingerprints(o
->fingerprints
, o
->file
.ptr
, line_starts
,
1004 static void drop_origin_fingerprints(struct blame_origin
*o
)
1006 if (o
->fingerprints
) {
1007 free_line_fingerprints(o
->fingerprints
, o
->num_lines
);
1009 FREE_AND_NULL(o
->fingerprints
);
1014 * Given an origin, prepare mmfile_t structure to be used by the
1017 static void fill_origin_blob(struct diff_options
*opt
,
1018 struct blame_origin
*o
, mmfile_t
*file
,
1019 int *num_read_blob
, int fill_fingerprints
)
1022 enum object_type type
;
1023 unsigned long file_size
;
1026 if (opt
->flags
.allow_textconv
&&
1027 textconv_object(opt
->repo
, o
->path
, o
->mode
,
1028 &o
->blob_oid
, 1, &file
->ptr
, &file_size
))
1031 file
->ptr
= read_object_file(&o
->blob_oid
, &type
,
1033 file
->size
= file_size
;
1036 die("Cannot read blob %s for path %s",
1037 oid_to_hex(&o
->blob_oid
),
1043 if (fill_fingerprints
)
1044 fill_origin_fingerprints(o
);
1047 static void drop_origin_blob(struct blame_origin
*o
)
1049 FREE_AND_NULL(o
->file
.ptr
);
1050 drop_origin_fingerprints(o
);
1054 * Any merge of blames happens on lists of blames that arrived via
1055 * different parents in a single suspect. In this case, we want to
1056 * sort according to the suspect line numbers as opposed to the final
1057 * image line numbers. The function body is somewhat longish because
1058 * it avoids unnecessary writes.
1061 static struct blame_entry
*blame_merge(struct blame_entry
*list1
,
1062 struct blame_entry
*list2
)
1064 struct blame_entry
*p1
= list1
, *p2
= list2
,
1072 if (p1
->s_lno
<= p2
->s_lno
) {
1075 if (!(p1
= *tail
)) {
1079 } while (p1
->s_lno
<= p2
->s_lno
);
1085 if (!(p2
= *tail
)) {
1089 } while (p1
->s_lno
> p2
->s_lno
);
1093 if (!(p1
= *tail
)) {
1097 } while (p1
->s_lno
<= p2
->s_lno
);
1101 DEFINE_LIST_SORT(static, sort_blame_entries
, struct blame_entry
, next
);
1104 * Final image line numbers are all different, so we don't need a
1105 * three-way comparison here.
1108 static int compare_blame_final(const struct blame_entry
*e1
,
1109 const struct blame_entry
*e2
)
1111 return e1
->lno
> e2
->lno
? 1 : -1;
1114 static int compare_blame_suspect(const struct blame_entry
*s1
,
1115 const struct blame_entry
*s2
)
1118 * to allow for collating suspects, we sort according to the
1119 * respective pointer value as the primary sorting criterion.
1120 * The actual relation is pretty unimportant as long as it
1121 * establishes a total order. Comparing as integers gives us
1124 if (s1
->suspect
!= s2
->suspect
)
1125 return (intptr_t)s1
->suspect
> (intptr_t)s2
->suspect
? 1 : -1;
1126 if (s1
->s_lno
== s2
->s_lno
)
1128 return s1
->s_lno
> s2
->s_lno
? 1 : -1;
1131 void blame_sort_final(struct blame_scoreboard
*sb
)
1133 sort_blame_entries(&sb
->ent
, compare_blame_final
);
1136 static int compare_commits_by_reverse_commit_date(const void *a
,
1140 return -compare_commits_by_commit_date(a
, b
, c
);
1144 * For debugging -- origin is refcounted, and this asserts that
1145 * we do not underflow.
1147 static void sanity_check_refcnt(struct blame_scoreboard
*sb
)
1150 struct blame_entry
*ent
;
1152 for (ent
= sb
->ent
; ent
; ent
= ent
->next
) {
1153 /* Nobody should have zero or negative refcnt */
1154 if (ent
->suspect
->refcnt
<= 0) {
1155 fprintf(stderr
, "%s in %s has negative refcnt %d\n",
1157 oid_to_hex(&ent
->suspect
->commit
->object
.oid
),
1158 ent
->suspect
->refcnt
);
1163 sb
->on_sanity_fail(sb
, baa
);
1167 * If two blame entries that are next to each other came from
1168 * contiguous lines in the same origin (i.e. <commit, path> pair),
1169 * merge them together.
1171 void blame_coalesce(struct blame_scoreboard
*sb
)
1173 struct blame_entry
*ent
, *next
;
1175 for (ent
= sb
->ent
; ent
&& (next
= ent
->next
); ent
= next
) {
1176 if (ent
->suspect
== next
->suspect
&&
1177 ent
->s_lno
+ ent
->num_lines
== next
->s_lno
&&
1178 ent
->lno
+ ent
->num_lines
== next
->lno
&&
1179 ent
->ignored
== next
->ignored
&&
1180 ent
->unblamable
== next
->unblamable
) {
1181 ent
->num_lines
+= next
->num_lines
;
1182 ent
->next
= next
->next
;
1183 blame_origin_decref(next
->suspect
);
1186 next
= ent
; /* again */
1190 if (sb
->debug
) /* sanity */
1191 sanity_check_refcnt(sb
);
1195 * Merge the given sorted list of blames into a preexisting origin.
1196 * If there were no previous blames to that commit, it is entered into
1197 * the commit priority queue of the score board.
1200 static void queue_blames(struct blame_scoreboard
*sb
, struct blame_origin
*porigin
,
1201 struct blame_entry
*sorted
)
1203 if (porigin
->suspects
)
1204 porigin
->suspects
= blame_merge(porigin
->suspects
, sorted
);
1206 struct blame_origin
*o
;
1207 for (o
= get_blame_suspects(porigin
->commit
); o
; o
= o
->next
) {
1209 porigin
->suspects
= sorted
;
1213 porigin
->suspects
= sorted
;
1214 prio_queue_put(&sb
->commits
, porigin
->commit
);
1219 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1220 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1221 * for an origin is also used to pass the blame for the entire file to
1222 * the parent to detect the case where a child's blob is identical to
1223 * that of its parent's.
1225 * This also fills origin->mode for corresponding tree path.
1227 static int fill_blob_sha1_and_mode(struct repository
*r
,
1228 struct blame_origin
*origin
)
1230 if (!is_null_oid(&origin
->blob_oid
))
1232 if (get_tree_entry(r
, &origin
->commit
->object
.oid
, origin
->path
, &origin
->blob_oid
, &origin
->mode
))
1234 if (oid_object_info(r
, &origin
->blob_oid
, NULL
) != OBJ_BLOB
)
1238 oidclr(&origin
->blob_oid
);
1239 origin
->mode
= S_IFINVALID
;
1243 struct blame_bloom_data
{
1245 * Changed-path Bloom filter keys. These can help prevent
1246 * computing diffs against first parents, but we need to
1247 * expand the list as code is moved or files are renamed.
1249 struct bloom_filter_settings
*settings
;
1250 struct bloom_key
**keys
;
1255 static int bloom_count_queries
= 0;
1256 static int bloom_count_no
= 0;
1257 static int maybe_changed_path(struct repository
*r
,
1258 struct blame_origin
*origin
,
1259 struct blame_bloom_data
*bd
)
1262 struct bloom_filter
*filter
;
1267 if (commit_graph_generation(origin
->commit
) == GENERATION_NUMBER_INFINITY
)
1270 filter
= get_bloom_filter(r
, origin
->commit
);
1275 bloom_count_queries
++;
1276 for (i
= 0; i
< bd
->nr
; i
++) {
1277 if (bloom_filter_contains(filter
,
1287 static void add_bloom_key(struct blame_bloom_data
*bd
,
1293 if (bd
->nr
>= bd
->alloc
) {
1295 REALLOC_ARRAY(bd
->keys
, bd
->alloc
);
1298 bd
->keys
[bd
->nr
] = xmalloc(sizeof(struct bloom_key
));
1299 fill_bloom_key(path
, strlen(path
), bd
->keys
[bd
->nr
], bd
->settings
);
1304 * We have an origin -- check if the same path exists in the
1305 * parent and return an origin structure to represent it.
1307 static struct blame_origin
*find_origin(struct repository
*r
,
1308 struct commit
*parent
,
1309 struct blame_origin
*origin
,
1310 struct blame_bloom_data
*bd
)
1312 struct blame_origin
*porigin
;
1313 struct diff_options diff_opts
;
1314 const char *paths
[2];
1316 /* First check any existing origins */
1317 for (porigin
= get_blame_suspects(parent
); porigin
; porigin
= porigin
->next
)
1318 if (!strcmp(porigin
->path
, origin
->path
)) {
1320 * The same path between origin and its parent
1321 * without renaming -- the most common case.
1323 return blame_origin_incref (porigin
);
1326 /* See if the origin->path is different between parent
1327 * and origin first. Most of the time they are the
1328 * same and diff-tree is fairly efficient about this.
1330 repo_diff_setup(r
, &diff_opts
);
1331 diff_opts
.flags
.recursive
= 1;
1332 diff_opts
.detect_rename
= 0;
1333 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1334 paths
[0] = origin
->path
;
1337 parse_pathspec(&diff_opts
.pathspec
,
1338 PATHSPEC_ALL_MAGIC
& ~PATHSPEC_LITERAL
,
1339 PATHSPEC_LITERAL_PATH
, "", paths
);
1340 diff_setup_done(&diff_opts
);
1342 if (is_null_oid(&origin
->commit
->object
.oid
))
1343 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1345 int compute_diff
= 1;
1346 if (origin
->commit
->parents
&&
1347 oideq(&parent
->object
.oid
,
1348 &origin
->commit
->parents
->item
->object
.oid
))
1349 compute_diff
= maybe_changed_path(r
, origin
, bd
);
1352 diff_tree_oid(get_commit_tree_oid(parent
),
1353 get_commit_tree_oid(origin
->commit
),
1356 diffcore_std(&diff_opts
);
1358 if (!diff_queued_diff
.nr
) {
1359 /* The path is the same as parent */
1360 porigin
= get_origin(parent
, origin
->path
);
1361 oidcpy(&porigin
->blob_oid
, &origin
->blob_oid
);
1362 porigin
->mode
= origin
->mode
;
1365 * Since origin->path is a pathspec, if the parent
1366 * commit had it as a directory, we will see a whole
1367 * bunch of deletion of files in the directory that we
1368 * do not care about.
1371 struct diff_filepair
*p
= NULL
;
1372 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1374 p
= diff_queued_diff
.queue
[i
];
1375 name
= p
->one
->path
? p
->one
->path
: p
->two
->path
;
1376 if (!strcmp(name
, origin
->path
))
1380 die("internal error in blame::find_origin");
1381 switch (p
->status
) {
1383 die("internal error in blame::find_origin (%c)",
1386 porigin
= get_origin(parent
, origin
->path
);
1387 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1388 porigin
->mode
= p
->one
->mode
;
1392 /* Did not exist in parent, or type changed */
1396 diff_flush(&diff_opts
);
1401 * We have an origin -- find the path that corresponds to it in its
1402 * parent and return an origin structure to represent it.
1404 static struct blame_origin
*find_rename(struct repository
*r
,
1405 struct commit
*parent
,
1406 struct blame_origin
*origin
,
1407 struct blame_bloom_data
*bd
)
1409 struct blame_origin
*porigin
= NULL
;
1410 struct diff_options diff_opts
;
1413 repo_diff_setup(r
, &diff_opts
);
1414 diff_opts
.flags
.recursive
= 1;
1415 diff_opts
.detect_rename
= DIFF_DETECT_RENAME
;
1416 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1417 diff_opts
.single_follow
= origin
->path
;
1418 diff_setup_done(&diff_opts
);
1420 if (is_null_oid(&origin
->commit
->object
.oid
))
1421 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1423 diff_tree_oid(get_commit_tree_oid(parent
),
1424 get_commit_tree_oid(origin
->commit
),
1426 diffcore_std(&diff_opts
);
1428 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1429 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
1430 if ((p
->status
== 'R' || p
->status
== 'C') &&
1431 !strcmp(p
->two
->path
, origin
->path
)) {
1432 add_bloom_key(bd
, p
->one
->path
);
1433 porigin
= get_origin(parent
, p
->one
->path
);
1434 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1435 porigin
->mode
= p
->one
->mode
;
1439 diff_flush(&diff_opts
);
1444 * Append a new blame entry to a given output queue.
1446 static void add_blame_entry(struct blame_entry
***queue
,
1447 const struct blame_entry
*src
)
1449 struct blame_entry
*e
= xmalloc(sizeof(*e
));
1450 memcpy(e
, src
, sizeof(*e
));
1451 blame_origin_incref(e
->suspect
);
1459 * src typically is on-stack; we want to copy the information in it to
1460 * a malloced blame_entry that gets added to the given queue. The
1461 * origin of dst loses a refcnt.
1463 static void dup_entry(struct blame_entry
***queue
,
1464 struct blame_entry
*dst
, struct blame_entry
*src
)
1466 blame_origin_incref(src
->suspect
);
1467 blame_origin_decref(dst
->suspect
);
1468 memcpy(dst
, src
, sizeof(*src
));
1469 dst
->next
= **queue
;
1471 *queue
= &dst
->next
;
1474 const char *blame_nth_line(struct blame_scoreboard
*sb
, long lno
)
1476 return sb
->final_buf
+ sb
->lineno
[lno
];
1480 * It is known that lines between tlno to same came from parent, and e
1481 * has an overlap with that range. it also is known that parent's
1482 * line plno corresponds to e's line tlno.
1488 * <------------------>
1490 * Split e into potentially three parts; before this chunk, the chunk
1491 * to be blamed for the parent, and after that portion.
1493 static void split_overlap(struct blame_entry
*split
,
1494 struct blame_entry
*e
,
1495 int tlno
, int plno
, int same
,
1496 struct blame_origin
*parent
)
1500 memset(split
, 0, sizeof(struct blame_entry
[3]));
1502 for (i
= 0; i
< 3; i
++) {
1503 split
[i
].ignored
= e
->ignored
;
1504 split
[i
].unblamable
= e
->unblamable
;
1507 if (e
->s_lno
< tlno
) {
1508 /* there is a pre-chunk part not blamed on parent */
1509 split
[0].suspect
= blame_origin_incref(e
->suspect
);
1510 split
[0].lno
= e
->lno
;
1511 split
[0].s_lno
= e
->s_lno
;
1512 split
[0].num_lines
= tlno
- e
->s_lno
;
1513 split
[1].lno
= e
->lno
+ tlno
- e
->s_lno
;
1514 split
[1].s_lno
= plno
;
1517 split
[1].lno
= e
->lno
;
1518 split
[1].s_lno
= plno
+ (e
->s_lno
- tlno
);
1521 if (same
< e
->s_lno
+ e
->num_lines
) {
1522 /* there is a post-chunk part not blamed on parent */
1523 split
[2].suspect
= blame_origin_incref(e
->suspect
);
1524 split
[2].lno
= e
->lno
+ (same
- e
->s_lno
);
1525 split
[2].s_lno
= e
->s_lno
+ (same
- e
->s_lno
);
1526 split
[2].num_lines
= e
->s_lno
+ e
->num_lines
- same
;
1527 chunk_end_lno
= split
[2].lno
;
1530 chunk_end_lno
= e
->lno
+ e
->num_lines
;
1531 split
[1].num_lines
= chunk_end_lno
- split
[1].lno
;
1534 * if it turns out there is nothing to blame the parent for,
1535 * forget about the splitting. !split[1].suspect signals this.
1537 if (split
[1].num_lines
< 1)
1539 split
[1].suspect
= blame_origin_incref(parent
);
1543 * split_overlap() divided an existing blame e into up to three parts
1544 * in split. Any assigned blame is moved to queue to
1545 * reflect the split.
1547 static void split_blame(struct blame_entry
***blamed
,
1548 struct blame_entry
***unblamed
,
1549 struct blame_entry
*split
,
1550 struct blame_entry
*e
)
1552 if (split
[0].suspect
&& split
[2].suspect
) {
1553 /* The first part (reuse storage for the existing entry e) */
1554 dup_entry(unblamed
, e
, &split
[0]);
1556 /* The last part -- me */
1557 add_blame_entry(unblamed
, &split
[2]);
1559 /* ... and the middle part -- parent */
1560 add_blame_entry(blamed
, &split
[1]);
1562 else if (!split
[0].suspect
&& !split
[2].suspect
)
1564 * The parent covers the entire area; reuse storage for
1565 * e and replace it with the parent.
1567 dup_entry(blamed
, e
, &split
[1]);
1568 else if (split
[0].suspect
) {
1569 /* me and then parent */
1570 dup_entry(unblamed
, e
, &split
[0]);
1571 add_blame_entry(blamed
, &split
[1]);
1574 /* parent and then me */
1575 dup_entry(blamed
, e
, &split
[1]);
1576 add_blame_entry(unblamed
, &split
[2]);
1581 * After splitting the blame, the origins used by the
1582 * on-stack blame_entry should lose one refcnt each.
1584 static void decref_split(struct blame_entry
*split
)
1588 for (i
= 0; i
< 3; i
++)
1589 blame_origin_decref(split
[i
].suspect
);
1593 * reverse_blame reverses the list given in head, appending tail.
1594 * That allows us to build lists in reverse order, then reverse them
1595 * afterwards. This can be faster than building the list in proper
1596 * order right away. The reason is that building in proper order
1597 * requires writing a link in the _previous_ element, while building
1598 * in reverse order just requires placing the list head into the
1599 * _current_ element.
1602 static struct blame_entry
*reverse_blame(struct blame_entry
*head
,
1603 struct blame_entry
*tail
)
1606 struct blame_entry
*next
= head
->next
;
1615 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1616 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1617 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1618 * e->num_lines). The caller needs to sort out the reference counting for the
1619 * new entry's suspect.
1621 static struct blame_entry
*split_blame_at(struct blame_entry
*e
, int len
,
1622 struct blame_origin
*new_suspect
)
1624 struct blame_entry
*n
= xcalloc(1, sizeof(struct blame_entry
));
1626 n
->suspect
= new_suspect
;
1627 n
->ignored
= e
->ignored
;
1628 n
->unblamable
= e
->unblamable
;
1629 n
->lno
= e
->lno
+ len
;
1630 n
->s_lno
= e
->s_lno
+ len
;
1631 n
->num_lines
= e
->num_lines
- len
;
1637 struct blame_line_tracker
{
1642 static int are_lines_adjacent(struct blame_line_tracker
*first
,
1643 struct blame_line_tracker
*second
)
1645 return first
->is_parent
== second
->is_parent
&&
1646 first
->s_lno
+ 1 == second
->s_lno
;
1649 static int scan_parent_range(struct fingerprint
*p_fps
,
1650 struct fingerprint
*t_fps
, int t_idx
,
1651 int from
, int nr_lines
)
1654 #define FINGERPRINT_FILE_THRESHOLD 10
1655 int best_sim_val
= FINGERPRINT_FILE_THRESHOLD
;
1656 int best_sim_idx
= -1;
1658 for (p_idx
= from
; p_idx
< from
+ nr_lines
; p_idx
++) {
1659 sim
= fingerprint_similarity(&t_fps
[t_idx
], &p_fps
[p_idx
]);
1660 if (sim
< best_sim_val
)
1662 /* Break ties with the closest-to-target line number */
1663 if (sim
== best_sim_val
&& best_sim_idx
!= -1 &&
1664 abs(best_sim_idx
- t_idx
) < abs(p_idx
- t_idx
))
1667 best_sim_idx
= p_idx
;
1669 return best_sim_idx
;
1673 * The first pass checks the blame entry (from the target) against the parent's
1674 * diff chunk. If that fails for a line, the second pass tries to match that
1675 * line to any part of parent file. That catches cases where a change was
1676 * broken into two chunks by 'context.'
1678 static void guess_line_blames(struct blame_origin
*parent
,
1679 struct blame_origin
*target
,
1680 int tlno
, int offset
, int same
, int parent_len
,
1681 struct blame_line_tracker
*line_blames
)
1683 int i
, best_idx
, target_idx
;
1684 int parent_slno
= tlno
+ offset
;
1687 fuzzy_matches
= fuzzy_find_matching_lines(parent
, target
,
1688 tlno
, parent_slno
, same
,
1690 for (i
= 0; i
< same
- tlno
; i
++) {
1691 target_idx
= tlno
+ i
;
1692 if (fuzzy_matches
&& fuzzy_matches
[i
] >= 0) {
1693 best_idx
= fuzzy_matches
[i
];
1695 best_idx
= scan_parent_range(parent
->fingerprints
,
1696 target
->fingerprints
,
1700 if (best_idx
>= 0) {
1701 line_blames
[i
].is_parent
= 1;
1702 line_blames
[i
].s_lno
= best_idx
;
1704 line_blames
[i
].is_parent
= 0;
1705 line_blames
[i
].s_lno
= target_idx
;
1708 free(fuzzy_matches
);
1712 * This decides which parts of a blame entry go to the parent (added to the
1713 * ignoredp list) and which stay with the target (added to the diffp list). The
1714 * actual decision was made in a separate heuristic function, and those answers
1715 * for the lines in 'e' are in line_blames. This consumes e, essentially
1716 * putting it on a list.
1718 * Note that the blame entries on the ignoredp list are not necessarily sorted
1719 * with respect to the parent's line numbers yet.
1721 static void ignore_blame_entry(struct blame_entry
*e
,
1722 struct blame_origin
*parent
,
1723 struct blame_entry
**diffp
,
1724 struct blame_entry
**ignoredp
,
1725 struct blame_line_tracker
*line_blames
)
1727 int entry_len
, nr_lines
, i
;
1730 * We carve new entries off the front of e. Each entry comes from a
1731 * contiguous chunk of lines: adjacent lines from the same origin
1732 * (either the parent or the target).
1735 nr_lines
= e
->num_lines
; /* e changes in the loop */
1736 for (i
= 0; i
< nr_lines
; i
++) {
1737 struct blame_entry
*next
= NULL
;
1740 * We are often adjacent to the next line - only split the blame
1741 * entry when we have to.
1743 if (i
+ 1 < nr_lines
) {
1744 if (are_lines_adjacent(&line_blames
[i
],
1745 &line_blames
[i
+ 1])) {
1749 next
= split_blame_at(e
, entry_len
,
1750 blame_origin_incref(e
->suspect
));
1752 if (line_blames
[i
].is_parent
) {
1754 blame_origin_decref(e
->suspect
);
1755 e
->suspect
= blame_origin_incref(parent
);
1756 e
->s_lno
= line_blames
[i
- entry_len
+ 1].s_lno
;
1757 e
->next
= *ignoredp
;
1761 /* e->s_lno is already in the target's address space. */
1765 assert(e
->num_lines
== entry_len
);
1773 * Process one hunk from the patch between the current suspect for
1774 * blame_entry e and its parent. This first blames any unfinished
1775 * entries before the chunk (which is where target and parent start
1776 * differing) on the parent, and then splits blame entries at the
1777 * start and at the end of the difference region. Since use of -M and
1778 * -C options may lead to overlapping/duplicate source line number
1779 * ranges, all we can rely on from sorting/merging is the order of the
1780 * first suspect line number.
1782 * tlno: line number in the target where this chunk begins
1783 * same: line number in the target where this chunk ends
1784 * offset: add to tlno to get the chunk starting point in the parent
1785 * parent_len: number of lines in the parent chunk
1787 static void blame_chunk(struct blame_entry
***dstq
, struct blame_entry
***srcq
,
1788 int tlno
, int offset
, int same
, int parent_len
,
1789 struct blame_origin
*parent
,
1790 struct blame_origin
*target
, int ignore_diffs
)
1792 struct blame_entry
*e
= **srcq
;
1793 struct blame_entry
*samep
= NULL
, *diffp
= NULL
, *ignoredp
= NULL
;
1794 struct blame_line_tracker
*line_blames
= NULL
;
1796 while (e
&& e
->s_lno
< tlno
) {
1797 struct blame_entry
*next
= e
->next
;
1799 * current record starts before differing portion. If
1800 * it reaches into it, we need to split it up and
1801 * examine the second part separately.
1803 if (e
->s_lno
+ e
->num_lines
> tlno
) {
1804 /* Move second half to a new record */
1805 struct blame_entry
*n
;
1807 n
= split_blame_at(e
, tlno
- e
->s_lno
, e
->suspect
);
1808 /* Push new record to diffp */
1812 blame_origin_decref(e
->suspect
);
1813 /* Pass blame for everything before the differing
1814 * chunk to the parent */
1815 e
->suspect
= blame_origin_incref(parent
);
1822 * As we don't know how much of a common stretch after this
1823 * diff will occur, the currently blamed parts are all that we
1824 * can assign to the parent for now.
1828 **dstq
= reverse_blame(samep
, **dstq
);
1829 *dstq
= &samep
->next
;
1832 * Prepend the split off portions: everything after e starts
1833 * after the blameable portion.
1835 e
= reverse_blame(diffp
, e
);
1838 * Now retain records on the target while parts are different
1844 if (ignore_diffs
&& same
- tlno
> 0) {
1845 CALLOC_ARRAY(line_blames
, same
- tlno
);
1846 guess_line_blames(parent
, target
, tlno
, offset
, same
,
1847 parent_len
, line_blames
);
1850 while (e
&& e
->s_lno
< same
) {
1851 struct blame_entry
*next
= e
->next
;
1854 * If current record extends into sameness, need to split.
1856 if (e
->s_lno
+ e
->num_lines
> same
) {
1858 * Move second half to a new record to be
1859 * processed by later chunks
1861 struct blame_entry
*n
;
1863 n
= split_blame_at(e
, same
- e
->s_lno
,
1864 blame_origin_incref(e
->suspect
));
1865 /* Push new record to samep */
1870 ignore_blame_entry(e
, parent
, &diffp
, &ignoredp
,
1871 line_blames
+ e
->s_lno
- tlno
);
1881 * Note ignoredp is not sorted yet, and thus neither is dstq.
1882 * That list must be sorted before we queue_blames(). We defer
1883 * sorting until after all diff hunks are processed, so that
1884 * guess_line_blames() can pick *any* line in the parent. The
1885 * slight drawback is that we end up sorting all blame entries
1886 * passed to the parent, including those that are unrelated to
1887 * changes made by the ignored commit.
1889 **dstq
= reverse_blame(ignoredp
, **dstq
);
1890 *dstq
= &ignoredp
->next
;
1892 **srcq
= reverse_blame(diffp
, reverse_blame(samep
, e
));
1893 /* Move across elements that are in the unblamable portion */
1895 *srcq
= &diffp
->next
;
1898 struct blame_chunk_cb_data
{
1899 struct blame_origin
*parent
;
1900 struct blame_origin
*target
;
1903 struct blame_entry
**dstq
;
1904 struct blame_entry
**srcq
;
1907 /* diff chunks are from parent to target */
1908 static int blame_chunk_cb(long start_a
, long count_a
,
1909 long start_b
, long count_b
, void *data
)
1911 struct blame_chunk_cb_data
*d
= data
;
1912 if (start_a
- start_b
!= d
->offset
)
1913 die("internal error in blame::blame_chunk_cb");
1914 blame_chunk(&d
->dstq
, &d
->srcq
, start_b
, start_a
- start_b
,
1915 start_b
+ count_b
, count_a
, d
->parent
, d
->target
,
1917 d
->offset
= start_a
+ count_a
- (start_b
+ count_b
);
1922 * We are looking at the origin 'target' and aiming to pass blame
1923 * for the lines it is suspected to its parent. Run diff to find
1924 * which lines came from parent and pass blame for them.
1926 static void pass_blame_to_parent(struct blame_scoreboard
*sb
,
1927 struct blame_origin
*target
,
1928 struct blame_origin
*parent
, int ignore_diffs
)
1930 mmfile_t file_p
, file_o
;
1931 struct blame_chunk_cb_data d
;
1932 struct blame_entry
*newdest
= NULL
;
1934 if (!target
->suspects
)
1935 return; /* nothing remains for this target */
1940 d
.ignore_diffs
= ignore_diffs
;
1941 d
.dstq
= &newdest
; d
.srcq
= &target
->suspects
;
1943 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
1944 &sb
->num_read_blob
, ignore_diffs
);
1945 fill_origin_blob(&sb
->revs
->diffopt
, target
, &file_o
,
1946 &sb
->num_read_blob
, ignore_diffs
);
1947 sb
->num_get_patch
++;
1949 if (diff_hunks(&file_p
, &file_o
, blame_chunk_cb
, &d
, sb
->xdl_opts
))
1950 die("unable to generate diff (%s -> %s)",
1951 oid_to_hex(&parent
->commit
->object
.oid
),
1952 oid_to_hex(&target
->commit
->object
.oid
));
1953 /* The rest are the same as the parent */
1954 blame_chunk(&d
.dstq
, &d
.srcq
, INT_MAX
, d
.offset
, INT_MAX
, 0,
1958 sort_blame_entries(&newdest
, compare_blame_suspect
);
1959 queue_blames(sb
, parent
, newdest
);
1965 * The lines in blame_entry after splitting blames many times can become
1966 * very small and trivial, and at some point it becomes pointless to
1967 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1968 * ordinary C program, and it is not worth to say it was copied from
1969 * totally unrelated file in the parent.
1971 * Compute how trivial the lines in the blame_entry are.
1973 unsigned blame_entry_score(struct blame_scoreboard
*sb
, struct blame_entry
*e
)
1976 const char *cp
, *ep
;
1982 cp
= blame_nth_line(sb
, e
->lno
);
1983 ep
= blame_nth_line(sb
, e
->lno
+ e
->num_lines
);
1985 unsigned ch
= *((unsigned char *)cp
);
1995 * best_so_far[] and potential[] are both a split of an existing blame_entry
1996 * that passes blame to the parent. Maintain best_so_far the best split so
1997 * far, by comparing potential and best_so_far and copying potential into
1998 * bst_so_far as needed.
2000 static void copy_split_if_better(struct blame_scoreboard
*sb
,
2001 struct blame_entry
*best_so_far
,
2002 struct blame_entry
*potential
)
2006 if (!potential
[1].suspect
)
2008 if (best_so_far
[1].suspect
) {
2009 if (blame_entry_score(sb
, &potential
[1]) <
2010 blame_entry_score(sb
, &best_so_far
[1]))
2014 for (i
= 0; i
< 3; i
++)
2015 blame_origin_incref(potential
[i
].suspect
);
2016 decref_split(best_so_far
);
2017 memcpy(best_so_far
, potential
, sizeof(struct blame_entry
[3]));
2021 * We are looking at a part of the final image represented by
2022 * ent (tlno and same are offset by ent->s_lno).
2023 * tlno is where we are looking at in the final image.
2024 * up to (but not including) same match preimage.
2025 * plno is where we are looking at in the preimage.
2027 * <-------------- final image ---------------------->
2030 * <---------preimage----->
2033 * All line numbers are 0-based.
2035 static void handle_split(struct blame_scoreboard
*sb
,
2036 struct blame_entry
*ent
,
2037 int tlno
, int plno
, int same
,
2038 struct blame_origin
*parent
,
2039 struct blame_entry
*split
)
2041 if (ent
->num_lines
<= tlno
)
2044 struct blame_entry potential
[3];
2047 split_overlap(potential
, ent
, tlno
, plno
, same
, parent
);
2048 copy_split_if_better(sb
, split
, potential
);
2049 decref_split(potential
);
2053 struct handle_split_cb_data
{
2054 struct blame_scoreboard
*sb
;
2055 struct blame_entry
*ent
;
2056 struct blame_origin
*parent
;
2057 struct blame_entry
*split
;
2062 static int handle_split_cb(long start_a
, long count_a
,
2063 long start_b
, long count_b
, void *data
)
2065 struct handle_split_cb_data
*d
= data
;
2066 handle_split(d
->sb
, d
->ent
, d
->tlno
, d
->plno
, start_b
, d
->parent
,
2068 d
->plno
= start_a
+ count_a
;
2069 d
->tlno
= start_b
+ count_b
;
2074 * Find the lines from parent that are the same as ent so that
2075 * we can pass blames to it. file_p has the blob contents for
2078 static void find_copy_in_blob(struct blame_scoreboard
*sb
,
2079 struct blame_entry
*ent
,
2080 struct blame_origin
*parent
,
2081 struct blame_entry
*split
,
2086 struct handle_split_cb_data d
;
2088 memset(&d
, 0, sizeof(d
));
2089 d
.sb
= sb
; d
.ent
= ent
; d
.parent
= parent
; d
.split
= split
;
2091 * Prepare mmfile that contains only the lines in ent.
2093 cp
= blame_nth_line(sb
, ent
->lno
);
2094 file_o
.ptr
= (char *) cp
;
2095 file_o
.size
= blame_nth_line(sb
, ent
->lno
+ ent
->num_lines
) - cp
;
2098 * file_o is a part of final image we are annotating.
2099 * file_p partially may match that image.
2101 memset(split
, 0, sizeof(struct blame_entry
[3]));
2102 if (diff_hunks(file_p
, &file_o
, handle_split_cb
, &d
, sb
->xdl_opts
))
2103 die("unable to generate diff (%s)",
2104 oid_to_hex(&parent
->commit
->object
.oid
));
2105 /* remainder, if any, all match the preimage */
2106 handle_split(sb
, ent
, d
.tlno
, d
.plno
, ent
->num_lines
, parent
, split
);
2109 /* Move all blame entries from list *source that have a score smaller
2110 * than score_min to the front of list *small.
2111 * Returns a pointer to the link pointing to the old head of the small list.
2114 static struct blame_entry
**filter_small(struct blame_scoreboard
*sb
,
2115 struct blame_entry
**small
,
2116 struct blame_entry
**source
,
2119 struct blame_entry
*p
= *source
;
2120 struct blame_entry
*oldsmall
= *small
;
2122 if (blame_entry_score(sb
, p
) <= score_min
) {
2138 * See if lines currently target is suspected for can be attributed to
2141 static void find_move_in_parent(struct blame_scoreboard
*sb
,
2142 struct blame_entry
***blamed
,
2143 struct blame_entry
**toosmall
,
2144 struct blame_origin
*target
,
2145 struct blame_origin
*parent
)
2147 struct blame_entry
*e
, split
[3];
2148 struct blame_entry
*unblamed
= target
->suspects
;
2149 struct blame_entry
*leftover
= NULL
;
2153 return; /* nothing remains for this target */
2155 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
2156 &sb
->num_read_blob
, 0);
2160 /* At each iteration, unblamed has a NULL-terminated list of
2161 * entries that have not yet been tested for blame. leftover
2162 * contains the reversed list of entries that have been tested
2163 * without being assignable to the parent.
2166 struct blame_entry
**unblamedtail
= &unblamed
;
2167 struct blame_entry
*next
;
2168 for (e
= unblamed
; e
; e
= next
) {
2170 find_copy_in_blob(sb
, e
, parent
, split
, &file_p
);
2171 if (split
[1].suspect
&&
2172 sb
->move_score
< blame_entry_score(sb
, &split
[1])) {
2173 split_blame(blamed
, &unblamedtail
, split
, e
);
2178 decref_split(split
);
2180 *unblamedtail
= NULL
;
2181 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->move_score
);
2183 target
->suspects
= reverse_blame(leftover
, NULL
);
2187 struct blame_entry
*ent
;
2188 struct blame_entry split
[3];
2192 * Count the number of entries the target is suspected for,
2193 * and prepare a list of entry and the best split.
2195 static struct blame_list
*setup_blame_list(struct blame_entry
*unblamed
,
2198 struct blame_entry
*e
;
2200 struct blame_list
*blame_list
= NULL
;
2202 for (e
= unblamed
, num_ents
= 0; e
; e
= e
->next
)
2205 CALLOC_ARRAY(blame_list
, num_ents
);
2206 for (e
= unblamed
, i
= 0; e
; e
= e
->next
)
2207 blame_list
[i
++].ent
= e
;
2209 *num_ents_p
= num_ents
;
2214 * For lines target is suspected for, see if we can find code movement
2215 * across file boundary from the parent commit. porigin is the path
2216 * in the parent we already tried.
2218 static void find_copy_in_parent(struct blame_scoreboard
*sb
,
2219 struct blame_entry
***blamed
,
2220 struct blame_entry
**toosmall
,
2221 struct blame_origin
*target
,
2222 struct commit
*parent
,
2223 struct blame_origin
*porigin
,
2226 struct diff_options diff_opts
;
2228 struct blame_list
*blame_list
;
2230 struct blame_entry
*unblamed
= target
->suspects
;
2231 struct blame_entry
*leftover
= NULL
;
2234 return; /* nothing remains for this target */
2236 repo_diff_setup(sb
->repo
, &diff_opts
);
2237 diff_opts
.flags
.recursive
= 1;
2238 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
2240 diff_setup_done(&diff_opts
);
2242 /* Try "find copies harder" on new path if requested;
2243 * we do not want to use diffcore_rename() actually to
2244 * match things up; find_copies_harder is set only to
2245 * force diff_tree_oid() to feed all filepairs to diff_queue,
2246 * and this code needs to be after diff_setup_done(), which
2247 * usually makes find-copies-harder imply copy detection.
2249 if ((opt
& PICKAXE_BLAME_COPY_HARDEST
)
2250 || ((opt
& PICKAXE_BLAME_COPY_HARDER
)
2251 && (!porigin
|| strcmp(target
->path
, porigin
->path
))))
2252 diff_opts
.flags
.find_copies_harder
= 1;
2254 if (is_null_oid(&target
->commit
->object
.oid
))
2255 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
2257 diff_tree_oid(get_commit_tree_oid(parent
),
2258 get_commit_tree_oid(target
->commit
),
2261 if (!diff_opts
.flags
.find_copies_harder
)
2262 diffcore_std(&diff_opts
);
2265 struct blame_entry
**unblamedtail
= &unblamed
;
2266 blame_list
= setup_blame_list(unblamed
, &num_ents
);
2268 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
2269 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
2270 struct blame_origin
*norigin
;
2272 struct blame_entry potential
[3];
2274 if (!DIFF_FILE_VALID(p
->one
))
2275 continue; /* does not exist in parent */
2276 if (S_ISGITLINK(p
->one
->mode
))
2277 continue; /* ignore git links */
2278 if (porigin
&& !strcmp(p
->one
->path
, porigin
->path
))
2279 /* find_move already dealt with this path */
2282 norigin
= get_origin(parent
, p
->one
->path
);
2283 oidcpy(&norigin
->blob_oid
, &p
->one
->oid
);
2284 norigin
->mode
= p
->one
->mode
;
2285 fill_origin_blob(&sb
->revs
->diffopt
, norigin
, &file_p
,
2286 &sb
->num_read_blob
, 0);
2290 for (j
= 0; j
< num_ents
; j
++) {
2291 find_copy_in_blob(sb
, blame_list
[j
].ent
,
2292 norigin
, potential
, &file_p
);
2293 copy_split_if_better(sb
, blame_list
[j
].split
,
2295 decref_split(potential
);
2297 blame_origin_decref(norigin
);
2300 for (j
= 0; j
< num_ents
; j
++) {
2301 struct blame_entry
*split
= blame_list
[j
].split
;
2302 if (split
[1].suspect
&&
2303 sb
->copy_score
< blame_entry_score(sb
, &split
[1])) {
2304 split_blame(blamed
, &unblamedtail
, split
,
2307 blame_list
[j
].ent
->next
= leftover
;
2308 leftover
= blame_list
[j
].ent
;
2310 decref_split(split
);
2313 *unblamedtail
= NULL
;
2314 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->copy_score
);
2316 target
->suspects
= reverse_blame(leftover
, NULL
);
2317 diff_flush(&diff_opts
);
2321 * The blobs of origin and porigin exactly match, so everything
2322 * origin is suspected for can be blamed on the parent.
2324 static void pass_whole_blame(struct blame_scoreboard
*sb
,
2325 struct blame_origin
*origin
, struct blame_origin
*porigin
)
2327 struct blame_entry
*e
, *suspects
;
2329 if (!porigin
->file
.ptr
&& origin
->file
.ptr
) {
2330 /* Steal its file */
2331 porigin
->file
= origin
->file
;
2332 origin
->file
.ptr
= NULL
;
2334 suspects
= origin
->suspects
;
2335 origin
->suspects
= NULL
;
2336 for (e
= suspects
; e
; e
= e
->next
) {
2337 blame_origin_incref(porigin
);
2338 blame_origin_decref(e
->suspect
);
2339 e
->suspect
= porigin
;
2341 queue_blames(sb
, porigin
, suspects
);
2345 * We pass blame from the current commit to its parents. We keep saying
2346 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2347 * exonerate ourselves.
2349 static struct commit_list
*first_scapegoat(struct rev_info
*revs
, struct commit
*commit
,
2353 if (revs
->first_parent_only
&&
2355 commit
->parents
->next
) {
2356 free_commit_list(commit
->parents
->next
);
2357 commit
->parents
->next
= NULL
;
2359 return commit
->parents
;
2361 return lookup_decoration(&revs
->children
, &commit
->object
);
2364 static int num_scapegoats(struct rev_info
*revs
, struct commit
*commit
, int reverse
)
2366 struct commit_list
*l
= first_scapegoat(revs
, commit
, reverse
);
2367 return commit_list_count(l
);
2370 /* Distribute collected unsorted blames to the respected sorted lists
2371 * in the various origins.
2373 static void distribute_blame(struct blame_scoreboard
*sb
, struct blame_entry
*blamed
)
2375 sort_blame_entries(&blamed
, compare_blame_suspect
);
2378 struct blame_origin
*porigin
= blamed
->suspect
;
2379 struct blame_entry
*suspects
= NULL
;
2381 struct blame_entry
*next
= blamed
->next
;
2382 blamed
->next
= suspects
;
2385 } while (blamed
&& blamed
->suspect
== porigin
);
2386 suspects
= reverse_blame(suspects
, NULL
);
2387 queue_blames(sb
, porigin
, suspects
);
2393 typedef struct blame_origin
*(*blame_find_alg
)(struct repository
*,
2395 struct blame_origin
*,
2396 struct blame_bloom_data
*);
2398 static void pass_blame(struct blame_scoreboard
*sb
, struct blame_origin
*origin
, int opt
)
2400 struct rev_info
*revs
= sb
->revs
;
2401 int i
, pass
, num_sg
;
2402 struct commit
*commit
= origin
->commit
;
2403 struct commit_list
*sg
;
2404 struct blame_origin
*sg_buf
[MAXSG
];
2405 struct blame_origin
*porigin
, **sg_origin
= sg_buf
;
2406 struct blame_entry
*toosmall
= NULL
;
2407 struct blame_entry
*blames
, **blametail
= &blames
;
2409 num_sg
= num_scapegoats(revs
, commit
, sb
->reverse
);
2412 else if (num_sg
< ARRAY_SIZE(sg_buf
))
2413 memset(sg_buf
, 0, sizeof(sg_buf
));
2415 CALLOC_ARRAY(sg_origin
, num_sg
);
2418 * The first pass looks for unrenamed path to optimize for
2419 * common cases, then we look for renames in the second pass.
2421 for (pass
= 0; pass
< 2 - sb
->no_whole_file_rename
; pass
++) {
2422 blame_find_alg find
= pass
? find_rename
: find_origin
;
2424 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2426 sg
= sg
->next
, i
++) {
2427 struct commit
*p
= sg
->item
;
2432 if (parse_commit(p
))
2434 porigin
= find(sb
->repo
, p
, origin
, sb
->bloom_data
);
2437 if (oideq(&porigin
->blob_oid
, &origin
->blob_oid
)) {
2438 pass_whole_blame(sb
, origin
, porigin
);
2439 blame_origin_decref(porigin
);
2442 for (j
= same
= 0; j
< i
; j
++)
2444 oideq(&sg_origin
[j
]->blob_oid
, &porigin
->blob_oid
)) {
2449 sg_origin
[i
] = porigin
;
2451 blame_origin_decref(porigin
);
2456 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2458 sg
= sg
->next
, i
++) {
2459 struct blame_origin
*porigin
= sg_origin
[i
];
2462 if (!origin
->previous
) {
2463 blame_origin_incref(porigin
);
2464 origin
->previous
= porigin
;
2466 pass_blame_to_parent(sb
, origin
, porigin
, 0);
2467 if (!origin
->suspects
)
2472 * Pass remaining suspects for ignored commits to their parents.
2474 if (oidset_contains(&sb
->ignore_list
, &commit
->object
.oid
)) {
2475 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2477 sg
= sg
->next
, i
++) {
2478 struct blame_origin
*porigin
= sg_origin
[i
];
2482 pass_blame_to_parent(sb
, origin
, porigin
, 1);
2484 * Preemptively drop porigin so we can refresh the
2485 * fingerprints if we use the parent again, which can
2486 * occur if you ignore back-to-back commits.
2488 drop_origin_blob(porigin
);
2489 if (!origin
->suspects
)
2495 * Optionally find moves in parents' files.
2497 if (opt
& PICKAXE_BLAME_MOVE
) {
2498 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->move_score
);
2499 if (origin
->suspects
) {
2500 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2502 sg
= sg
->next
, i
++) {
2503 struct blame_origin
*porigin
= sg_origin
[i
];
2506 find_move_in_parent(sb
, &blametail
, &toosmall
, origin
, porigin
);
2507 if (!origin
->suspects
)
2514 * Optionally find copies from parents' files.
2516 if (opt
& PICKAXE_BLAME_COPY
) {
2517 if (sb
->copy_score
> sb
->move_score
)
2518 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2519 else if (sb
->copy_score
< sb
->move_score
) {
2520 origin
->suspects
= blame_merge(origin
->suspects
, toosmall
);
2522 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2524 if (!origin
->suspects
)
2527 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2529 sg
= sg
->next
, i
++) {
2530 struct blame_origin
*porigin
= sg_origin
[i
];
2531 find_copy_in_parent(sb
, &blametail
, &toosmall
,
2532 origin
, sg
->item
, porigin
, opt
);
2533 if (!origin
->suspects
)
2540 distribute_blame(sb
, blames
);
2542 * prepend toosmall to origin->suspects
2544 * There is no point in sorting: this ends up on a big
2545 * unsorted list in the caller anyway.
2548 struct blame_entry
**tail
= &toosmall
;
2550 tail
= &(*tail
)->next
;
2551 *tail
= origin
->suspects
;
2552 origin
->suspects
= toosmall
;
2554 for (i
= 0; i
< num_sg
; i
++) {
2556 if (!sg_origin
[i
]->suspects
)
2557 drop_origin_blob(sg_origin
[i
]);
2558 blame_origin_decref(sg_origin
[i
]);
2561 drop_origin_blob(origin
);
2562 if (sg_buf
!= sg_origin
)
2567 * The main loop -- while we have blobs with lines whose true origin
2568 * is still unknown, pick one blob, and allow its lines to pass blames
2569 * to its parents. */
2570 void assign_blame(struct blame_scoreboard
*sb
, int opt
)
2572 struct rev_info
*revs
= sb
->revs
;
2573 struct commit
*commit
= prio_queue_get(&sb
->commits
);
2576 struct blame_entry
*ent
;
2577 struct blame_origin
*suspect
= get_blame_suspects(commit
);
2579 /* find one suspect to break down */
2580 while (suspect
&& !suspect
->suspects
)
2581 suspect
= suspect
->next
;
2584 commit
= prio_queue_get(&sb
->commits
);
2588 assert(commit
== suspect
->commit
);
2591 * We will use this suspect later in the loop,
2592 * so hold onto it in the meantime.
2594 blame_origin_incref(suspect
);
2595 parse_commit(commit
);
2597 (!(commit
->object
.flags
& UNINTERESTING
) &&
2598 !(revs
->max_age
!= -1 && commit
->date
< revs
->max_age
)))
2599 pass_blame(sb
, suspect
, opt
);
2601 commit
->object
.flags
|= UNINTERESTING
;
2602 if (commit
->object
.parsed
)
2603 mark_parents_uninteresting(sb
->revs
, commit
);
2605 /* treat root commit as boundary */
2606 if (!commit
->parents
&& !sb
->show_root
)
2607 commit
->object
.flags
|= UNINTERESTING
;
2609 /* Take responsibility for the remaining entries */
2610 ent
= suspect
->suspects
;
2612 suspect
->guilty
= 1;
2614 struct blame_entry
*next
= ent
->next
;
2615 if (sb
->found_guilty_entry
)
2616 sb
->found_guilty_entry(ent
, sb
->found_guilty_entry_data
);
2621 ent
->next
= sb
->ent
;
2622 sb
->ent
= suspect
->suspects
;
2623 suspect
->suspects
= NULL
;
2627 blame_origin_decref(suspect
);
2629 if (sb
->debug
) /* sanity */
2630 sanity_check_refcnt(sb
);
2635 * To allow quick access to the contents of nth line in the
2636 * final image, prepare an index in the scoreboard.
2638 static int prepare_lines(struct blame_scoreboard
*sb
)
2640 sb
->num_lines
= find_line_starts(&sb
->lineno
, sb
->final_buf
,
2641 sb
->final_buf_size
);
2642 return sb
->num_lines
;
2645 static struct commit
*find_single_final(struct rev_info
*revs
,
2646 const char **name_p
)
2649 struct commit
*found
= NULL
;
2650 const char *name
= NULL
;
2652 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2653 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2654 if (obj
->flags
& UNINTERESTING
)
2656 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2657 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2658 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2660 die("More than one commit to dig from %s and %s?",
2661 revs
->pending
.objects
[i
].name
, name
);
2662 found
= (struct commit
*)obj
;
2663 name
= revs
->pending
.objects
[i
].name
;
2666 *name_p
= xstrdup_or_null(name
);
2670 static struct commit
*dwim_reverse_initial(struct rev_info
*revs
,
2671 const char **name_p
)
2674 * DWIM "git blame --reverse ONE -- PATH" as
2675 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2676 * when it makes sense.
2679 struct commit
*head_commit
;
2680 struct object_id head_oid
;
2682 if (revs
->pending
.nr
!= 1)
2685 /* Is that sole rev a committish? */
2686 obj
= revs
->pending
.objects
[0].item
;
2687 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2688 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2691 /* Do we have HEAD? */
2692 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
2694 head_commit
= lookup_commit_reference_gently(revs
->repo
,
2699 /* Turn "ONE" into "ONE..HEAD" then */
2700 obj
->flags
|= UNINTERESTING
;
2701 add_pending_object(revs
, &head_commit
->object
, "HEAD");
2704 *name_p
= revs
->pending
.objects
[0].name
;
2705 return (struct commit
*)obj
;
2708 static struct commit
*find_single_initial(struct rev_info
*revs
,
2709 const char **name_p
)
2712 struct commit
*found
= NULL
;
2713 const char *name
= NULL
;
2716 * There must be one and only one negative commit, and it must be
2719 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2720 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2721 if (!(obj
->flags
& UNINTERESTING
))
2723 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2724 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2725 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2727 die("More than one commit to dig up from, %s and %s?",
2728 revs
->pending
.objects
[i
].name
, name
);
2729 found
= (struct commit
*) obj
;
2730 name
= revs
->pending
.objects
[i
].name
;
2734 found
= dwim_reverse_initial(revs
, &name
);
2736 die("No commit to dig up from?");
2739 *name_p
= xstrdup(name
);
2743 void init_scoreboard(struct blame_scoreboard
*sb
)
2745 memset(sb
, 0, sizeof(struct blame_scoreboard
));
2746 sb
->move_score
= BLAME_DEFAULT_MOVE_SCORE
;
2747 sb
->copy_score
= BLAME_DEFAULT_COPY_SCORE
;
2750 void setup_scoreboard(struct blame_scoreboard
*sb
,
2751 struct blame_origin
**orig
)
2753 const char *final_commit_name
= NULL
;
2754 struct blame_origin
*o
;
2755 struct commit
*final_commit
= NULL
;
2756 enum object_type type
;
2758 init_blame_suspects(&blame_suspects
);
2760 if (sb
->reverse
&& sb
->contents_from
)
2761 die(_("--contents and --reverse do not blend well."));
2764 BUG("repo is NULL");
2767 sb
->final
= find_single_final(sb
->revs
, &final_commit_name
);
2768 sb
->commits
.compare
= compare_commits_by_commit_date
;
2770 sb
->final
= find_single_initial(sb
->revs
, &final_commit_name
);
2771 sb
->commits
.compare
= compare_commits_by_reverse_commit_date
;
2774 if (sb
->final
&& sb
->contents_from
)
2775 die(_("cannot use --contents with final commit object name"));
2777 if (sb
->reverse
&& sb
->revs
->first_parent_only
)
2778 sb
->revs
->children
.name
= NULL
;
2782 * "--not A B -- path" without anything positive;
2783 * do not default to HEAD, but use the working tree
2787 sb
->final
= fake_working_tree_commit(sb
->repo
,
2789 sb
->path
, sb
->contents_from
);
2790 add_pending_object(sb
->revs
, &(sb
->final
->object
), ":");
2793 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2794 final_commit
= find_single_final(sb
->revs
, NULL
);
2796 die(_("--reverse and --first-parent together require specified latest commit"));
2800 * If we have bottom, this will mark the ancestors of the
2801 * bottom commits we would reach while traversing as
2804 if (prepare_revision_walk(sb
->revs
))
2805 die(_("revision walk setup failed"));
2807 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2808 struct commit
*c
= final_commit
;
2810 sb
->revs
->children
.name
= "children";
2811 while (c
->parents
&&
2812 !oideq(&c
->object
.oid
, &sb
->final
->object
.oid
)) {
2813 struct commit_list
*l
= xcalloc(1, sizeof(*l
));
2816 if (add_decoration(&sb
->revs
->children
,
2817 &c
->parents
->item
->object
, l
))
2818 BUG("not unique item in first-parent chain");
2819 c
= c
->parents
->item
;
2822 if (!oideq(&c
->object
.oid
, &sb
->final
->object
.oid
))
2823 die(_("--reverse --first-parent together require range along first-parent chain"));
2826 if (is_null_oid(&sb
->final
->object
.oid
)) {
2827 o
= get_blame_suspects(sb
->final
);
2828 sb
->final_buf
= xmemdupz(o
->file
.ptr
, o
->file
.size
);
2829 sb
->final_buf_size
= o
->file
.size
;
2832 o
= get_origin(sb
->final
, sb
->path
);
2833 if (fill_blob_sha1_and_mode(sb
->repo
, o
))
2834 die(_("no such path %s in %s"), sb
->path
, final_commit_name
);
2836 if (sb
->revs
->diffopt
.flags
.allow_textconv
&&
2837 textconv_object(sb
->repo
, sb
->path
, o
->mode
, &o
->blob_oid
, 1, (char **) &sb
->final_buf
,
2838 &sb
->final_buf_size
))
2841 sb
->final_buf
= read_object_file(&o
->blob_oid
, &type
,
2842 &sb
->final_buf_size
);
2845 die(_("cannot read blob %s for path %s"),
2846 oid_to_hex(&o
->blob_oid
),
2849 sb
->num_read_blob
++;
2855 free((char *)final_commit_name
);
2860 struct blame_entry
*blame_entry_prepend(struct blame_entry
*head
,
2861 long start
, long end
,
2862 struct blame_origin
*o
)
2864 struct blame_entry
*new_head
= xcalloc(1, sizeof(struct blame_entry
));
2865 new_head
->lno
= start
;
2866 new_head
->num_lines
= end
- start
;
2867 new_head
->suspect
= o
;
2868 new_head
->s_lno
= start
;
2869 new_head
->next
= head
;
2870 blame_origin_incref(o
);
2874 void setup_blame_bloom_data(struct blame_scoreboard
*sb
)
2876 struct blame_bloom_data
*bd
;
2877 struct bloom_filter_settings
*bs
;
2879 if (!sb
->repo
->objects
->commit_graph
)
2882 bs
= get_bloom_filter_settings(sb
->repo
);
2886 bd
= xmalloc(sizeof(struct blame_bloom_data
));
2892 ALLOC_ARRAY(bd
->keys
, bd
->alloc
);
2894 add_bloom_key(bd
, sb
->path
);
2896 sb
->bloom_data
= bd
;
2899 void cleanup_scoreboard(struct blame_scoreboard
*sb
)
2901 if (sb
->bloom_data
) {
2903 for (i
= 0; i
< sb
->bloom_data
->nr
; i
++) {
2904 free(sb
->bloom_data
->keys
[i
]->hashes
);
2905 free(sb
->bloom_data
->keys
[i
]);
2907 free(sb
->bloom_data
->keys
);
2908 FREE_AND_NULL(sb
->bloom_data
);
2910 trace2_data_intmax("blame", sb
->repo
,
2911 "bloom/queries", bloom_count_queries
);
2912 trace2_data_intmax("blame", sb
->repo
,
2913 "bloom/response-no", bloom_count_no
);