3 #include "object-store.h"
4 #include "cache-tree.h"
11 #include "commit-slab.h"
13 define_commit_slab(blame_suspects
, struct blame_origin
*);
14 static struct blame_suspects blame_suspects
;
16 struct blame_origin
*get_blame_suspects(struct commit
*commit
)
18 struct blame_origin
**result
;
20 result
= blame_suspects_peek(&blame_suspects
, commit
);
22 return result
? *result
: NULL
;
25 static void set_blame_suspects(struct commit
*commit
, struct blame_origin
*origin
)
27 *blame_suspects_at(&blame_suspects
, commit
) = origin
;
30 void blame_origin_decref(struct blame_origin
*o
)
32 if (o
&& --o
->refcnt
<= 0) {
33 struct blame_origin
*p
, *l
= NULL
;
35 blame_origin_decref(o
->previous
);
37 /* Should be present exactly once in commit chain */
38 for (p
= get_blame_suspects(o
->commit
); p
; l
= p
, p
= p
->next
) {
43 set_blame_suspects(o
->commit
, p
->next
);
48 die("internal error in blame_origin_decref");
53 * Given a commit and a path in it, create a new origin structure.
54 * The callers that add blame to the scoreboard should use
55 * get_origin() to obtain shared, refcounted copy instead of calling
56 * this function directly.
58 static struct blame_origin
*make_origin(struct commit
*commit
, const char *path
)
60 struct blame_origin
*o
;
61 FLEX_ALLOC_STR(o
, path
, path
);
64 o
->next
= get_blame_suspects(commit
);
65 set_blame_suspects(commit
, o
);
70 * Locate an existing origin or create a new one.
71 * This moves the origin to front position in the commit util list.
73 static struct blame_origin
*get_origin(struct commit
*commit
, const char *path
)
75 struct blame_origin
*o
, *l
;
77 for (o
= get_blame_suspects(commit
), l
= NULL
; o
; l
= o
, o
= o
->next
) {
78 if (!strcmp(o
->path
, path
)) {
82 o
->next
= get_blame_suspects(commit
);
83 set_blame_suspects(commit
, o
);
85 return blame_origin_incref(o
);
88 return make_origin(commit
, path
);
93 static void verify_working_tree_path(struct repository
*r
,
94 struct commit
*work_tree
, const char *path
)
96 struct commit_list
*parents
;
99 for (parents
= work_tree
->parents
; parents
; parents
= parents
->next
) {
100 const struct object_id
*commit_oid
= &parents
->item
->object
.oid
;
101 struct object_id blob_oid
;
104 if (!get_tree_entry(commit_oid
, path
, &blob_oid
, &mode
) &&
105 oid_object_info(r
, &blob_oid
, NULL
) == OBJ_BLOB
)
109 pos
= index_name_pos(r
->index
, path
, strlen(path
));
111 ; /* path is in the index */
112 else if (-1 - pos
< r
->index
->cache_nr
&&
113 !strcmp(r
->index
->cache
[-1 - pos
]->name
, path
))
114 ; /* path is in the index, unmerged */
116 die("no such path '%s' in HEAD", path
);
119 static struct commit_list
**append_parent(struct repository
*r
,
120 struct commit_list
**tail
,
121 const struct object_id
*oid
)
123 struct commit
*parent
;
125 parent
= lookup_commit_reference(r
, oid
);
127 die("no such commit %s", oid_to_hex(oid
));
128 return &commit_list_insert(parent
, tail
)->next
;
131 static void append_merge_parents(struct repository
*r
,
132 struct commit_list
**tail
)
135 struct strbuf line
= STRBUF_INIT
;
137 merge_head
= open(git_path_merge_head(r
), O_RDONLY
);
138 if (merge_head
< 0) {
141 die("cannot open '%s' for reading",
142 git_path_merge_head(r
));
145 while (!strbuf_getwholeline_fd(&line
, merge_head
, '\n')) {
146 struct object_id oid
;
147 if (line
.len
< GIT_SHA1_HEXSZ
|| get_oid_hex(line
.buf
, &oid
))
148 die("unknown line in '%s': %s",
149 git_path_merge_head(r
), line
.buf
);
150 tail
= append_parent(r
, tail
, &oid
);
153 strbuf_release(&line
);
157 * This isn't as simple as passing sb->buf and sb->len, because we
158 * want to transfer ownership of the buffer to the commit (so we
161 static void set_commit_buffer_from_strbuf(struct repository
*r
,
166 void *buf
= strbuf_detach(sb
, &len
);
167 set_commit_buffer(r
, c
, buf
, len
);
171 * Prepare a dummy commit that represents the work tree (or staged) item.
172 * Note that annotating work tree item never works in the reverse.
174 static struct commit
*fake_working_tree_commit(struct repository
*r
,
175 struct diff_options
*opt
,
177 const char *contents_from
)
179 struct commit
*commit
;
180 struct blame_origin
*origin
;
181 struct commit_list
**parent_tail
, *parent
;
182 struct object_id head_oid
;
183 struct strbuf buf
= STRBUF_INIT
;
187 struct cache_entry
*ce
;
189 struct strbuf msg
= STRBUF_INIT
;
191 read_index(r
->index
);
193 commit
= alloc_commit_node(r
);
194 commit
->object
.parsed
= 1;
196 parent_tail
= &commit
->parents
;
198 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
199 die("no such ref: HEAD");
201 parent_tail
= append_parent(r
, parent_tail
, &head_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", NULL
, 0);
208 strbuf_addstr(&msg
, "tree 0000000000000000000000000000000000000000\n");
209 for (parent
= commit
->parents
; parent
; parent
= parent
->next
)
210 strbuf_addf(&msg
, "parent %s\n",
211 oid_to_hex(&parent
->item
->object
.oid
));
215 "Version of %s from %s\n",
217 (!contents_from
? path
:
218 (!strcmp(contents_from
, "-") ? "standard input" : contents_from
)));
219 set_commit_buffer_from_strbuf(r
, commit
, &msg
);
221 if (!contents_from
|| strcmp("-", contents_from
)) {
223 const char *read_from
;
225 unsigned long buf_len
;
228 if (stat(contents_from
, &st
) < 0)
229 die_errno("Cannot stat '%s'", contents_from
);
230 read_from
= contents_from
;
233 if (lstat(path
, &st
) < 0)
234 die_errno("Cannot lstat '%s'", path
);
237 mode
= canon_mode(st
.st_mode
);
239 switch (st
.st_mode
& S_IFMT
) {
241 if (opt
->flags
.allow_textconv
&&
242 textconv_object(r
, read_from
, mode
, &null_oid
, 0, &buf_ptr
, &buf_len
))
243 strbuf_attach(&buf
, buf_ptr
, buf_len
, buf_len
+ 1);
244 else if (strbuf_read_file(&buf
, read_from
, st
.st_size
) != st
.st_size
)
245 die_errno("cannot open or read '%s'", read_from
);
248 if (strbuf_readlink(&buf
, read_from
, st
.st_size
) < 0)
249 die_errno("cannot readlink '%s'", read_from
);
252 die("unsupported file type %s", read_from
);
256 /* Reading from stdin */
258 if (strbuf_read(&buf
, 0, 0) < 0)
259 die_errno("failed to read from stdin");
261 convert_to_git(r
->index
, path
, buf
.buf
, buf
.len
, &buf
, 0);
262 origin
->file
.ptr
= buf
.buf
;
263 origin
->file
.size
= buf
.len
;
264 pretend_object_file(buf
.buf
, buf
.len
, OBJ_BLOB
, &origin
->blob_oid
);
267 * Read the current index, replace the path entry with
268 * origin->blob_sha1 without mucking with its mode or type
269 * bits; we are not going to write this index out -- we just
270 * want to run "diff-index --cached".
272 discard_index(r
->index
);
273 read_index(r
->index
);
277 int pos
= index_name_pos(r
->index
, path
, len
);
279 mode
= r
->index
->cache
[pos
]->ce_mode
;
281 /* Let's not bother reading from HEAD tree */
282 mode
= S_IFREG
| 0644;
284 ce
= make_empty_cache_entry(r
->index
, len
);
285 oidcpy(&ce
->oid
, &origin
->blob_oid
);
286 memcpy(ce
->name
, path
, len
);
287 ce
->ce_flags
= create_ce_flags(0);
288 ce
->ce_namelen
= len
;
289 ce
->ce_mode
= create_ce_mode(mode
);
290 add_index_entry(r
->index
, ce
,
291 ADD_CACHE_OK_TO_ADD
| ADD_CACHE_OK_TO_REPLACE
);
293 cache_tree_invalidate_path(r
->index
, path
);
300 static int diff_hunks(mmfile_t
*file_a
, mmfile_t
*file_b
,
301 xdl_emit_hunk_consume_func_t hunk_func
, void *cb_data
, int xdl_opts
)
304 xdemitconf_t xecfg
= {0};
305 xdemitcb_t ecb
= {NULL
};
307 xpp
.flags
= xdl_opts
;
308 xecfg
.hunk_func
= hunk_func
;
310 return xdi_diff(file_a
, file_b
, &xpp
, &xecfg
, &ecb
);
313 static const char *get_next_line(const char *start
, const char *end
)
315 const char *nl
= memchr(start
, '\n', end
- start
);
317 return nl
? nl
+ 1 : end
;
320 static int find_line_starts(int **line_starts
, const char *buf
,
323 const char *end
= buf
+ len
;
328 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
331 ALLOC_ARRAY(*line_starts
, num
+ 1);
332 lineno
= *line_starts
;
334 for (p
= buf
; p
< end
; p
= get_next_line(p
, end
))
342 struct fingerprint_entry
;
344 /* A fingerprint is intended to loosely represent a string, such that two
345 * fingerprints can be quickly compared to give an indication of the similarity
346 * of the strings that they represent.
348 * A fingerprint is represented as a multiset of the lower-cased byte pairs in
349 * the string that it represents. Whitespace is added at each end of the
350 * string. Whitespace pairs are ignored. Whitespace is converted to '\0'.
351 * For example, the string "Darth Radar" will be converted to the following
353 * {"\0d", "da", "da", "ar", "ar", "rt", "th", "h\0", "\0r", "ra", "ad", "r\0"}
355 * The similarity between two fingerprints is the size of the intersection of
356 * their multisets, including repeated elements. See fingerprint_similarity for
359 * For ease of implementation, the fingerprint is implemented as a map
360 * of byte pairs to the count of that byte pair in the string, instead of
361 * allowing repeated elements in a set.
365 /* As we know the maximum number of entries in advance, it's
366 * convenient to store the entries in a single array instead of having
367 * the hashmap manage the memory.
369 struct fingerprint_entry
*entries
;
372 /* A byte pair in a fingerprint. Stores the number of times the byte pair
373 * occurs in the string that the fingerprint represents.
375 struct fingerprint_entry
{
376 /* The hashmap entry - the hash represents the byte pair in its
377 * entirety so we don't need to store the byte pair separately.
379 struct hashmap_entry entry
;
380 /* The number of times the byte pair occurs in the string that the
381 * fingerprint represents.
386 /* See `struct fingerprint` for an explanation of what a fingerprint is.
387 * \param result the fingerprint of the string is stored here. This must be
388 * freed later using free_fingerprint.
389 * \param line_begin the start of the string
390 * \param line_end the end of the string
392 static void get_fingerprint(struct fingerprint
*result
,
393 const char *line_begin
,
394 const char *line_end
)
396 unsigned int hash
, c0
= 0, c1
;
398 int max_map_entry_count
= 1 + line_end
- line_begin
;
399 struct fingerprint_entry
*entry
= xcalloc(max_map_entry_count
,
400 sizeof(struct fingerprint_entry
));
401 struct fingerprint_entry
*found_entry
;
403 hashmap_init(&result
->map
, NULL
, NULL
, max_map_entry_count
);
404 result
->entries
= entry
;
405 for (p
= line_begin
; p
<= line_end
; ++p
, c0
= c1
) {
406 /* Always terminate the string with whitespace.
407 * Normalise whitespace to 0, and normalise letters to
408 * lower case. This won't work for multibyte characters but at
409 * worst will match some unrelated characters.
411 if ((p
== line_end
) || isspace(*p
))
415 hash
= c0
| (c1
<< 8);
416 /* Ignore whitespace pairs */
419 hashmap_entry_init(entry
, hash
);
421 found_entry
= hashmap_get(&result
->map
, entry
, NULL
);
423 found_entry
->count
+= 1;
426 hashmap_add(&result
->map
, entry
);
432 static void free_fingerprint(struct fingerprint
*f
)
434 hashmap_free(&f
->map
, 0);
438 /* Calculates the similarity between two fingerprints as the size of the
439 * intersection of their multisets, including repeated elements. See
440 * `struct fingerprint` for an explanation of the fingerprint representation.
441 * The similarity between "cat mat" and "father rather" is 2 because "at" is
442 * present twice in both strings while the similarity between "tim" and "mit"
445 static int fingerprint_similarity(struct fingerprint
*a
, struct fingerprint
*b
)
447 int intersection
= 0;
448 struct hashmap_iter iter
;
449 const struct fingerprint_entry
*entry_a
, *entry_b
;
451 hashmap_iter_init(&b
->map
, &iter
);
453 while ((entry_b
= hashmap_iter_next(&iter
))) {
454 if ((entry_a
= hashmap_get(&a
->map
, entry_b
, NULL
))) {
455 intersection
+= entry_a
->count
< entry_b
->count
?
456 entry_a
->count
: entry_b
->count
;
462 /* Subtracts byte-pair elements in B from A, modifying A in place.
464 static void fingerprint_subtract(struct fingerprint
*a
, struct fingerprint
*b
)
466 struct hashmap_iter iter
;
467 struct fingerprint_entry
*entry_a
;
468 const struct fingerprint_entry
*entry_b
;
470 hashmap_iter_init(&b
->map
, &iter
);
472 while ((entry_b
= hashmap_iter_next(&iter
))) {
473 if ((entry_a
= hashmap_get(&a
->map
, entry_b
, NULL
))) {
474 if (entry_a
->count
<= entry_b
->count
)
475 hashmap_remove(&a
->map
, entry_b
, NULL
);
477 entry_a
->count
-= entry_b
->count
;
482 /* Calculate fingerprints for a series of lines.
483 * Puts the fingerprints in the fingerprints array, which must have been
484 * preallocated to allow storing line_count elements.
486 static void get_line_fingerprints(struct fingerprint
*fingerprints
,
487 const char *content
, const int *line_starts
,
488 long first_line
, long line_count
)
491 const char *linestart
, *lineend
;
493 line_starts
+= first_line
;
494 for (i
= 0; i
< line_count
; ++i
) {
495 linestart
= content
+ line_starts
[i
];
496 lineend
= content
+ line_starts
[i
+ 1];
497 get_fingerprint(fingerprints
+ i
, linestart
, lineend
);
501 static void free_line_fingerprints(struct fingerprint
*fingerprints
,
506 for (i
= 0; i
< nr_fingerprints
; i
++)
507 free_fingerprint(&fingerprints
[i
]);
510 /* This contains the data necessary to linearly map a line number in one half
511 * of a diff chunk to the line in the other half of the diff chunk that is
512 * closest in terms of its position as a fraction of the length of the chunk.
514 struct line_number_mapping
{
515 int destination_start
, destination_length
,
516 source_start
, source_length
;
519 /* Given a line number in one range, offset and scale it to map it onto the
521 * Essentially this mapping is a simple linear equation but the calculation is
522 * more complicated to allow performing it with integer operations.
523 * Another complication is that if a line could map onto many lines in the
524 * destination range then we want to choose the line at the center of those
526 * Example: if the chunk is 2 lines long in A and 10 lines long in B then the
527 * first 5 lines in B will map onto the first line in the A chunk, while the
528 * last 5 lines will all map onto the second line in the A chunk.
529 * Example: if the chunk is 10 lines long in A and 2 lines long in B then line
530 * 0 in B will map onto line 2 in A, and line 1 in B will map onto line 7 in A.
532 static int map_line_number(int line_number
,
533 const struct line_number_mapping
*mapping
)
535 return ((line_number
- mapping
->source_start
) * 2 + 1) *
536 mapping
->destination_length
/
537 (mapping
->source_length
* 2) +
538 mapping
->destination_start
;
541 /* Get a pointer to the element storing the similarity between a line in A
544 * The similarities are stored in a 2-dimensional array. Each "row" in the
545 * array contains the similarities for a line in B. The similarities stored in
546 * a row are the similarities between the line in B and the nearby lines in A.
547 * To keep the length of each row the same, it is padded out with values of -1
548 * where the search range extends beyond the lines in A.
549 * For example, if max_search_distance_a is 2 and the two sides of a diff chunk
556 * Then the similarity array will contain:
557 * [-1, -1, am, bm, cm,
558 * -1, an, bn, cn, dn,
559 * ao, bo, co, do, eo,
560 * bp, cp, dp, ep, -1,
561 * cq, dq, eq, -1, -1]
562 * Where similarities are denoted either by -1 for invalid, or the
563 * concatenation of the two lines in the diff being compared.
565 * \param similarities array of similarities between lines in A and B
566 * \param line_a the index of the line in A, in the same frame of reference as
568 * \param local_line_b the index of the line in B, relative to the first line
569 * in B that similarities represents.
570 * \param closest_line_a the index of the line in A that is deemed to be
571 * closest to local_line_b. This must be in the same
572 * frame of reference as line_a. This value defines
573 * where similarities is centered for the line in B.
574 * \param max_search_distance_a maximum distance in lines from the closest line
575 * in A for other lines in A for which
576 * similarities may be calculated.
578 static int *get_similarity(int *similarities
,
579 int line_a
, int local_line_b
,
580 int closest_line_a
, int max_search_distance_a
)
582 assert(abs(line_a
- closest_line_a
) <=
583 max_search_distance_a
);
584 return similarities
+ line_a
- closest_line_a
+
585 max_search_distance_a
+
586 local_line_b
* (max_search_distance_a
* 2 + 1);
589 #define CERTAIN_NOTHING_MATCHES -2
590 #define CERTAINTY_NOT_CALCULATED -1
592 /* Given a line in B, first calculate its similarities with nearby lines in A
593 * if not already calculated, then identify the most similar and second most
594 * similar lines. The "certainty" is calculated based on those two
597 * \param start_a the index of the first line of the chunk in A
598 * \param length_a the length in lines of the chunk in A
599 * \param local_line_b the index of the line in B, relative to the first line
601 * \param fingerprints_a array of fingerprints for the chunk in A
602 * \param fingerprints_b array of fingerprints for the chunk in B
603 * \param similarities 2-dimensional array of similarities between lines in A
604 * and B. See get_similarity() for more details.
605 * \param certainties array of values indicating how strongly a line in B is
606 * matched with some line in A.
607 * \param second_best_result array of absolute indices in A for the second
608 * closest match of a line in B.
609 * \param result array of absolute indices in A for the closest match of a line
611 * \param max_search_distance_a maximum distance in lines from the closest line
612 * in A for other lines in A for which
613 * similarities may be calculated.
614 * \param map_line_number_in_b_to_a parameter to map_line_number().
616 static void find_best_line_matches(
621 struct fingerprint
*fingerprints_a
,
622 struct fingerprint
*fingerprints_b
,
625 int *second_best_result
,
627 const int max_search_distance_a
,
628 const struct line_number_mapping
*map_line_number_in_b_to_a
)
631 int i
, search_start
, search_end
, closest_local_line_a
, *similarity
,
632 best_similarity
= 0, second_best_similarity
= 0,
633 best_similarity_index
= 0, second_best_similarity_index
= 0;
635 /* certainty has already been calculated so no need to redo the work */
636 if (certainties
[local_line_b
] != CERTAINTY_NOT_CALCULATED
)
639 closest_local_line_a
= map_line_number(
640 local_line_b
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
642 search_start
= closest_local_line_a
- max_search_distance_a
;
643 if (search_start
< 0)
646 search_end
= closest_local_line_a
+ max_search_distance_a
+ 1;
647 if (search_end
> length_a
)
648 search_end
= length_a
;
650 for (i
= search_start
; i
< search_end
; ++i
) {
651 similarity
= get_similarity(similarities
,
653 closest_local_line_a
,
654 max_search_distance_a
);
655 if (*similarity
== -1) {
656 /* This value will never exceed 10 but assert just in
659 assert(abs(i
- closest_local_line_a
) < 1000);
660 /* scale the similarity by (1000 - distance from
661 * closest line) to act as a tie break between lines
662 * that otherwise are equally similar.
664 *similarity
= fingerprint_similarity(
665 fingerprints_b
+ local_line_b
,
666 fingerprints_a
+ i
) *
667 (1000 - abs(i
- closest_local_line_a
));
669 if (*similarity
> best_similarity
) {
670 second_best_similarity
= best_similarity
;
671 second_best_similarity_index
= best_similarity_index
;
672 best_similarity
= *similarity
;
673 best_similarity_index
= i
;
674 } else if (*similarity
> second_best_similarity
) {
675 second_best_similarity
= *similarity
;
676 second_best_similarity_index
= i
;
680 if (best_similarity
== 0) {
681 /* this line definitely doesn't match with anything. Mark it
682 * with this special value so it doesn't get invalidated and
683 * won't be recalculated.
685 certainties
[local_line_b
] = CERTAIN_NOTHING_MATCHES
;
686 result
[local_line_b
] = -1;
688 /* Calculate the certainty with which this line matches.
689 * If the line matches well with two lines then that reduces
690 * the certainty. However we still want to prioritise matching
691 * a line that matches very well with two lines over matching a
692 * line that matches poorly with one line, hence doubling
694 * This means that if we have
695 * line X that matches only one line with a score of 3,
696 * line Y that matches two lines equally with a score of 5,
697 * and line Z that matches only one line with a score or 2,
698 * then the lines in order of certainty are X, Y, Z.
700 certainties
[local_line_b
] = best_similarity
* 2 -
701 second_best_similarity
;
703 /* We keep both the best and second best results to allow us to
704 * check at a later stage of the matching process whether the
705 * result needs to be invalidated.
707 result
[local_line_b
] = start_a
+ best_similarity_index
;
708 second_best_result
[local_line_b
] =
709 start_a
+ second_best_similarity_index
;
714 * This finds the line that we can match with the most confidence, and
715 * uses it as a partition. It then calls itself on the lines on either side of
716 * that partition. In this way we avoid lines appearing out of order, and
717 * retain a sensible line ordering.
718 * \param start_a index of the first line in A with which lines in B may be
720 * \param start_b index of the first line in B for which matching should be
722 * \param length_a number of lines in A with which lines in B may be compared.
723 * \param length_b number of lines in B for which matching should be done.
724 * \param fingerprints_a mutable array of fingerprints in A. The first element
725 * corresponds to the line at start_a.
726 * \param fingerprints_b array of fingerprints in B. The first element
727 * corresponds to the line at start_b.
728 * \param similarities 2-dimensional array of similarities between lines in A
729 * and B. See get_similarity() for more details.
730 * \param certainties array of values indicating how strongly a line in B is
731 * matched with some line in A.
732 * \param second_best_result array of absolute indices in A for the second
733 * closest match of a line in B.
734 * \param result array of absolute indices in A for the closest match of a line
736 * \param max_search_distance_a maximum distance in lines from the closest line
737 * in A for other lines in A for which
738 * similarities may be calculated.
739 * \param max_search_distance_b an upper bound on the greatest possible
740 * distance between lines in B such that they will
741 * both be compared with the same line in A
742 * according to max_search_distance_a.
743 * \param map_line_number_in_b_to_a parameter to map_line_number().
745 static void fuzzy_find_matching_lines_recurse(
746 int start_a
, int start_b
,
747 int length_a
, int length_b
,
748 struct fingerprint
*fingerprints_a
,
749 struct fingerprint
*fingerprints_b
,
752 int *second_best_result
,
754 int max_search_distance_a
,
755 int max_search_distance_b
,
756 const struct line_number_mapping
*map_line_number_in_b_to_a
)
758 int i
, invalidate_min
, invalidate_max
, offset_b
,
759 second_half_start_a
, second_half_start_b
,
760 second_half_length_a
, second_half_length_b
,
761 most_certain_line_a
, most_certain_local_line_b
= -1,
762 most_certain_line_certainty
= -1,
763 closest_local_line_a
;
765 for (i
= 0; i
< length_b
; ++i
) {
766 find_best_line_matches(start_a
,
776 max_search_distance_a
,
777 map_line_number_in_b_to_a
);
779 if (certainties
[i
] > most_certain_line_certainty
) {
780 most_certain_line_certainty
= certainties
[i
];
781 most_certain_local_line_b
= i
;
786 if (most_certain_local_line_b
== -1)
789 most_certain_line_a
= result
[most_certain_local_line_b
];
792 * Subtract the most certain line's fingerprint in B from the matched
793 * fingerprint in A. This means that other lines in B can't also match
794 * the same parts of the line in A.
796 fingerprint_subtract(fingerprints_a
+ most_certain_line_a
- start_a
,
797 fingerprints_b
+ most_certain_local_line_b
);
799 /* Invalidate results that may be affected by the choice of most
802 invalidate_min
= most_certain_local_line_b
- max_search_distance_b
;
803 invalidate_max
= most_certain_local_line_b
+ max_search_distance_b
+ 1;
804 if (invalidate_min
< 0)
806 if (invalidate_max
> length_b
)
807 invalidate_max
= length_b
;
809 /* As the fingerprint in A has changed, discard previously calculated
810 * similarity values with that fingerprint.
812 for (i
= invalidate_min
; i
< invalidate_max
; ++i
) {
813 closest_local_line_a
= map_line_number(
814 i
+ start_b
, map_line_number_in_b_to_a
) - start_a
;
816 /* Check that the lines in A and B are close enough that there
817 * is a similarity value for them.
819 if (abs(most_certain_line_a
- start_a
- closest_local_line_a
) >
820 max_search_distance_a
) {
824 *get_similarity(similarities
, most_certain_line_a
- start_a
,
825 i
, closest_local_line_a
,
826 max_search_distance_a
) = -1;
829 /* More invalidating of results that may be affected by the choice of
831 * Discard the matches for lines in B that are currently matched with a
832 * line in A such that their ordering contradicts the ordering imposed
833 * by the choice of most certain line.
835 for (i
= most_certain_local_line_b
- 1; i
>= invalidate_min
; --i
) {
836 /* In this loop we discard results for lines in B that are
837 * before most-certain-line-B but are matched with a line in A
838 * that is after most-certain-line-A.
840 if (certainties
[i
] >= 0 &&
841 (result
[i
] >= most_certain_line_a
||
842 second_best_result
[i
] >= most_certain_line_a
)) {
843 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
846 for (i
= most_certain_local_line_b
+ 1; i
< invalidate_max
; ++i
) {
847 /* In this loop we discard results for lines in B that are
848 * after most-certain-line-B but are matched with a line in A
849 * that is before 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
;
858 /* Repeat the matching process for lines before the most certain line.
860 if (most_certain_local_line_b
> 0) {
861 fuzzy_find_matching_lines_recurse(
863 most_certain_line_a
+ 1 - start_a
,
864 most_certain_local_line_b
,
865 fingerprints_a
, fingerprints_b
, similarities
,
866 certainties
, second_best_result
, result
,
867 max_search_distance_a
,
868 max_search_distance_b
,
869 map_line_number_in_b_to_a
);
871 /* Repeat the matching process for lines after the most certain line.
873 if (most_certain_local_line_b
+ 1 < length_b
) {
874 second_half_start_a
= most_certain_line_a
;
875 offset_b
= most_certain_local_line_b
+ 1;
876 second_half_start_b
= start_b
+ offset_b
;
877 second_half_length_a
=
878 length_a
+ start_a
- second_half_start_a
;
879 second_half_length_b
=
880 length_b
+ start_b
- second_half_start_b
;
881 fuzzy_find_matching_lines_recurse(
882 second_half_start_a
, second_half_start_b
,
883 second_half_length_a
, second_half_length_b
,
884 fingerprints_a
+ second_half_start_a
- start_a
,
885 fingerprints_b
+ offset_b
,
887 offset_b
* (max_search_distance_a
* 2 + 1),
888 certainties
+ offset_b
,
889 second_best_result
+ offset_b
, result
+ offset_b
,
890 max_search_distance_a
,
891 max_search_distance_b
,
892 map_line_number_in_b_to_a
);
896 /* Find the lines in the parent line range that most closely match the lines in
897 * the target line range. This is accomplished by matching fingerprints in each
898 * blame_origin, and choosing the best matches that preserve the line ordering.
899 * See struct fingerprint for details of fingerprint matching, and
900 * fuzzy_find_matching_lines_recurse for details of preserving line ordering.
902 * The performance is believed to be O(n log n) in the typical case and O(n^2)
903 * in a pathological case, where n is the number of lines in the target range.
905 static int *fuzzy_find_matching_lines(struct blame_origin
*parent
,
906 struct blame_origin
*target
,
907 int tlno
, int parent_slno
, int same
,
910 /* We use the terminology "A" for the left hand side of the diff AKA
911 * parent, and "B" for the right hand side of the diff AKA target. */
912 int start_a
= parent_slno
;
913 int length_a
= parent_len
;
915 int length_b
= same
- tlno
;
917 struct line_number_mapping map_line_number_in_b_to_a
= {
918 start_a
, length_a
, start_b
, length_b
921 struct fingerprint
*fingerprints_a
= parent
->fingerprints
;
922 struct fingerprint
*fingerprints_b
= target
->fingerprints
;
924 int i
, *result
, *second_best_result
,
925 *certainties
, *similarities
, similarity_count
;
928 * max_search_distance_a means that given a line in B, compare it to
929 * the line in A that is closest to its position, and the lines in A
930 * that are no greater than max_search_distance_a lines away from the
933 * max_search_distance_b is an upper bound on the greatest possible
934 * distance between lines in B such that they will both be compared
935 * with the same line in A according to max_search_distance_a.
937 int max_search_distance_a
= 10, max_search_distance_b
;
942 if (max_search_distance_a
>= length_a
)
943 max_search_distance_a
= length_a
? length_a
- 1 : 0;
945 max_search_distance_b
= ((2 * max_search_distance_a
+ 1) * length_b
948 result
= xcalloc(sizeof(int), length_b
);
949 second_best_result
= xcalloc(sizeof(int), length_b
);
950 certainties
= xcalloc(sizeof(int), length_b
);
952 /* See get_similarity() for details of similarities. */
953 similarity_count
= length_b
* (max_search_distance_a
* 2 + 1);
954 similarities
= xcalloc(sizeof(int), similarity_count
);
956 for (i
= 0; i
< length_b
; ++i
) {
958 second_best_result
[i
] = -1;
959 certainties
[i
] = CERTAINTY_NOT_CALCULATED
;
962 for (i
= 0; i
< similarity_count
; ++i
)
963 similarities
[i
] = -1;
965 fuzzy_find_matching_lines_recurse(start_a
, start_b
,
967 fingerprints_a
+ start_a
,
968 fingerprints_b
+ start_b
,
973 max_search_distance_a
,
974 max_search_distance_b
,
975 &map_line_number_in_b_to_a
);
979 free(second_best_result
);
984 static void fill_origin_fingerprints(struct blame_origin
*o
)
990 o
->num_lines
= find_line_starts(&line_starts
, o
->file
.ptr
,
992 o
->fingerprints
= xcalloc(sizeof(struct fingerprint
), o
->num_lines
);
993 get_line_fingerprints(o
->fingerprints
, o
->file
.ptr
, line_starts
,
998 static void drop_origin_fingerprints(struct blame_origin
*o
)
1000 if (o
->fingerprints
) {
1001 free_line_fingerprints(o
->fingerprints
, o
->num_lines
);
1003 FREE_AND_NULL(o
->fingerprints
);
1008 * Given an origin, prepare mmfile_t structure to be used by the
1011 static void fill_origin_blob(struct diff_options
*opt
,
1012 struct blame_origin
*o
, mmfile_t
*file
,
1013 int *num_read_blob
, int fill_fingerprints
)
1016 enum object_type type
;
1017 unsigned long file_size
;
1020 if (opt
->flags
.allow_textconv
&&
1021 textconv_object(opt
->repo
, o
->path
, o
->mode
,
1022 &o
->blob_oid
, 1, &file
->ptr
, &file_size
))
1025 file
->ptr
= read_object_file(&o
->blob_oid
, &type
,
1027 file
->size
= file_size
;
1030 die("Cannot read blob %s for path %s",
1031 oid_to_hex(&o
->blob_oid
),
1037 if (fill_fingerprints
)
1038 fill_origin_fingerprints(o
);
1041 static void drop_origin_blob(struct blame_origin
*o
)
1043 FREE_AND_NULL(o
->file
.ptr
);
1044 drop_origin_fingerprints(o
);
1048 * Any merge of blames happens on lists of blames that arrived via
1049 * different parents in a single suspect. In this case, we want to
1050 * sort according to the suspect line numbers as opposed to the final
1051 * image line numbers. The function body is somewhat longish because
1052 * it avoids unnecessary writes.
1055 static struct blame_entry
*blame_merge(struct blame_entry
*list1
,
1056 struct blame_entry
*list2
)
1058 struct blame_entry
*p1
= list1
, *p2
= list2
,
1066 if (p1
->s_lno
<= p2
->s_lno
) {
1069 if ((p1
= *tail
) == NULL
) {
1073 } while (p1
->s_lno
<= p2
->s_lno
);
1079 if ((p2
= *tail
) == NULL
) {
1083 } while (p1
->s_lno
> p2
->s_lno
);
1087 if ((p1
= *tail
) == NULL
) {
1091 } while (p1
->s_lno
<= p2
->s_lno
);
1095 static void *get_next_blame(const void *p
)
1097 return ((struct blame_entry
*)p
)->next
;
1100 static void set_next_blame(void *p1
, void *p2
)
1102 ((struct blame_entry
*)p1
)->next
= p2
;
1106 * Final image line numbers are all different, so we don't need a
1107 * three-way comparison here.
1110 static int compare_blame_final(const void *p1
, const void *p2
)
1112 return ((struct blame_entry
*)p1
)->lno
> ((struct blame_entry
*)p2
)->lno
1116 static int compare_blame_suspect(const void *p1
, const void *p2
)
1118 const struct blame_entry
*s1
= p1
, *s2
= p2
;
1120 * to allow for collating suspects, we sort according to the
1121 * respective pointer value as the primary sorting criterion.
1122 * The actual relation is pretty unimportant as long as it
1123 * establishes a total order. Comparing as integers gives us
1126 if (s1
->suspect
!= s2
->suspect
)
1127 return (intptr_t)s1
->suspect
> (intptr_t)s2
->suspect
? 1 : -1;
1128 if (s1
->s_lno
== s2
->s_lno
)
1130 return s1
->s_lno
> s2
->s_lno
? 1 : -1;
1133 void blame_sort_final(struct blame_scoreboard
*sb
)
1135 sb
->ent
= llist_mergesort(sb
->ent
, get_next_blame
, set_next_blame
,
1136 compare_blame_final
);
1139 static int compare_commits_by_reverse_commit_date(const void *a
,
1143 return -compare_commits_by_commit_date(a
, b
, c
);
1147 * For debugging -- origin is refcounted, and this asserts that
1148 * we do not underflow.
1150 static void sanity_check_refcnt(struct blame_scoreboard
*sb
)
1153 struct blame_entry
*ent
;
1155 for (ent
= sb
->ent
; ent
; ent
= ent
->next
) {
1156 /* Nobody should have zero or negative refcnt */
1157 if (ent
->suspect
->refcnt
<= 0) {
1158 fprintf(stderr
, "%s in %s has negative refcnt %d\n",
1160 oid_to_hex(&ent
->suspect
->commit
->object
.oid
),
1161 ent
->suspect
->refcnt
);
1166 sb
->on_sanity_fail(sb
, baa
);
1170 * If two blame entries that are next to each other came from
1171 * contiguous lines in the same origin (i.e. <commit, path> pair),
1172 * merge them together.
1174 void blame_coalesce(struct blame_scoreboard
*sb
)
1176 struct blame_entry
*ent
, *next
;
1178 for (ent
= sb
->ent
; ent
&& (next
= ent
->next
); ent
= next
) {
1179 if (ent
->suspect
== next
->suspect
&&
1180 ent
->s_lno
+ ent
->num_lines
== next
->s_lno
&&
1181 ent
->ignored
== next
->ignored
&&
1182 ent
->unblamable
== next
->unblamable
) {
1183 ent
->num_lines
+= next
->num_lines
;
1184 ent
->next
= next
->next
;
1185 blame_origin_decref(next
->suspect
);
1188 next
= ent
; /* again */
1192 if (sb
->debug
) /* sanity */
1193 sanity_check_refcnt(sb
);
1197 * Merge the given sorted list of blames into a preexisting origin.
1198 * If there were no previous blames to that commit, it is entered into
1199 * the commit priority queue of the score board.
1202 static void queue_blames(struct blame_scoreboard
*sb
, struct blame_origin
*porigin
,
1203 struct blame_entry
*sorted
)
1205 if (porigin
->suspects
)
1206 porigin
->suspects
= blame_merge(porigin
->suspects
, sorted
);
1208 struct blame_origin
*o
;
1209 for (o
= get_blame_suspects(porigin
->commit
); o
; o
= o
->next
) {
1211 porigin
->suspects
= sorted
;
1215 porigin
->suspects
= sorted
;
1216 prio_queue_put(&sb
->commits
, porigin
->commit
);
1221 * Fill the blob_sha1 field of an origin if it hasn't, so that later
1222 * call to fill_origin_blob() can use it to locate the data. blob_sha1
1223 * for an origin is also used to pass the blame for the entire file to
1224 * the parent to detect the case where a child's blob is identical to
1225 * that of its parent's.
1227 * This also fills origin->mode for corresponding tree path.
1229 static int fill_blob_sha1_and_mode(struct repository
*r
,
1230 struct blame_origin
*origin
)
1232 if (!is_null_oid(&origin
->blob_oid
))
1234 if (get_tree_entry(&origin
->commit
->object
.oid
, origin
->path
, &origin
->blob_oid
, &origin
->mode
))
1236 if (oid_object_info(r
, &origin
->blob_oid
, NULL
) != OBJ_BLOB
)
1240 oidclr(&origin
->blob_oid
);
1241 origin
->mode
= S_IFINVALID
;
1246 * We have an origin -- check if the same path exists in the
1247 * parent and return an origin structure to represent it.
1249 static struct blame_origin
*find_origin(struct repository
*r
,
1250 struct commit
*parent
,
1251 struct blame_origin
*origin
)
1253 struct blame_origin
*porigin
;
1254 struct diff_options diff_opts
;
1255 const char *paths
[2];
1257 /* First check any existing origins */
1258 for (porigin
= get_blame_suspects(parent
); porigin
; porigin
= porigin
->next
)
1259 if (!strcmp(porigin
->path
, origin
->path
)) {
1261 * The same path between origin and its parent
1262 * without renaming -- the most common case.
1264 return blame_origin_incref (porigin
);
1267 /* See if the origin->path is different between parent
1268 * and origin first. Most of the time they are the
1269 * same and diff-tree is fairly efficient about this.
1271 repo_diff_setup(r
, &diff_opts
);
1272 diff_opts
.flags
.recursive
= 1;
1273 diff_opts
.detect_rename
= 0;
1274 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1275 paths
[0] = origin
->path
;
1278 parse_pathspec(&diff_opts
.pathspec
,
1279 PATHSPEC_ALL_MAGIC
& ~PATHSPEC_LITERAL
,
1280 PATHSPEC_LITERAL_PATH
, "", paths
);
1281 diff_setup_done(&diff_opts
);
1283 if (is_null_oid(&origin
->commit
->object
.oid
))
1284 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1286 diff_tree_oid(get_commit_tree_oid(parent
),
1287 get_commit_tree_oid(origin
->commit
),
1289 diffcore_std(&diff_opts
);
1291 if (!diff_queued_diff
.nr
) {
1292 /* The path is the same as parent */
1293 porigin
= get_origin(parent
, origin
->path
);
1294 oidcpy(&porigin
->blob_oid
, &origin
->blob_oid
);
1295 porigin
->mode
= origin
->mode
;
1298 * Since origin->path is a pathspec, if the parent
1299 * commit had it as a directory, we will see a whole
1300 * bunch of deletion of files in the directory that we
1301 * do not care about.
1304 struct diff_filepair
*p
= NULL
;
1305 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1307 p
= diff_queued_diff
.queue
[i
];
1308 name
= p
->one
->path
? p
->one
->path
: p
->two
->path
;
1309 if (!strcmp(name
, origin
->path
))
1313 die("internal error in blame::find_origin");
1314 switch (p
->status
) {
1316 die("internal error in blame::find_origin (%c)",
1319 porigin
= get_origin(parent
, origin
->path
);
1320 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1321 porigin
->mode
= p
->one
->mode
;
1325 /* Did not exist in parent, or type changed */
1329 diff_flush(&diff_opts
);
1330 clear_pathspec(&diff_opts
.pathspec
);
1335 * We have an origin -- find the path that corresponds to it in its
1336 * parent and return an origin structure to represent it.
1338 static struct blame_origin
*find_rename(struct repository
*r
,
1339 struct commit
*parent
,
1340 struct blame_origin
*origin
)
1342 struct blame_origin
*porigin
= NULL
;
1343 struct diff_options diff_opts
;
1346 repo_diff_setup(r
, &diff_opts
);
1347 diff_opts
.flags
.recursive
= 1;
1348 diff_opts
.detect_rename
= DIFF_DETECT_RENAME
;
1349 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
1350 diff_opts
.single_follow
= origin
->path
;
1351 diff_setup_done(&diff_opts
);
1353 if (is_null_oid(&origin
->commit
->object
.oid
))
1354 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
1356 diff_tree_oid(get_commit_tree_oid(parent
),
1357 get_commit_tree_oid(origin
->commit
),
1359 diffcore_std(&diff_opts
);
1361 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
1362 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
1363 if ((p
->status
== 'R' || p
->status
== 'C') &&
1364 !strcmp(p
->two
->path
, origin
->path
)) {
1365 porigin
= get_origin(parent
, p
->one
->path
);
1366 oidcpy(&porigin
->blob_oid
, &p
->one
->oid
);
1367 porigin
->mode
= p
->one
->mode
;
1371 diff_flush(&diff_opts
);
1372 clear_pathspec(&diff_opts
.pathspec
);
1377 * Append a new blame entry to a given output queue.
1379 static void add_blame_entry(struct blame_entry
***queue
,
1380 const struct blame_entry
*src
)
1382 struct blame_entry
*e
= xmalloc(sizeof(*e
));
1383 memcpy(e
, src
, sizeof(*e
));
1384 blame_origin_incref(e
->suspect
);
1392 * src typically is on-stack; we want to copy the information in it to
1393 * a malloced blame_entry that gets added to the given queue. The
1394 * origin of dst loses a refcnt.
1396 static void dup_entry(struct blame_entry
***queue
,
1397 struct blame_entry
*dst
, struct blame_entry
*src
)
1399 blame_origin_incref(src
->suspect
);
1400 blame_origin_decref(dst
->suspect
);
1401 memcpy(dst
, src
, sizeof(*src
));
1402 dst
->next
= **queue
;
1404 *queue
= &dst
->next
;
1407 const char *blame_nth_line(struct blame_scoreboard
*sb
, long lno
)
1409 return sb
->final_buf
+ sb
->lineno
[lno
];
1413 * It is known that lines between tlno to same came from parent, and e
1414 * has an overlap with that range. it also is known that parent's
1415 * line plno corresponds to e's line tlno.
1421 * <------------------>
1423 * Split e into potentially three parts; before this chunk, the chunk
1424 * to be blamed for the parent, and after that portion.
1426 static void split_overlap(struct blame_entry
*split
,
1427 struct blame_entry
*e
,
1428 int tlno
, int plno
, int same
,
1429 struct blame_origin
*parent
)
1433 memset(split
, 0, sizeof(struct blame_entry
[3]));
1435 for (i
= 0; i
< 3; i
++) {
1436 split
[i
].ignored
= e
->ignored
;
1437 split
[i
].unblamable
= e
->unblamable
;
1440 if (e
->s_lno
< tlno
) {
1441 /* there is a pre-chunk part not blamed on parent */
1442 split
[0].suspect
= blame_origin_incref(e
->suspect
);
1443 split
[0].lno
= e
->lno
;
1444 split
[0].s_lno
= e
->s_lno
;
1445 split
[0].num_lines
= tlno
- e
->s_lno
;
1446 split
[1].lno
= e
->lno
+ tlno
- e
->s_lno
;
1447 split
[1].s_lno
= plno
;
1450 split
[1].lno
= e
->lno
;
1451 split
[1].s_lno
= plno
+ (e
->s_lno
- tlno
);
1454 if (same
< e
->s_lno
+ e
->num_lines
) {
1455 /* there is a post-chunk part not blamed on parent */
1456 split
[2].suspect
= blame_origin_incref(e
->suspect
);
1457 split
[2].lno
= e
->lno
+ (same
- e
->s_lno
);
1458 split
[2].s_lno
= e
->s_lno
+ (same
- e
->s_lno
);
1459 split
[2].num_lines
= e
->s_lno
+ e
->num_lines
- same
;
1460 chunk_end_lno
= split
[2].lno
;
1463 chunk_end_lno
= e
->lno
+ e
->num_lines
;
1464 split
[1].num_lines
= chunk_end_lno
- split
[1].lno
;
1467 * if it turns out there is nothing to blame the parent for,
1468 * forget about the splitting. !split[1].suspect signals this.
1470 if (split
[1].num_lines
< 1)
1472 split
[1].suspect
= blame_origin_incref(parent
);
1476 * split_overlap() divided an existing blame e into up to three parts
1477 * in split. Any assigned blame is moved to queue to
1478 * reflect the split.
1480 static void split_blame(struct blame_entry
***blamed
,
1481 struct blame_entry
***unblamed
,
1482 struct blame_entry
*split
,
1483 struct blame_entry
*e
)
1485 if (split
[0].suspect
&& split
[2].suspect
) {
1486 /* The first part (reuse storage for the existing entry e) */
1487 dup_entry(unblamed
, e
, &split
[0]);
1489 /* The last part -- me */
1490 add_blame_entry(unblamed
, &split
[2]);
1492 /* ... and the middle part -- parent */
1493 add_blame_entry(blamed
, &split
[1]);
1495 else if (!split
[0].suspect
&& !split
[2].suspect
)
1497 * The parent covers the entire area; reuse storage for
1498 * e and replace it with the parent.
1500 dup_entry(blamed
, e
, &split
[1]);
1501 else if (split
[0].suspect
) {
1502 /* me and then parent */
1503 dup_entry(unblamed
, e
, &split
[0]);
1504 add_blame_entry(blamed
, &split
[1]);
1507 /* parent and then me */
1508 dup_entry(blamed
, e
, &split
[1]);
1509 add_blame_entry(unblamed
, &split
[2]);
1514 * After splitting the blame, the origins used by the
1515 * on-stack blame_entry should lose one refcnt each.
1517 static void decref_split(struct blame_entry
*split
)
1521 for (i
= 0; i
< 3; i
++)
1522 blame_origin_decref(split
[i
].suspect
);
1526 * reverse_blame reverses the list given in head, appending tail.
1527 * That allows us to build lists in reverse order, then reverse them
1528 * afterwards. This can be faster than building the list in proper
1529 * order right away. The reason is that building in proper order
1530 * requires writing a link in the _previous_ element, while building
1531 * in reverse order just requires placing the list head into the
1532 * _current_ element.
1535 static struct blame_entry
*reverse_blame(struct blame_entry
*head
,
1536 struct blame_entry
*tail
)
1539 struct blame_entry
*next
= head
->next
;
1548 * Splits a blame entry into two entries at 'len' lines. The original 'e'
1549 * consists of len lines, i.e. [e->lno, e->lno + len), and the second part,
1550 * which is returned, consists of the remainder: [e->lno + len, e->lno +
1551 * e->num_lines). The caller needs to sort out the reference counting for the
1552 * new entry's suspect.
1554 static struct blame_entry
*split_blame_at(struct blame_entry
*e
, int len
,
1555 struct blame_origin
*new_suspect
)
1557 struct blame_entry
*n
= xcalloc(1, sizeof(struct blame_entry
));
1559 n
->suspect
= new_suspect
;
1560 n
->ignored
= e
->ignored
;
1561 n
->unblamable
= e
->unblamable
;
1562 n
->lno
= e
->lno
+ len
;
1563 n
->s_lno
= e
->s_lno
+ len
;
1564 n
->num_lines
= e
->num_lines
- len
;
1570 struct blame_line_tracker
{
1575 static int are_lines_adjacent(struct blame_line_tracker
*first
,
1576 struct blame_line_tracker
*second
)
1578 return first
->is_parent
== second
->is_parent
&&
1579 first
->s_lno
+ 1 == second
->s_lno
;
1582 static int scan_parent_range(struct fingerprint
*p_fps
,
1583 struct fingerprint
*t_fps
, int t_idx
,
1584 int from
, int nr_lines
)
1587 #define FINGERPRINT_FILE_THRESHOLD 10
1588 int best_sim_val
= FINGERPRINT_FILE_THRESHOLD
;
1589 int best_sim_idx
= -1;
1591 for (p_idx
= from
; p_idx
< from
+ nr_lines
; p_idx
++) {
1592 sim
= fingerprint_similarity(&t_fps
[t_idx
], &p_fps
[p_idx
]);
1593 if (sim
< best_sim_val
)
1595 /* Break ties with the closest-to-target line number */
1596 if (sim
== best_sim_val
&& best_sim_idx
!= -1 &&
1597 abs(best_sim_idx
- t_idx
) < abs(p_idx
- t_idx
))
1600 best_sim_idx
= p_idx
;
1602 return best_sim_idx
;
1606 * The first pass checks the blame entry (from the target) against the parent's
1607 * diff chunk. If that fails for a line, the second pass tries to match that
1608 * line to any part of parent file. That catches cases where a change was
1609 * broken into two chunks by 'context.'
1611 static void guess_line_blames(struct blame_origin
*parent
,
1612 struct blame_origin
*target
,
1613 int tlno
, int offset
, int same
, int parent_len
,
1614 struct blame_line_tracker
*line_blames
)
1616 int i
, best_idx
, target_idx
;
1617 int parent_slno
= tlno
+ offset
;
1620 fuzzy_matches
= fuzzy_find_matching_lines(parent
, target
,
1621 tlno
, parent_slno
, same
,
1623 for (i
= 0; i
< same
- tlno
; i
++) {
1624 target_idx
= tlno
+ i
;
1625 if (fuzzy_matches
&& fuzzy_matches
[i
] >= 0) {
1626 best_idx
= fuzzy_matches
[i
];
1628 best_idx
= scan_parent_range(parent
->fingerprints
,
1629 target
->fingerprints
,
1633 if (best_idx
>= 0) {
1634 line_blames
[i
].is_parent
= 1;
1635 line_blames
[i
].s_lno
= best_idx
;
1637 line_blames
[i
].is_parent
= 0;
1638 line_blames
[i
].s_lno
= target_idx
;
1641 free(fuzzy_matches
);
1645 * This decides which parts of a blame entry go to the parent (added to the
1646 * ignoredp list) and which stay with the target (added to the diffp list). The
1647 * actual decision was made in a separate heuristic function, and those answers
1648 * for the lines in 'e' are in line_blames. This consumes e, essentially
1649 * putting it on a list.
1651 * Note that the blame entries on the ignoredp list are not necessarily sorted
1652 * with respect to the parent's line numbers yet.
1654 static void ignore_blame_entry(struct blame_entry
*e
,
1655 struct blame_origin
*parent
,
1656 struct blame_entry
**diffp
,
1657 struct blame_entry
**ignoredp
,
1658 struct blame_line_tracker
*line_blames
)
1660 int entry_len
, nr_lines
, i
;
1663 * We carve new entries off the front of e. Each entry comes from a
1664 * contiguous chunk of lines: adjacent lines from the same origin
1665 * (either the parent or the target).
1668 nr_lines
= e
->num_lines
; /* e changes in the loop */
1669 for (i
= 0; i
< nr_lines
; i
++) {
1670 struct blame_entry
*next
= NULL
;
1673 * We are often adjacent to the next line - only split the blame
1674 * entry when we have to.
1676 if (i
+ 1 < nr_lines
) {
1677 if (are_lines_adjacent(&line_blames
[i
],
1678 &line_blames
[i
+ 1])) {
1682 next
= split_blame_at(e
, entry_len
,
1683 blame_origin_incref(e
->suspect
));
1685 if (line_blames
[i
].is_parent
) {
1687 blame_origin_decref(e
->suspect
);
1688 e
->suspect
= blame_origin_incref(parent
);
1689 e
->s_lno
= line_blames
[i
- entry_len
+ 1].s_lno
;
1690 e
->next
= *ignoredp
;
1694 /* e->s_lno is already in the target's address space. */
1698 assert(e
->num_lines
== entry_len
);
1706 * Process one hunk from the patch between the current suspect for
1707 * blame_entry e and its parent. This first blames any unfinished
1708 * entries before the chunk (which is where target and parent start
1709 * differing) on the parent, and then splits blame entries at the
1710 * start and at the end of the difference region. Since use of -M and
1711 * -C options may lead to overlapping/duplicate source line number
1712 * ranges, all we can rely on from sorting/merging is the order of the
1713 * first suspect line number.
1715 * tlno: line number in the target where this chunk begins
1716 * same: line number in the target where this chunk ends
1717 * offset: add to tlno to get the chunk starting point in the parent
1718 * parent_len: number of lines in the parent chunk
1720 static void blame_chunk(struct blame_entry
***dstq
, struct blame_entry
***srcq
,
1721 int tlno
, int offset
, int same
, int parent_len
,
1722 struct blame_origin
*parent
,
1723 struct blame_origin
*target
, int ignore_diffs
)
1725 struct blame_entry
*e
= **srcq
;
1726 struct blame_entry
*samep
= NULL
, *diffp
= NULL
, *ignoredp
= NULL
;
1727 struct blame_line_tracker
*line_blames
= NULL
;
1729 while (e
&& e
->s_lno
< tlno
) {
1730 struct blame_entry
*next
= e
->next
;
1732 * current record starts before differing portion. If
1733 * it reaches into it, we need to split it up and
1734 * examine the second part separately.
1736 if (e
->s_lno
+ e
->num_lines
> tlno
) {
1737 /* Move second half to a new record */
1738 struct blame_entry
*n
;
1740 n
= split_blame_at(e
, tlno
- e
->s_lno
, e
->suspect
);
1741 /* Push new record to diffp */
1745 blame_origin_decref(e
->suspect
);
1746 /* Pass blame for everything before the differing
1747 * chunk to the parent */
1748 e
->suspect
= blame_origin_incref(parent
);
1755 * As we don't know how much of a common stretch after this
1756 * diff will occur, the currently blamed parts are all that we
1757 * can assign to the parent for now.
1761 **dstq
= reverse_blame(samep
, **dstq
);
1762 *dstq
= &samep
->next
;
1765 * Prepend the split off portions: everything after e starts
1766 * after the blameable portion.
1768 e
= reverse_blame(diffp
, e
);
1771 * Now retain records on the target while parts are different
1777 if (ignore_diffs
&& same
- tlno
> 0) {
1778 line_blames
= xcalloc(sizeof(struct blame_line_tracker
),
1780 guess_line_blames(parent
, target
, tlno
, offset
, same
,
1781 parent_len
, line_blames
);
1784 while (e
&& e
->s_lno
< same
) {
1785 struct blame_entry
*next
= e
->next
;
1788 * If current record extends into sameness, need to split.
1790 if (e
->s_lno
+ e
->num_lines
> same
) {
1792 * Move second half to a new record to be
1793 * processed by later chunks
1795 struct blame_entry
*n
;
1797 n
= split_blame_at(e
, same
- e
->s_lno
,
1798 blame_origin_incref(e
->suspect
));
1799 /* Push new record to samep */
1804 ignore_blame_entry(e
, parent
, &diffp
, &ignoredp
,
1805 line_blames
+ e
->s_lno
- tlno
);
1815 * Note ignoredp is not sorted yet, and thus neither is dstq.
1816 * That list must be sorted before we queue_blames(). We defer
1817 * sorting until after all diff hunks are processed, so that
1818 * guess_line_blames() can pick *any* line in the parent. The
1819 * slight drawback is that we end up sorting all blame entries
1820 * passed to the parent, including those that are unrelated to
1821 * changes made by the ignored commit.
1823 **dstq
= reverse_blame(ignoredp
, **dstq
);
1824 *dstq
= &ignoredp
->next
;
1826 **srcq
= reverse_blame(diffp
, reverse_blame(samep
, e
));
1827 /* Move across elements that are in the unblamable portion */
1829 *srcq
= &diffp
->next
;
1832 struct blame_chunk_cb_data
{
1833 struct blame_origin
*parent
;
1834 struct blame_origin
*target
;
1837 struct blame_entry
**dstq
;
1838 struct blame_entry
**srcq
;
1841 /* diff chunks are from parent to target */
1842 static int blame_chunk_cb(long start_a
, long count_a
,
1843 long start_b
, long count_b
, void *data
)
1845 struct blame_chunk_cb_data
*d
= data
;
1846 if (start_a
- start_b
!= d
->offset
)
1847 die("internal error in blame::blame_chunk_cb");
1848 blame_chunk(&d
->dstq
, &d
->srcq
, start_b
, start_a
- start_b
,
1849 start_b
+ count_b
, count_a
, d
->parent
, d
->target
,
1851 d
->offset
= start_a
+ count_a
- (start_b
+ count_b
);
1856 * We are looking at the origin 'target' and aiming to pass blame
1857 * for the lines it is suspected to its parent. Run diff to find
1858 * which lines came from parent and pass blame for them.
1860 static void pass_blame_to_parent(struct blame_scoreboard
*sb
,
1861 struct blame_origin
*target
,
1862 struct blame_origin
*parent
, int ignore_diffs
)
1864 mmfile_t file_p
, file_o
;
1865 struct blame_chunk_cb_data d
;
1866 struct blame_entry
*newdest
= NULL
;
1868 if (!target
->suspects
)
1869 return; /* nothing remains for this target */
1874 d
.ignore_diffs
= ignore_diffs
;
1875 d
.dstq
= &newdest
; d
.srcq
= &target
->suspects
;
1877 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
1878 &sb
->num_read_blob
, ignore_diffs
);
1879 fill_origin_blob(&sb
->revs
->diffopt
, target
, &file_o
,
1880 &sb
->num_read_blob
, ignore_diffs
);
1881 sb
->num_get_patch
++;
1883 if (diff_hunks(&file_p
, &file_o
, blame_chunk_cb
, &d
, sb
->xdl_opts
))
1884 die("unable to generate diff (%s -> %s)",
1885 oid_to_hex(&parent
->commit
->object
.oid
),
1886 oid_to_hex(&target
->commit
->object
.oid
));
1887 /* The rest are the same as the parent */
1888 blame_chunk(&d
.dstq
, &d
.srcq
, INT_MAX
, d
.offset
, INT_MAX
, 0,
1892 newdest
= llist_mergesort(newdest
, get_next_blame
,
1894 compare_blame_suspect
);
1895 queue_blames(sb
, parent
, newdest
);
1901 * The lines in blame_entry after splitting blames many times can become
1902 * very small and trivial, and at some point it becomes pointless to
1903 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
1904 * ordinary C program, and it is not worth to say it was copied from
1905 * totally unrelated file in the parent.
1907 * Compute how trivial the lines in the blame_entry are.
1909 unsigned blame_entry_score(struct blame_scoreboard
*sb
, struct blame_entry
*e
)
1912 const char *cp
, *ep
;
1918 cp
= blame_nth_line(sb
, e
->lno
);
1919 ep
= blame_nth_line(sb
, e
->lno
+ e
->num_lines
);
1921 unsigned ch
= *((unsigned char *)cp
);
1931 * best_so_far[] and potential[] are both a split of an existing blame_entry
1932 * that passes blame to the parent. Maintain best_so_far the best split so
1933 * far, by comparing potential and best_so_far and copying potential into
1934 * bst_so_far as needed.
1936 static void copy_split_if_better(struct blame_scoreboard
*sb
,
1937 struct blame_entry
*best_so_far
,
1938 struct blame_entry
*potential
)
1942 if (!potential
[1].suspect
)
1944 if (best_so_far
[1].suspect
) {
1945 if (blame_entry_score(sb
, &potential
[1]) <
1946 blame_entry_score(sb
, &best_so_far
[1]))
1950 for (i
= 0; i
< 3; i
++)
1951 blame_origin_incref(potential
[i
].suspect
);
1952 decref_split(best_so_far
);
1953 memcpy(best_so_far
, potential
, sizeof(struct blame_entry
[3]));
1957 * We are looking at a part of the final image represented by
1958 * ent (tlno and same are offset by ent->s_lno).
1959 * tlno is where we are looking at in the final image.
1960 * up to (but not including) same match preimage.
1961 * plno is where we are looking at in the preimage.
1963 * <-------------- final image ---------------------->
1966 * <---------preimage----->
1969 * All line numbers are 0-based.
1971 static void handle_split(struct blame_scoreboard
*sb
,
1972 struct blame_entry
*ent
,
1973 int tlno
, int plno
, int same
,
1974 struct blame_origin
*parent
,
1975 struct blame_entry
*split
)
1977 if (ent
->num_lines
<= tlno
)
1980 struct blame_entry potential
[3];
1983 split_overlap(potential
, ent
, tlno
, plno
, same
, parent
);
1984 copy_split_if_better(sb
, split
, potential
);
1985 decref_split(potential
);
1989 struct handle_split_cb_data
{
1990 struct blame_scoreboard
*sb
;
1991 struct blame_entry
*ent
;
1992 struct blame_origin
*parent
;
1993 struct blame_entry
*split
;
1998 static int handle_split_cb(long start_a
, long count_a
,
1999 long start_b
, long count_b
, void *data
)
2001 struct handle_split_cb_data
*d
= data
;
2002 handle_split(d
->sb
, d
->ent
, d
->tlno
, d
->plno
, start_b
, d
->parent
,
2004 d
->plno
= start_a
+ count_a
;
2005 d
->tlno
= start_b
+ count_b
;
2010 * Find the lines from parent that are the same as ent so that
2011 * we can pass blames to it. file_p has the blob contents for
2014 static void find_copy_in_blob(struct blame_scoreboard
*sb
,
2015 struct blame_entry
*ent
,
2016 struct blame_origin
*parent
,
2017 struct blame_entry
*split
,
2022 struct handle_split_cb_data d
;
2024 memset(&d
, 0, sizeof(d
));
2025 d
.sb
= sb
; d
.ent
= ent
; d
.parent
= parent
; d
.split
= split
;
2027 * Prepare mmfile that contains only the lines in ent.
2029 cp
= blame_nth_line(sb
, ent
->lno
);
2030 file_o
.ptr
= (char *) cp
;
2031 file_o
.size
= blame_nth_line(sb
, ent
->lno
+ ent
->num_lines
) - cp
;
2034 * file_o is a part of final image we are annotating.
2035 * file_p partially may match that image.
2037 memset(split
, 0, sizeof(struct blame_entry
[3]));
2038 if (diff_hunks(file_p
, &file_o
, handle_split_cb
, &d
, sb
->xdl_opts
))
2039 die("unable to generate diff (%s)",
2040 oid_to_hex(&parent
->commit
->object
.oid
));
2041 /* remainder, if any, all match the preimage */
2042 handle_split(sb
, ent
, d
.tlno
, d
.plno
, ent
->num_lines
, parent
, split
);
2045 /* Move all blame entries from list *source that have a score smaller
2046 * than score_min to the front of list *small.
2047 * Returns a pointer to the link pointing to the old head of the small list.
2050 static struct blame_entry
**filter_small(struct blame_scoreboard
*sb
,
2051 struct blame_entry
**small
,
2052 struct blame_entry
**source
,
2055 struct blame_entry
*p
= *source
;
2056 struct blame_entry
*oldsmall
= *small
;
2058 if (blame_entry_score(sb
, p
) <= score_min
) {
2074 * See if lines currently target is suspected for can be attributed to
2077 static void find_move_in_parent(struct blame_scoreboard
*sb
,
2078 struct blame_entry
***blamed
,
2079 struct blame_entry
**toosmall
,
2080 struct blame_origin
*target
,
2081 struct blame_origin
*parent
)
2083 struct blame_entry
*e
, split
[3];
2084 struct blame_entry
*unblamed
= target
->suspects
;
2085 struct blame_entry
*leftover
= NULL
;
2089 return; /* nothing remains for this target */
2091 fill_origin_blob(&sb
->revs
->diffopt
, parent
, &file_p
,
2092 &sb
->num_read_blob
, 0);
2096 /* At each iteration, unblamed has a NULL-terminated list of
2097 * entries that have not yet been tested for blame. leftover
2098 * contains the reversed list of entries that have been tested
2099 * without being assignable to the parent.
2102 struct blame_entry
**unblamedtail
= &unblamed
;
2103 struct blame_entry
*next
;
2104 for (e
= unblamed
; e
; e
= next
) {
2106 find_copy_in_blob(sb
, e
, parent
, split
, &file_p
);
2107 if (split
[1].suspect
&&
2108 sb
->move_score
< blame_entry_score(sb
, &split
[1])) {
2109 split_blame(blamed
, &unblamedtail
, split
, e
);
2114 decref_split(split
);
2116 *unblamedtail
= NULL
;
2117 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->move_score
);
2119 target
->suspects
= reverse_blame(leftover
, NULL
);
2123 struct blame_entry
*ent
;
2124 struct blame_entry split
[3];
2128 * Count the number of entries the target is suspected for,
2129 * and prepare a list of entry and the best split.
2131 static struct blame_list
*setup_blame_list(struct blame_entry
*unblamed
,
2134 struct blame_entry
*e
;
2136 struct blame_list
*blame_list
= NULL
;
2138 for (e
= unblamed
, num_ents
= 0; e
; e
= e
->next
)
2141 blame_list
= xcalloc(num_ents
, sizeof(struct blame_list
));
2142 for (e
= unblamed
, i
= 0; e
; e
= e
->next
)
2143 blame_list
[i
++].ent
= e
;
2145 *num_ents_p
= num_ents
;
2150 * For lines target is suspected for, see if we can find code movement
2151 * across file boundary from the parent commit. porigin is the path
2152 * in the parent we already tried.
2154 static void find_copy_in_parent(struct blame_scoreboard
*sb
,
2155 struct blame_entry
***blamed
,
2156 struct blame_entry
**toosmall
,
2157 struct blame_origin
*target
,
2158 struct commit
*parent
,
2159 struct blame_origin
*porigin
,
2162 struct diff_options diff_opts
;
2164 struct blame_list
*blame_list
;
2166 struct blame_entry
*unblamed
= target
->suspects
;
2167 struct blame_entry
*leftover
= NULL
;
2170 return; /* nothing remains for this target */
2172 repo_diff_setup(sb
->repo
, &diff_opts
);
2173 diff_opts
.flags
.recursive
= 1;
2174 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
2176 diff_setup_done(&diff_opts
);
2178 /* Try "find copies harder" on new path if requested;
2179 * we do not want to use diffcore_rename() actually to
2180 * match things up; find_copies_harder is set only to
2181 * force diff_tree_oid() to feed all filepairs to diff_queue,
2182 * and this code needs to be after diff_setup_done(), which
2183 * usually makes find-copies-harder imply copy detection.
2185 if ((opt
& PICKAXE_BLAME_COPY_HARDEST
)
2186 || ((opt
& PICKAXE_BLAME_COPY_HARDER
)
2187 && (!porigin
|| strcmp(target
->path
, porigin
->path
))))
2188 diff_opts
.flags
.find_copies_harder
= 1;
2190 if (is_null_oid(&target
->commit
->object
.oid
))
2191 do_diff_cache(get_commit_tree_oid(parent
), &diff_opts
);
2193 diff_tree_oid(get_commit_tree_oid(parent
),
2194 get_commit_tree_oid(target
->commit
),
2197 if (!diff_opts
.flags
.find_copies_harder
)
2198 diffcore_std(&diff_opts
);
2201 struct blame_entry
**unblamedtail
= &unblamed
;
2202 blame_list
= setup_blame_list(unblamed
, &num_ents
);
2204 for (i
= 0; i
< diff_queued_diff
.nr
; i
++) {
2205 struct diff_filepair
*p
= diff_queued_diff
.queue
[i
];
2206 struct blame_origin
*norigin
;
2208 struct blame_entry potential
[3];
2210 if (!DIFF_FILE_VALID(p
->one
))
2211 continue; /* does not exist in parent */
2212 if (S_ISGITLINK(p
->one
->mode
))
2213 continue; /* ignore git links */
2214 if (porigin
&& !strcmp(p
->one
->path
, porigin
->path
))
2215 /* find_move already dealt with this path */
2218 norigin
= get_origin(parent
, p
->one
->path
);
2219 oidcpy(&norigin
->blob_oid
, &p
->one
->oid
);
2220 norigin
->mode
= p
->one
->mode
;
2221 fill_origin_blob(&sb
->revs
->diffopt
, norigin
, &file_p
,
2222 &sb
->num_read_blob
, 0);
2226 for (j
= 0; j
< num_ents
; j
++) {
2227 find_copy_in_blob(sb
, blame_list
[j
].ent
,
2228 norigin
, potential
, &file_p
);
2229 copy_split_if_better(sb
, blame_list
[j
].split
,
2231 decref_split(potential
);
2233 blame_origin_decref(norigin
);
2236 for (j
= 0; j
< num_ents
; j
++) {
2237 struct blame_entry
*split
= blame_list
[j
].split
;
2238 if (split
[1].suspect
&&
2239 sb
->copy_score
< blame_entry_score(sb
, &split
[1])) {
2240 split_blame(blamed
, &unblamedtail
, split
,
2243 blame_list
[j
].ent
->next
= leftover
;
2244 leftover
= blame_list
[j
].ent
;
2246 decref_split(split
);
2249 *unblamedtail
= NULL
;
2250 toosmall
= filter_small(sb
, toosmall
, &unblamed
, sb
->copy_score
);
2252 target
->suspects
= reverse_blame(leftover
, NULL
);
2253 diff_flush(&diff_opts
);
2254 clear_pathspec(&diff_opts
.pathspec
);
2258 * The blobs of origin and porigin exactly match, so everything
2259 * origin is suspected for can be blamed on the parent.
2261 static void pass_whole_blame(struct blame_scoreboard
*sb
,
2262 struct blame_origin
*origin
, struct blame_origin
*porigin
)
2264 struct blame_entry
*e
, *suspects
;
2266 if (!porigin
->file
.ptr
&& origin
->file
.ptr
) {
2267 /* Steal its file */
2268 porigin
->file
= origin
->file
;
2269 origin
->file
.ptr
= NULL
;
2271 suspects
= origin
->suspects
;
2272 origin
->suspects
= NULL
;
2273 for (e
= suspects
; e
; e
= e
->next
) {
2274 blame_origin_incref(porigin
);
2275 blame_origin_decref(e
->suspect
);
2276 e
->suspect
= porigin
;
2278 queue_blames(sb
, porigin
, suspects
);
2282 * We pass blame from the current commit to its parents. We keep saying
2283 * "parent" (and "porigin"), but what we mean is to find scapegoat to
2284 * exonerate ourselves.
2286 static struct commit_list
*first_scapegoat(struct rev_info
*revs
, struct commit
*commit
,
2290 if (revs
->first_parent_only
&&
2292 commit
->parents
->next
) {
2293 free_commit_list(commit
->parents
->next
);
2294 commit
->parents
->next
= NULL
;
2296 return commit
->parents
;
2298 return lookup_decoration(&revs
->children
, &commit
->object
);
2301 static int num_scapegoats(struct rev_info
*revs
, struct commit
*commit
, int reverse
)
2303 struct commit_list
*l
= first_scapegoat(revs
, commit
, reverse
);
2304 return commit_list_count(l
);
2307 /* Distribute collected unsorted blames to the respected sorted lists
2308 * in the various origins.
2310 static void distribute_blame(struct blame_scoreboard
*sb
, struct blame_entry
*blamed
)
2312 blamed
= llist_mergesort(blamed
, get_next_blame
, set_next_blame
,
2313 compare_blame_suspect
);
2316 struct blame_origin
*porigin
= blamed
->suspect
;
2317 struct blame_entry
*suspects
= NULL
;
2319 struct blame_entry
*next
= blamed
->next
;
2320 blamed
->next
= suspects
;
2323 } while (blamed
&& blamed
->suspect
== porigin
);
2324 suspects
= reverse_blame(suspects
, NULL
);
2325 queue_blames(sb
, porigin
, suspects
);
2331 static void pass_blame(struct blame_scoreboard
*sb
, struct blame_origin
*origin
, int opt
)
2333 struct rev_info
*revs
= sb
->revs
;
2334 int i
, pass
, num_sg
;
2335 struct commit
*commit
= origin
->commit
;
2336 struct commit_list
*sg
;
2337 struct blame_origin
*sg_buf
[MAXSG
];
2338 struct blame_origin
*porigin
, **sg_origin
= sg_buf
;
2339 struct blame_entry
*toosmall
= NULL
;
2340 struct blame_entry
*blames
, **blametail
= &blames
;
2342 num_sg
= num_scapegoats(revs
, commit
, sb
->reverse
);
2345 else if (num_sg
< ARRAY_SIZE(sg_buf
))
2346 memset(sg_buf
, 0, sizeof(sg_buf
));
2348 sg_origin
= xcalloc(num_sg
, sizeof(*sg_origin
));
2351 * The first pass looks for unrenamed path to optimize for
2352 * common cases, then we look for renames in the second pass.
2354 for (pass
= 0; pass
< 2 - sb
->no_whole_file_rename
; pass
++) {
2355 struct blame_origin
*(*find
)(struct repository
*, struct commit
*, struct blame_origin
*);
2356 find
= pass
? find_rename
: find_origin
;
2358 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2360 sg
= sg
->next
, i
++) {
2361 struct commit
*p
= sg
->item
;
2366 if (parse_commit(p
))
2368 porigin
= find(sb
->repo
, p
, origin
);
2371 if (oideq(&porigin
->blob_oid
, &origin
->blob_oid
)) {
2372 pass_whole_blame(sb
, origin
, porigin
);
2373 blame_origin_decref(porigin
);
2376 for (j
= same
= 0; j
< i
; j
++)
2378 oideq(&sg_origin
[j
]->blob_oid
, &porigin
->blob_oid
)) {
2383 sg_origin
[i
] = porigin
;
2385 blame_origin_decref(porigin
);
2390 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2392 sg
= sg
->next
, i
++) {
2393 struct blame_origin
*porigin
= sg_origin
[i
];
2396 if (!origin
->previous
) {
2397 blame_origin_incref(porigin
);
2398 origin
->previous
= porigin
;
2400 pass_blame_to_parent(sb
, origin
, porigin
, 0);
2401 if (!origin
->suspects
)
2406 * Pass remaining suspects for ignored commits to their parents.
2408 if (oidset_contains(&sb
->ignore_list
, &commit
->object
.oid
)) {
2409 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2411 sg
= sg
->next
, i
++) {
2412 struct blame_origin
*porigin
= sg_origin
[i
];
2416 pass_blame_to_parent(sb
, origin
, porigin
, 1);
2418 * Preemptively drop porigin so we can refresh the
2419 * fingerprints if we use the parent again, which can
2420 * occur if you ignore back-to-back commits.
2422 drop_origin_blob(porigin
);
2423 if (!origin
->suspects
)
2429 * Optionally find moves in parents' files.
2431 if (opt
& PICKAXE_BLAME_MOVE
) {
2432 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->move_score
);
2433 if (origin
->suspects
) {
2434 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2436 sg
= sg
->next
, i
++) {
2437 struct blame_origin
*porigin
= sg_origin
[i
];
2440 find_move_in_parent(sb
, &blametail
, &toosmall
, origin
, porigin
);
2441 if (!origin
->suspects
)
2448 * Optionally find copies from parents' files.
2450 if (opt
& PICKAXE_BLAME_COPY
) {
2451 if (sb
->copy_score
> sb
->move_score
)
2452 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2453 else if (sb
->copy_score
< sb
->move_score
) {
2454 origin
->suspects
= blame_merge(origin
->suspects
, toosmall
);
2456 filter_small(sb
, &toosmall
, &origin
->suspects
, sb
->copy_score
);
2458 if (!origin
->suspects
)
2461 for (i
= 0, sg
= first_scapegoat(revs
, commit
, sb
->reverse
);
2463 sg
= sg
->next
, i
++) {
2464 struct blame_origin
*porigin
= sg_origin
[i
];
2465 find_copy_in_parent(sb
, &blametail
, &toosmall
,
2466 origin
, sg
->item
, porigin
, opt
);
2467 if (!origin
->suspects
)
2474 distribute_blame(sb
, blames
);
2476 * prepend toosmall to origin->suspects
2478 * There is no point in sorting: this ends up on a big
2479 * unsorted list in the caller anyway.
2482 struct blame_entry
**tail
= &toosmall
;
2484 tail
= &(*tail
)->next
;
2485 *tail
= origin
->suspects
;
2486 origin
->suspects
= toosmall
;
2488 for (i
= 0; i
< num_sg
; i
++) {
2490 drop_origin_blob(sg_origin
[i
]);
2491 blame_origin_decref(sg_origin
[i
]);
2494 drop_origin_blob(origin
);
2495 if (sg_buf
!= sg_origin
)
2500 * The main loop -- while we have blobs with lines whose true origin
2501 * is still unknown, pick one blob, and allow its lines to pass blames
2502 * to its parents. */
2503 void assign_blame(struct blame_scoreboard
*sb
, int opt
)
2505 struct rev_info
*revs
= sb
->revs
;
2506 struct commit
*commit
= prio_queue_get(&sb
->commits
);
2509 struct blame_entry
*ent
;
2510 struct blame_origin
*suspect
= get_blame_suspects(commit
);
2512 /* find one suspect to break down */
2513 while (suspect
&& !suspect
->suspects
)
2514 suspect
= suspect
->next
;
2517 commit
= prio_queue_get(&sb
->commits
);
2521 assert(commit
== suspect
->commit
);
2524 * We will use this suspect later in the loop,
2525 * so hold onto it in the meantime.
2527 blame_origin_incref(suspect
);
2528 parse_commit(commit
);
2530 (!(commit
->object
.flags
& UNINTERESTING
) &&
2531 !(revs
->max_age
!= -1 && commit
->date
< revs
->max_age
)))
2532 pass_blame(sb
, suspect
, opt
);
2534 commit
->object
.flags
|= UNINTERESTING
;
2535 if (commit
->object
.parsed
)
2536 mark_parents_uninteresting(commit
);
2538 /* treat root commit as boundary */
2539 if (!commit
->parents
&& !sb
->show_root
)
2540 commit
->object
.flags
|= UNINTERESTING
;
2542 /* Take responsibility for the remaining entries */
2543 ent
= suspect
->suspects
;
2545 suspect
->guilty
= 1;
2547 struct blame_entry
*next
= ent
->next
;
2548 if (sb
->found_guilty_entry
)
2549 sb
->found_guilty_entry(ent
, sb
->found_guilty_entry_data
);
2554 ent
->next
= sb
->ent
;
2555 sb
->ent
= suspect
->suspects
;
2556 suspect
->suspects
= NULL
;
2560 blame_origin_decref(suspect
);
2562 if (sb
->debug
) /* sanity */
2563 sanity_check_refcnt(sb
);
2568 * To allow quick access to the contents of nth line in the
2569 * final image, prepare an index in the scoreboard.
2571 static int prepare_lines(struct blame_scoreboard
*sb
)
2573 sb
->num_lines
= find_line_starts(&sb
->lineno
, sb
->final_buf
,
2574 sb
->final_buf_size
);
2575 return sb
->num_lines
;
2578 static struct commit
*find_single_final(struct rev_info
*revs
,
2579 const char **name_p
)
2582 struct commit
*found
= NULL
;
2583 const char *name
= NULL
;
2585 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2586 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2587 if (obj
->flags
& UNINTERESTING
)
2589 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2590 if (obj
->type
!= OBJ_COMMIT
)
2591 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2593 die("More than one commit to dig from %s and %s?",
2594 revs
->pending
.objects
[i
].name
, name
);
2595 found
= (struct commit
*)obj
;
2596 name
= revs
->pending
.objects
[i
].name
;
2599 *name_p
= xstrdup_or_null(name
);
2603 static struct commit
*dwim_reverse_initial(struct rev_info
*revs
,
2604 const char **name_p
)
2607 * DWIM "git blame --reverse ONE -- PATH" as
2608 * "git blame --reverse ONE..HEAD -- PATH" but only do so
2609 * when it makes sense.
2612 struct commit
*head_commit
;
2613 struct object_id head_oid
;
2615 if (revs
->pending
.nr
!= 1)
2618 /* Is that sole rev a committish? */
2619 obj
= revs
->pending
.objects
[0].item
;
2620 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2621 if (obj
->type
!= OBJ_COMMIT
)
2624 /* Do we have HEAD? */
2625 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING
, &head_oid
, NULL
))
2627 head_commit
= lookup_commit_reference_gently(revs
->repo
,
2632 /* Turn "ONE" into "ONE..HEAD" then */
2633 obj
->flags
|= UNINTERESTING
;
2634 add_pending_object(revs
, &head_commit
->object
, "HEAD");
2637 *name_p
= revs
->pending
.objects
[0].name
;
2638 return (struct commit
*)obj
;
2641 static struct commit
*find_single_initial(struct rev_info
*revs
,
2642 const char **name_p
)
2645 struct commit
*found
= NULL
;
2646 const char *name
= NULL
;
2649 * There must be one and only one negative commit, and it must be
2652 for (i
= 0; i
< revs
->pending
.nr
; i
++) {
2653 struct object
*obj
= revs
->pending
.objects
[i
].item
;
2654 if (!(obj
->flags
& UNINTERESTING
))
2656 obj
= deref_tag(revs
->repo
, obj
, NULL
, 0);
2657 if (obj
->type
!= OBJ_COMMIT
)
2658 die("Non commit %s?", revs
->pending
.objects
[i
].name
);
2660 die("More than one commit to dig up from, %s and %s?",
2661 revs
->pending
.objects
[i
].name
, name
);
2662 found
= (struct commit
*) obj
;
2663 name
= revs
->pending
.objects
[i
].name
;
2667 found
= dwim_reverse_initial(revs
, &name
);
2669 die("No commit to dig up from?");
2672 *name_p
= xstrdup(name
);
2676 void init_scoreboard(struct blame_scoreboard
*sb
)
2678 memset(sb
, 0, sizeof(struct blame_scoreboard
));
2679 sb
->move_score
= BLAME_DEFAULT_MOVE_SCORE
;
2680 sb
->copy_score
= BLAME_DEFAULT_COPY_SCORE
;
2683 void setup_scoreboard(struct blame_scoreboard
*sb
,
2685 struct blame_origin
**orig
)
2687 const char *final_commit_name
= NULL
;
2688 struct blame_origin
*o
;
2689 struct commit
*final_commit
= NULL
;
2690 enum object_type type
;
2692 init_blame_suspects(&blame_suspects
);
2694 if (sb
->reverse
&& sb
->contents_from
)
2695 die(_("--contents and --reverse do not blend well."));
2698 BUG("repo is NULL");
2701 sb
->final
= find_single_final(sb
->revs
, &final_commit_name
);
2702 sb
->commits
.compare
= compare_commits_by_commit_date
;
2704 sb
->final
= find_single_initial(sb
->revs
, &final_commit_name
);
2705 sb
->commits
.compare
= compare_commits_by_reverse_commit_date
;
2708 if (sb
->final
&& sb
->contents_from
)
2709 die(_("cannot use --contents with final commit object name"));
2711 if (sb
->reverse
&& sb
->revs
->first_parent_only
)
2712 sb
->revs
->children
.name
= NULL
;
2716 * "--not A B -- path" without anything positive;
2717 * do not default to HEAD, but use the working tree
2721 sb
->final
= fake_working_tree_commit(sb
->repo
,
2723 path
, sb
->contents_from
);
2724 add_pending_object(sb
->revs
, &(sb
->final
->object
), ":");
2727 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2728 final_commit
= find_single_final(sb
->revs
, NULL
);
2730 die(_("--reverse and --first-parent together require specified latest commit"));
2734 * If we have bottom, this will mark the ancestors of the
2735 * bottom commits we would reach while traversing as
2738 if (prepare_revision_walk(sb
->revs
))
2739 die(_("revision walk setup failed"));
2741 if (sb
->reverse
&& sb
->revs
->first_parent_only
) {
2742 struct commit
*c
= final_commit
;
2744 sb
->revs
->children
.name
= "children";
2745 while (c
->parents
&&
2746 !oideq(&c
->object
.oid
, &sb
->final
->object
.oid
)) {
2747 struct commit_list
*l
= xcalloc(1, sizeof(*l
));
2750 if (add_decoration(&sb
->revs
->children
,
2751 &c
->parents
->item
->object
, l
))
2752 BUG("not unique item in first-parent chain");
2753 c
= c
->parents
->item
;
2756 if (!oideq(&c
->object
.oid
, &sb
->final
->object
.oid
))
2757 die(_("--reverse --first-parent together require range along first-parent chain"));
2760 if (is_null_oid(&sb
->final
->object
.oid
)) {
2761 o
= get_blame_suspects(sb
->final
);
2762 sb
->final_buf
= xmemdupz(o
->file
.ptr
, o
->file
.size
);
2763 sb
->final_buf_size
= o
->file
.size
;
2766 o
= get_origin(sb
->final
, path
);
2767 if (fill_blob_sha1_and_mode(sb
->repo
, o
))
2768 die(_("no such path %s in %s"), path
, final_commit_name
);
2770 if (sb
->revs
->diffopt
.flags
.allow_textconv
&&
2771 textconv_object(sb
->repo
, path
, o
->mode
, &o
->blob_oid
, 1, (char **) &sb
->final_buf
,
2772 &sb
->final_buf_size
))
2775 sb
->final_buf
= read_object_file(&o
->blob_oid
, &type
,
2776 &sb
->final_buf_size
);
2779 die(_("cannot read blob %s for path %s"),
2780 oid_to_hex(&o
->blob_oid
),
2783 sb
->num_read_blob
++;
2789 free((char *)final_commit_name
);
2794 struct blame_entry
*blame_entry_prepend(struct blame_entry
*head
,
2795 long start
, long end
,
2796 struct blame_origin
*o
)
2798 struct blame_entry
*new_head
= xcalloc(1, sizeof(struct blame_entry
));
2799 new_head
->lno
= start
;
2800 new_head
->num_lines
= end
- start
;
2801 new_head
->suspect
= o
;
2802 new_head
->s_lno
= start
;
2803 new_head
->next
= head
;
2804 blame_origin_incref(o
);