3 #include "object-store.h"
4 #include "cache-tree.h"
16 #include "commit-slab.h"
18 #include "commit-graph.h"
20 define_commit_slab(blame_suspects
, struct blame_origin
*);
21 static struct blame_suspects blame_suspects
;
23 struct blame_origin
*get_blame_suspects(struct commit
*commit
)
25 struct blame_origin
**result
;
27 result
= blame_suspects_peek(&blame_suspects
, commit
);
29 return result
? *result
: NULL
;
32 static void set_blame_suspects(struct commit
*commit
, struct blame_origin
*origin
)
34 *blame_suspects_at(&blame_suspects
, commit
) = origin
;
37 void blame_origin_decref(struct blame_origin
*o
)
39 if (o
&& --o
->refcnt
<= 0) {
40 struct blame_origin
*p
, *l
= NULL
;
42 blame_origin_decref(o
->previous
);
44 /* Should be present exactly once in commit chain */
45 for (p
= get_blame_suspects(o
->commit
); p
; l
= p
, p
= p
->next
) {
50 set_blame_suspects(o
->commit
, p
->next
);
55 die("internal error in blame_origin_decref");
60 * Given a commit and a path in it, create a new origin structure.
61 * The callers that add blame to the scoreboard should use
62 * get_origin() to obtain shared, refcounted copy instead of calling
63 * this function directly.
65 static struct blame_origin
*make_origin(struct commit
*commit
, const char *path
)
67 struct blame_origin
*o
;
68 FLEX_ALLOC_STR(o
, path
, path
);
71 o
->next
= get_blame_suspects(commit
);
72 set_blame_suspects(commit
, o
);
77 * Locate an existing origin or create a new one.
78 * This moves the origin to front position in the commit util list.
80 static struct blame_origin
*get_origin(struct commit
*commit
, const char *path
)
82 struct blame_origin
*o
, *l
;
84 for (o
= get_blame_suspects(commit
), l
= NULL
; o
; l
= o
, o
= o
->next
) {
85 if (!strcmp(o
->path
, path
)) {
89 o
->next
= get_blame_suspects(commit
);
90 set_blame_suspects(commit
, o
);
92 return blame_origin_incref(o
);
95 return make_origin(commit
, path
);
100 static void verify_working_tree_path(struct repository
*r
,
101 struct commit
*work_tree
, const char *path
)
103 struct commit_list
*parents
;
106 for (parents
= work_tree
->parents
; parents
; parents
= parents
->next
) {
107 const struct object_id
*commit_oid
= &parents
->item
->object
.oid
;
108 struct object_id blob_oid
;
111 if (!get_tree_entry(r
, commit_oid
, path
, &blob_oid
, &mode
) &&
112 oid_object_info(r
, &blob_oid
, NULL
) == OBJ_BLOB
)
116 pos
= index_name_pos(r
->index
, path
, strlen(path
));
118 ; /* path is in the index */
119 else if (-1 - pos
< r
->index
->cache_nr
&&
120 !strcmp(r
->index
->cache
[-1 - pos
]->name
, path
))
121 ; /* path is in the index, unmerged */
123 die("no such path '%s' in HEAD", path
);
126 static struct commit_list
**append_parent(struct repository
*r
,
127 struct commit_list
**tail
,
128 const struct object_id
*oid
)
130 struct commit
*parent
;
132 parent
= lookup_commit_reference(r
, oid
);
134 die("no such commit %s", oid_to_hex(oid
));
135 return &commit_list_insert(parent
, tail
)->next
;
138 static void append_merge_parents(struct repository
*r
,
139 struct commit_list
**tail
)
142 struct strbuf line
= STRBUF_INIT
;
144 merge_head
= open(git_path_merge_head(r
), O_RDONLY
);
145 if (merge_head
< 0) {
148 die("cannot open '%s' for reading",
149 git_path_merge_head(r
));
152 while (!strbuf_getwholeline_fd(&line
, merge_head
, '\n')) {
153 struct object_id oid
;
154 if (get_oid_hex(line
.buf
, &oid
))
155 die("unknown line in '%s': %s",
156 git_path_merge_head(r
), line
.buf
);
157 tail
= append_parent(r
, tail
, &oid
);
160 strbuf_release(&line
);
164 * This isn't as simple as passing sb->buf and sb->len, because we
165 * want to transfer ownership of the buffer to the commit (so we
168 static void set_commit_buffer_from_strbuf(struct repository
*r
,
173 void *buf
= strbuf_detach(sb
, &len
);
174 set_commit_buffer(r
, c
, buf
, len
);
178 * Prepare a dummy commit that represents the work tree (or staged) item.
179 * Note that annotating work tree item never works in the reverse.
181 static struct commit
*fake_working_tree_commit(struct repository
*r
,
182 struct diff_options
*opt
,
184 const char *contents_from
)
186 struct commit
*commit
;
187 struct blame_origin
*origin
;
188 struct commit_list
**parent_tail
, *parent
;
189 struct object_id head_oid
;
190 struct strbuf buf
= STRBUF_INIT
;
194 struct cache_entry
*ce
;
196 struct strbuf msg
= STRBUF_INIT
;
200 commit
= alloc_commit_node(r
);
201 commit
->object
.parsed
= 1;
203 parent_tail
= &commit
->parents
;
205 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
206 die("no such ref: HEAD");
208 parent_tail
= append_parent(r
, parent_tail
, &head_oid
);
209 append_merge_parents(r
, parent_tail
);
210 verify_working_tree_path(r
, commit
, path
);
212 origin
= make_origin(commit
, path
);
214 ident
= fmt_ident("Not Committed Yet", "not.committed.yet",
215 WANT_BLANK_IDENT
, NULL
, 0);
216 strbuf_addstr(&msg
, "tree 0000000000000000000000000000000000000000\n");
217 for (parent
= commit
->parents
; parent
; parent
= parent
->next
)
218 strbuf_addf(&msg
, "parent %s\n",
219 oid_to_hex(&parent
->item
->object
.oid
));
223 "Version of %s from %s\n",
225 (!contents_from
? path
:
226 (!strcmp(contents_from
, "-") ? "standard input" : contents_from
)));
227 set_commit_buffer_from_strbuf(r
, commit
, &msg
);
229 if (!contents_from
|| strcmp("-", contents_from
)) {
231 const char *read_from
;
233 unsigned long buf_len
;
236 if (stat(contents_from
, &st
) < 0)
237 die_errno("Cannot stat '%s'", contents_from
);
238 read_from
= contents_from
;
241 if (lstat(path
, &st
) < 0)
242 die_errno("Cannot lstat '%s'", path
);
245 mode
= canon_mode(st
.st_mode
);
247 switch (st
.st_mode
& S_IFMT
) {
249 if (opt
->flags
.allow_textconv
&&
250 textconv_object(r
, read_from
, mode
, null_oid(), 0, &buf_ptr
, &buf_len
))
251 strbuf_attach(&buf
, buf_ptr
, buf_len
, buf_len
+ 1);
252 else if (strbuf_read_file(&buf
, read_from
, st
.st_size
) != st
.st_size
)
253 die_errno("cannot open or read '%s'", read_from
);
256 if (strbuf_readlink(&buf
, read_from
, st
.st_size
) < 0)
257 die_errno("cannot readlink '%s'", read_from
);
260 die("unsupported file type %s", read_from
);
264 /* Reading from stdin */
266 if (strbuf_read(&buf
, 0, 0) < 0)
267 die_errno("failed to read from stdin");
269 convert_to_git(r
->index
, path
, buf
.buf
, buf
.len
, &buf
, 0);
270 origin
->file
.ptr
= buf
.buf
;
271 origin
->file
.size
= buf
.len
;
272 pretend_object_file(buf
.buf
, buf
.len
, OBJ_BLOB
, &origin
->blob_oid
);
275 * Read the current index, replace the path entry with
276 * origin->blob_sha1 without mucking with its mode or type
277 * bits; we are not going to write this index out -- we just
278 * want to run "diff-index --cached".
280 discard_index(r
->index
);
285 int pos
= index_name_pos(r
->index
, path
, len
);
287 mode
= r
->index
->cache
[pos
]->ce_mode
;
289 /* Let's not bother reading from HEAD tree */
290 mode
= S_IFREG
| 0644;
292 ce
= make_empty_cache_entry(r
->index
, len
);
293 oidcpy(&ce
->oid
, &origin
->blob_oid
);
294 memcpy(ce
->name
, path
, len
);
295 ce
->ce_flags
= create_ce_flags(0);
296 ce
->ce_namelen
= len
;
297 ce
->ce_mode
= create_ce_mode(mode
);
298 add_index_entry(r
->index
, ce
,
299 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
301 cache_tree_invalidate_path(r
->index
, path
);
308 static int diff_hunks(mmfile_t
*file_a
, mmfile_t
*file_b
,
309 xdl_emit_hunk_consume_func_t hunk_func
, void *cb_data
, int xdl_opts
)
312 xdemitconf_t xecfg
= {0};
313 xdemitcb_t ecb
= {NULL
};
315 xpp
.flags
= xdl_opts
;
316 xecfg
.hunk_func
= hunk_func
;
318 return xdi_diff(file_a
, file_b
, &xpp
, &xecfg
, &ecb
);
321 static const char *get_next_line(const char *start
, const char *end
)
323 const char *nl
= memchr(start
, '\n', end
- start
);
325 return nl
? nl
+ 1 : end
;
328 static int find_line_starts(int **line_starts
, const char *buf
,
331 const char *end
= buf
+ len
;
336 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
339 ALLOC_ARRAY(*line_starts
, num
+ 1);
340 lineno
= *line_starts
;
342 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
350 struct fingerprint_entry
;
352 /* A fingerprint is intended to loosely represent a string, such that two
353 * fingerprints can be quickly compared to give an indication of the similarity
354 * of the strings that they represent.
356 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
357 * the string that it represents. Whitespace is added at each end of the
358 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
359 * For example, the string "Darth Radar" will be converted to the following
361 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
363 * The similarity between two fingerprints is the size of the intersection of
364 * their multisets, including repeated elements. See fingerprint_similarity for
367 * For ease of implementation, the fingerprint is implemented as a map
368 * of byte pairs to the count of that byte pair in the string, instead of
369 * allowing repeated elements in a set.
373 /* As we know the maximum number of entries in advance, it's
374 * convenient to store the entries in a single array instead of having
375 * the hashmap manage the memory.
377 struct fingerprint_entry
*entries
;
380 /* A byte pair in a fingerprint. Stores the number of times the byte pair
381 * occurs in the string that the fingerprint represents.
383 struct fingerprint_entry
{
384 /* The hashmap entry - the hash represents the byte pair in its
385 * entirety so we don't need to store the byte pair separately.
387 struct hashmap_entry entry
;
388 /* The number of times the byte pair occurs in the string that the
389 * fingerprint represents.
394 /* See `struct fingerprint` for an explanation of what a fingerprint is.
395 * \param result the fingerprint of the string is stored here. This must be
396 * freed later using free_fingerprint.
397 * \param line_begin the start of the string
398 * \param line_end the end of the string
400 static void get_fingerprint(struct fingerprint
*result
,
401 const char *line_begin
,
402 const char *line_end
)
404 unsigned int hash
, c0
= 0, c1
;
406 int max_map_entry_count
= 1 + line_end
- line_begin
;
407 struct fingerprint_entry
*entry
= xcalloc(max_map_entry_count
,
408 sizeof(struct fingerprint_entry
));
409 struct fingerprint_entry
*found_entry
;
411 hashmap_init(&result
->map
, NULL
, NULL
, max_map_entry_count
);
412 result
->entries
= entry
;
413 for (p
= line_begin
; p
<= line_end
; ++p
, c0
= c1
) {
414 /* Always terminate the string with whitespace.
415 * Normalise whitespace to 0, and normalise letters to
416 * lower case. This won't work for multibyte characters but at
417 * worst will match some unrelated characters.
419 if ((p
== line_end
) || isspace(*p
))
423 hash
= c0
| (c1
<< 8);
424 /* Ignore whitespace pairs */
427 hashmap_entry_init(&entry
->entry
, hash
);
429 found_entry
= hashmap_get_entry(&result
->map
, entry
,
430 /* member name */ entry
, NULL
);
432 found_entry
->count
+= 1;
435 hashmap_add(&result
->map
, &entry
->entry
);
441 static void free_fingerprint(struct fingerprint
*f
)
443 hashmap_clear(&f
->map
);
447 /* Calculates the similarity between two fingerprints as the size of the
448 * intersection of their multisets, including repeated elements. See
449 * `struct fingerprint` for an explanation of the fingerprint representation.
450 * The similarity between "cat mat" and "father rather" is 2 because "at" is
451 * present twice in both strings while the similarity between "tim" and "mit"
454 static int fingerprint_similarity(struct fingerprint
*a
, struct fingerprint
*b
)
456 int intersection
= 0;
457 struct hashmap_iter iter
;
458 const struct fingerprint_entry
*entry_a
, *entry_b
;
460 hashmap_for_each_entry(&b
->map
, &iter
, entry_b
,
461 entry
/* member name */) {
462 entry_a
= hashmap_get_entry(&a
->map
, entry_b
, entry
, NULL
);
464 intersection
+= entry_a
->count
< entry_b
->count
?
465 entry_a
->count
: entry_b
->count
;
471 /* Subtracts byte-pair elements in B from A, modifying A in place.
473 static void fingerprint_subtract(struct fingerprint
*a
, struct fingerprint
*b
)
475 struct hashmap_iter iter
;
476 struct fingerprint_entry
*entry_a
;
477 const struct fingerprint_entry
*entry_b
;
479 hashmap_iter_init(&b
->map
, &iter
);
481 hashmap_for_each_entry(&b
->map
, &iter
, entry_b
,
482 entry
/* member name */) {
483 entry_a
= hashmap_get_entry(&a
->map
, entry_b
, entry
, NULL
);
485 if (entry_a
->count
<= entry_b
->count
)
486 hashmap_remove(&a
->map
, &entry_b
->entry
, NULL
);
488 entry_a
->count
-= entry_b
->count
;
493 /* Calculate fingerprints for a series of lines.
494 * Puts the fingerprints in the fingerprints array, which must have been
495 * preallocated to allow storing line_count elements.
497 static void get_line_fingerprints(struct fingerprint
*fingerprints
,
498 const char *content
, const int *line_starts
,
499 long first_line
, long line_count
)
502 const char *linestart
, *lineend
;
504 line_starts
+= first_line
;
505 for (i
= 0; i
< line_count
; ++i
) {
506 linestart
= content
+ line_starts
[i
];
507 lineend
= content
+ line_starts
[i
+ 1];
508 get_fingerprint(fingerprints
+ i
, linestart
, lineend
);
512 static void free_line_fingerprints(struct fingerprint
*fingerprints
,
517 for (i
= 0; i
< nr_fingerprints
; i
++)
518 free_fingerprint(&fingerprints
[i
]);
521 /* This contains the data necessary to linearly map a line number in one half
522 * of a diff chunk to the line in the other half of the diff chunk that is
523 * closest in terms of its position as a fraction of the length of the chunk.
525 struct line_number_mapping
{
526 int destination_start
, destination_length
,
527 source_start
, source_length
;
530 /* Given a line number in one range, offset and scale it to map it onto the
532 * Essentially this mapping is a simple linear equation but the calculation is
533 * more complicated to allow performing it with integer operations.
534 * Another complication is that if a line could map onto many lines in the
535 * destination range then we want to choose the line at the center of those
537 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
538 * first 5 lines in B will map onto the first line in the A chunk, while the
539 * last 5 lines will all map onto the second line in the A chunk.
540 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
541 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
543 static int map_line_number(int line_number
,
544 const struct line_number_mapping
*mapping
)
546 return ((line_number
- mapping
->source_start
) * 2 + 1) *
547 mapping
->destination_length
/
548 (mapping
->source_length
* 2) +
549 mapping
->destination_start
;
552 /* Get a pointer to the element storing the similarity between a line in A
555 * The similarities are stored in a 2-dimensional array. Each "row" in the
556 * array contains the similarities for a line in B. The similarities stored in
557 * a row are the similarities between the line in B and the nearby lines in A.
558 * To keep the length of each row the same, it is padded out with values of -1
559 * where the search range extends beyond the lines in A.
560 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
567 * Then the similarity array will contain:
568 * [-1, -1, am, bm, cm,
569 * -1, an, bn, cn, dn,
570 * ao, bo, co, do, eo,
571 * bp, cp, dp, ep, -1,
572 * cq, dq, eq, -1, -1]
573 * Where similarities are denoted either by -1 for invalid, or the
574 * concatenation of the two lines in the diff being compared.
576 * \param similarities array of similarities between lines in A and B
577 * \param line_a the index of the line in A, in the same frame of reference as
579 * \param local_line_b the index of the line in B, relative to the first line
580 * in B that similarities represents.
581 * \param closest_line_a the index of the line in A that is deemed to be
582 * closest to local_line_b. This must be in the same
583 * frame of reference as line_a. This value defines
584 * where similarities is centered for the line in B.
585 * \param max_search_distance_a maximum distance in lines from the closest line
586 * in A for other lines in A for which
587 * similarities may be calculated.
589 static int *get_similarity(int *similarities
,
590 int line_a
, int local_line_b
,
591 int closest_line_a
, int max_search_distance_a
)
593 assert(abs(line_a
- closest_line_a
) <=
594 max_search_distance_a
);
595 return similarities
+ line_a
- closest_line_a
+
596 max_search_distance_a
+
597 local_line_b
* (max_search_distance_a
* 2 + 1);
600 #define CERTAIN_NOTHING_MATCHES -2
601 #define CERTAINTY_NOT_CALCULATED -1
603 /* Given a line in B, first calculate its similarities with nearby lines in A
604 * if not already calculated, then identify the most similar and second most
605 * similar lines. The "certainty" is calculated based on those two
608 * \param start_a the index of the first line of the chunk in A
609 * \param length_a the length in lines of the chunk in A
610 * \param local_line_b the index of the line in B, relative to the first line
612 * \param fingerprints_a array of fingerprints for the chunk in A
613 * \param fingerprints_b array of fingerprints for the chunk in B
614 * \param similarities 2-dimensional array of similarities between lines in A
615 * and B. See get_similarity() for more details.
616 * \param certainties array of values indicating how strongly a line in B is
617 * matched with some line in A.
618 * \param second_best_result array of absolute indices in A for the second
619 * closest match of a line in B.
620 * \param result array of absolute indices in A for the closest match of a line
622 * \param max_search_distance_a maximum distance in lines from the closest line
623 * in A for other lines in A for which
624 * similarities may be calculated.
625 * \param map_line_number_in_b_to_a parameter to map_line_number().
627 static void find_best_line_matches(
632 struct fingerprint
*fingerprints_a
,
633 struct fingerprint
*fingerprints_b
,
636 int *second_best_result
,
638 const int max_search_distance_a
,
639 const struct line_number_mapping
*map_line_number_in_b_to_a
)
642 int i
, search_start
, search_end
, closest_local_line_a
, *similarity
,
643 best_similarity
= 0, second_best_similarity
= 0,
644 best_similarity_index
= 0, second_best_similarity_index
= 0;
646 /* certainty has already been calculated so no need to redo the work */
647 if (certainties
[local_line_b
] != CERTAINTY_NOT_CALCULATED
)
650 closest_local_line_a
= map_line_number(
651 local_line_b
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
653 search_start
= closest_local_line_a
- max_search_distance_a
;
654 if (search_start
< 0)
657 search_end
= closest_local_line_a
+ max_search_distance_a
+ 1;
658 if (search_end
> length_a
)
659 search_end
= length_a
;
661 for (i
= search_start
; i
< search_end
; ++i
) {
662 similarity
= get_similarity(similarities
,
664 closest_local_line_a
,
665 max_search_distance_a
);
666 if (*similarity
== -1) {
667 /* This value will never exceed 10 but assert just in
670 assert(abs(i
- closest_local_line_a
) < 1000);
671 /* scale the similarity by (1000 - distance from
672 * closest line) to act as a tie break between lines
673 * that otherwise are equally similar.
675 *similarity
= fingerprint_similarity(
676 fingerprints_b
+ local_line_b
,
677 fingerprints_a
+ i
) *
678 (1000 - abs(i
- closest_local_line_a
));
680 if (*similarity
> best_similarity
) {
681 second_best_similarity
= best_similarity
;
682 second_best_similarity_index
= best_similarity_index
;
683 best_similarity
= *similarity
;
684 best_similarity_index
= i
;
685 } else if (*similarity
> second_best_similarity
) {
686 second_best_similarity
= *similarity
;
687 second_best_similarity_index
= i
;
691 if (best_similarity
== 0) {
692 /* this line definitely doesn't match with anything. Mark it
693 * with this special value so it doesn't get invalidated and
694 * won't be recalculated.
696 certainties
[local_line_b
] = CERTAIN_NOTHING_MATCHES
;
697 result
[local_line_b
] = -1;
699 /* Calculate the certainty with which this line matches.
700 * If the line matches well with two lines then that reduces
701 * the certainty. However we still want to prioritise matching
702 * a line that matches very well with two lines over matching a
703 * line that matches poorly with one line, hence doubling
705 * This means that if we have
706 * line X that matches only one line with a score of 3,
707 * line Y that matches two lines equally with a score of 5,
708 * and line Z that matches only one line with a score or 2,
709 * then the lines in order of certainty are X, Y, Z.
711 certainties
[local_line_b
] = best_similarity
* 2 -
712 second_best_similarity
;
714 /* We keep both the best and second best results to allow us to
715 * check at a later stage of the matching process whether the
716 * result needs to be invalidated.
718 result
[local_line_b
] = start_a
+ best_similarity_index
;
719 second_best_result
[local_line_b
] =
720 start_a
+ second_best_similarity_index
;
725 * This finds the line that we can match with the most confidence, and
726 * uses it as a partition. It then calls itself on the lines on either side of
727 * that partition. In this way we avoid lines appearing out of order, and
728 * retain a sensible line ordering.
729 * \param start_a index of the first line in A with which lines in B may be
731 * \param start_b index of the first line in B for which matching should be
733 * \param length_a number of lines in A with which lines in B may be compared.
734 * \param length_b number of lines in B for which matching should be done.
735 * \param fingerprints_a mutable array of fingerprints in A. The first element
736 * corresponds to the line at start_a.
737 * \param fingerprints_b array of fingerprints in B. The first element
738 * corresponds to the line at start_b.
739 * \param similarities 2-dimensional array of similarities between lines in A
740 * and B. See get_similarity() for more details.
741 * \param certainties array of values indicating how strongly a line in B is
742 * matched with some line in A.
743 * \param second_best_result array of absolute indices in A for the second
744 * closest match of a line in B.
745 * \param result array of absolute indices in A for the closest match of a line
747 * \param max_search_distance_a maximum distance in lines from the closest line
748 * in A for other lines in A for which
749 * similarities may be calculated.
750 * \param max_search_distance_b an upper bound on the greatest possible
751 * distance between lines in B such that they will
752 * both be compared with the same line in A
753 * according to max_search_distance_a.
754 * \param map_line_number_in_b_to_a parameter to map_line_number().
756 static void fuzzy_find_matching_lines_recurse(
757 int start_a
, int start_b
,
758 int length_a
, int length_b
,
759 struct fingerprint
*fingerprints_a
,
760 struct fingerprint
*fingerprints_b
,
763 int *second_best_result
,
765 int max_search_distance_a
,
766 int max_search_distance_b
,
767 const struct line_number_mapping
*map_line_number_in_b_to_a
)
769 int i
, invalidate_min
, invalidate_max
, offset_b
,
770 second_half_start_a
, second_half_start_b
,
771 second_half_length_a
, second_half_length_b
,
772 most_certain_line_a
, most_certain_local_line_b
= -1,
773 most_certain_line_certainty
= -1,
774 closest_local_line_a
;
776 for (i
= 0; i
< length_b
; ++i
) {
777 find_best_line_matches(start_a
,
787 max_search_distance_a
,
788 map_line_number_in_b_to_a
);
790 if (certainties
[i
] > most_certain_line_certainty
) {
791 most_certain_line_certainty
= certainties
[i
];
792 most_certain_local_line_b
= i
;
797 if (most_certain_local_line_b
== -1)
800 most_certain_line_a
= result
[most_certain_local_line_b
];
803 * Subtract the most certain line's fingerprint in B from the matched
804 * fingerprint in A. This means that other lines in B can't also match
805 * the same parts of the line in A.
807 fingerprint_subtract(fingerprints_a
+ most_certain_line_a
- start_a
,
808 fingerprints_b
+ most_certain_local_line_b
);
810 /* Invalidate results that may be affected by the choice of most
813 invalidate_min
= most_certain_local_line_b
- max_search_distance_b
;
814 invalidate_max
= most_certain_local_line_b
+ max_search_distance_b
+ 1;
815 if (invalidate_min
< 0)
817 if (invalidate_max
> length_b
)
818 invalidate_max
= length_b
;
820 /* As the fingerprint in A has changed, discard previously calculated
821 * similarity values with that fingerprint.
823 for (i
= invalidate_min
; i
< invalidate_max
; ++i
) {
824 closest_local_line_a
= map_line_number(
825 i
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
827 /* Check that the lines in A and B are close enough that there
828 * is a similarity value for them.
830 if (abs(most_certain_line_a
- start_a
- closest_local_line_a
) >
831 max_search_distance_a
) {
835 *get_similarity(similarities
, most_certain_line_a
- start_a
,
836 i
, closest_local_line_a
,
837 max_search_distance_a
) = -1;
840 /* More invalidating of results that may be affected by the choice of
842 * Discard the matches for lines in B that are currently matched with a
843 * line in A such that their ordering contradicts the ordering imposed
844 * by the choice of most certain line.
846 for (i
= most_certain_local_line_b
- 1; i
>= invalidate_min
; --i
) {
847 /* In this loop we discard results for lines in B that are
848 * before most-certain-line-B but are matched with a line in A
849 * that is after most-certain-line-A.
851 if (certainties
[i
] >= 0 &&
852 (result
[i
] >= most_certain_line_a
||
853 second_best_result
[i
] >= most_certain_line_a
)) {
854 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
857 for (i
= most_certain_local_line_b
+ 1; i
< invalidate_max
; ++i
) {
858 /* In this loop we discard results for lines in B that are
859 * after most-certain-line-B but are matched with a line in A
860 * that is before most-certain-line-A.
862 if (certainties
[i
] >= 0 &&
863 (result
[i
] <= most_certain_line_a
||
864 second_best_result
[i
] <= most_certain_line_a
)) {
865 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
869 /* Repeat the matching process for lines before the most certain line.
871 if (most_certain_local_line_b
> 0) {
872 fuzzy_find_matching_lines_recurse(
874 most_certain_line_a
+ 1 - start_a
,
875 most_certain_local_line_b
,
876 fingerprints_a
, fingerprints_b
, similarities
,
877 certainties
, second_best_result
, result
,
878 max_search_distance_a
,
879 max_search_distance_b
,
880 map_line_number_in_b_to_a
);
882 /* Repeat the matching process for lines after the most certain line.
884 if (most_certain_local_line_b
+ 1 < length_b
) {
885 second_half_start_a
= most_certain_line_a
;
886 offset_b
= most_certain_local_line_b
+ 1;
887 second_half_start_b
= start_b
+ offset_b
;
888 second_half_length_a
=
889 length_a
+ start_a
- second_half_start_a
;
890 second_half_length_b
=
891 length_b
+ start_b
- second_half_start_b
;
892 fuzzy_find_matching_lines_recurse(
893 second_half_start_a
, second_half_start_b
,
894 second_half_length_a
, second_half_length_b
,
895 fingerprints_a
+ second_half_start_a
- start_a
,
896 fingerprints_b
+ offset_b
,
898 offset_b
* (max_search_distance_a
* 2 + 1),
899 certainties
+ offset_b
,
900 second_best_result
+ offset_b
, result
+ offset_b
,
901 max_search_distance_a
,
902 max_search_distance_b
,
903 map_line_number_in_b_to_a
);
907 /* Find the lines in the parent line range that most closely match the lines in
908 * the target line range. This is accomplished by matching fingerprints in each
909 * blame_origin, and choosing the best matches that preserve the line ordering.
910 * See struct fingerprint for details of fingerprint matching, and
911 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
913 * The performance is believed to be O(n log n) in the typical case and O(n^2)
914 * in a pathological case, where n is the number of lines in the target range.
916 static int *fuzzy_find_matching_lines(struct blame_origin
*parent
,
917 struct blame_origin
*target
,
918 int tlno
, int parent_slno
, int same
,
921 /* We use the terminology "A" for the left hand side of the diff AKA
922 * parent, and "B" for the right hand side of the diff AKA target. */
923 int start_a
= parent_slno
;
924 int length_a
= parent_len
;
926 int length_b
= same
- tlno
;
928 struct line_number_mapping map_line_number_in_b_to_a
= {
929 start_a
, length_a
, start_b
, length_b
932 struct fingerprint
*fingerprints_a
= parent
->fingerprints
;
933 struct fingerprint
*fingerprints_b
= target
->fingerprints
;
935 int i
, *result
, *second_best_result
,
936 *certainties
, *similarities
, similarity_count
;
939 * max_search_distance_a means that given a line in B, compare it to
940 * the line in A that is closest to its position, and the lines in A
941 * that are no greater than max_search_distance_a lines away from the
944 * max_search_distance_b is an upper bound on the greatest possible
945 * distance between lines in B such that they will both be compared
946 * with the same line in A according to max_search_distance_a.
948 int max_search_distance_a
= 10, max_search_distance_b
;
953 if (max_search_distance_a
>= length_a
)
954 max_search_distance_a
= length_a
? length_a
- 1 : 0;
956 max_search_distance_b
= ((2 * max_search_distance_a
+ 1) * length_b
959 CALLOC_ARRAY(result
, length_b
);
960 CALLOC_ARRAY(second_best_result
, length_b
);
961 CALLOC_ARRAY(certainties
, length_b
);
963 /* See get_similarity() for details of similarities. */
964 similarity_count
= length_b
* (max_search_distance_a
* 2 + 1);
965 CALLOC_ARRAY(similarities
, similarity_count
);
967 for (i
= 0; i
< length_b
; ++i
) {
969 second_best_result
[i
] = -1;
970 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
973 for (i
= 0; i
< similarity_count
; ++i
)
974 similarities
[i
] = -1;
976 fuzzy_find_matching_lines_recurse(start_a
, start_b
,
978 fingerprints_a
+ start_a
,
979 fingerprints_b
+ start_b
,
984 max_search_distance_a
,
985 max_search_distance_b
,
986 &map_line_number_in_b_to_a
);
990 free(second_best_result
);
995 static void fill_origin_fingerprints(struct blame_origin
*o
)
1001 o
->num_lines
= find_line_starts(&line_starts
, o
->file
.ptr
,
1003 CALLOC_ARRAY(o
->fingerprints
, o
->num_lines
);
1004 get_line_fingerprints(o
->fingerprints
, o
->file
.ptr
, line_starts
,
1009 static void drop_origin_fingerprints(struct blame_origin
*o
)
1011 if (o
->fingerprints
) {
1012 free_line_fingerprints(o
->fingerprints
, o
->num_lines
);
1014 FREE_AND_NULL(o
->fingerprints
);
1019 * Given an origin, prepare mmfile_t structure to be used by the
1022 static void fill_origin_blob(struct diff_options
*opt
,
1023 struct blame_origin
*o
, mmfile_t
*file
,
1024 int *num_read_blob
, int fill_fingerprints
)
1027 enum object_type type
;
1028 unsigned long file_size
;
1031 if (opt
->flags
.allow_textconv
&&
1032 textconv_object(opt
->repo
, o
->path
, o
->mode
,
1033 &o
->blob_oid
, 1, &file
->ptr
, &file_size
))
1036 file
->ptr
= repo_read_object_file(the_repository
,
1037 &o
->blob_oid
, &type
,
1039 file
->size
= file_size
;
1042 die("Cannot read blob %s for path %s",
1043 oid_to_hex(&o
->blob_oid
),
1049 if (fill_fingerprints
)
1050 fill_origin_fingerprints(o
);
1053 static void drop_origin_blob(struct blame_origin
*o
)
1055 FREE_AND_NULL(o
->file
.ptr
);
1056 drop_origin_fingerprints(o
);
1060 * Any merge of blames happens on lists of blames that arrived via
1061 * different parents in a single suspect. In this case, we want to
1062 * sort according to the suspect line numbers as opposed to the final
1063 * image line numbers. The function body is somewhat longish because
1064 * it avoids unnecessary writes.
1067 static struct blame_entry
*blame_merge(struct blame_entry
*list1
,
1068 struct blame_entry
*list2
)
1070 struct blame_entry
*p1
= list1
, *p2
= list2
,
1078 if (p1
->s_lno
<= p2
->s_lno
) {
1081 if (!(p1
= *tail
)) {
1085 } while (p1
->s_lno
<= p2
->s_lno
);
1091 if (!(p2
= *tail
)) {
1095 } while (p1
->s_lno
> p2
->s_lno
);
1099 if (!(p1
= *tail
)) {
1103 } while (p1
->s_lno
<= p2
->s_lno
);
1107 DEFINE_LIST_SORT(static, sort_blame_entries
, struct blame_entry
, next
);
1110 * Final image line numbers are all different, so we don't need a
1111 * three-way comparison here.
1114 static int compare_blame_final(const struct blame_entry
*e1
,
1115 const struct blame_entry
*e2
)
1117 return e1
->lno
> e2
->lno
? 1 : -1;
1120 static int compare_blame_suspect(const struct blame_entry
*s1
,
1121 const struct blame_entry
*s2
)
1124 * to allow for collating suspects, we sort according to the
1125 * respective pointer value as the primary sorting criterion.
1126 * The actual relation is pretty unimportant as long as it
1127 * establishes a total order. Comparing as integers gives us
1130 if (s1
->suspect
!= s2
->suspect
)
1131 return (intptr_t)s1
->suspect
> (intptr_t)s2
->suspect
? 1 : -1;
1132 if (s1
->s_lno
== s2
->s_lno
)
1134 return s1
->s_lno
> s2
->s_lno
? 1 : -1;
1137 void blame_sort_final(struct blame_scoreboard
*sb
)
1139 sort_blame_entries(&sb
->ent
, compare_blame_final
);
1142 static int compare_commits_by_reverse_commit_date(const void *a
,
1146 return -compare_commits_by_commit_date(a
, b
, c
);
1150 * For debugging -- origin is refcounted, and this asserts that
1151 * we do not underflow.
1153 static void sanity_check_refcnt(struct blame_scoreboard
*sb
)
1156 struct blame_entry
*ent
;
1158 for (ent
= sb
->ent
; ent
; ent
= ent
->next
) {
1159 /* Nobody should have zero or negative refcnt */
1160 if (ent
->suspect
->refcnt
<= 0) {
1161 fprintf(stderr
, "%s in %s has negative refcnt %d\n",
1163 oid_to_hex(&ent
->suspect
->commit
->object
.oid
),
1164 ent
->suspect
->refcnt
);
1169 sb
->on_sanity_fail(sb
, baa
);
1173 * If two blame entries that are next to each other came from
1174 * contiguous lines in the same origin (i.e. <commit, path> pair),
1175 * merge them together.
1177 void blame_coalesce(struct blame_scoreboard
*sb
)
1179 struct blame_entry
*ent
, *next
;
1181 for (ent
= sb
->ent
; ent
&& (next
= ent
->next
); ent
= next
) {
1182 if (ent
->suspect
== next
->suspect
&&
1183 ent
->s_lno
+ ent
->num_lines
== next
->s_lno
&&
1184 ent
->lno
+ ent
->num_lines
== next
->lno
&&
1185 ent
->ignored
== next
->ignored
&&
1186 ent
->unblamable
== next
->unblamable
) {
1187 ent
->num_lines
+= next
->num_lines
;
1188 ent
->next
= next
->next
;
1189 blame_origin_decref(next
->suspect
);
1192 next
= ent
; /* again */
1196 if (sb
->debug
) /* sanity */
1197 sanity_check_refcnt(sb
);
1201 * Merge the given sorted list of blames into a preexisting origin.
1202 * If there were no previous blames to that commit, it is entered into
1203 * the commit priority queue of the score board.
1206 static void queue_blames(struct blame_scoreboard
*sb
, struct blame_origin
*porigin
,
1207 struct blame_entry
*sorted
)
1209 if (porigin
->suspects
)
1210 porigin
->suspects
= blame_merge(porigin
->suspects
, sorted
);
1212 struct blame_origin
*o
;
1213 for (o
= get_blame_suspects(porigin
->commit
); o
; o
= o
->next
) {
1215 porigin
->suspects
= sorted
;
1219 porigin
->suspects
= sorted
;
1220 prio_queue_put(&sb
->commits
, porigin
->commit
);
1225 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1226 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1227 * for an origin is also used to pass the blame for the entire file to
1228 * the parent to detect the case where a child's blob is identical to
1229 * that of its parent's.
1231 * This also fills origin->mode for corresponding tree path.
1233 static int fill_blob_sha1_and_mode(struct repository
*r
,
1234 struct blame_origin
*origin
)
1236 if (!is_null_oid(&origin
->blob_oid
))
1238 if (get_tree_entry(r
, &origin
->commit
->object
.oid
, origin
->path
, &origin
->blob_oid
, &origin
->mode
))
1240 if (oid_object_info(r
, &origin
->blob_oid
, NULL
) != OBJ_BLOB
)
1244 oidclr(&origin
->blob_oid
);
1245 origin
->mode
= S_IFINVALID
;
1249 struct blame_bloom_data
{
1251 * Changed-path Bloom filter keys. These can help prevent
1252 * computing diffs against first parents, but we need to
1253 * expand the list as code is moved or files are renamed.
1255 struct bloom_filter_settings
*settings
;
1256 struct bloom_key
**keys
;
1261 static int bloom_count_queries
= 0;
1262 static int bloom_count_no
= 0;
1263 static int maybe_changed_path(struct repository
*r
,
1264 struct blame_origin
*origin
,
1265 struct blame_bloom_data
*bd
)
1268 struct bloom_filter
*filter
;
1273 if (commit_graph_generation(origin
->commit
) == GENERATION_NUMBER_INFINITY
)
1276 filter
= get_bloom_filter(r
, origin
->commit
);
1281 bloom_count_queries
++;
1282 for (i
= 0; i
< bd
->nr
; i
++) {
1283 if (bloom_filter_contains(filter
,
1293 static void add_bloom_key(struct blame_bloom_data
*bd
,
1299 if (bd
->nr
>= bd
->alloc
) {
1301 REALLOC_ARRAY(bd
->keys
, bd
->alloc
);
1304 bd
->keys
[bd
->nr
] = xmalloc(sizeof(struct bloom_key
));
1305 fill_bloom_key(path
, strlen(path
), bd
->keys
[bd
->nr
], bd
->settings
);
1310 * We have an origin -- check if the same path exists in the
1311 * parent and return an origin structure to represent it.
1313 static struct blame_origin
*find_origin(struct repository
*r
,
1314 struct commit
*parent
,
1315 struct blame_origin
*origin
,
1316 struct blame_bloom_data
*bd
)
1318 struct blame_origin
*porigin
;
1319 struct diff_options diff_opts
;
1320 const char *paths
[2];
1322 /* First check any existing origins */
1323 for (porigin
= get_blame_suspects(parent
); porigin
; porigin
= porigin
->next
)
1324 if (!strcmp(porigin
->path
, origin
->path
)) {
1326 * The same path between origin and its parent
1327 * without renaming -- the most common case.
1329 return blame_origin_incref (porigin
);
1332 /* See if the origin->path is different between parent
1333 * and origin first. Most of the time they are the
1334 * same and diff-tree is fairly efficient about this.
1336 repo_diff_setup(r
, &diff_opts
);
1337 diff_opts
.flags
.recursive
= 1;
1338 diff_opts
.detect_rename
= 0;
1339 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1340 paths
[0] = origin
->path
;
1343 parse_pathspec(&diff_opts
.pathspec
,
1344 PATHSPEC_ALL_MAGIC
& ~PATHSPEC_LITERAL
,
1345 PATHSPEC_LITERAL_PATH
, "", paths
);
1346 diff_setup_done(&diff_opts
);
1348 if (is_null_oid(&origin
->commit
->object
.oid
))
1349 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1351 int compute_diff
= 1;
1352 if (origin
->commit
->parents
&&
1353 oideq(&parent
->object
.oid
,
1354 &origin
->commit
->parents
->item
->object
.oid
))
1355 compute_diff
= maybe_changed_path(r
, origin
, bd
);
1358 diff_tree_oid(get_commit_tree_oid(parent
),
1359 get_commit_tree_oid(origin
->commit
),
1362 diffcore_std(&diff_opts
);
1364 if (!diff_queued_diff
.nr
) {
1365 /* The path is the same as parent */
1366 porigin
= get_origin(parent
, origin
->path
);
1367 oidcpy(&porigin
->blob_oid
, &origin
->blob_oid
);
1368 porigin
->mode
= origin
->mode
;
1371 * Since origin->path is a pathspec, if the parent
1372 * commit had it as a directory, we will see a whole
1373 * bunch of deletion of files in the directory that we
1374 * do not care about.
1377 struct diff_filepair
*p
= NULL
;
1378 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1380 p
= diff_queued_diff
.queue
[i
];
1381 name
= p
->one
->path
? p
->one
->path
: p
->two
->path
;
1382 if (!strcmp(name
, origin
->path
))
1386 die("internal error in blame::find_origin");
1387 switch (p
->status
) {
1389 die("internal error in blame::find_origin (%c)",
1392 porigin
= get_origin(parent
, origin
->path
);
1393 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1394 porigin
->mode
= p
->one
->mode
;
1398 /* Did not exist in parent, or type changed */
1402 diff_flush(&diff_opts
);
1407 * We have an origin -- find the path that corresponds to it in its
1408 * parent and return an origin structure to represent it.
1410 static struct blame_origin
*find_rename(struct repository
*r
,
1411 struct commit
*parent
,
1412 struct blame_origin
*origin
,
1413 struct blame_bloom_data
*bd
)
1415 struct blame_origin
*porigin
= NULL
;
1416 struct diff_options diff_opts
;
1419 repo_diff_setup(r
, &diff_opts
);
1420 diff_opts
.flags
.recursive
= 1;
1421 diff_opts
.detect_rename
= DIFF_DETECT_RENAME
;
1422 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1423 diff_opts
.single_follow
= origin
->path
;
1424 diff_setup_done(&diff_opts
);
1426 if (is_null_oid(&origin
->commit
->object
.oid
))
1427 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1429 diff_tree_oid(get_commit_tree_oid(parent
),
1430 get_commit_tree_oid(origin
->commit
),
1432 diffcore_std(&diff_opts
);
1434 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1435 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
1436 if ((p
->status
== 'R' || p
->status
== 'C') &&
1437 !strcmp(p
->two
->path
, origin
->path
)) {
1438 add_bloom_key(bd
, p
->one
->path
);
1439 porigin
= get_origin(parent
, p
->one
->path
);
1440 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1441 porigin
->mode
= p
->one
->mode
;
1445 diff_flush(&diff_opts
);
1450 * Append a new blame entry to a given output queue.
1452 static void add_blame_entry(struct blame_entry
***queue
,
1453 const struct blame_entry
*src
)
1455 struct blame_entry
*e
= xmalloc(sizeof(*e
));
1456 memcpy(e
, src
, sizeof(*e
));
1457 blame_origin_incref(e
->suspect
);
1465 * src typically is on-stack; we want to copy the information in it to
1466 * a malloced blame_entry that gets added to the given queue. The
1467 * origin of dst loses a refcnt.
1469 static void dup_entry(struct blame_entry
***queue
,
1470 struct blame_entry
*dst
, struct blame_entry
*src
)
1472 blame_origin_incref(src
->suspect
);
1473 blame_origin_decref(dst
->suspect
);
1474 memcpy(dst
, src
, sizeof(*src
));
1475 dst
->next
= **queue
;
1477 *queue
= &dst
->next
;
1480 const char *blame_nth_line(struct blame_scoreboard
*sb
, long lno
)
1482 return sb
->final_buf
+ sb
->lineno
[lno
];
1486 * It is known that lines between tlno to same came from parent, and e
1487 * has an overlap with that range. it also is known that parent's
1488 * line plno corresponds to e's line tlno.
1494 * <------------------>
1496 * Split e into potentially three parts; before this chunk, the chunk
1497 * to be blamed for the parent, and after that portion.
1499 static void split_overlap(struct blame_entry
*split
,
1500 struct blame_entry
*e
,
1501 int tlno
, int plno
, int same
,
1502 struct blame_origin
*parent
)
1506 memset(split
, 0, sizeof(struct blame_entry
[3]));
1508 for (i
= 0; i
< 3; i
++) {
1509 split
[i
].ignored
= e
->ignored
;
1510 split
[i
].unblamable
= e
->unblamable
;
1513 if (e
->s_lno
< tlno
) {
1514 /* there is a pre-chunk part not blamed on parent */
1515 split
[0].suspect
= blame_origin_incref(e
->suspect
);
1516 split
[0].lno
= e
->lno
;
1517 split
[0].s_lno
= e
->s_lno
;
1518 split
[0].num_lines
= tlno
- e
->s_lno
;
1519 split
[1].lno
= e
->lno
+ tlno
- e
->s_lno
;
1520 split
[1].s_lno
= plno
;
1523 split
[1].lno
= e
->lno
;
1524 split
[1].s_lno
= plno
+ (e
->s_lno
- tlno
);
1527 if (same
< e
->s_lno
+ e
->num_lines
) {
1528 /* there is a post-chunk part not blamed on parent */
1529 split
[2].suspect
= blame_origin_incref(e
->suspect
);
1530 split
[2].lno
= e
->lno
+ (same
- e
->s_lno
);
1531 split
[2].s_lno
= e
->s_lno
+ (same
- e
->s_lno
);
1532 split
[2].num_lines
= e
->s_lno
+ e
->num_lines
- same
;
1533 chunk_end_lno
= split
[2].lno
;
1536 chunk_end_lno
= e
->lno
+ e
->num_lines
;
1537 split
[1].num_lines
= chunk_end_lno
- split
[1].lno
;
1540 * if it turns out there is nothing to blame the parent for,
1541 * forget about the splitting. !split[1].suspect signals this.
1543 if (split
[1].num_lines
< 1)
1545 split
[1].suspect
= blame_origin_incref(parent
);
1549 * split_overlap() divided an existing blame e into up to three parts
1550 * in split. Any assigned blame is moved to queue to
1551 * reflect the split.
1553 static void split_blame(struct blame_entry
***blamed
,
1554 struct blame_entry
***unblamed
,
1555 struct blame_entry
*split
,
1556 struct blame_entry
*e
)
1558 if (split
[0].suspect
&& split
[2].suspect
) {
1559 /* The first part (reuse storage for the existing entry e) */
1560 dup_entry(unblamed
, e
, &split
[0]);
1562 /* The last part -- me */
1563 add_blame_entry(unblamed
, &split
[2]);
1565 /* ... and the middle part -- parent */
1566 add_blame_entry(blamed
, &split
[1]);
1568 else if (!split
[0].suspect
&& !split
[2].suspect
)
1570 * The parent covers the entire area; reuse storage for
1571 * e and replace it with the parent.
1573 dup_entry(blamed
, e
, &split
[1]);
1574 else if (split
[0].suspect
) {
1575 /* me and then parent */
1576 dup_entry(unblamed
, e
, &split
[0]);
1577 add_blame_entry(blamed
, &split
[1]);
1580 /* parent and then me */
1581 dup_entry(blamed
, e
, &split
[1]);
1582 add_blame_entry(unblamed
, &split
[2]);
1587 * After splitting the blame, the origins used by the
1588 * on-stack blame_entry should lose one refcnt each.
1590 static void decref_split(struct blame_entry
*split
)
1594 for (i
= 0; i
< 3; i
++)
1595 blame_origin_decref(split
[i
].suspect
);
1599 * reverse_blame reverses the list given in head, appending tail.
1600 * That allows us to build lists in reverse order, then reverse them
1601 * afterwards. This can be faster than building the list in proper
1602 * order right away. The reason is that building in proper order
1603 * requires writing a link in the _previous_ element, while building
1604 * in reverse order just requires placing the list head into the
1605 * _current_ element.
1608 static struct blame_entry
*reverse_blame(struct blame_entry
*head
,
1609 struct blame_entry
*tail
)
1612 struct blame_entry
*next
= head
->next
;
1621 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1622 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1623 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1624 * e->num_lines). The caller needs to sort out the reference counting for the
1625 * new entry's suspect.
1627 static struct blame_entry
*split_blame_at(struct blame_entry
*e
, int len
,
1628 struct blame_origin
*new_suspect
)
1630 struct blame_entry
*n
= xcalloc(1, sizeof(struct blame_entry
));
1632 n
->suspect
= new_suspect
;
1633 n
->ignored
= e
->ignored
;
1634 n
->unblamable
= e
->unblamable
;
1635 n
->lno
= e
->lno
+ len
;
1636 n
->s_lno
= e
->s_lno
+ len
;
1637 n
->num_lines
= e
->num_lines
- len
;
1643 struct blame_line_tracker
{
1648 static int are_lines_adjacent(struct blame_line_tracker
*first
,
1649 struct blame_line_tracker
*second
)
1651 return first
->is_parent
== second
->is_parent
&&
1652 first
->s_lno
+ 1 == second
->s_lno
;
1655 static int scan_parent_range(struct fingerprint
*p_fps
,
1656 struct fingerprint
*t_fps
, int t_idx
,
1657 int from
, int nr_lines
)
1660 #define FINGERPRINT_FILE_THRESHOLD 10
1661 int best_sim_val
= FINGERPRINT_FILE_THRESHOLD
;
1662 int best_sim_idx
= -1;
1664 for (p_idx
= from
; p_idx
< from
+ nr_lines
; p_idx
++) {
1665 sim
= fingerprint_similarity(&t_fps
[t_idx
], &p_fps
[p_idx
]);
1666 if (sim
< best_sim_val
)
1668 /* Break ties with the closest-to-target line number */
1669 if (sim
== best_sim_val
&& best_sim_idx
!= -1 &&
1670 abs(best_sim_idx
- t_idx
) < abs(p_idx
- t_idx
))
1673 best_sim_idx
= p_idx
;
1675 return best_sim_idx
;
1679 * The first pass checks the blame entry (from the target) against the parent's
1680 * diff chunk. If that fails for a line, the second pass tries to match that
1681 * line to any part of parent file. That catches cases where a change was
1682 * broken into two chunks by 'context.'
1684 static void guess_line_blames(struct blame_origin
*parent
,
1685 struct blame_origin
*target
,
1686 int tlno
, int offset
, int same
, int parent_len
,
1687 struct blame_line_tracker
*line_blames
)
1689 int i
, best_idx
, target_idx
;
1690 int parent_slno
= tlno
+ offset
;
1693 fuzzy_matches
= fuzzy_find_matching_lines(parent
, target
,
1694 tlno
, parent_slno
, same
,
1696 for (i
= 0; i
< same
- tlno
; i
++) {
1697 target_idx
= tlno
+ i
;
1698 if (fuzzy_matches
&& fuzzy_matches
[i
] >= 0) {
1699 best_idx
= fuzzy_matches
[i
];
1701 best_idx
= scan_parent_range(parent
->fingerprints
,
1702 target
->fingerprints
,
1706 if (best_idx
>= 0) {
1707 line_blames
[i
].is_parent
= 1;
1708 line_blames
[i
].s_lno
= best_idx
;
1710 line_blames
[i
].is_parent
= 0;
1711 line_blames
[i
].s_lno
= target_idx
;
1714 free(fuzzy_matches
);
1718 * This decides which parts of a blame entry go to the parent (added to the
1719 * ignoredp list) and which stay with the target (added to the diffp list). The
1720 * actual decision was made in a separate heuristic function, and those answers
1721 * for the lines in 'e' are in line_blames. This consumes e, essentially
1722 * putting it on a list.
1724 * Note that the blame entries on the ignoredp list are not necessarily sorted
1725 * with respect to the parent's line numbers yet.
1727 static void ignore_blame_entry(struct blame_entry
*e
,
1728 struct blame_origin
*parent
,
1729 struct blame_entry
**diffp
,
1730 struct blame_entry
**ignoredp
,
1731 struct blame_line_tracker
*line_blames
)
1733 int entry_len
, nr_lines
, i
;
1736 * We carve new entries off the front of e. Each entry comes from a
1737 * contiguous chunk of lines: adjacent lines from the same origin
1738 * (either the parent or the target).
1741 nr_lines
= e
->num_lines
; /* e changes in the loop */
1742 for (i
= 0; i
< nr_lines
; i
++) {
1743 struct blame_entry
*next
= NULL
;
1746 * We are often adjacent to the next line - only split the blame
1747 * entry when we have to.
1749 if (i
+ 1 < nr_lines
) {
1750 if (are_lines_adjacent(&line_blames
[i
],
1751 &line_blames
[i
+ 1])) {
1755 next
= split_blame_at(e
, entry_len
,
1756 blame_origin_incref(e
->suspect
));
1758 if (line_blames
[i
].is_parent
) {
1760 blame_origin_decref(e
->suspect
);
1761 e
->suspect
= blame_origin_incref(parent
);
1762 e
->s_lno
= line_blames
[i
- entry_len
+ 1].s_lno
;
1763 e
->next
= *ignoredp
;
1767 /* e->s_lno is already in the target's address space. */
1771 assert(e
->num_lines
== entry_len
);
1779 * Process one hunk from the patch between the current suspect for
1780 * blame_entry e and its parent. This first blames any unfinished
1781 * entries before the chunk (which is where target and parent start
1782 * differing) on the parent, and then splits blame entries at the
1783 * start and at the end of the difference region. Since use of -M and
1784 * -C options may lead to overlapping/duplicate source line number
1785 * ranges, all we can rely on from sorting/merging is the order of the
1786 * first suspect line number.
1788 * tlno: line number in the target where this chunk begins
1789 * same: line number in the target where this chunk ends
1790 * offset: add to tlno to get the chunk starting point in the parent
1791 * parent_len: number of lines in the parent chunk
1793 static void blame_chunk(struct blame_entry
***dstq
, struct blame_entry
***srcq
,
1794 int tlno
, int offset
, int same
, int parent_len
,
1795 struct blame_origin
*parent
,
1796 struct blame_origin
*target
, int ignore_diffs
)
1798 struct blame_entry
*e
= **srcq
;
1799 struct blame_entry
*samep
= NULL
, *diffp
= NULL
, *ignoredp
= NULL
;
1800 struct blame_line_tracker
*line_blames
= NULL
;
1802 while (e
&& e
->s_lno
< tlno
) {
1803 struct blame_entry
*next
= e
->next
;
1805 * current record starts before differing portion. If
1806 * it reaches into it, we need to split it up and
1807 * examine the second part separately.
1809 if (e
->s_lno
+ e
->num_lines
> tlno
) {
1810 /* Move second half to a new record */
1811 struct blame_entry
*n
;
1813 n
= split_blame_at(e
, tlno
- e
->s_lno
, e
->suspect
);
1814 /* Push new record to diffp */
1818 blame_origin_decref(e
->suspect
);
1819 /* Pass blame for everything before the differing
1820 * chunk to the parent */
1821 e
->suspect
= blame_origin_incref(parent
);
1828 * As we don't know how much of a common stretch after this
1829 * diff will occur, the currently blamed parts are all that we
1830 * can assign to the parent for now.
1834 **dstq
= reverse_blame(samep
, **dstq
);
1835 *dstq
= &samep
->next
;
1838 * Prepend the split off portions: everything after e starts
1839 * after the blameable portion.
1841 e
= reverse_blame(diffp
, e
);
1844 * Now retain records on the target while parts are different
1850 if (ignore_diffs
&& same
- tlno
> 0) {
1851 CALLOC_ARRAY(line_blames
, same
- tlno
);
1852 guess_line_blames(parent
, target
, tlno
, offset
, same
,
1853 parent_len
, line_blames
);
1856 while (e
&& e
->s_lno
< same
) {
1857 struct blame_entry
*next
= e
->next
;
1860 * If current record extends into sameness, need to split.
1862 if (e
->s_lno
+ e
->num_lines
> same
) {
1864 * Move second half to a new record to be
1865 * processed by later chunks
1867 struct blame_entry
*n
;
1869 n
= split_blame_at(e
, same
- e
->s_lno
,
1870 blame_origin_incref(e
->suspect
));
1871 /* Push new record to samep */
1876 ignore_blame_entry(e
, parent
, &diffp
, &ignoredp
,
1877 line_blames
+ e
->s_lno
- tlno
);
1887 * Note ignoredp is not sorted yet, and thus neither is dstq.
1888 * That list must be sorted before we queue_blames(). We defer
1889 * sorting until after all diff hunks are processed, so that
1890 * guess_line_blames() can pick *any* line in the parent. The
1891 * slight drawback is that we end up sorting all blame entries
1892 * passed to the parent, including those that are unrelated to
1893 * changes made by the ignored commit.
1895 **dstq
= reverse_blame(ignoredp
, **dstq
);
1896 *dstq
= &ignoredp
->next
;
1898 **srcq
= reverse_blame(diffp
, reverse_blame(samep
, e
));
1899 /* Move across elements that are in the unblamable portion */
1901 *srcq
= &diffp
->next
;
1904 struct blame_chunk_cb_data
{
1905 struct blame_origin
*parent
;
1906 struct blame_origin
*target
;
1909 struct blame_entry
**dstq
;
1910 struct blame_entry
**srcq
;
1913 /* diff chunks are from parent to target */
1914 static int blame_chunk_cb(long start_a
, long count_a
,
1915 long start_b
, long count_b
, void *data
)
1917 struct blame_chunk_cb_data
*d
= data
;
1918 if (start_a
- start_b
!= d
->offset
)
1919 die("internal error in blame::blame_chunk_cb");
1920 blame_chunk(&d
->dstq
, &d
->srcq
, start_b
, start_a
- start_b
,
1921 start_b
+ count_b
, count_a
, d
->parent
, d
->target
,
1923 d
->offset
= start_a
+ count_a
- (start_b
+ count_b
);
1928 * We are looking at the origin 'target' and aiming to pass blame
1929 * for the lines it is suspected to its parent. Run diff to find
1930 * which lines came from parent and pass blame for them.
1932 static void pass_blame_to_parent(struct blame_scoreboard
*sb
,
1933 struct blame_origin
*target
,
1934 struct blame_origin
*parent
, int ignore_diffs
)
1936 mmfile_t file_p
, file_o
;
1937 struct blame_chunk_cb_data d
;
1938 struct blame_entry
*newdest
= NULL
;
1940 if (!target
->suspects
)
1941 return; /* nothing remains for this target */
1946 d
.ignore_diffs
= ignore_diffs
;
1947 d
.dstq
= &newdest
; d
.srcq
= &target
->suspects
;
1949 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
1950 &sb
->num_read_blob
, ignore_diffs
);
1951 fill_origin_blob(&sb
->revs
->diffopt
, target
, &file_o
,
1952 &sb
->num_read_blob
, ignore_diffs
);
1953 sb
->num_get_patch
++;
1955 if (diff_hunks(&file_p
, &file_o
, blame_chunk_cb
, &d
, sb
->xdl_opts
))
1956 die("unable to generate diff (%s -> %s)",
1957 oid_to_hex(&parent
->commit
->object
.oid
),
1958 oid_to_hex(&target
->commit
->object
.oid
));
1959 /* The rest are the same as the parent */
1960 blame_chunk(&d
.dstq
, &d
.srcq
, INT_MAX
, d
.offset
, INT_MAX
, 0,
1964 sort_blame_entries(&newdest
, compare_blame_suspect
);
1965 queue_blames(sb
, parent
, newdest
);
1971 * The lines in blame_entry after splitting blames many times can become
1972 * very small and trivial, and at some point it becomes pointless to
1973 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1974 * ordinary C program, and it is not worth to say it was copied from
1975 * totally unrelated file in the parent.
1977 * Compute how trivial the lines in the blame_entry are.
1979 unsigned blame_entry_score(struct blame_scoreboard
*sb
, struct blame_entry
*e
)
1982 const char *cp
, *ep
;
1988 cp
= blame_nth_line(sb
, e
->lno
);
1989 ep
= blame_nth_line(sb
, e
->lno
+ e
->num_lines
);
1991 unsigned ch
= *((unsigned char *)cp
);
2001 * best_so_far[] and potential[] are both a split of an existing blame_entry
2002 * that passes blame to the parent. Maintain best_so_far the best split so
2003 * far, by comparing potential and best_so_far and copying potential into
2004 * bst_so_far as needed.
2006 static void copy_split_if_better(struct blame_scoreboard
*sb
,
2007 struct blame_entry
*best_so_far
,
2008 struct blame_entry
*potential
)
2012 if (!potential
[1].suspect
)
2014 if (best_so_far
[1].suspect
) {
2015 if (blame_entry_score(sb
, &potential
[1]) <
2016 blame_entry_score(sb
, &best_so_far
[1]))
2020 for (i
= 0; i
< 3; i
++)
2021 blame_origin_incref(potential
[i
].suspect
);
2022 decref_split(best_so_far
);
2023 memcpy(best_so_far
, potential
, sizeof(struct blame_entry
[3]));
2027 * We are looking at a part of the final image represented by
2028 * ent (tlno and same are offset by ent->s_lno).
2029 * tlno is where we are looking at in the final image.
2030 * up to (but not including) same match preimage.
2031 * plno is where we are looking at in the preimage.
2033 * <-------------- final image ---------------------->
2036 * <---------preimage----->
2039 * All line numbers are 0-based.
2041 static void handle_split(struct blame_scoreboard
*sb
,
2042 struct blame_entry
*ent
,
2043 int tlno
, int plno
, int same
,
2044 struct blame_origin
*parent
,
2045 struct blame_entry
*split
)
2047 if (ent
->num_lines
<= tlno
)
2050 struct blame_entry potential
[3];
2053 split_overlap(potential
, ent
, tlno
, plno
, same
, parent
);
2054 copy_split_if_better(sb
, split
, potential
);
2055 decref_split(potential
);
2059 struct handle_split_cb_data
{
2060 struct blame_scoreboard
*sb
;
2061 struct blame_entry
*ent
;
2062 struct blame_origin
*parent
;
2063 struct blame_entry
*split
;
2068 static int handle_split_cb(long start_a
, long count_a
,
2069 long start_b
, long count_b
, void *data
)
2071 struct handle_split_cb_data
*d
= data
;
2072 handle_split(d
->sb
, d
->ent
, d
->tlno
, d
->plno
, start_b
, d
->parent
,
2074 d
->plno
= start_a
+ count_a
;
2075 d
->tlno
= start_b
+ count_b
;
2080 * Find the lines from parent that are the same as ent so that
2081 * we can pass blames to it. file_p has the blob contents for
2084 static void find_copy_in_blob(struct blame_scoreboard
*sb
,
2085 struct blame_entry
*ent
,
2086 struct blame_origin
*parent
,
2087 struct blame_entry
*split
,
2092 struct handle_split_cb_data d
;
2094 memset(&d
, 0, sizeof(d
));
2095 d
.sb
= sb
; d
.ent
= ent
; d
.parent
= parent
; d
.split
= split
;
2097 * Prepare mmfile that contains only the lines in ent.
2099 cp
= blame_nth_line(sb
, ent
->lno
);
2100 file_o
.ptr
= (char *) cp
;
2101 file_o
.size
= blame_nth_line(sb
, ent
->lno
+ ent
->num_lines
) - cp
;
2104 * file_o is a part of final image we are annotating.
2105 * file_p partially may match that image.
2107 memset(split
, 0, sizeof(struct blame_entry
[3]));
2108 if (diff_hunks(file_p
, &file_o
, handle_split_cb
, &d
, sb
->xdl_opts
))
2109 die("unable to generate diff (%s)",
2110 oid_to_hex(&parent
->commit
->object
.oid
));
2111 /* remainder, if any, all match the preimage */
2112 handle_split(sb
, ent
, d
.tlno
, d
.plno
, ent
->num_lines
, parent
, split
);
2115 /* Move all blame entries from list *source that have a score smaller
2116 * than score_min to the front of list *small.
2117 * Returns a pointer to the link pointing to the old head of the small list.
2120 static struct blame_entry
**filter_small(struct blame_scoreboard
*sb
,
2121 struct blame_entry
**small
,
2122 struct blame_entry
**source
,
2125 struct blame_entry
*p
= *source
;
2126 struct blame_entry
*oldsmall
= *small
;
2128 if (blame_entry_score(sb
, p
) <= score_min
) {
2144 * See if lines currently target is suspected for can be attributed to
2147 static void find_move_in_parent(struct blame_scoreboard
*sb
,
2148 struct blame_entry
***blamed
,
2149 struct blame_entry
**toosmall
,
2150 struct blame_origin
*target
,
2151 struct blame_origin
*parent
)
2153 struct blame_entry
*e
, split
[3];
2154 struct blame_entry
*unblamed
= target
->suspects
;
2155 struct blame_entry
*leftover
= NULL
;
2159 return; /* nothing remains for this target */
2161 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
2162 &sb
->num_read_blob
, 0);
2166 /* At each iteration, unblamed has a NULL-terminated list of
2167 * entries that have not yet been tested for blame. leftover
2168 * contains the reversed list of entries that have been tested
2169 * without being assignable to the parent.
2172 struct blame_entry
**unblamedtail
= &unblamed
;
2173 struct blame_entry
*next
;
2174 for (e
= unblamed
; e
; e
= next
) {
2176 find_copy_in_blob(sb
, e
, parent
, split
, &file_p
);
2177 if (split
[1].suspect
&&
2178 sb
->move_score
< blame_entry_score(sb
, &split
[1])) {
2179 split_blame(blamed
, &unblamedtail
, split
, e
);
2184 decref_split(split
);
2186 *unblamedtail
= NULL
;
2187 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->move_score
);
2189 target
->suspects
= reverse_blame(leftover
, NULL
);
2193 struct blame_entry
*ent
;
2194 struct blame_entry split
[3];
2198 * Count the number of entries the target is suspected for,
2199 * and prepare a list of entry and the best split.
2201 static struct blame_list
*setup_blame_list(struct blame_entry
*unblamed
,
2204 struct blame_entry
*e
;
2206 struct blame_list
*blame_list
= NULL
;
2208 for (e
= unblamed
, num_ents
= 0; e
; e
= e
->next
)
2211 CALLOC_ARRAY(blame_list
, num_ents
);
2212 for (e
= unblamed
, i
= 0; e
; e
= e
->next
)
2213 blame_list
[i
++].ent
= e
;
2215 *num_ents_p
= num_ents
;
2220 * For lines target is suspected for, see if we can find code movement
2221 * across file boundary from the parent commit. porigin is the path
2222 * in the parent we already tried.
2224 static void find_copy_in_parent(struct blame_scoreboard
*sb
,
2225 struct blame_entry
***blamed
,
2226 struct blame_entry
**toosmall
,
2227 struct blame_origin
*target
,
2228 struct commit
*parent
,
2229 struct blame_origin
*porigin
,
2232 struct diff_options diff_opts
;
2234 struct blame_list
*blame_list
;
2236 struct blame_entry
*unblamed
= target
->suspects
;
2237 struct blame_entry
*leftover
= NULL
;
2240 return; /* nothing remains for this target */
2242 repo_diff_setup(sb
->repo
, &diff_opts
);
2243 diff_opts
.flags
.recursive
= 1;
2244 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
2246 diff_setup_done(&diff_opts
);
2248 /* Try "find copies harder" on new path if requested;
2249 * we do not want to use diffcore_rename() actually to
2250 * match things up; find_copies_harder is set only to
2251 * force diff_tree_oid() to feed all filepairs to diff_queue,
2252 * and this code needs to be after diff_setup_done(), which
2253 * usually makes find-copies-harder imply copy detection.
2255 if ((opt
& PICKAXE_BLAME_COPY_HARDEST
)
2256 || ((opt
& PICKAXE_BLAME_COPY_HARDER
)
2257 && (!porigin
|| strcmp(target
->path
, porigin
->path
))))
2258 diff_opts
.flags
.find_copies_harder
= 1;
2260 if (is_null_oid(&target
->commit
->object
.oid
))
2261 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
2263 diff_tree_oid(get_commit_tree_oid(parent
),
2264 get_commit_tree_oid(target
->commit
),
2267 if (!diff_opts
.flags
.find_copies_harder
)
2268 diffcore_std(&diff_opts
);
2271 struct blame_entry
**unblamedtail
= &unblamed
;
2272 blame_list
= setup_blame_list(unblamed
, &num_ents
);
2274 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
2275 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
2276 struct blame_origin
*norigin
;
2278 struct blame_entry potential
[3];
2280 if (!DIFF_FILE_VALID(p
->one
))
2281 continue; /* does not exist in parent */
2282 if (S_ISGITLINK(p
->one
->mode
))
2283 continue; /* ignore git links */
2284 if (porigin
&& !strcmp(p
->one
->path
, porigin
->path
))
2285 /* find_move already dealt with this path */
2288 norigin
= get_origin(parent
, p
->one
->path
);
2289 oidcpy(&norigin
->blob_oid
, &p
->one
->oid
);
2290 norigin
->mode
= p
->one
->mode
;
2291 fill_origin_blob(&sb
->revs
->diffopt
, norigin
, &file_p
,
2292 &sb
->num_read_blob
, 0);
2296 for (j
= 0; j
< num_ents
; j
++) {
2297 find_copy_in_blob(sb
, blame_list
[j
].ent
,
2298 norigin
, potential
, &file_p
);
2299 copy_split_if_better(sb
, blame_list
[j
].split
,
2301 decref_split(potential
);
2303 blame_origin_decref(norigin
);
2306 for (j
= 0; j
< num_ents
; j
++) {
2307 struct blame_entry
*split
= blame_list
[j
].split
;
2308 if (split
[1].suspect
&&
2309 sb
->copy_score
< blame_entry_score(sb
, &split
[1])) {
2310 split_blame(blamed
, &unblamedtail
, split
,
2313 blame_list
[j
].ent
->next
= leftover
;
2314 leftover
= blame_list
[j
].ent
;
2316 decref_split(split
);
2319 *unblamedtail
= NULL
;
2320 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->copy_score
);
2322 target
->suspects
= reverse_blame(leftover
, NULL
);
2323 diff_flush(&diff_opts
);
2327 * The blobs of origin and porigin exactly match, so everything
2328 * origin is suspected for can be blamed on the parent.
2330 static void pass_whole_blame(struct blame_scoreboard
*sb
,
2331 struct blame_origin
*origin
, struct blame_origin
*porigin
)
2333 struct blame_entry
*e
, *suspects
;
2335 if (!porigin
->file
.ptr
&& origin
->file
.ptr
) {
2336 /* Steal its file */
2337 porigin
->file
= origin
->file
;
2338 origin
->file
.ptr
= NULL
;
2340 suspects
= origin
->suspects
;
2341 origin
->suspects
= NULL
;
2342 for (e
= suspects
; e
; e
= e
->next
) {
2343 blame_origin_incref(porigin
);
2344 blame_origin_decref(e
->suspect
);
2345 e
->suspect
= porigin
;
2347 queue_blames(sb
, porigin
, suspects
);
2351 * We pass blame from the current commit to its parents. We keep saying
2352 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2353 * exonerate ourselves.
2355 static struct commit_list
*first_scapegoat(struct rev_info
*revs
, struct commit
*commit
,
2359 if (revs
->first_parent_only
&&
2361 commit
->parents
->next
) {
2362 free_commit_list(commit
->parents
->next
);
2363 commit
->parents
->next
= NULL
;
2365 return commit
->parents
;
2367 return lookup_decoration(&revs
->children
, &commit
->object
);
2370 static int num_scapegoats(struct rev_info
*revs
, struct commit
*commit
, int reverse
)
2372 struct commit_list
*l
= first_scapegoat(revs
, commit
, reverse
);
2373 return commit_list_count(l
);
2376 /* Distribute collected unsorted blames to the respected sorted lists
2377 * in the various origins.
2379 static void distribute_blame(struct blame_scoreboard
*sb
, struct blame_entry
*blamed
)
2381 sort_blame_entries(&blamed
, compare_blame_suspect
);
2384 struct blame_origin
*porigin
= blamed
->suspect
;
2385 struct blame_entry
*suspects
= NULL
;
2387 struct blame_entry
*next
= blamed
->next
;
2388 blamed
->next
= suspects
;
2391 } while (blamed
&& blamed
->suspect
== porigin
);
2392 suspects
= reverse_blame(suspects
, NULL
);
2393 queue_blames(sb
, porigin
, suspects
);
2399 typedef struct blame_origin
*(*blame_find_alg
)(struct repository
*,
2401 struct blame_origin
*,
2402 struct blame_bloom_data
*);
2404 static void pass_blame(struct blame_scoreboard
*sb
, struct blame_origin
*origin
, int opt
)
2406 struct rev_info
*revs
= sb
->revs
;
2407 int i
, pass
, num_sg
;
2408 struct commit
*commit
= origin
->commit
;
2409 struct commit_list
*sg
;
2410 struct blame_origin
*sg_buf
[MAXSG
];
2411 struct blame_origin
*porigin
, **sg_origin
= sg_buf
;
2412 struct blame_entry
*toosmall
= NULL
;
2413 struct blame_entry
*blames
, **blametail
= &blames
;
2415 num_sg
= num_scapegoats(revs
, commit
, sb
->reverse
);
2418 else if (num_sg
< ARRAY_SIZE(sg_buf
))
2419 memset(sg_buf
, 0, sizeof(sg_buf
));
2421 CALLOC_ARRAY(sg_origin
, num_sg
);
2424 * The first pass looks for unrenamed path to optimize for
2425 * common cases, then we look for renames in the second pass.
2427 for (pass
= 0; pass
< 2 - sb
->no_whole_file_rename
; pass
++) {
2428 blame_find_alg find
= pass
? find_rename
: find_origin
;
2430 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2432 sg
= sg
->next
, i
++) {
2433 struct commit
*p
= sg
->item
;
2438 if (repo_parse_commit(the_repository
, p
))
2440 porigin
= find(sb
->repo
, p
, origin
, sb
->bloom_data
);
2443 if (oideq(&porigin
->blob_oid
, &origin
->blob_oid
)) {
2444 pass_whole_blame(sb
, origin
, porigin
);
2445 blame_origin_decref(porigin
);
2448 for (j
= same
= 0; j
< i
; j
++)
2450 oideq(&sg_origin
[j
]->blob_oid
, &porigin
->blob_oid
)) {
2455 sg_origin
[i
] = porigin
;
2457 blame_origin_decref(porigin
);
2462 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2464 sg
= sg
->next
, i
++) {
2465 struct blame_origin
*porigin
= sg_origin
[i
];
2468 if (!origin
->previous
) {
2469 blame_origin_incref(porigin
);
2470 origin
->previous
= porigin
;
2472 pass_blame_to_parent(sb
, origin
, porigin
, 0);
2473 if (!origin
->suspects
)
2478 * Pass remaining suspects for ignored commits to their parents.
2480 if (oidset_contains(&sb
->ignore_list
, &commit
->object
.oid
)) {
2481 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2483 sg
= sg
->next
, i
++) {
2484 struct blame_origin
*porigin
= sg_origin
[i
];
2488 pass_blame_to_parent(sb
, origin
, porigin
, 1);
2490 * Preemptively drop porigin so we can refresh the
2491 * fingerprints if we use the parent again, which can
2492 * occur if you ignore back-to-back commits.
2494 drop_origin_blob(porigin
);
2495 if (!origin
->suspects
)
2501 * Optionally find moves in parents' files.
2503 if (opt
& PICKAXE_BLAME_MOVE
) {
2504 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->move_score
);
2505 if (origin
->suspects
) {
2506 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2508 sg
= sg
->next
, i
++) {
2509 struct blame_origin
*porigin
= sg_origin
[i
];
2512 find_move_in_parent(sb
, &blametail
, &toosmall
, origin
, porigin
);
2513 if (!origin
->suspects
)
2520 * Optionally find copies from parents' files.
2522 if (opt
& PICKAXE_BLAME_COPY
) {
2523 if (sb
->copy_score
> sb
->move_score
)
2524 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2525 else if (sb
->copy_score
< sb
->move_score
) {
2526 origin
->suspects
= blame_merge(origin
->suspects
, toosmall
);
2528 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2530 if (!origin
->suspects
)
2533 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2535 sg
= sg
->next
, i
++) {
2536 struct blame_origin
*porigin
= sg_origin
[i
];
2537 find_copy_in_parent(sb
, &blametail
, &toosmall
,
2538 origin
, sg
->item
, porigin
, opt
);
2539 if (!origin
->suspects
)
2546 distribute_blame(sb
, blames
);
2548 * prepend toosmall to origin->suspects
2550 * There is no point in sorting: this ends up on a big
2551 * unsorted list in the caller anyway.
2554 struct blame_entry
**tail
= &toosmall
;
2556 tail
= &(*tail
)->next
;
2557 *tail
= origin
->suspects
;
2558 origin
->suspects
= toosmall
;
2560 for (i
= 0; i
< num_sg
; i
++) {
2562 if (!sg_origin
[i
]->suspects
)
2563 drop_origin_blob(sg_origin
[i
]);
2564 blame_origin_decref(sg_origin
[i
]);
2567 drop_origin_blob(origin
);
2568 if (sg_buf
!= sg_origin
)
2573 * The main loop -- while we have blobs with lines whose true origin
2574 * is still unknown, pick one blob, and allow its lines to pass blames
2575 * to its parents. */
2576 void assign_blame(struct blame_scoreboard
*sb
, int opt
)
2578 struct rev_info
*revs
= sb
->revs
;
2579 struct commit
*commit
= prio_queue_get(&sb
->commits
);
2582 struct blame_entry
*ent
;
2583 struct blame_origin
*suspect
= get_blame_suspects(commit
);
2585 /* find one suspect to break down */
2586 while (suspect
&& !suspect
->suspects
)
2587 suspect
= suspect
->next
;
2590 commit
= prio_queue_get(&sb
->commits
);
2594 assert(commit
== suspect
->commit
);
2597 * We will use this suspect later in the loop,
2598 * so hold onto it in the meantime.
2600 blame_origin_incref(suspect
);
2601 repo_parse_commit(the_repository
, commit
);
2603 (!(commit
->object
.flags
& UNINTERESTING
) &&
2604 !(revs
->max_age
!= -1 && commit
->date
< revs
->max_age
)))
2605 pass_blame(sb
, suspect
, opt
);
2607 commit
->object
.flags
|= UNINTERESTING
;
2608 if (commit
->object
.parsed
)
2609 mark_parents_uninteresting(sb
->revs
, commit
);
2611 /* treat root commit as boundary */
2612 if (!commit
->parents
&& !sb
->show_root
)
2613 commit
->object
.flags
|= UNINTERESTING
;
2615 /* Take responsibility for the remaining entries */
2616 ent
= suspect
->suspects
;
2618 suspect
->guilty
= 1;
2620 struct blame_entry
*next
= ent
->next
;
2621 if (sb
->found_guilty_entry
)
2622 sb
->found_guilty_entry(ent
, sb
->found_guilty_entry_data
);
2627 ent
->next
= sb
->ent
;
2628 sb
->ent
= suspect
->suspects
;
2629 suspect
->suspects
= NULL
;
2633 blame_origin_decref(suspect
);
2635 if (sb
->debug
) /* sanity */
2636 sanity_check_refcnt(sb
);
2641 * To allow quick access to the contents of nth line in the
2642 * final image, prepare an index in the scoreboard.
2644 static int prepare_lines(struct blame_scoreboard
*sb
)
2646 sb
->num_lines
= find_line_starts(&sb
->lineno
, sb
->final_buf
,
2647 sb
->final_buf_size
);
2648 return sb
->num_lines
;
2651 static struct commit
*find_single_final(struct rev_info
*revs
,
2652 const char **name_p
)
2655 struct commit
*found
= NULL
;
2656 const char *name
= NULL
;
2658 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2659 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2660 if (obj
->flags
& UNINTERESTING
)
2662 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2663 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2664 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2666 die("More than one commit to dig from %s and %s?",
2667 revs
->pending
.objects
[i
].name
, name
);
2668 found
= (struct commit
*)obj
;
2669 name
= revs
->pending
.objects
[i
].name
;
2672 *name_p
= xstrdup_or_null(name
);
2676 static struct commit
*dwim_reverse_initial(struct rev_info
*revs
,
2677 const char **name_p
)
2680 * DWIM "git blame --reverse ONE -- PATH" as
2681 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2682 * when it makes sense.
2685 struct commit
*head_commit
;
2686 struct object_id head_oid
;
2688 if (revs
->pending
.nr
!= 1)
2691 /* Is that sole rev a committish? */
2692 obj
= revs
->pending
.objects
[0].item
;
2693 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2694 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2697 /* Do we have HEAD? */
2698 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
2700 head_commit
= lookup_commit_reference_gently(revs
->repo
,
2705 /* Turn "ONE" into "ONE..HEAD" then */
2706 obj
->flags
|= UNINTERESTING
;
2707 add_pending_object(revs
, &head_commit
->object
, "HEAD");
2710 *name_p
= revs
->pending
.objects
[0].name
;
2711 return (struct commit
*)obj
;
2714 static struct commit
*find_single_initial(struct rev_info
*revs
,
2715 const char **name_p
)
2718 struct commit
*found
= NULL
;
2719 const char *name
= NULL
;
2722 * There must be one and only one negative commit, and it must be
2725 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2726 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2727 if (!(obj
->flags
& UNINTERESTING
))
2729 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2730 if (!obj
|| obj
->type
!= OBJ_COMMIT
)
2731 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2733 die("More than one commit to dig up from, %s and %s?",
2734 revs
->pending
.objects
[i
].name
, name
);
2735 found
= (struct commit
*) obj
;
2736 name
= revs
->pending
.objects
[i
].name
;
2740 found
= dwim_reverse_initial(revs
, &name
);
2742 die("No commit to dig up from?");
2745 *name_p
= xstrdup(name
);
2749 void init_scoreboard(struct blame_scoreboard
*sb
)
2751 memset(sb
, 0, sizeof(struct blame_scoreboard
));
2752 sb
->move_score
= BLAME_DEFAULT_MOVE_SCORE
;
2753 sb
->copy_score
= BLAME_DEFAULT_COPY_SCORE
;
2756 void setup_scoreboard(struct blame_scoreboard
*sb
,
2757 struct blame_origin
**orig
)
2759 const char *final_commit_name
= NULL
;
2760 struct blame_origin
*o
;
2761 struct commit
*final_commit
= NULL
;
2762 enum object_type type
;
2764 init_blame_suspects(&blame_suspects
);
2766 if (sb
->reverse
&& sb
->contents_from
)
2767 die(_("--contents and --reverse do not blend well."));
2770 BUG("repo is NULL");
2773 sb
->final
= find_single_final(sb
->revs
, &final_commit_name
);
2774 sb
->commits
.compare
= compare_commits_by_commit_date
;
2776 sb
->final
= find_single_initial(sb
->revs
, &final_commit_name
);
2777 sb
->commits
.compare
= compare_commits_by_reverse_commit_date
;
2780 if (sb
->final
&& sb
->contents_from
)
2781 die(_("cannot use --contents with final commit object name"));
2783 if (sb
->reverse
&& sb
->revs
->first_parent_only
)
2784 sb
->revs
->children
.name
= NULL
;
2788 * "--not A B -- path" without anything positive;
2789 * do not default to HEAD, but use the working tree
2793 sb
->final
= fake_working_tree_commit(sb
->repo
,
2795 sb
->path
, sb
->contents_from
);
2796 add_pending_object(sb
->revs
, &(sb
->final
->object
), ":");
2799 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2800 final_commit
= find_single_final(sb
->revs
, NULL
);
2802 die(_("--reverse and --first-parent together require specified latest commit"));
2806 * If we have bottom, this will mark the ancestors of the
2807 * bottom commits we would reach while traversing as
2810 if (prepare_revision_walk(sb
->revs
))
2811 die(_("revision walk setup failed"));
2813 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2814 struct commit
*c
= final_commit
;
2816 sb
->revs
->children
.name
= "children";
2817 while (c
->parents
&&
2818 !oideq(&c
->object
.oid
, &sb
->final
->object
.oid
)) {
2819 struct commit_list
*l
= xcalloc(1, sizeof(*l
));
2822 if (add_decoration(&sb
->revs
->children
,
2823 &c
->parents
->item
->object
, l
))
2824 BUG("not unique item in first-parent chain");
2825 c
= c
->parents
->item
;
2828 if (!oideq(&c
->object
.oid
, &sb
->final
->object
.oid
))
2829 die(_("--reverse --first-parent together require range along first-parent chain"));
2832 if (is_null_oid(&sb
->final
->object
.oid
)) {
2833 o
= get_blame_suspects(sb
->final
);
2834 sb
->final_buf
= xmemdupz(o
->file
.ptr
, o
->file
.size
);
2835 sb
->final_buf_size
= o
->file
.size
;
2838 o
= get_origin(sb
->final
, sb
->path
);
2839 if (fill_blob_sha1_and_mode(sb
->repo
, o
))
2840 die(_("no such path %s in %s"), sb
->path
, final_commit_name
);
2842 if (sb
->revs
->diffopt
.flags
.allow_textconv
&&
2843 textconv_object(sb
->repo
, sb
->path
, o
->mode
, &o
->blob_oid
, 1, (char **) &sb
->final_buf
,
2844 &sb
->final_buf_size
))
2847 sb
->final_buf
= repo_read_object_file(the_repository
,
2850 &sb
->final_buf_size
);
2853 die(_("cannot read blob %s for path %s"),
2854 oid_to_hex(&o
->blob_oid
),
2857 sb
->num_read_blob
++;
2863 free((char *)final_commit_name
);
2868 struct blame_entry
*blame_entry_prepend(struct blame_entry
*head
,
2869 long start
, long end
,
2870 struct blame_origin
*o
)
2872 struct blame_entry
*new_head
= xcalloc(1, sizeof(struct blame_entry
));
2873 new_head
->lno
= start
;
2874 new_head
->num_lines
= end
- start
;
2875 new_head
->suspect
= o
;
2876 new_head
->s_lno
= start
;
2877 new_head
->next
= head
;
2878 blame_origin_incref(o
);
2882 void setup_blame_bloom_data(struct blame_scoreboard
*sb
)
2884 struct blame_bloom_data
*bd
;
2885 struct bloom_filter_settings
*bs
;
2887 if (!sb
->repo
->objects
->commit_graph
)
2890 bs
= get_bloom_filter_settings(sb
->repo
);
2894 bd
= xmalloc(sizeof(struct blame_bloom_data
));
2900 ALLOC_ARRAY(bd
->keys
, bd
->alloc
);
2902 add_bloom_key(bd
, sb
->path
);
2904 sb
->bloom_data
= bd
;
2907 void cleanup_scoreboard(struct blame_scoreboard
*sb
)
2909 if (sb
->bloom_data
) {
2911 for (i
= 0; i
< sb
->bloom_data
->nr
; i
++) {
2912 free(sb
->bloom_data
->keys
[i
]->hashes
);
2913 free(sb
->bloom_data
->keys
[i
]);
2915 free(sb
->bloom_data
->keys
);
2916 FREE_AND_NULL(sb
->bloom_data
);
2918 trace2_data_intmax("blame", sb
->repo
,
2919 "bloom/queries", bloom_count_queries
);
2920 trace2_data_intmax("blame", sb
->repo
,
2921 "bloom/response-no", bloom_count_no
);