3 #include "object-store.h"
4 #include "cache-tree.h"
12 #include "commit-slab.h"
14 #include "commit-graph.h"
16 define_commit_slab(blame_suspects
, struct blame_origin
*);
17 static struct blame_suspects blame_suspects
;
19 struct blame_origin
*get_blame_suspects(struct commit
*commit
)
21 struct blame_origin
**result
;
23 result
= blame_suspects_peek(&blame_suspects
, commit
);
25 return result
? *result
: NULL
;
28 static void set_blame_suspects(struct commit
*commit
, struct blame_origin
*origin
)
30 *blame_suspects_at(&blame_suspects
, commit
) = origin
;
33 void blame_origin_decref(struct blame_origin
*o
)
35 if (o
&& --o
->refcnt
<= 0) {
36 struct blame_origin
*p
, *l
= NULL
;
38 blame_origin_decref(o
->previous
);
40 /* Should be present exactly once in commit chain */
41 for (p
= get_blame_suspects(o
->commit
); p
; l
= p
, p
= p
->next
) {
46 set_blame_suspects(o
->commit
, p
->next
);
51 die("internal error in blame_origin_decref");
56 * Given a commit and a path in it, create a new origin structure.
57 * The callers that add blame to the scoreboard should use
58 * get_origin() to obtain shared, refcounted copy instead of calling
59 * this function directly.
61 static struct blame_origin
*make_origin(struct commit
*commit
, const char *path
)
63 struct blame_origin
*o
;
64 FLEX_ALLOC_STR(o
, path
, path
);
67 o
->next
= get_blame_suspects(commit
);
68 set_blame_suspects(commit
, o
);
73 * Locate an existing origin or create a new one.
74 * This moves the origin to front position in the commit util list.
76 static struct blame_origin
*get_origin(struct commit
*commit
, const char *path
)
78 struct blame_origin
*o
, *l
;
80 for (o
= get_blame_suspects(commit
), l
= NULL
; o
; l
= o
, o
= o
->next
) {
81 if (!strcmp(o
->path
, path
)) {
85 o
->next
= get_blame_suspects(commit
);
86 set_blame_suspects(commit
, o
);
88 return blame_origin_incref(o
);
91 return make_origin(commit
, path
);
96 static void verify_working_tree_path(struct repository
*r
,
97 struct commit
*work_tree
, const char *path
)
99 struct commit_list
*parents
;
102 for (parents
= work_tree
->parents
; parents
; parents
= parents
->next
) {
103 const struct object_id
*commit_oid
= &parents
->item
->object
.oid
;
104 struct object_id blob_oid
;
107 if (!get_tree_entry(r
, commit_oid
, path
, &blob_oid
, &mode
) &&
108 oid_object_info(r
, &blob_oid
, NULL
) == OBJ_BLOB
)
112 pos
= index_name_pos(r
->index
, path
, strlen(path
));
114 ; /* path is in the index */
115 else if (-1 - pos
< r
->index
->cache_nr
&&
116 !strcmp(r
->index
->cache
[-1 - pos
]->name
, path
))
117 ; /* path is in the index, unmerged */
119 die("no such path '%s' in HEAD", path
);
122 static struct commit_list
**append_parent(struct repository
*r
,
123 struct commit_list
**tail
,
124 const struct object_id
*oid
)
126 struct commit
*parent
;
128 parent
= lookup_commit_reference(r
, oid
);
130 die("no such commit %s", oid_to_hex(oid
));
131 return &commit_list_insert(parent
, tail
)->next
;
134 static void append_merge_parents(struct repository
*r
,
135 struct commit_list
**tail
)
138 struct strbuf line
= STRBUF_INIT
;
140 merge_head
= open(git_path_merge_head(r
), O_RDONLY
);
141 if (merge_head
< 0) {
144 die("cannot open '%s' for reading",
145 git_path_merge_head(r
));
148 while (!strbuf_getwholeline_fd(&line
, merge_head
, '\n')) {
149 struct object_id oid
;
150 if (get_oid_hex(line
.buf
, &oid
))
151 die("unknown line in '%s': %s",
152 git_path_merge_head(r
), line
.buf
);
153 tail
= append_parent(r
, tail
, &oid
);
156 strbuf_release(&line
);
160 * This isn't as simple as passing sb->buf and sb->len, because we
161 * want to transfer ownership of the buffer to the commit (so we
164 static void set_commit_buffer_from_strbuf(struct repository
*r
,
169 void *buf
= strbuf_detach(sb
, &len
);
170 set_commit_buffer(r
, c
, buf
, len
);
174 * Prepare a dummy commit that represents the work tree (or staged) item.
175 * Note that annotating work tree item never works in the reverse.
177 static struct commit
*fake_working_tree_commit(struct repository
*r
,
178 struct diff_options
*opt
,
180 const char *contents_from
,
181 struct object_id
*oid
)
183 struct commit
*commit
;
184 struct blame_origin
*origin
;
185 struct commit_list
**parent_tail
, *parent
;
186 struct strbuf buf
= STRBUF_INIT
;
190 struct cache_entry
*ce
;
192 struct strbuf msg
= STRBUF_INIT
;
196 commit
= alloc_commit_node(r
);
197 commit
->object
.parsed
= 1;
199 parent_tail
= &commit
->parents
;
201 parent_tail
= append_parent(r
, parent_tail
, oid
);
202 append_merge_parents(r
, parent_tail
);
203 verify_working_tree_path(r
, commit
, path
);
205 origin
= make_origin(commit
, path
);
207 ident
= fmt_ident("Not Committed Yet", "not.committed.yet",
208 WANT_BLANK_IDENT
, NULL
, 0);
209 strbuf_addstr(&msg
, "tree 0000000000000000000000000000000000000000\n");
210 for (parent
= commit
->parents
; parent
; parent
= parent
->next
)
211 strbuf_addf(&msg
, "parent %s\n",
212 oid_to_hex(&parent
->item
->object
.oid
));
216 "Version of %s from %s\n",
218 (!contents_from
? path
:
219 (!strcmp(contents_from
, "-") ? "standard input" : contents_from
)));
220 set_commit_buffer_from_strbuf(r
, commit
, &msg
);
222 if (!contents_from
|| strcmp("-", contents_from
)) {
224 const char *read_from
;
226 unsigned long buf_len
;
229 if (stat(contents_from
, &st
) < 0)
230 die_errno("Cannot stat '%s'", contents_from
);
231 read_from
= contents_from
;
234 if (lstat(path
, &st
) < 0)
235 die_errno("Cannot lstat '%s'", path
);
238 mode
= canon_mode(st
.st_mode
);
240 switch (st
.st_mode
& S_IFMT
) {
242 if (opt
->flags
.allow_textconv
&&
243 textconv_object(r
, read_from
, mode
, null_oid(), 0, &buf_ptr
, &buf_len
))
244 strbuf_attach(&buf
, buf_ptr
, buf_len
, buf_len
+ 1);
245 else if (strbuf_read_file(&buf
, read_from
, st
.st_size
) != st
.st_size
)
246 die_errno("cannot open or read '%s'", read_from
);
249 if (strbuf_readlink(&buf
, read_from
, st
.st_size
) < 0)
250 die_errno("cannot readlink '%s'", read_from
);
253 die("unsupported file type %s", read_from
);
257 /* Reading from stdin */
259 if (strbuf_read(&buf
, 0, 0) < 0)
260 die_errno("failed to read from stdin");
262 convert_to_git(r
->index
, path
, buf
.buf
, buf
.len
, &buf
, 0);
263 origin
->file
.ptr
= buf
.buf
;
264 origin
->file
.size
= buf
.len
;
265 pretend_object_file(buf
.buf
, buf
.len
, OBJ_BLOB
, &origin
->blob_oid
);
268 * Read the current index, replace the path entry with
269 * origin->blob_sha1 without mucking with its mode or type
270 * bits; we are not going to write this index out -- we just
271 * want to run "diff-index --cached".
273 discard_index(r
->index
);
278 int pos
= index_name_pos(r
->index
, path
, len
);
280 mode
= r
->index
->cache
[pos
]->ce_mode
;
282 /* Let's not bother reading from HEAD tree */
283 mode
= S_IFREG
| 0644;
285 ce
= make_empty_cache_entry(r
->index
, len
);
286 oidcpy(&ce
->oid
, &origin
->blob_oid
);
287 memcpy(ce
->name
, path
, len
);
288 ce
->ce_flags
= create_ce_flags(0);
289 ce
->ce_namelen
= len
;
290 ce
->ce_mode
= create_ce_mode(mode
);
291 add_index_entry(r
->index
, ce
,
292 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
294 cache_tree_invalidate_path(r
->index
, path
);
301 static int diff_hunks(mmfile_t
*file_a
, mmfile_t
*file_b
,
302 xdl_emit_hunk_consume_func_t hunk_func
, void *cb_data
, int xdl_opts
)
305 xdemitconf_t xecfg
= {0};
306 xdemitcb_t ecb
= {NULL
};
308 xpp
.flags
= xdl_opts
;
309 xecfg
.hunk_func
= hunk_func
;
311 return xdi_diff(file_a
, file_b
, &xpp
, &xecfg
, &ecb
);
314 static const char *get_next_line(const char *start
, const char *end
)
316 const char *nl
= memchr(start
, '\n', end
- start
);
318 return nl
? nl
+ 1 : end
;
321 static int find_line_starts(int **line_starts
, const char *buf
,
324 const char *end
= buf
+ len
;
329 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
332 ALLOC_ARRAY(*line_starts
, num
+ 1);
333 lineno
= *line_starts
;
335 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
343 struct fingerprint_entry
;
345 /* A fingerprint is intended to loosely represent a string, such that two
346 * fingerprints can be quickly compared to give an indication of the similarity
347 * of the strings that they represent.
349 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
350 * the string that it represents. Whitespace is added at each end of the
351 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
352 * For example, the string "Darth Radar" will be converted to the following
354 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
356 * The similarity between two fingerprints is the size of the intersection of
357 * their multisets, including repeated elements. See fingerprint_similarity for
360 * For ease of implementation, the fingerprint is implemented as a map
361 * of byte pairs to the count of that byte pair in the string, instead of
362 * allowing repeated elements in a set.
366 /* As we know the maximum number of entries in advance, it's
367 * convenient to store the entries in a single array instead of having
368 * the hashmap manage the memory.
370 struct fingerprint_entry
*entries
;
373 /* A byte pair in a fingerprint. Stores the number of times the byte pair
374 * occurs in the string that the fingerprint represents.
376 struct fingerprint_entry
{
377 /* The hashmap entry - the hash represents the byte pair in its
378 * entirety so we don't need to store the byte pair separately.
380 struct hashmap_entry entry
;
381 /* The number of times the byte pair occurs in the string that the
382 * fingerprint represents.
387 /* See `struct fingerprint` for an explanation of what a fingerprint is.
388 * \param result the fingerprint of the string is stored here. This must be
389 * freed later using free_fingerprint.
390 * \param line_begin the start of the string
391 * \param line_end the end of the string
393 static void get_fingerprint(struct fingerprint
*result
,
394 const char *line_begin
,
395 const char *line_end
)
397 unsigned int hash
, c0
= 0, c1
;
399 int max_map_entry_count
= 1 + line_end
- line_begin
;
400 struct fingerprint_entry
*entry
= xcalloc(max_map_entry_count
,
401 sizeof(struct fingerprint_entry
));
402 struct fingerprint_entry
*found_entry
;
404 hashmap_init(&result
->map
, NULL
, NULL
, max_map_entry_count
);
405 result
->entries
= entry
;
406 for (p
= line_begin
; p
<= line_end
; ++p
, c0
= c1
) {
407 /* Always terminate the string with whitespace.
408 * Normalise whitespace to 0, and normalise letters to
409 * lower case. This won't work for multibyte characters but at
410 * worst will match some unrelated characters.
412 if ((p
== line_end
) || isspace(*p
))
416 hash
= c0
| (c1
<< 8);
417 /* Ignore whitespace pairs */
420 hashmap_entry_init(&entry
->entry
, hash
);
422 found_entry
= hashmap_get_entry(&result
->map
, entry
,
423 /* member name */ entry
, NULL
);
425 found_entry
->count
+= 1;
428 hashmap_add(&result
->map
, &entry
->entry
);
434 static void free_fingerprint(struct fingerprint
*f
)
436 hashmap_clear(&f
->map
);
440 /* Calculates the similarity between two fingerprints as the size of the
441 * intersection of their multisets, including repeated elements. See
442 * `struct fingerprint` for an explanation of the fingerprint representation.
443 * The similarity between "cat mat" and "father rather" is 2 because "at" is
444 * present twice in both strings while the similarity between "tim" and "mit"
447 static int fingerprint_similarity(struct fingerprint
*a
, struct fingerprint
*b
)
449 int intersection
= 0;
450 struct hashmap_iter iter
;
451 const struct fingerprint_entry
*entry_a
, *entry_b
;
453 hashmap_for_each_entry(&b
->map
, &iter
, entry_b
,
454 entry
/* member name */) {
455 entry_a
= hashmap_get_entry(&a
->map
, entry_b
, entry
, NULL
);
457 intersection
+= entry_a
->count
< entry_b
->count
?
458 entry_a
->count
: entry_b
->count
;
464 /* Subtracts byte-pair elements in B from A, modifying A in place.
466 static void fingerprint_subtract(struct fingerprint
*a
, struct fingerprint
*b
)
468 struct hashmap_iter iter
;
469 struct fingerprint_entry
*entry_a
;
470 const struct fingerprint_entry
*entry_b
;
472 hashmap_iter_init(&b
->map
, &iter
);
474 hashmap_for_each_entry(&b
->map
, &iter
, entry_b
,
475 entry
/* member name */) {
476 entry_a
= hashmap_get_entry(&a
->map
, entry_b
, entry
, NULL
);
478 if (entry_a
->count
<= entry_b
->count
)
479 hashmap_remove(&a
->map
, &entry_b
->entry
, NULL
);
481 entry_a
->count
-= entry_b
->count
;
486 /* Calculate fingerprints for a series of lines.
487 * Puts the fingerprints in the fingerprints array, which must have been
488 * preallocated to allow storing line_count elements.
490 static void get_line_fingerprints(struct fingerprint
*fingerprints
,
491 const char *content
, const int *line_starts
,
492 long first_line
, long line_count
)
495 const char *linestart
, *lineend
;
497 line_starts
+= first_line
;
498 for (i
= 0; i
< line_count
; ++i
) {
499 linestart
= content
+ line_starts
[i
];
500 lineend
= content
+ line_starts
[i
+ 1];
501 get_fingerprint(fingerprints
+ i
, linestart
, lineend
);
505 static void free_line_fingerprints(struct fingerprint
*fingerprints
,
510 for (i
= 0; i
< nr_fingerprints
; i
++)
511 free_fingerprint(&fingerprints
[i
]);
514 /* This contains the data necessary to linearly map a line number in one half
515 * of a diff chunk to the line in the other half of the diff chunk that is
516 * closest in terms of its position as a fraction of the length of the chunk.
518 struct line_number_mapping
{
519 int destination_start
, destination_length
,
520 source_start
, source_length
;
523 /* Given a line number in one range, offset and scale it to map it onto the
525 * Essentially this mapping is a simple linear equation but the calculation is
526 * more complicated to allow performing it with integer operations.
527 * Another complication is that if a line could map onto many lines in the
528 * destination range then we want to choose the line at the center of those
530 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
531 * first 5 lines in B will map onto the first line in the A chunk, while the
532 * last 5 lines will all map onto the second line in the A chunk.
533 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
534 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
536 static int map_line_number(int line_number
,
537 const struct line_number_mapping
*mapping
)
539 return ((line_number
- mapping
->source_start
) * 2 + 1) *
540 mapping
->destination_length
/
541 (mapping
->source_length
* 2) +
542 mapping
->destination_start
;
545 /* Get a pointer to the element storing the similarity between a line in A
548 * The similarities are stored in a 2-dimensional array. Each "row" in the
549 * array contains the similarities for a line in B. The similarities stored in
550 * a row are the similarities between the line in B and the nearby lines in A.
551 * To keep the length of each row the same, it is padded out with values of -1
552 * where the search range extends beyond the lines in A.
553 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
560 * Then the similarity array will contain:
561 * [-1, -1, am, bm, cm,
562 * -1, an, bn, cn, dn,
563 * ao, bo, co, do, eo,
564 * bp, cp, dp, ep, -1,
565 * cq, dq, eq, -1, -1]
566 * Where similarities are denoted either by -1 for invalid, or the
567 * concatenation of the two lines in the diff being compared.
569 * \param similarities array of similarities between lines in A and B
570 * \param line_a the index of the line in A, in the same frame of reference as
572 * \param local_line_b the index of the line in B, relative to the first line
573 * in B that similarities represents.
574 * \param closest_line_a the index of the line in A that is deemed to be
575 * closest to local_line_b. This must be in the same
576 * frame of reference as line_a. This value defines
577 * where similarities is centered for the line in B.
578 * \param max_search_distance_a maximum distance in lines from the closest line
579 * in A for other lines in A for which
580 * similarities may be calculated.
582 static int *get_similarity(int *similarities
,
583 int line_a
, int local_line_b
,
584 int closest_line_a
, int max_search_distance_a
)
586 assert(abs(line_a
- closest_line_a
) <=
587 max_search_distance_a
);
588 return similarities
+ line_a
- closest_line_a
+
589 max_search_distance_a
+
590 local_line_b
* (max_search_distance_a
* 2 + 1);
593 #define CERTAIN_NOTHING_MATCHES -2
594 #define CERTAINTY_NOT_CALCULATED -1
596 /* Given a line in B, first calculate its similarities with nearby lines in A
597 * if not already calculated, then identify the most similar and second most
598 * similar lines. The "certainty" is calculated based on those two
601 * \param start_a the index of the first line of the chunk in A
602 * \param length_a the length in lines of the chunk in A
603 * \param local_line_b the index of the line in B, relative to the first line
605 * \param fingerprints_a array of fingerprints for the chunk in A
606 * \param fingerprints_b array of fingerprints for the chunk in B
607 * \param similarities 2-dimensional array of similarities between lines in A
608 * and B. See get_similarity() for more details.
609 * \param certainties array of values indicating how strongly a line in B is
610 * matched with some line in A.
611 * \param second_best_result array of absolute indices in A for the second
612 * closest match of a line in B.
613 * \param result array of absolute indices in A for the closest match of a line
615 * \param max_search_distance_a maximum distance in lines from the closest line
616 * in A for other lines in A for which
617 * similarities may be calculated.
618 * \param map_line_number_in_b_to_a parameter to map_line_number().
620 static void find_best_line_matches(
625 struct fingerprint
*fingerprints_a
,
626 struct fingerprint
*fingerprints_b
,
629 int *second_best_result
,
631 const int max_search_distance_a
,
632 const struct line_number_mapping
*map_line_number_in_b_to_a
)
635 int i
, search_start
, search_end
, closest_local_line_a
, *similarity
,
636 best_similarity
= 0, second_best_similarity
= 0,
637 best_similarity_index
= 0, second_best_similarity_index
= 0;
639 /* certainty has already been calculated so no need to redo the work */
640 if (certainties
[local_line_b
] != CERTAINTY_NOT_CALCULATED
)
643 closest_local_line_a
= map_line_number(
644 local_line_b
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
646 search_start
= closest_local_line_a
- max_search_distance_a
;
647 if (search_start
< 0)
650 search_end
= closest_local_line_a
+ max_search_distance_a
+ 1;
651 if (search_end
> length_a
)
652 search_end
= length_a
;
654 for (i
= search_start
; i
< search_end
; ++i
) {
655 similarity
= get_similarity(similarities
,
657 closest_local_line_a
,
658 max_search_distance_a
);
659 if (*similarity
== -1) {
660 /* This value will never exceed 10 but assert just in
663 assert(abs(i
- closest_local_line_a
) < 1000);
664 /* scale the similarity by (1000 - distance from
665 * closest line) to act as a tie break between lines
666 * that otherwise are equally similar.
668 *similarity
= fingerprint_similarity(
669 fingerprints_b
+ local_line_b
,
670 fingerprints_a
+ i
) *
671 (1000 - abs(i
- closest_local_line_a
));
673 if (*similarity
> best_similarity
) {
674 second_best_similarity
= best_similarity
;
675 second_best_similarity_index
= best_similarity_index
;
676 best_similarity
= *similarity
;
677 best_similarity_index
= i
;
678 } else if (*similarity
> second_best_similarity
) {
679 second_best_similarity
= *similarity
;
680 second_best_similarity_index
= i
;
684 if (best_similarity
== 0) {
685 /* this line definitely doesn't match with anything. Mark it
686 * with this special value so it doesn't get invalidated and
687 * won't be recalculated.
689 certainties
[local_line_b
] = CERTAIN_NOTHING_MATCHES
;
690 result
[local_line_b
] = -1;
692 /* Calculate the certainty with which this line matches.
693 * If the line matches well with two lines then that reduces
694 * the certainty. However we still want to prioritise matching
695 * a line that matches very well with two lines over matching a
696 * line that matches poorly with one line, hence doubling
698 * This means that if we have
699 * line X that matches only one line with a score of 3,
700 * line Y that matches two lines equally with a score of 5,
701 * and line Z that matches only one line with a score or 2,
702 * then the lines in order of certainty are X, Y, Z.
704 certainties
[local_line_b
] = best_similarity
* 2 -
705 second_best_similarity
;
707 /* We keep both the best and second best results to allow us to
708 * check at a later stage of the matching process whether the
709 * result needs to be invalidated.
711 result
[local_line_b
] = start_a
+ best_similarity_index
;
712 second_best_result
[local_line_b
] =
713 start_a
+ second_best_similarity_index
;
718 * This finds the line that we can match with the most confidence, and
719 * uses it as a partition. It then calls itself on the lines on either side of
720 * that partition. In this way we avoid lines appearing out of order, and
721 * retain a sensible line ordering.
722 * \param start_a index of the first line in A with which lines in B may be
724 * \param start_b index of the first line in B for which matching should be
726 * \param length_a number of lines in A with which lines in B may be compared.
727 * \param length_b number of lines in B for which matching should be done.
728 * \param fingerprints_a mutable array of fingerprints in A. The first element
729 * corresponds to the line at start_a.
730 * \param fingerprints_b array of fingerprints in B. The first element
731 * corresponds to the line at start_b.
732 * \param similarities 2-dimensional array of similarities between lines in A
733 * and B. See get_similarity() for more details.
734 * \param certainties array of values indicating how strongly a line in B is
735 * matched with some line in A.
736 * \param second_best_result array of absolute indices in A for the second
737 * closest match of a line in B.
738 * \param result array of absolute indices in A for the closest match of a line
740 * \param max_search_distance_a maximum distance in lines from the closest line
741 * in A for other lines in A for which
742 * similarities may be calculated.
743 * \param max_search_distance_b an upper bound on the greatest possible
744 * distance between lines in B such that they will
745 * both be compared with the same line in A
746 * according to max_search_distance_a.
747 * \param map_line_number_in_b_to_a parameter to map_line_number().
749 static void fuzzy_find_matching_lines_recurse(
750 int start_a
, int start_b
,
751 int length_a
, int length_b
,
752 struct fingerprint
*fingerprints_a
,
753 struct fingerprint
*fingerprints_b
,
756 int *second_best_result
,
758 int max_search_distance_a
,
759 int max_search_distance_b
,
760 const struct line_number_mapping
*map_line_number_in_b_to_a
)
762 int i
, invalidate_min
, invalidate_max
, offset_b
,
763 second_half_start_a
, second_half_start_b
,
764 second_half_length_a
, second_half_length_b
,
765 most_certain_line_a
, most_certain_local_line_b
= -1,
766 most_certain_line_certainty
= -1,
767 closest_local_line_a
;
769 for (i
= 0; i
< length_b
; ++i
) {
770 find_best_line_matches(start_a
,
780 max_search_distance_a
,
781 map_line_number_in_b_to_a
);
783 if (certainties
[i
] > most_certain_line_certainty
) {
784 most_certain_line_certainty
= certainties
[i
];
785 most_certain_local_line_b
= i
;
790 if (most_certain_local_line_b
== -1)
793 most_certain_line_a
= result
[most_certain_local_line_b
];
796 * Subtract the most certain line's fingerprint in B from the matched
797 * fingerprint in A. This means that other lines in B can't also match
798 * the same parts of the line in A.
800 fingerprint_subtract(fingerprints_a
+ most_certain_line_a
- start_a
,
801 fingerprints_b
+ most_certain_local_line_b
);
803 /* Invalidate results that may be affected by the choice of most
806 invalidate_min
= most_certain_local_line_b
- max_search_distance_b
;
807 invalidate_max
= most_certain_local_line_b
+ max_search_distance_b
+ 1;
808 if (invalidate_min
< 0)
810 if (invalidate_max
> length_b
)
811 invalidate_max
= length_b
;
813 /* As the fingerprint in A has changed, discard previously calculated
814 * similarity values with that fingerprint.
816 for (i
= invalidate_min
; i
< invalidate_max
; ++i
) {
817 closest_local_line_a
= map_line_number(
818 i
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
820 /* Check that the lines in A and B are close enough that there
821 * is a similarity value for them.
823 if (abs(most_certain_line_a
- start_a
- closest_local_line_a
) >
824 max_search_distance_a
) {
828 *get_similarity(similarities
, most_certain_line_a
- start_a
,
829 i
, closest_local_line_a
,
830 max_search_distance_a
) = -1;
833 /* More invalidating of results that may be affected by the choice of
835 * Discard the matches for lines in B that are currently matched with a
836 * line in A such that their ordering contradicts the ordering imposed
837 * by the choice of most certain line.
839 for (i
= most_certain_local_line_b
- 1; i
>= invalidate_min
; --i
) {
840 /* In this loop we discard results for lines in B that are
841 * before most-certain-line-B but are matched with a line in A
842 * that is after most-certain-line-A.
844 if (certainties
[i
] >= 0 &&
845 (result
[i
] >= most_certain_line_a
||
846 second_best_result
[i
] >= most_certain_line_a
)) {
847 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
850 for (i
= most_certain_local_line_b
+ 1; i
< invalidate_max
; ++i
) {
851 /* In this loop we discard results for lines in B that are
852 * after most-certain-line-B but are matched with a line in A
853 * that is before most-certain-line-A.
855 if (certainties
[i
] >= 0 &&
856 (result
[i
] <= most_certain_line_a
||
857 second_best_result
[i
] <= most_certain_line_a
)) {
858 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
862 /* Repeat the matching process for lines before the most certain line.
864 if (most_certain_local_line_b
> 0) {
865 fuzzy_find_matching_lines_recurse(
867 most_certain_line_a
+ 1 - start_a
,
868 most_certain_local_line_b
,
869 fingerprints_a
, fingerprints_b
, similarities
,
870 certainties
, second_best_result
, result
,
871 max_search_distance_a
,
872 max_search_distance_b
,
873 map_line_number_in_b_to_a
);
875 /* Repeat the matching process for lines after the most certain line.
877 if (most_certain_local_line_b
+ 1 < length_b
) {
878 second_half_start_a
= most_certain_line_a
;
879 offset_b
= most_certain_local_line_b
+ 1;
880 second_half_start_b
= start_b
+ offset_b
;
881 second_half_length_a
=
882 length_a
+ start_a
- second_half_start_a
;
883 second_half_length_b
=
884 length_b
+ start_b
- second_half_start_b
;
885 fuzzy_find_matching_lines_recurse(
886 second_half_start_a
, second_half_start_b
,
887 second_half_length_a
, second_half_length_b
,
888 fingerprints_a
+ second_half_start_a
- start_a
,
889 fingerprints_b
+ offset_b
,
891 offset_b
* (max_search_distance_a
* 2 + 1),
892 certainties
+ offset_b
,
893 second_best_result
+ offset_b
, result
+ offset_b
,
894 max_search_distance_a
,
895 max_search_distance_b
,
896 map_line_number_in_b_to_a
);
900 /* Find the lines in the parent line range that most closely match the lines in
901 * the target line range. This is accomplished by matching fingerprints in each
902 * blame_origin, and choosing the best matches that preserve the line ordering.
903 * See struct fingerprint for details of fingerprint matching, and
904 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
906 * The performance is believed to be O(n log n) in the typical case and O(n^2)
907 * in a pathological case, where n is the number of lines in the target range.
909 static int *fuzzy_find_matching_lines(struct blame_origin
*parent
,
910 struct blame_origin
*target
,
911 int tlno
, int parent_slno
, int same
,
914 /* We use the terminology "A" for the left hand side of the diff AKA
915 * parent, and "B" for the right hand side of the diff AKA target. */
916 int start_a
= parent_slno
;
917 int length_a
= parent_len
;
919 int length_b
= same
- tlno
;
921 struct line_number_mapping map_line_number_in_b_to_a
= {
922 start_a
, length_a
, start_b
, length_b
925 struct fingerprint
*fingerprints_a
= parent
->fingerprints
;
926 struct fingerprint
*fingerprints_b
= target
->fingerprints
;
928 int i
, *result
, *second_best_result
,
929 *certainties
, *similarities
, similarity_count
;
932 * max_search_distance_a means that given a line in B, compare it to
933 * the line in A that is closest to its position, and the lines in A
934 * that are no greater than max_search_distance_a lines away from the
937 * max_search_distance_b is an upper bound on the greatest possible
938 * distance between lines in B such that they will both be compared
939 * with the same line in A according to max_search_distance_a.
941 int max_search_distance_a
= 10, max_search_distance_b
;
946 if (max_search_distance_a
>= length_a
)
947 max_search_distance_a
= length_a
? length_a
- 1 : 0;
949 max_search_distance_b
= ((2 * max_search_distance_a
+ 1) * length_b
952 CALLOC_ARRAY(result
, length_b
);
953 CALLOC_ARRAY(second_best_result
, length_b
);
954 CALLOC_ARRAY(certainties
, length_b
);
956 /* See get_similarity() for details of similarities. */
957 similarity_count
= length_b
* (max_search_distance_a
* 2 + 1);
958 CALLOC_ARRAY(similarities
, similarity_count
);
960 for (i
= 0; i
< length_b
; ++i
) {
962 second_best_result
[i
] = -1;
963 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
966 for (i
= 0; i
< similarity_count
; ++i
)
967 similarities
[i
] = -1;
969 fuzzy_find_matching_lines_recurse(start_a
, start_b
,
971 fingerprints_a
+ start_a
,
972 fingerprints_b
+ start_b
,
977 max_search_distance_a
,
978 max_search_distance_b
,
979 &map_line_number_in_b_to_a
);
983 free(second_best_result
);
988 static void fill_origin_fingerprints(struct blame_origin
*o
)
994 o
->num_lines
= find_line_starts(&line_starts
, o
->file
.ptr
,
996 CALLOC_ARRAY(o
->fingerprints
, o
->num_lines
);
997 get_line_fingerprints(o
->fingerprints
, o
->file
.ptr
, line_starts
,
1002 static void drop_origin_fingerprints(struct blame_origin
*o
)
1004 if (o
->fingerprints
) {
1005 free_line_fingerprints(o
->fingerprints
, o
->num_lines
);
1007 FREE_AND_NULL(o
->fingerprints
);
1012 * Given an origin, prepare mmfile_t structure to be used by the
1015 static void fill_origin_blob(struct diff_options
*opt
,
1016 struct blame_origin
*o
, mmfile_t
*file
,
1017 int *num_read_blob
, int fill_fingerprints
)
1020 enum object_type type
;
1021 unsigned long file_size
;
1024 if (opt
->flags
.allow_textconv
&&
1025 textconv_object(opt
->repo
, o
->path
, o
->mode
,
1026 &o
->blob_oid
, 1, &file
->ptr
, &file_size
))
1029 file
->ptr
= repo_read_object_file(the_repository
,
1030 &o
->blob_oid
, &type
,
1032 file
->size
= file_size
;
1035 die("Cannot read blob %s for path %s",
1036 oid_to_hex(&o
->blob_oid
),
1042 if (fill_fingerprints
)
1043 fill_origin_fingerprints(o
);
1046 static void drop_origin_blob(struct blame_origin
*o
)
1048 FREE_AND_NULL(o
->file
.ptr
);
1049 drop_origin_fingerprints(o
);
1053 * Any merge of blames happens on lists of blames that arrived via
1054 * different parents in a single suspect. In this case, we want to
1055 * sort according to the suspect line numbers as opposed to the final
1056 * image line numbers. The function body is somewhat longish because
1057 * it avoids unnecessary writes.
1060 static struct blame_entry
*blame_merge(struct blame_entry
*list1
,
1061 struct blame_entry
*list2
)
1063 struct blame_entry
*p1
= list1
, *p2
= list2
,
1071 if (p1
->s_lno
<= p2
->s_lno
) {
1074 if (!(p1
= *tail
)) {
1078 } while (p1
->s_lno
<= p2
->s_lno
);
1084 if (!(p2
= *tail
)) {
1088 } while (p1
->s_lno
> p2
->s_lno
);
1092 if (!(p1
= *tail
)) {
1096 } while (p1
->s_lno
<= p2
->s_lno
);
1100 DEFINE_LIST_SORT(static, sort_blame_entries
, struct blame_entry
, next
);
1103 * Final image line numbers are all different, so we don't need a
1104 * three-way comparison here.
1107 static int compare_blame_final(const struct blame_entry
*e1
,
1108 const struct blame_entry
*e2
)
1110 return e1
->lno
> e2
->lno
? 1 : -1;
1113 static int compare_blame_suspect(const struct blame_entry
*s1
,
1114 const struct blame_entry
*s2
)
1117 * to allow for collating suspects, we sort according to the
1118 * respective pointer value as the primary sorting criterion.
1119 * The actual relation is pretty unimportant as long as it
1120 * establishes a total order. Comparing as integers gives us
1123 if (s1
->suspect
!= s2
->suspect
)
1124 return (intptr_t)s1
->suspect
> (intptr_t)s2
->suspect
? 1 : -1;
1125 if (s1
->s_lno
== s2
->s_lno
)
1127 return s1
->s_lno
> s2
->s_lno
? 1 : -1;
1130 void blame_sort_final(struct blame_scoreboard
*sb
)
1132 sort_blame_entries(&sb
->ent
, compare_blame_final
);
1135 static int compare_commits_by_reverse_commit_date(const void *a
,
1139 return -compare_commits_by_commit_date(a
, b
, c
);
1143 * For debugging -- origin is refcounted, and this asserts that
1144 * we do not underflow.
1146 static void sanity_check_refcnt(struct blame_scoreboard
*sb
)
1149 struct blame_entry
*ent
;
1151 for (ent
= sb
->ent
; ent
; ent
= ent
->next
) {
1152 /* Nobody should have zero or negative refcnt */
1153 if (ent
->suspect
->refcnt
<= 0) {
1154 fprintf(stderr
, "%s in %s has negative refcnt %d\n",
1156 oid_to_hex(&ent
->suspect
->commit
->object
.oid
),
1157 ent
->suspect
->refcnt
);
1162 sb
->on_sanity_fail(sb
, baa
);
1166 * If two blame entries that are next to each other came from
1167 * contiguous lines in the same origin (i.e. <commit, path> pair),
1168 * merge them together.
1170 void blame_coalesce(struct blame_scoreboard
*sb
)
1172 struct blame_entry
*ent
, *next
;
1174 for (ent
= sb
->ent
; ent
&& (next
= ent
->next
); ent
= next
) {
1175 if (ent
->suspect
== next
->suspect
&&
1176 ent
->s_lno
+ ent
->num_lines
== next
->s_lno
&&
1177 ent
->lno
+ ent
->num_lines
== next
->lno
&&
1178 ent
->ignored
== next
->ignored
&&
1179 ent
->unblamable
== next
->unblamable
) {
1180 ent
->num_lines
+= next
->num_lines
;
1181 ent
->next
= next
->next
;
1182 blame_origin_decref(next
->suspect
);
1185 next
= ent
; /* again */
1189 if (sb
->debug
) /* sanity */
1190 sanity_check_refcnt(sb
);
1194 * Merge the given sorted list of blames into a preexisting origin.
1195 * If there were no previous blames to that commit, it is entered into
1196 * the commit priority queue of the score board.
1199 static void queue_blames(struct blame_scoreboard
*sb
, struct blame_origin
*porigin
,
1200 struct blame_entry
*sorted
)
1202 if (porigin
->suspects
)
1203 porigin
->suspects
= blame_merge(porigin
->suspects
, sorted
);
1205 struct blame_origin
*o
;
1206 for (o
= get_blame_suspects(porigin
->commit
); o
; o
= o
->next
) {
1208 porigin
->suspects
= sorted
;
1212 porigin
->suspects
= sorted
;
1213 prio_queue_put(&sb
->commits
, porigin
->commit
);
1218 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1219 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1220 * for an origin is also used to pass the blame for the entire file to
1221 * the parent to detect the case where a child's blob is identical to
1222 * that of its parent's.
1224 * This also fills origin->mode for corresponding tree path.
1226 static int fill_blob_sha1_and_mode(struct repository
*r
,
1227 struct blame_origin
*origin
)
1229 if (!is_null_oid(&origin
->blob_oid
))
1231 if (get_tree_entry(r
, &origin
->commit
->object
.oid
, origin
->path
, &origin
->blob_oid
, &origin
->mode
))
1233 if (oid_object_info(r
, &origin
->blob_oid
, NULL
) != OBJ_BLOB
)
1237 oidclr(&origin
->blob_oid
);
1238 origin
->mode
= S_IFINVALID
;
1242 struct blame_bloom_data
{
1244 * Changed-path Bloom filter keys. These can help prevent
1245 * computing diffs against first parents, but we need to
1246 * expand the list as code is moved or files are renamed.
1248 struct bloom_filter_settings
*settings
;
1249 struct bloom_key
**keys
;
1254 static int bloom_count_queries
= 0;
1255 static int bloom_count_no
= 0;
1256 static int maybe_changed_path(struct repository
*r
,
1257 struct blame_origin
*origin
,
1258 struct blame_bloom_data
*bd
)
1261 struct bloom_filter
*filter
;
1266 if (commit_graph_generation(origin
->commit
) == GENERATION_NUMBER_INFINITY
)
1269 filter
= get_bloom_filter(r
, origin
->commit
);
1274 bloom_count_queries
++;
1275 for (i
= 0; i
< bd
->nr
; i
++) {
1276 if (bloom_filter_contains(filter
,
1286 static void add_bloom_key(struct blame_bloom_data
*bd
,
1292 if (bd
->nr
>= bd
->alloc
) {
1294 REALLOC_ARRAY(bd
->keys
, bd
->alloc
);
1297 bd
->keys
[bd
->nr
] = xmalloc(sizeof(struct bloom_key
));
1298 fill_bloom_key(path
, strlen(path
), bd
->keys
[bd
->nr
], bd
->settings
);
1303 * We have an origin -- check if the same path exists in the
1304 * parent and return an origin structure to represent it.
1306 static struct blame_origin
*find_origin(struct repository
*r
,
1307 struct commit
*parent
,
1308 struct blame_origin
*origin
,
1309 struct blame_bloom_data
*bd
)
1311 struct blame_origin
*porigin
;
1312 struct diff_options diff_opts
;
1313 const char *paths
[2];
1315 /* First check any existing origins */
1316 for (porigin
= get_blame_suspects(parent
); porigin
; porigin
= porigin
->next
)
1317 if (!strcmp(porigin
->path
, origin
->path
)) {
1319 * The same path between origin and its parent
1320 * without renaming -- the most common case.
1322 return blame_origin_incref (porigin
);
1325 /* See if the origin->path is different between parent
1326 * and origin first. Most of the time they are the
1327 * same and diff-tree is fairly efficient about this.
1329 repo_diff_setup(r
, &diff_opts
);
1330 diff_opts
.flags
.recursive
= 1;
1331 diff_opts
.detect_rename
= 0;
1332 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1333 paths
[0] = origin
->path
;
1336 parse_pathspec(&diff_opts
.pathspec
,
1337 PATHSPEC_ALL_MAGIC
& ~PATHSPEC_LITERAL
,
1338 PATHSPEC_LITERAL_PATH
, "", paths
);
1339 diff_setup_done(&diff_opts
);
1341 if (is_null_oid(&origin
->commit
->object
.oid
))
1342 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1344 int compute_diff
= 1;
1345 if (origin
->commit
->parents
&&
1346 oideq(&parent
->object
.oid
,
1347 &origin
->commit
->parents
->item
->object
.oid
))
1348 compute_diff
= maybe_changed_path(r
, origin
, bd
);
1351 diff_tree_oid(get_commit_tree_oid(parent
),
1352 get_commit_tree_oid(origin
->commit
),
1355 diffcore_std(&diff_opts
);
1357 if (!diff_queued_diff
.nr
) {
1358 /* The path is the same as parent */
1359 porigin
= get_origin(parent
, origin
->path
);
1360 oidcpy(&porigin
->blob_oid
, &origin
->blob_oid
);
1361 porigin
->mode
= origin
->mode
;
1364 * Since origin->path is a pathspec, if the parent
1365 * commit had it as a directory, we will see a whole
1366 * bunch of deletion of files in the directory that we
1367 * do not care about.
1370 struct diff_filepair
*p
= NULL
;
1371 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1373 p
= diff_queued_diff
.queue
[i
];
1374 name
= p
->one
->path
? p
->one
->path
: p
->two
->path
;
1375 if (!strcmp(name
, origin
->path
))
1379 die("internal error in blame::find_origin");
1380 switch (p
->status
) {
1382 die("internal error in blame::find_origin (%c)",
1385 porigin
= get_origin(parent
, origin
->path
);
1386 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1387 porigin
->mode
= p
->one
->mode
;
1391 /* Did not exist in parent, or type changed */
1395 diff_flush(&diff_opts
);
1400 * We have an origin -- find the path that corresponds to it in its
1401 * parent and return an origin structure to represent it.
1403 static struct blame_origin
*find_rename(struct repository
*r
,
1404 struct commit
*parent
,
1405 struct blame_origin
*origin
,
1406 struct blame_bloom_data
*bd
)
1408 struct blame_origin
*porigin
= NULL
;
1409 struct diff_options diff_opts
;
1412 repo_diff_setup(r
, &diff_opts
);
1413 diff_opts
.flags
.recursive
= 1;
1414 diff_opts
.detect_rename
= DIFF_DETECT_RENAME
;
1415 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1416 diff_opts
.single_follow
= origin
->path
;
1417 diff_setup_done(&diff_opts
);
1419 if (is_null_oid(&origin
->commit
->object
.oid
))
1420 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1422 diff_tree_oid(get_commit_tree_oid(parent
),
1423 get_commit_tree_oid(origin
->commit
),
1425 diffcore_std(&diff_opts
);
1427 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1428 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
1429 if ((p
->status
== 'R' || p
->status
== 'C') &&
1430 !strcmp(p
->two
->path
, origin
->path
)) {
1431 add_bloom_key(bd
, p
->one
->path
);
1432 porigin
= get_origin(parent
, p
->one
->path
);
1433 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1434 porigin
->mode
= p
->one
->mode
;
1438 diff_flush(&diff_opts
);
1443 * Append a new blame entry to a given output queue.
1445 static void add_blame_entry(struct blame_entry
***queue
,
1446 const struct blame_entry
*src
)
1448 struct blame_entry
*e
= xmalloc(sizeof(*e
));
1449 memcpy(e
, src
, sizeof(*e
));
1450 blame_origin_incref(e
->suspect
);
1458 * src typically is on-stack; we want to copy the information in it to
1459 * a malloced blame_entry that gets added to the given queue. The
1460 * origin of dst loses a refcnt.
1462 static void dup_entry(struct blame_entry
***queue
,
1463 struct blame_entry
*dst
, struct blame_entry
*src
)
1465 blame_origin_incref(src
->suspect
);
1466 blame_origin_decref(dst
->suspect
);
1467 memcpy(dst
, src
, sizeof(*src
));
1468 dst
->next
= **queue
;
1470 *queue
= &dst
->next
;
1473 const char *blame_nth_line(struct blame_scoreboard
*sb
, long lno
)
1475 return sb
->final_buf
+ sb
->lineno
[lno
];
1479 * It is known that lines between tlno to same came from parent, and e
1480 * has an overlap with that range. it also is known that parent's
1481 * line plno corresponds to e's line tlno.
1487 * <------------------>
1489 * Split e into potentially three parts; before this chunk, the chunk
1490 * to be blamed for the parent, and after that portion.
1492 static void split_overlap(struct blame_entry
*split
,
1493 struct blame_entry
*e
,
1494 int tlno
, int plno
, int same
,
1495 struct blame_origin
*parent
)
1499 memset(split
, 0, sizeof(struct blame_entry
[3]));
1501 for (i
= 0; i
< 3; i
++) {
1502 split
[i
].ignored
= e
->ignored
;
1503 split
[i
].unblamable
= e
->unblamable
;
1506 if (e
->s_lno
< tlno
) {
1507 /* there is a pre-chunk part not blamed on parent */
1508 split
[0].suspect
= blame_origin_incref(e
->suspect
);
1509 split
[0].lno
= e
->lno
;
1510 split
[0].s_lno
= e
->s_lno
;
1511 split
[0].num_lines
= tlno
- e
->s_lno
;
1512 split
[1].lno
= e
->lno
+ tlno
- e
->s_lno
;
1513 split
[1].s_lno
= plno
;
1516 split
[1].lno
= e
->lno
;
1517 split
[1].s_lno
= plno
+ (e
->s_lno
- tlno
);
1520 if (same
< e
->s_lno
+ e
->num_lines
) {
1521 /* there is a post-chunk part not blamed on parent */
1522 split
[2].suspect
= blame_origin_incref(e
->suspect
);
1523 split
[2].lno
= e
->lno
+ (same
- e
->s_lno
);
1524 split
[2].s_lno
= e
->s_lno
+ (same
- e
->s_lno
);
1525 split
[2].num_lines
= e
->s_lno
+ e
->num_lines
- same
;
1526 chunk_end_lno
= split
[2].lno
;
1529 chunk_end_lno
= e
->lno
+ e
->num_lines
;
1530 split
[1].num_lines
= chunk_end_lno
- split
[1].lno
;
1533 * if it turns out there is nothing to blame the parent for,
1534 * forget about the splitting. !split[1].suspect signals this.
1536 if (split
[1].num_lines
< 1)
1538 split
[1].suspect
= blame_origin_incref(parent
);
1542 * split_overlap() divided an existing blame e into up to three parts
1543 * in split. Any assigned blame is moved to queue to
1544 * reflect the split.
1546 static void split_blame(struct blame_entry
***blamed
,
1547 struct blame_entry
***unblamed
,
1548 struct blame_entry
*split
,
1549 struct blame_entry
*e
)
1551 if (split
[0].suspect
&& split
[2].suspect
) {
1552 /* The first part (reuse storage for the existing entry e) */
1553 dup_entry(unblamed
, e
, &split
[0]);
1555 /* The last part -- me */
1556 add_blame_entry(unblamed
, &split
[2]);
1558 /* ... and the middle part -- parent */
1559 add_blame_entry(blamed
, &split
[1]);
1561 else if (!split
[0].suspect
&& !split
[2].suspect
)
1563 * The parent covers the entire area; reuse storage for
1564 * e and replace it with the parent.
1566 dup_entry(blamed
, e
, &split
[1]);
1567 else if (split
[0].suspect
) {
1568 /* me and then parent */
1569 dup_entry(unblamed
, e
, &split
[0]);
1570 add_blame_entry(blamed
, &split
[1]);
1573 /* parent and then me */
1574 dup_entry(blamed
, e
, &split
[1]);
1575 add_blame_entry(unblamed
, &split
[2]);
1580 * After splitting the blame, the origins used by the
1581 * on-stack blame_entry should lose one refcnt each.
1583 static void decref_split(struct blame_entry
*split
)
1587 for (i
= 0; i
< 3; i
++)
1588 blame_origin_decref(split
[i
].suspect
);
1592 * reverse_blame reverses the list given in head, appending tail.
1593 * That allows us to build lists in reverse order, then reverse them
1594 * afterwards. This can be faster than building the list in proper
1595 * order right away. The reason is that building in proper order
1596 * requires writing a link in the _previous_ element, while building
1597 * in reverse order just requires placing the list head into the
1598 * _current_ element.
1601 static struct blame_entry
*reverse_blame(struct blame_entry
*head
,
1602 struct blame_entry
*tail
)
1605 struct blame_entry
*next
= head
->next
;
1614 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1615 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1616 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1617 * e->num_lines). The caller needs to sort out the reference counting for the
1618 * new entry's suspect.
1620 static struct blame_entry
*split_blame_at(struct blame_entry
*e
, int len
,
1621 struct blame_origin
*new_suspect
)
1623 struct blame_entry
*n
= xcalloc(1, sizeof(struct blame_entry
));
1625 n
->suspect
= new_suspect
;
1626 n
->ignored
= e
->ignored
;
1627 n
->unblamable
= e
->unblamable
;
1628 n
->lno
= e
->lno
+ len
;
1629 n
->s_lno
= e
->s_lno
+ len
;
1630 n
->num_lines
= e
->num_lines
- len
;
1636 struct blame_line_tracker
{
1641 static int are_lines_adjacent(struct blame_line_tracker
*first
,
1642 struct blame_line_tracker
*second
)
1644 return first
->is_parent
== second
->is_parent
&&
1645 first
->s_lno
+ 1 == second
->s_lno
;
1648 static int scan_parent_range(struct fingerprint
*p_fps
,
1649 struct fingerprint
*t_fps
, int t_idx
,
1650 int from
, int nr_lines
)
1653 #define FINGERPRINT_FILE_THRESHOLD 10
1654 int best_sim_val
= FINGERPRINT_FILE_THRESHOLD
;
1655 int best_sim_idx
= -1;
1657 for (p_idx
= from
; p_idx
< from
+ nr_lines
; p_idx
++) {
1658 sim
= fingerprint_similarity(&t_fps
[t_idx
], &p_fps
[p_idx
]);
1659 if (sim
< best_sim_val
)
1661 /* Break ties with the closest-to-target line number */
1662 if (sim
== best_sim_val
&& best_sim_idx
!= -1 &&
1663 abs(best_sim_idx
- t_idx
) < abs(p_idx
- t_idx
))
1666 best_sim_idx
= p_idx
;
1668 return best_sim_idx
;
1672 * The first pass checks the blame entry (from the target) against the parent's
1673 * diff chunk. If that fails for a line, the second pass tries to match that
1674 * line to any part of parent file. That catches cases where a change was
1675 * broken into two chunks by 'context.'
1677 static void guess_line_blames(struct blame_origin
*parent
,
1678 struct blame_origin
*target
,
1679 int tlno
, int offset
, int same
, int parent_len
,
1680 struct blame_line_tracker
*line_blames
)
1682 int i
, best_idx
, target_idx
;
1683 int parent_slno
= tlno
+ offset
;
1686 fuzzy_matches
= fuzzy_find_matching_lines(parent
, target
,
1687 tlno
, parent_slno
, same
,
1689 for (i
= 0; i
< same
- tlno
; i
++) {
1690 target_idx
= tlno
+ i
;
1691 if (fuzzy_matches
&& fuzzy_matches
[i
] >= 0) {
1692 best_idx
= fuzzy_matches
[i
];
1694 best_idx
= scan_parent_range(parent
->fingerprints
,
1695 target
->fingerprints
,
1699 if (best_idx
>= 0) {
1700 line_blames
[i
].is_parent
= 1;
1701 line_blames
[i
].s_lno
= best_idx
;
1703 line_blames
[i
].is_parent
= 0;
1704 line_blames
[i
].s_lno
= target_idx
;
1707 free(fuzzy_matches
);
1711 * This decides which parts of a blame entry go to the parent (added to the
1712 * ignoredp list) and which stay with the target (added to the diffp list). The
1713 * actual decision was made in a separate heuristic function, and those answers
1714 * for the lines in 'e' are in line_blames. This consumes e, essentially
1715 * putting it on a list.
1717 * Note that the blame entries on the ignoredp list are not necessarily sorted
1718 * with respect to the parent's line numbers yet.
1720 static void ignore_blame_entry(struct blame_entry
*e
,
1721 struct blame_origin
*parent
,
1722 struct blame_entry
**diffp
,
1723 struct blame_entry
**ignoredp
,
1724 struct blame_line_tracker
*line_blames
)
1726 int entry_len
, nr_lines
, i
;
1729 * We carve new entries off the front of e. Each entry comes from a
1730 * contiguous chunk of lines: adjacent lines from the same origin
1731 * (either the parent or the target).
1734 nr_lines
= e
->num_lines
; /* e changes in the loop */
1735 for (i
= 0; i
< nr_lines
; i
++) {
1736 struct blame_entry
*next
= NULL
;
1739 * We are often adjacent to the next line - only split the blame
1740 * entry when we have to.
1742 if (i
+ 1 < nr_lines
) {
1743 if (are_lines_adjacent(&line_blames
[i
],
1744 &line_blames
[i
+ 1])) {
1748 next
= split_blame_at(e
, entry_len
,
1749 blame_origin_incref(e
->suspect
));
1751 if (line_blames
[i
].is_parent
) {
1753 blame_origin_decref(e
->suspect
);
1754 e
->suspect
= blame_origin_incref(parent
);
1755 e
->s_lno
= line_blames
[i
- entry_len
+ 1].s_lno
;
1756 e
->next
= *ignoredp
;
1760 /* e->s_lno is already in the target's address space. */
1764 assert(e
->num_lines
== entry_len
);
1772 * Process one hunk from the patch between the current suspect for
1773 * blame_entry e and its parent. This first blames any unfinished
1774 * entries before the chunk (which is where target and parent start
1775 * differing) on the parent, and then splits blame entries at the
1776 * start and at the end of the difference region. Since use of -M and
1777 * -C options may lead to overlapping/duplicate source line number
1778 * ranges, all we can rely on from sorting/merging is the order of the
1779 * first suspect line number.
1781 * tlno: line number in the target where this chunk begins
1782 * same: line number in the target where this chunk ends
1783 * offset: add to tlno to get the chunk starting point in the parent
1784 * parent_len: number of lines in the parent chunk
1786 static void blame_chunk(struct blame_entry
***dstq
, struct blame_entry
***srcq
,
1787 int tlno
, int offset
, int same
, int parent_len
,
1788 struct blame_origin
*parent
,
1789 struct blame_origin
*target
, int ignore_diffs
)
1791 struct blame_entry
*e
= **srcq
;
1792 struct blame_entry
*samep
= NULL
, *diffp
= NULL
, *ignoredp
= NULL
;
1793 struct blame_line_tracker
*line_blames
= NULL
;
1795 while (e
&& e
->s_lno
< tlno
) {
1796 struct blame_entry
*next
= e
->next
;
1798 * current record starts before differing portion. If
1799 * it reaches into it, we need to split it up and
1800 * examine the second part separately.
1802 if (e
->s_lno
+ e
->num_lines
> tlno
) {
1803 /* Move second half to a new record */
1804 struct blame_entry
*n
;
1806 n
= split_blame_at(e
, tlno
- e
->s_lno
, e
->suspect
);
1807 /* Push new record to diffp */
1811 blame_origin_decref(e
->suspect
);
1812 /* Pass blame for everything before the differing
1813 * chunk to the parent */
1814 e
->suspect
= blame_origin_incref(parent
);
1821 * As we don't know how much of a common stretch after this
1822 * diff will occur, the currently blamed parts are all that we
1823 * can assign to the parent for now.
1827 **dstq
= reverse_blame(samep
, **dstq
);
1828 *dstq
= &samep
->next
;
1831 * Prepend the split off portions: everything after e starts
1832 * after the blameable portion.
1834 e
= reverse_blame(diffp
, e
);
1837 * Now retain records on the target while parts are different
1843 if (ignore_diffs
&& same
- tlno
> 0) {
1844 CALLOC_ARRAY(line_blames
, same
- tlno
);
1845 guess_line_blames(parent
, target
, tlno
, offset
, same
,
1846 parent_len
, line_blames
);
1849 while (e
&& e
->s_lno
< same
) {
1850 struct blame_entry
*next
= e
->next
;
1853 * If current record extends into sameness, need to split.
1855 if (e
->s_lno
+ e
->num_lines
> same
) {
1857 * Move second half to a new record to be
1858 * processed by later chunks
1860 struct blame_entry
*n
;
1862 n
= split_blame_at(e
, same
- e
->s_lno
,
1863 blame_origin_incref(e
->suspect
));
1864 /* Push new record to samep */
1869 ignore_blame_entry(e
, parent
, &diffp
, &ignoredp
,
1870 line_blames
+ e
->s_lno
- tlno
);
1880 * Note ignoredp is not sorted yet, and thus neither is dstq.
1881 * That list must be sorted before we queue_blames(). We defer
1882 * sorting until after all diff hunks are processed, so that
1883 * guess_line_blames() can pick *any* line in the parent. The
1884 * slight drawback is that we end up sorting all blame entries
1885 * passed to the parent, including those that are unrelated to
1886 * changes made by the ignored commit.
1888 **dstq
= reverse_blame(ignoredp
, **dstq
);
1889 *dstq
= &ignoredp
->next
;
1891 **srcq
= reverse_blame(diffp
, reverse_blame(samep
, e
));
1892 /* Move across elements that are in the unblamable portion */
1894 *srcq
= &diffp
->next
;
1897 struct blame_chunk_cb_data
{
1898 struct blame_origin
*parent
;
1899 struct blame_origin
*target
;
1902 struct blame_entry
**dstq
;
1903 struct blame_entry
**srcq
;
1906 /* diff chunks are from parent to target */
1907 static int blame_chunk_cb(long start_a
, long count_a
,
1908 long start_b
, long count_b
, void *data
)
1910 struct blame_chunk_cb_data
*d
= data
;
1911 if (start_a
- start_b
!= d
->offset
)
1912 die("internal error in blame::blame_chunk_cb");
1913 blame_chunk(&d
->dstq
, &d
->srcq
, start_b
, start_a
- start_b
,
1914 start_b
+ count_b
, count_a
, d
->parent
, d
->target
,
1916 d
->offset
= start_a
+ count_a
- (start_b
+ count_b
);
1921 * We are looking at the origin 'target' and aiming to pass blame
1922 * for the lines it is suspected to its parent. Run diff to find
1923 * which lines came from parent and pass blame for them.
1925 static void pass_blame_to_parent(struct blame_scoreboard
*sb
,
1926 struct blame_origin
*target
,
1927 struct blame_origin
*parent
, int ignore_diffs
)
1929 mmfile_t file_p
, file_o
;
1930 struct blame_chunk_cb_data d
;
1931 struct blame_entry
*newdest
= NULL
;
1933 if (!target
->suspects
)
1934 return; /* nothing remains for this target */
1939 d
.ignore_diffs
= ignore_diffs
;
1940 d
.dstq
= &newdest
; d
.srcq
= &target
->suspects
;
1942 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
1943 &sb
->num_read_blob
, ignore_diffs
);
1944 fill_origin_blob(&sb
->revs
->diffopt
, target
, &file_o
,
1945 &sb
->num_read_blob
, ignore_diffs
);
1946 sb
->num_get_patch
++;
1948 if (diff_hunks(&file_p
, &file_o
, blame_chunk_cb
, &d
, sb
->xdl_opts
))
1949 die("unable to generate diff (%s -> %s)",
1950 oid_to_hex(&parent
->commit
->object
.oid
),
1951 oid_to_hex(&target
->commit
->object
.oid
));
1952 /* The rest are the same as the parent */
1953 blame_chunk(&d
.dstq
, &d
.srcq
, INT_MAX
, d
.offset
, INT_MAX
, 0,
1957 sort_blame_entries(&newdest
, compare_blame_suspect
);
1958 queue_blames(sb
, parent
, newdest
);
1964 * The lines in blame_entry after splitting blames many times can become
1965 * very small and trivial, and at some point it becomes pointless to
1966 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1967 * ordinary C program, and it is not worth to say it was copied from
1968 * totally unrelated file in the parent.
1970 * Compute how trivial the lines in the blame_entry are.
1972 unsigned blame_entry_score(struct blame_scoreboard
*sb
, struct blame_entry
*e
)
1975 const char *cp
, *ep
;
1981 cp
= blame_nth_line(sb
, e
->lno
);
1982 ep
= blame_nth_line(sb
, e
->lno
+ e
->num_lines
);
1984 unsigned ch
= *((unsigned char *)cp
);
1994 * best_so_far[] and potential[] are both a split of an existing blame_entry
1995 * that passes blame to the parent. Maintain best_so_far the best split so
1996 * far, by comparing potential and best_so_far and copying potential into
1997 * bst_so_far as needed.
1999 static void copy_split_if_better(struct blame_scoreboard
*sb
,
2000 struct blame_entry
*best_so_far
,
2001 struct blame_entry
*potential
)
2005 if (!potential
[1].suspect
)
2007 if (best_so_far
[1].suspect
) {
2008 if (blame_entry_score(sb
, &potential
[1]) <
2009 blame_entry_score(sb
, &best_so_far
[1]))
2013 for (i
= 0; i
< 3; i
++)
2014 blame_origin_incref(potential
[i
].suspect
);
2015 decref_split(best_so_far
);
2016 memcpy(best_so_far
, potential
, sizeof(struct blame_entry
[3]));
2020 * We are looking at a part of the final image represented by
2021 * ent (tlno and same are offset by ent->s_lno).
2022 * tlno is where we are looking at in the final image.
2023 * up to (but not including) same match preimage.
2024 * plno is where we are looking at in the preimage.
2026 * <-------------- final image ---------------------->
2029 * <---------preimage----->
2032 * All line numbers are 0-based.
2034 static void handle_split(struct blame_scoreboard
*sb
,
2035 struct blame_entry
*ent
,
2036 int tlno
, int plno
, int same
,
2037 struct blame_origin
*parent
,
2038 struct blame_entry
*split
)
2040 if (ent
->num_lines
<= tlno
)
2043 struct blame_entry potential
[3];
2046 split_overlap(potential
, ent
, tlno
, plno
, same
, parent
);
2047 copy_split_if_better(sb
, split
, potential
);
2048 decref_split(potential
);
2052 struct handle_split_cb_data
{
2053 struct blame_scoreboard
*sb
;
2054 struct blame_entry
*ent
;
2055 struct blame_origin
*parent
;
2056 struct blame_entry
*split
;
2061 static int handle_split_cb(long start_a
, long count_a
,
2062 long start_b
, long count_b
, void *data
)
2064 struct handle_split_cb_data
*d
= data
;
2065 handle_split(d
->sb
, d
->ent
, d
->tlno
, d
->plno
, start_b
, d
->parent
,
2067 d
->plno
= start_a
+ count_a
;
2068 d
->tlno
= start_b
+ count_b
;
2073 * Find the lines from parent that are the same as ent so that
2074 * we can pass blames to it. file_p has the blob contents for
2077 static void find_copy_in_blob(struct blame_scoreboard
*sb
,
2078 struct blame_entry
*ent
,
2079 struct blame_origin
*parent
,
2080 struct blame_entry
*split
,
2085 struct handle_split_cb_data d
;
2087 memset(&d
, 0, sizeof(d
));
2088 d
.sb
= sb
; d
.ent
= ent
; d
.parent
= parent
; d
.split
= split
;
2090 * Prepare mmfile that contains only the lines in ent.
2092 cp
= blame_nth_line(sb
, ent
->lno
);
2093 file_o
.ptr
= (char *) cp
;
2094 file_o
.size
= blame_nth_line(sb
, ent
->lno
+ ent
->num_lines
) - cp
;
2097 * file_o is a part of final image we are annotating.
2098 * file_p partially may match that image.
2100 memset(split
, 0, sizeof(struct blame_entry
[3]));
2101 if (diff_hunks(file_p
, &file_o
, handle_split_cb
, &d
, sb
->xdl_opts
))
2102 die("unable to generate diff (%s)",
2103 oid_to_hex(&parent
->commit
->object
.oid
));
2104 /* remainder, if any, all match the preimage */
2105 handle_split(sb
, ent
, d
.tlno
, d
.plno
, ent
->num_lines
, parent
, split
);
2108 /* Move all blame entries from list *source that have a score smaller
2109 * than score_min to the front of list *small.
2110 * Returns a pointer to the link pointing to the old head of the small list.
2113 static struct blame_entry
**filter_small(struct blame_scoreboard
*sb
,
2114 struct blame_entry
**small
,
2115 struct blame_entry
**source
,
2118 struct blame_entry
*p
= *source
;
2119 struct blame_entry
*oldsmall
= *small
;
2121 if (blame_entry_score(sb
, p
) <= score_min
) {
2137 * See if lines currently target is suspected for can be attributed to
2140 static void find_move_in_parent(struct blame_scoreboard
*sb
,
2141 struct blame_entry
***blamed
,
2142 struct blame_entry
**toosmall
,
2143 struct blame_origin
*target
,
2144 struct blame_origin
*parent
)
2146 struct blame_entry
*e
, split
[3];
2147 struct blame_entry
*unblamed
= target
->suspects
;
2148 struct blame_entry
*leftover
= NULL
;
2152 return; /* nothing remains for this target */
2154 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
2155 &sb
->num_read_blob
, 0);
2159 /* At each iteration, unblamed has a NULL-terminated list of
2160 * entries that have not yet been tested for blame. leftover
2161 * contains the reversed list of entries that have been tested
2162 * without being assignable to the parent.
2165 struct blame_entry
**unblamedtail
= &unblamed
;
2166 struct blame_entry
*next
;
2167 for (e
= unblamed
; e
; e
= next
) {
2169 find_copy_in_blob(sb
, e
, parent
, split
, &file_p
);
2170 if (split
[1].suspect
&&
2171 sb
->move_score
< blame_entry_score(sb
, &split
[1])) {
2172 split_blame(blamed
, &unblamedtail
, split
, e
);
2177 decref_split(split
);
2179 *unblamedtail
= NULL
;
2180 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->move_score
);
2182 target
->suspects
= reverse_blame(leftover
, NULL
);
2186 struct blame_entry
*ent
;
2187 struct blame_entry split
[3];
2191 * Count the number of entries the target is suspected for,
2192 * and prepare a list of entry and the best split.
2194 static struct blame_list
*setup_blame_list(struct blame_entry
*unblamed
,
2197 struct blame_entry
*e
;
2199 struct blame_list
*blame_list
= NULL
;
2201 for (e
= unblamed
, num_ents
= 0; e
; e
= e
->next
)
2204 CALLOC_ARRAY(blame_list
, num_ents
);
2205 for (e
= unblamed
, i
= 0; e
; e
= e
->next
)
2206 blame_list
[i
++].ent
= e
;
2208 *num_ents_p
= num_ents
;
2213 * For lines target is suspected for, see if we can find code movement
2214 * across file boundary from the parent commit. porigin is the path
2215 * in the parent we already tried.
2217 static void find_copy_in_parent(struct blame_scoreboard
*sb
,
2218 struct blame_entry
***blamed
,
2219 struct blame_entry
**toosmall
,
2220 struct blame_origin
*target
,
2221 struct commit
*parent
,
2222 struct blame_origin
*porigin
,
2225 struct diff_options diff_opts
;
2227 struct blame_list
*blame_list
;
2229 struct blame_entry
*unblamed
= target
->suspects
;
2230 struct blame_entry
*leftover
= NULL
;
2233 return; /* nothing remains for this target */
2235 repo_diff_setup(sb
->repo
, &diff_opts
);
2236 diff_opts
.flags
.recursive
= 1;
2237 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
2239 diff_setup_done(&diff_opts
);
2241 /* Try "find copies harder" on new path if requested;
2242 * we do not want to use diffcore_rename() actually to
2243 * match things up; find_copies_harder is set only to
2244 * force diff_tree_oid() to feed all filepairs to diff_queue,
2245 * and this code needs to be after diff_setup_done(), which
2246 * usually makes find-copies-harder imply copy detection.
2248 if ((opt
& PICKAXE_BLAME_COPY_HARDEST
)
2249 || ((opt
& PICKAXE_BLAME_COPY_HARDER
)
2250 && (!porigin
|| strcmp(target
->path
, porigin
->path
))))
2251 diff_opts
.flags
.find_copies_harder
= 1;
2253 if (is_null_oid(&target
->commit
->object
.oid
))
2254 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
2256 diff_tree_oid(get_commit_tree_oid(parent
),
2257 get_commit_tree_oid(target
->commit
),
2260 if (!diff_opts
.flags
.find_copies_harder
)
2261 diffcore_std(&diff_opts
);
2264 struct blame_entry
**unblamedtail
= &unblamed
;
2265 blame_list
= setup_blame_list(unblamed
, &num_ents
);
2267 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
2268 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
2269 struct blame_origin
*norigin
;
2271 struct blame_entry potential
[3];
2273 if (!DIFF_FILE_VALID(p
->one
))
2274 continue; /* does not exist in parent */
2275 if (S_ISGITLINK(p
->one
->mode
))
2276 continue; /* ignore git links */
2277 if (porigin
&& !strcmp(p
->one
->path
, porigin
->path
))
2278 /* find_move already dealt with this path */
2281 norigin
= get_origin(parent
, p
->one
->path
);
2282 oidcpy(&norigin
->blob_oid
, &p
->one
->oid
);
2283 norigin
->mode
= p
->one
->mode
;
2284 fill_origin_blob(&sb
->revs
->diffopt
, norigin
, &file_p
,
2285 &sb
->num_read_blob
, 0);
2289 for (j
= 0; j
< num_ents
; j
++) {
2290 find_copy_in_blob(sb
, blame_list
[j
].ent
,
2291 norigin
, potential
, &file_p
);
2292 copy_split_if_better(sb
, blame_list
[j
].split
,
2294 decref_split(potential
);
2296 blame_origin_decref(norigin
);
2299 for (j
= 0; j
< num_ents
; j
++) {
2300 struct blame_entry
*split
= blame_list
[j
].split
;
2301 if (split
[1].suspect
&&
2302 sb
->copy_score
< blame_entry_score(sb
, &split
[1])) {
2303 split_blame(blamed
, &unblamedtail
, split
,
2306 blame_list
[j
].ent
->next
= leftover
;
2307 leftover
= blame_list
[j
].ent
;
2309 decref_split(split
);
2312 *unblamedtail
= NULL
;
2313 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->copy_score
);
2315 target
->suspects
= reverse_blame(leftover
, NULL
);
2316 diff_flush(&diff_opts
);
2320 * The blobs of origin and porigin exactly match, so everything
2321 * origin is suspected for can be blamed on the parent.
2323 static void pass_whole_blame(struct blame_scoreboard
*sb
,
2324 struct blame_origin
*origin
, struct blame_origin
*porigin
)
2326 struct blame_entry
*e
, *suspects
;
2328 if (!porigin
->file
.ptr
&& origin
->file
.ptr
) {
2329 /* Steal its file */
2330 porigin
->file
= origin
->file
;
2331 origin
->file
.ptr
= NULL
;
2333 suspects
= origin
->suspects
;
2334 origin
->suspects
= NULL
;
2335 for (e
= suspects
; e
; e
= e
->next
) {
2336 blame_origin_incref(porigin
);
2337 blame_origin_decref(e
->suspect
);
2338 e
->suspect
= porigin
;
2340 queue_blames(sb
, porigin
, suspects
);
2344 * We pass blame from the current commit to its parents. We keep saying
2345 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2346 * exonerate ourselves.
2348 static struct commit_list
*first_scapegoat(struct rev_info
*revs
, struct commit
*commit
,
2352 if (revs
->first_parent_only
&&
2354 commit
->parents
->next
) {
2355 free_commit_list(commit
->parents
->next
);
2356 commit
->parents
->next
= NULL
;
2358 return commit
->parents
;
2360 return lookup_decoration(&revs
->children
, &commit
->object
);
2363 static int num_scapegoats(struct rev_info
*revs
, struct commit
*commit
, int reverse
)
2365 struct commit_list
*l
= first_scapegoat(revs
, commit
, reverse
);
2366 return commit_list_count(l
);
2369 /* Distribute collected unsorted blames to the respected sorted lists
2370 * in the various origins.
2372 static void distribute_blame(struct blame_scoreboard
*sb
, struct blame_entry
*blamed
)
2374 sort_blame_entries(&blamed
, compare_blame_suspect
);
2377 struct blame_origin
*porigin
= blamed
->suspect
;
2378 struct blame_entry
*suspects
= NULL
;
2380 struct blame_entry
*next
= blamed
->next
;
2381 blamed
->next
= suspects
;
2384 } while (blamed
&& blamed
->suspect
== porigin
);
2385 suspects
= reverse_blame(suspects
, NULL
);
2386 queue_blames(sb
, porigin
, suspects
);
2392 typedef struct blame_origin
*(*blame_find_alg
)(struct repository
*,
2394 struct blame_origin
*,
2395 struct blame_bloom_data
*);
2397 static void pass_blame(struct blame_scoreboard
*sb
, struct blame_origin
*origin
, int opt
)
2399 struct rev_info
*revs
= sb
->revs
;
2400 int i
, pass
, num_sg
;
2401 struct commit
*commit
= origin
->commit
;
2402 struct commit_list
*sg
;
2403 struct blame_origin
*sg_buf
[MAXSG
];
2404 struct blame_origin
*porigin
, **sg_origin
= sg_buf
;
2405 struct blame_entry
*toosmall
= NULL
;
2406 struct blame_entry
*blames
, **blametail
= &blames
;
2408 num_sg
= num_scapegoats(revs
, commit
, sb
->reverse
);
2411 else if (num_sg
< ARRAY_SIZE(sg_buf
))
2412 memset(sg_buf
, 0, sizeof(sg_buf
));
2414 CALLOC_ARRAY(sg_origin
, num_sg
);
2417 * The first pass looks for unrenamed path to optimize for
2418 * common cases, then we look for renames in the second pass.
2420 for (pass
= 0; pass
< 2 - sb
->no_whole_file_rename
; pass
++) {
2421 blame_find_alg find
= pass
? find_rename
: find_origin
;
2423 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2425 sg
= sg
->next
, i
++) {
2426 struct commit
*p
= sg
->item
;
2431 if (repo_parse_commit(the_repository
, p
))
2433 porigin
= find(sb
->repo
, p
, origin
, sb
->bloom_data
);
2436 if (oideq(&porigin
->blob_oid
, &origin
->blob_oid
)) {
2437 pass_whole_blame(sb
, origin
, porigin
);
2438 blame_origin_decref(porigin
);
2441 for (j
= same
= 0; j
< i
; j
++)
2443 oideq(&sg_origin
[j
]->blob_oid
, &porigin
->blob_oid
)) {
2448 sg_origin
[i
] = porigin
;
2450 blame_origin_decref(porigin
);
2455 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2457 sg
= sg
->next
, i
++) {
2458 struct blame_origin
*porigin
= sg_origin
[i
];
2461 if (!origin
->previous
) {
2462 blame_origin_incref(porigin
);
2463 origin
->previous
= porigin
;
2465 pass_blame_to_parent(sb
, origin
, porigin
, 0);
2466 if (!origin
->suspects
)
2471 * Pass remaining suspects for ignored commits to their parents.
2473 if (oidset_contains(&sb
->ignore_list
, &commit
->object
.oid
)) {
2474 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2476 sg
= sg
->next
, i
++) {
2477 struct blame_origin
*porigin
= sg_origin
[i
];
2481 pass_blame_to_parent(sb
, origin
, porigin
, 1);
2483 * Preemptively drop porigin so we can refresh the
2484 * fingerprints if we use the parent again, which can
2485 * occur if you ignore back-to-back commits.
2487 drop_origin_blob(porigin
);
2488 if (!origin
->suspects
)
2494 * Optionally find moves in parents' files.
2496 if (opt
& PICKAXE_BLAME_MOVE
) {
2497 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->move_score
);
2498 if (origin
->suspects
) {
2499 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2501 sg
= sg
->next
, i
++) {
2502 struct blame_origin
*porigin
= sg_origin
[i
];
2505 find_move_in_parent(sb
, &blametail
, &toosmall
, origin
, porigin
);
2506 if (!origin
->suspects
)
2513 * Optionally find copies from parents' files.
2515 if (opt
& PICKAXE_BLAME_COPY
) {
2516 if (sb
->copy_score
> sb
->move_score
)
2517 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2518 else if (sb
->copy_score
< sb
->move_score
) {
2519 origin
->suspects
= blame_merge(origin
->suspects
, toosmall
);
2521 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2523 if (!origin
->suspects
)
2526 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2528 sg
= sg
->next
, i
++) {
2529 struct blame_origin
*porigin
= sg_origin
[i
];
2530 find_copy_in_parent(sb
, &blametail
, &toosmall
,
2531 origin
, sg
->item
, porigin
, opt
);
2532 if (!origin
->suspects
)
2539 distribute_blame(sb
, blames
);
2541 * prepend toosmall to origin->suspects
2543 * There is no point in sorting: this ends up on a big
2544 * unsorted list in the caller anyway.
2547 struct blame_entry
**tail
= &toosmall
;
2549 tail
= &(*tail
)->next
;
2550 *tail
= origin
->suspects
;
2551 origin
->suspects
= toosmall
;
2553 for (i
= 0; i
< num_sg
; i
++) {
2555 if (!sg_origin
[i
]->suspects
)
2556 drop_origin_blob(sg_origin
[i
]);
2557 blame_origin_decref(sg_origin
[i
]);
2560 drop_origin_blob(origin
);
2561 if (sg_buf
!= sg_origin
)
2566 * The main loop -- while we have blobs with lines whose true origin
2567 * is still unknown, pick one blob, and allow its lines to pass blames
2568 * to its parents. */
2569 void assign_blame(struct blame_scoreboard
*sb
, int opt
)
2571 struct rev_info
*revs
= sb
->revs
;
2572 struct commit
*commit
= prio_queue_get(&sb
->commits
);
2575 struct blame_entry
*ent
;
2576 struct blame_origin
*suspect
= get_blame_suspects(commit
);
2578 /* find one suspect to break down */
2579 while (suspect
&& !suspect
->suspects
)
2580 suspect
= suspect
->next
;
2583 commit
= prio_queue_get(&sb
->commits
);
2587 assert(commit
== suspect
->commit
);
2590 * We will use this suspect later in the loop,
2591 * so hold onto it in the meantime.
2593 blame_origin_incref(suspect
);
2594 repo_parse_commit(the_repository
, commit
);
2596 (!(commit
->object
.flags
& UNINTERESTING
) &&
2597 !(revs
->max_age
!= -1 && commit
->date
< revs
->max_age
)))
2598 pass_blame(sb
, suspect
, opt
);
2600 commit
->object
.flags
|= UNINTERESTING
;
2601 if (commit
->object
.parsed
)
2602 mark_parents_uninteresting(sb
->revs
, commit
);
2604 /* treat root commit as boundary */
2605 if (!commit
->parents
&& !sb
->show_root
)
2606 commit
->object
.flags
|= UNINTERESTING
;
2608 /* Take responsibility for the remaining entries */
2609 ent
= suspect
->suspects
;
2611 suspect
->guilty
= 1;
2613 struct blame_entry
*next
= ent
->next
;
2614 if (sb
->found_guilty_entry
)
2615 sb
->found_guilty_entry(ent
, sb
->found_guilty_entry_data
);
2620 ent
->next
= sb
->ent
;
2621 sb
->ent
= suspect
->suspects
;
2622 suspect
->suspects
= NULL
;
2626 blame_origin_decref(suspect
);
2628 if (sb
->debug
) /* sanity */
2629 sanity_check_refcnt(sb
);
2634 * To allow quick access to the contents of nth line in the
2635 * final image, prepare an index in the scoreboard.
2637 static int prepare_lines(struct blame_scoreboard
*sb
)
2639 sb
->num_lines
= find_line_starts(&sb
->lineno
, sb
->final_buf
,
2640 sb
->final_buf_size
);
2641 return sb
->num_lines
;
2644 static struct commit
*find_single_final(struct rev_info
*revs
,
2645 const char **name_p
)
2648 struct commit
*found
= NULL
;
2649 const char *name
= NULL
;
2651 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2652 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2653 if (obj
->flags
& UNINTERESTING
)
2655 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2656 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2657 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2659 die("More than one commit to dig from %s and %s?",
2660 revs
->pending
.objects
[i
].name
, name
);
2661 found
= (struct commit
*)obj
;
2662 name
= revs
->pending
.objects
[i
].name
;
2665 *name_p
= xstrdup_or_null(name
);
2669 static struct commit
*dwim_reverse_initial(struct rev_info
*revs
,
2670 const char **name_p
)
2673 * DWIM "git blame --reverse ONE -- PATH" as
2674 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2675 * when it makes sense.
2678 struct commit
*head_commit
;
2679 struct object_id head_oid
;
2681 if (revs
->pending
.nr
!= 1)
2684 /* Is that sole rev a committish? */
2685 obj
= revs
->pending
.objects
[0].item
;
2686 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2687 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2690 /* Do we have HEAD? */
2691 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
2693 head_commit
= lookup_commit_reference_gently(revs
->repo
,
2698 /* Turn "ONE" into "ONE..HEAD" then */
2699 obj
->flags
|= UNINTERESTING
;
2700 add_pending_object(revs
, &head_commit
->object
, "HEAD");
2703 *name_p
= revs
->pending
.objects
[0].name
;
2704 return (struct commit
*)obj
;
2707 static struct commit
*find_single_initial(struct rev_info
*revs
,
2708 const char **name_p
)
2711 struct commit
*found
= NULL
;
2712 const char *name
= NULL
;
2715 * There must be one and only one negative commit, and it must be
2718 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2719 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2720 if (!(obj
->flags
& UNINTERESTING
))
2722 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2723 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2724 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2726 die("More than one commit to dig up from, %s and %s?",
2727 revs
->pending
.objects
[i
].name
, name
);
2728 found
= (struct commit
*) obj
;
2729 name
= revs
->pending
.objects
[i
].name
;
2733 found
= dwim_reverse_initial(revs
, &name
);
2735 die("No commit to dig up from?");
2738 *name_p
= xstrdup(name
);
2742 void init_scoreboard(struct blame_scoreboard
*sb
)
2744 memset(sb
, 0, sizeof(struct blame_scoreboard
));
2745 sb
->move_score
= BLAME_DEFAULT_MOVE_SCORE
;
2746 sb
->copy_score
= BLAME_DEFAULT_COPY_SCORE
;
2749 void setup_scoreboard(struct blame_scoreboard
*sb
,
2750 struct blame_origin
**orig
)
2752 const char *final_commit_name
= NULL
;
2753 struct blame_origin
*o
;
2754 struct commit
*final_commit
= NULL
;
2755 enum object_type type
;
2757 init_blame_suspects(&blame_suspects
);
2759 if (sb
->reverse
&& sb
->contents_from
)
2760 die(_("--contents and --reverse do not blend well."));
2763 BUG("repo is NULL");
2766 sb
->final
= find_single_final(sb
->revs
, &final_commit_name
);
2767 sb
->commits
.compare
= compare_commits_by_commit_date
;
2769 sb
->final
= find_single_initial(sb
->revs
, &final_commit_name
);
2770 sb
->commits
.compare
= compare_commits_by_reverse_commit_date
;
2773 if (sb
->reverse
&& sb
->revs
->first_parent_only
)
2774 sb
->revs
->children
.name
= NULL
;
2776 if (sb
->contents_from
|| !sb
->final
) {
2777 struct object_id head_oid
, *parent_oid
;
2780 * Build a fake commit at the top of the history, when
2781 * (1) "git blame [^A] --path", i.e. with no positive end
2782 * of the history range, in which case we build such
2783 * a fake commit on top of the HEAD to blame in-tree
2785 * (2) "git blame --contents=file [A] -- path", with or
2786 * without positive end of the history range but with
2787 * --contents, in which case we pretend that there is
2788 * a fake commit on top of the positive end (defaulting to
2789 * HEAD) that has the given contents in the path.
2792 parent_oid
= &sb
->final
->object
.oid
;
2794 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
2795 die("no such ref: HEAD");
2796 parent_oid
= &head_oid
;
2800 sb
->final
= fake_working_tree_commit(sb
->repo
,
2802 sb
->path
, sb
->contents_from
,
2804 add_pending_object(sb
->revs
, &(sb
->final
->object
), ":");
2807 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2808 final_commit
= find_single_final(sb
->revs
, NULL
);
2810 die(_("--reverse and --first-parent together require specified latest commit"));
2814 * If we have bottom, this will mark the ancestors of the
2815 * bottom commits we would reach while traversing as
2818 if (prepare_revision_walk(sb
->revs
))
2819 die(_("revision walk setup failed"));
2821 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2822 struct commit
*c
= final_commit
;
2824 sb
->revs
->children
.name
= "children";
2825 while (c
->parents
&&
2826 !oideq(&c
->object
.oid
, &sb
->final
->object
.oid
)) {
2827 struct commit_list
*l
= xcalloc(1, sizeof(*l
));
2830 if (add_decoration(&sb
->revs
->children
,
2831 &c
->parents
->item
->object
, l
))
2832 BUG("not unique item in first-parent chain");
2833 c
= c
->parents
->item
;
2836 if (!oideq(&c
->object
.oid
, &sb
->final
->object
.oid
))
2837 die(_("--reverse --first-parent together require range along first-parent chain"));
2840 if (is_null_oid(&sb
->final
->object
.oid
)) {
2841 o
= get_blame_suspects(sb
->final
);
2842 sb
->final_buf
= xmemdupz(o
->file
.ptr
, o
->file
.size
);
2843 sb
->final_buf_size
= o
->file
.size
;
2846 o
= get_origin(sb
->final
, sb
->path
);
2847 if (fill_blob_sha1_and_mode(sb
->repo
, o
))
2848 die(_("no such path %s in %s"), sb
->path
, final_commit_name
);
2850 if (sb
->revs
->diffopt
.flags
.allow_textconv
&&
2851 textconv_object(sb
->repo
, sb
->path
, o
->mode
, &o
->blob_oid
, 1, (char **) &sb
->final_buf
,
2852 &sb
->final_buf_size
))
2855 sb
->final_buf
= repo_read_object_file(the_repository
,
2858 &sb
->final_buf_size
);
2861 die(_("cannot read blob %s for path %s"),
2862 oid_to_hex(&o
->blob_oid
),
2865 sb
->num_read_blob
++;
2871 free((char *)final_commit_name
);
2876 struct blame_entry
*blame_entry_prepend(struct blame_entry
*head
,
2877 long start
, long end
,
2878 struct blame_origin
*o
)
2880 struct blame_entry
*new_head
= xcalloc(1, sizeof(struct blame_entry
));
2881 new_head
->lno
= start
;
2882 new_head
->num_lines
= end
- start
;
2883 new_head
->suspect
= o
;
2884 new_head
->s_lno
= start
;
2885 new_head
->next
= head
;
2886 blame_origin_incref(o
);
2890 void setup_blame_bloom_data(struct blame_scoreboard
*sb
)
2892 struct blame_bloom_data
*bd
;
2893 struct bloom_filter_settings
*bs
;
2895 if (!sb
->repo
->objects
->commit_graph
)
2898 bs
= get_bloom_filter_settings(sb
->repo
);
2902 bd
= xmalloc(sizeof(struct blame_bloom_data
));
2908 ALLOC_ARRAY(bd
->keys
, bd
->alloc
);
2910 add_bloom_key(bd
, sb
->path
);
2912 sb
->bloom_data
= bd
;
2915 void cleanup_scoreboard(struct blame_scoreboard
*sb
)
2917 if (sb
->bloom_data
) {
2919 for (i
= 0; i
< sb
->bloom_data
->nr
; i
++) {
2920 free(sb
->bloom_data
->keys
[i
]->hashes
);
2921 free(sb
->bloom_data
->keys
[i
]);
2923 free(sb
->bloom_data
->keys
);
2924 FREE_AND_NULL(sb
->bloom_data
);
2926 trace2_data_intmax("blame", sb
->repo
,
2927 "bloom/queries", bloom_count_queries
);
2928 trace2_data_intmax("blame", sb
->repo
,
2929 "bloom/response-no", bloom_count_no
);