1 /*
2  *
3  * Copyright (C) 2005 Junio C Hamano
4  */
5 #include "cache.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "object-store.h"
9 #include "hashmap.h"
10 #include "progress.h"
11 #include "promisor-remote.h"
12 #include "strmap.h"
13 
14 /* Table of rename/copy destinations */
15 
16 static struct diff_rename_dst {
17 	struct diff_filepair *p;
18 	struct diff_filespec *filespec_to_free;
19 	int is_rename; /* false -> just a create; true -> rename or copy */
20 } *rename_dst;
21 static int rename_dst_nr, rename_dst_alloc;
22 /* Mapping from break source pathname to break destination index */
23 static struct strintmap *break_idx = NULL;
24 
locate_rename_dst(struct diff_filepair * p)25 static struct diff_rename_dst *locate_rename_dst(struct diff_filepair *p)
26 {
27 	/* Lookup by p->ONE->path */
28 	int idx = break_idx ? strintmap_get(break_idx, p->one->path) : -1;
29 	return (idx == -1) ? NULL : &rename_dst[idx];
30 }
31 
32 /*
33  * Returns 0 on success, -1 if we found a duplicate.
34  */
add_rename_dst(struct diff_filepair * p)35 static int add_rename_dst(struct diff_filepair *p)
36 {
37 	ALLOC_GROW(rename_dst, rename_dst_nr + 1, rename_dst_alloc);
38 	rename_dst[rename_dst_nr].p = p;
39 	rename_dst[rename_dst_nr].filespec_to_free = NULL;
40 	rename_dst[rename_dst_nr].is_rename = 0;
41 	rename_dst_nr++;
42 	return 0;
43 }
44 
45 /* Table of rename/copy src files */
46 static struct diff_rename_src {
47 	struct diff_filepair *p;
48 	unsigned short score; /* to remember the break score */
49 } *rename_src;
50 static int rename_src_nr, rename_src_alloc;
51 
register_rename_src(struct diff_filepair * p)52 static void register_rename_src(struct diff_filepair *p)
53 {
54 	if (p->broken_pair) {
55 		if (!break_idx) {
56 			break_idx = xmalloc(sizeof(*break_idx));
57 			strintmap_init_with_options(break_idx, -1, NULL, 0);
58 		}
59 		strintmap_set(break_idx, p->one->path, rename_dst_nr);
60 	}
61 
62 	ALLOC_GROW(rename_src, rename_src_nr + 1, rename_src_alloc);
63 	rename_src[rename_src_nr].p = p;
64 	rename_src[rename_src_nr].score = p->score;
65 	rename_src_nr++;
66 }
67 
basename_same(struct diff_filespec * src,struct diff_filespec * dst)68 static int basename_same(struct diff_filespec *src, struct diff_filespec *dst)
69 {
70 	int src_len = strlen(src->path), dst_len = strlen(dst->path);
71 	while (src_len && dst_len) {
72 		char c1 = src->path[--src_len];
73 		char c2 = dst->path[--dst_len];
74 		if (c1 != c2)
75 			return 0;
76 		if (c1 == '/')
77 			return 1;
78 	}
79 	return (!src_len || src->path[src_len - 1] == '/') &&
80 		(!dst_len || dst->path[dst_len - 1] == '/');
81 }
82 
83 struct diff_score {
84 	int src; /* index in rename_src */
85 	int dst; /* index in rename_dst */
86 	unsigned short score;
87 	short name_score;
88 };
89 
90 struct inexact_prefetch_options {
91 	struct repository *repo;
92 	int skip_unmodified;
93 };
inexact_prefetch(void * prefetch_options)94 static void inexact_prefetch(void *prefetch_options)
95 {
96 	struct inexact_prefetch_options *options = prefetch_options;
97 	int i;
98 	struct oid_array to_fetch = OID_ARRAY_INIT;
99 
100 	for (i = 0; i < rename_dst_nr; i++) {
101 		if (rename_dst[i].p->renamed_pair)
102 			/*
103 			 * The loop in diffcore_rename() will not need these
104 			 * blobs, so skip prefetching.
105 			 */
106 			continue; /* already found exact match */
107 		diff_add_if_missing(options->repo, &to_fetch,
108 				    rename_dst[i].p->two);
109 	}
110 	for (i = 0; i < rename_src_nr; i++) {
111 		if (options->skip_unmodified &&
112 		    diff_unmodified_pair(rename_src[i].p))
113 			/*
114 			 * The loop in diffcore_rename() will not need these
115 			 * blobs, so skip prefetching.
116 			 */
117 			continue;
118 		diff_add_if_missing(options->repo, &to_fetch,
119 				    rename_src[i].p->one);
120 	}
121 	promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
122 	oid_array_clear(&to_fetch);
123 }
124 
estimate_similarity(struct repository * r,struct diff_filespec * src,struct diff_filespec * dst,int minimum_score,struct diff_populate_filespec_options * dpf_opt)125 static int estimate_similarity(struct repository *r,
126 			       struct diff_filespec *src,
127 			       struct diff_filespec *dst,
128 			       int minimum_score,
129 			       struct diff_populate_filespec_options *dpf_opt)
130 {
131 	/* src points at a file that existed in the original tree (or
132 	 * optionally a file in the destination tree) and dst points
133 	 * at a newly created file.  They may be quite similar, in which
134 	 * case we want to say src is renamed to dst or src is copied into
135 	 * dst, and then some edit has been applied to dst.
136 	 *
137 	 * Compare them and return how similar they are, representing
138 	 * the score as an integer between 0 and MAX_SCORE.
139 	 *
140 	 * When there is an exact match, it is considered a better
141 	 * match than anything else; the destination does not even
142 	 * call into this function in that case.
143 	 */
144 	unsigned long max_size, delta_size, base_size, src_copied, literal_added;
145 	int score;
146 
147 	/* We deal only with regular files.  Symlink renames are handled
148 	 * only when they are exact matches --- in other words, no edits
149 	 * after renaming.
150 	 */
151 	if (!S_ISREG(src->mode) || !S_ISREG(dst->mode))
152 		return 0;
153 
154 	/*
155 	 * Need to check that source and destination sizes are
156 	 * filled in before comparing them.
157 	 *
158 	 * If we already have "cnt_data" filled in, we know it's
159 	 * all good (avoid checking the size for zero, as that
160 	 * is a possible size - we really should have a flag to
161 	 * say whether the size is valid or not!)
162 	 */
163 	dpf_opt->check_size_only = 1;
164 
165 	if (!src->cnt_data &&
166 	    diff_populate_filespec(r, src, dpf_opt))
167 		return 0;
168 	if (!dst->cnt_data &&
169 	    diff_populate_filespec(r, dst, dpf_opt))
170 		return 0;
171 
172 	max_size = ((src->size > dst->size) ? src->size : dst->size);
173 	base_size = ((src->size < dst->size) ? src->size : dst->size);
174 	delta_size = max_size - base_size;
175 
176 	/* We would not consider edits that change the file size so
177 	 * drastically.  delta_size must be smaller than
178 	 * (MAX_SCORE-minimum_score)/MAX_SCORE * min(src->size, dst->size).
179 	 *
180 	 * Note that base_size == 0 case is handled here already
181 	 * and the final score computation below would not have a
182 	 * divide-by-zero issue.
183 	 */
184 	if (max_size * (MAX_SCORE-minimum_score) < delta_size * MAX_SCORE)
185 		return 0;
186 
187 	dpf_opt->check_size_only = 0;
188 
189 	if (!src->cnt_data && diff_populate_filespec(r, src, dpf_opt))
190 		return 0;
191 	if (!dst->cnt_data && diff_populate_filespec(r, dst, dpf_opt))
192 		return 0;
193 
194 	if (diffcore_count_changes(r, src, dst,
195 				   &src->cnt_data, &dst->cnt_data,
196 				   &src_copied, &literal_added))
197 		return 0;
198 
199 	/* How similar are they?
200 	 * what percentage of material in dst are from source?
201 	 */
202 	if (!dst->size)
203 		score = 0; /* should not happen */
204 	else
205 		score = (int)(src_copied * MAX_SCORE / max_size);
206 	return score;
207 }
208 
record_rename_pair(int dst_index,int src_index,int score)209 static void record_rename_pair(int dst_index, int src_index, int score)
210 {
211 	struct diff_filepair *src = rename_src[src_index].p;
212 	struct diff_filepair *dst = rename_dst[dst_index].p;
213 
214 	if (dst->renamed_pair)
215 		die("internal error: dst already matched.");
216 
217 	src->one->rename_used++;
218 	src->one->count++;
219 
220 	rename_dst[dst_index].filespec_to_free = dst->one;
221 	rename_dst[dst_index].is_rename = 1;
222 
223 	dst->one = src->one;
224 	dst->renamed_pair = 1;
225 	if (!strcmp(dst->one->path, dst->two->path))
226 		dst->score = rename_src[src_index].score;
227 	else
228 		dst->score = score;
229 }
230 
231 /*
232  * We sort the rename similarity matrix with the score, in descending
233  * order (the most similar first).
234  */
score_compare(const void * a_,const void * b_)235 static int score_compare(const void *a_, const void *b_)
236 {
237 	const struct diff_score *a = a_, *b = b_;
238 
239 	/* sink the unused ones to the bottom */
240 	if (a->dst < 0)
241 		return (0 <= b->dst);
242 	else if (b->dst < 0)
243 		return -1;
244 
245 	if (a->score == b->score)
246 		return b->name_score - a->name_score;
247 
248 	return b->score - a->score;
249 }
250 
251 struct file_similarity {
252 	struct hashmap_entry entry;
253 	int index;
254 	struct diff_filespec *filespec;
255 };
256 
hash_filespec(struct repository * r,struct diff_filespec * filespec)257 static unsigned int hash_filespec(struct repository *r,
258 				  struct diff_filespec *filespec)
259 {
260 	if (!filespec->oid_valid) {
261 		if (diff_populate_filespec(r, filespec, NULL))
262 			return 0;
263 		hash_object_file(r->hash_algo, filespec->data, filespec->size,
264 				 "blob", &filespec->oid);
265 	}
266 	return oidhash(&filespec->oid);
267 }
268 
find_identical_files(struct hashmap * srcs,int dst_index,struct diff_options * options)269 static int find_identical_files(struct hashmap *srcs,
270 				int dst_index,
271 				struct diff_options *options)
272 {
273 	int renames = 0;
274 	struct diff_filespec *target = rename_dst[dst_index].p->two;
275 	struct file_similarity *p, *best = NULL;
276 	int i = 100, best_score = -1;
277 	unsigned int hash = hash_filespec(options->repo, target);
278 
279 	/*
280 	 * Find the best source match for specified destination.
281 	 */
282 	p = hashmap_get_entry_from_hash(srcs, hash, NULL,
283 					struct file_similarity, entry);
284 	hashmap_for_each_entry_from(srcs, p, entry) {
285 		int score;
286 		struct diff_filespec *source = p->filespec;
287 
288 		/* False hash collision? */
289 		if (!oideq(&source->oid, &target->oid))
290 			continue;
291 		/* Non-regular files? If so, the modes must match! */
292 		if (!S_ISREG(source->mode) || !S_ISREG(target->mode)) {
293 			if (source->mode != target->mode)
294 				continue;
295 		}
296 		/* Give higher scores to sources that haven't been used already */
297 		score = !source->rename_used;
298 		if (source->rename_used && options->detect_rename != DIFF_DETECT_COPY)
299 			continue;
300 		score += basename_same(source, target);
301 		if (score > best_score) {
302 			best = p;
303 			best_score = score;
304 			if (score == 2)
305 				break;
306 		}
307 
308 		/* Too many identical alternatives? Pick one */
309 		if (!--i)
310 			break;
311 	}
312 	if (best) {
313 		record_rename_pair(dst_index, best->index, MAX_SCORE);
314 		renames++;
315 	}
316 	return renames;
317 }
318 
insert_file_table(struct repository * r,struct mem_pool * pool,struct hashmap * table,int index,struct diff_filespec * filespec)319 static void insert_file_table(struct repository *r,
320 			      struct mem_pool *pool,
321 			      struct hashmap *table, int index,
322 			      struct diff_filespec *filespec)
323 {
324 	struct file_similarity *entry = mem_pool_alloc(pool, sizeof(*entry));
325 
326 	entry->index = index;
327 	entry->filespec = filespec;
328 
329 	hashmap_entry_init(&entry->entry, hash_filespec(r, filespec));
330 	hashmap_add(table, &entry->entry);
331 }
332 
333 /*
334  * Find exact renames first.
335  *
336  * The first round matches up the up-to-date entries,
337  * and then during the second round we try to match
338  * cache-dirty entries as well.
339  */
find_exact_renames(struct diff_options * options,struct mem_pool * pool)340 static int find_exact_renames(struct diff_options *options,
341 			      struct mem_pool *pool)
342 {
343 	int i, renames = 0;
344 	struct hashmap file_table;
345 
346 	/* Add all sources to the hash table in reverse order, because
347 	 * later on they will be retrieved in LIFO order.
348 	 */
349 	hashmap_init(&file_table, NULL, NULL, rename_src_nr);
350 	for (i = rename_src_nr-1; i >= 0; i--)
351 		insert_file_table(options->repo, pool,
352 				  &file_table, i,
353 				  rename_src[i].p->one);
354 
355 	/* Walk the destinations and find best source match */
356 	for (i = 0; i < rename_dst_nr; i++)
357 		renames += find_identical_files(&file_table, i, options);
358 
359 	/* Free the hash data structure (entries will be freed with the pool) */
360 	hashmap_clear(&file_table);
361 
362 	return renames;
363 }
364 
365 struct dir_rename_info {
366 	struct strintmap idx_map;
367 	struct strmap dir_rename_guess;
368 	struct strmap *dir_rename_count;
369 	struct strintmap *relevant_source_dirs;
370 	unsigned setup;
371 };
372 
get_dirname(const char * filename)373 static char *get_dirname(const char *filename)
374 {
375 	char *slash = strrchr(filename, '/');
376 	return slash ? xstrndup(filename, slash - filename) : xstrdup("");
377 }
378 
dirname_munge(char * filename)379 static void dirname_munge(char *filename)
380 {
381 	char *slash = strrchr(filename, '/');
382 	if (!slash)
383 		slash = filename;
384 	*slash = '\0';
385 }
386 
get_highest_rename_path(struct strintmap * counts)387 static const char *get_highest_rename_path(struct strintmap *counts)
388 {
389 	int highest_count = 0;
390 	const char *highest_destination_dir = NULL;
391 	struct hashmap_iter iter;
392 	struct strmap_entry *entry;
393 
394 	strintmap_for_each_entry(counts, &iter, entry) {
395 		const char *destination_dir = entry->key;
396 		intptr_t count = (intptr_t)entry->value;
397 		if (count > highest_count) {
398 			highest_count = count;
399 			highest_destination_dir = destination_dir;
400 		}
401 	}
402 	return highest_destination_dir;
403 }
404 
405 static char *UNKNOWN_DIR = "/";  /* placeholder -- short, illegal directory */
406 
dir_rename_already_determinable(struct strintmap * counts)407 static int dir_rename_already_determinable(struct strintmap *counts)
408 {
409 	struct hashmap_iter iter;
410 	struct strmap_entry *entry;
411 	int first = 0, second = 0, unknown = 0;
412 	strintmap_for_each_entry(counts, &iter, entry) {
413 		const char *destination_dir = entry->key;
414 		intptr_t count = (intptr_t)entry->value;
415 		if (!strcmp(destination_dir, UNKNOWN_DIR)) {
416 			unknown = count;
417 		} else if (count >= first) {
418 			second = first;
419 			first = count;
420 		} else if (count >= second) {
421 			second = count;
422 		}
423 	}
424 	return first > second + unknown;
425 }
426 
increment_count(struct dir_rename_info * info,char * old_dir,char * new_dir)427 static void increment_count(struct dir_rename_info *info,
428 			    char *old_dir,
429 			    char *new_dir)
430 {
431 	struct strintmap *counts;
432 	struct strmap_entry *e;
433 
434 	/* Get the {new_dirs -> counts} mapping using old_dir */
435 	e = strmap_get_entry(info->dir_rename_count, old_dir);
436 	if (e) {
437 		counts = e->value;
438 	} else {
439 		counts = xmalloc(sizeof(*counts));
440 		strintmap_init_with_options(counts, 0, NULL, 1);
441 		strmap_put(info->dir_rename_count, old_dir, counts);
442 	}
443 
444 	/* Increment the count for new_dir */
445 	strintmap_incr(counts, new_dir, 1);
446 }
447 
update_dir_rename_counts(struct dir_rename_info * info,struct strintmap * dirs_removed,const char * oldname,const char * newname)448 static void update_dir_rename_counts(struct dir_rename_info *info,
449 				     struct strintmap *dirs_removed,
450 				     const char *oldname,
451 				     const char *newname)
452 {
453 	char *old_dir;
454 	char *new_dir;
455 	const char new_dir_first_char = newname[0];
456 	int first_time_in_loop = 1;
457 
458 	if (!info->setup)
459 		/*
460 		 * info->setup is 0 here in two cases: (1) all auxiliary
461 		 * vars (like dirs_removed) were NULL so
462 		 * initialize_dir_rename_info() returned early, or (2)
463 		 * either break detection or copy detection are active so
464 		 * that we never called initialize_dir_rename_info().  In
465 		 * the former case, we don't have enough info to know if
466 		 * directories were renamed (because dirs_removed lets us
467 		 * know about a necessary prerequisite, namely if they were
468 		 * removed), and in the latter, we don't care about
469 		 * directory renames or find_basename_matches.
470 		 *
471 		 * This matters because both basename and inexact matching
472 		 * will also call update_dir_rename_counts().  In either of
473 		 * the above two cases info->dir_rename_counts will not
474 		 * have been properly initialized which prevents us from
475 		 * updating it, but in these two cases we don't care about
476 		 * dir_rename_counts anyway, so we can just exit early.
477 		 */
478 		return;
479 
480 
481 	old_dir = xstrdup(oldname);
482 	new_dir = xstrdup(newname);
483 
484 	while (1) {
485 		int drd_flag = NOT_RELEVANT;
486 
487 		/* Get old_dir, skip if its directory isn't relevant. */
488 		dirname_munge(old_dir);
489 		if (info->relevant_source_dirs &&
490 		    !strintmap_contains(info->relevant_source_dirs, old_dir))
491 			break;
492 
493 		/* Get new_dir */
494 		dirname_munge(new_dir);
495 
496 		/*
497 		 * When renaming
498 		 *   "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
499 		 * then this suggests that both
500 		 *   a/b/c/d/e/ => a/b/some/thing/else/e/
501 		 *   a/b/c/d/   => a/b/some/thing/else/
502 		 * so we want to increment counters for both.  We do NOT,
503 		 * however, also want to suggest that there was the following
504 		 * rename:
505 		 *   a/b/c/ => a/b/some/thing/
506 		 * so we need to quit at that point.
507 		 *
508 		 * Note the when first_time_in_loop, we only strip off the
509 		 * basename, and we don't care if that's different.
510 		 */
511 		if (!first_time_in_loop) {
512 			char *old_sub_dir = strchr(old_dir, '\0')+1;
513 			char *new_sub_dir = strchr(new_dir, '\0')+1;
514 			if (!*new_dir) {
515 				/*
516 				 * Special case when renaming to root directory,
517 				 * i.e. when new_dir == "".  In this case, we had
518 				 * something like
519 				 *    a/b/subdir => subdir
520 				 * and so dirname_munge() sets things up so that
521 				 *    old_dir = "a/b\0subdir\0"
522 				 *    new_dir = "\0ubdir\0"
523 				 * We didn't have a '/' to overwrite a '\0' onto
524 				 * in new_dir, so we have to compare differently.
525 				 */
526 				if (new_dir_first_char != old_sub_dir[0] ||
527 				    strcmp(old_sub_dir+1, new_sub_dir))
528 					break;
529 			} else {
530 				if (strcmp(old_sub_dir, new_sub_dir))
531 					break;
532 			}
533 		}
534 
535 		/*
536 		 * Above we suggested that we'd keep recording renames for
537 		 * all ancestor directories where the trailing directories
538 		 * matched, i.e. for
539 		 *   "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
540 		 * we'd increment rename counts for each of
541 		 *   a/b/c/d/e/ => a/b/some/thing/else/e/
542 		 *   a/b/c/d/   => a/b/some/thing/else/
543 		 * However, we only need the rename counts for directories
544 		 * in dirs_removed whose value is RELEVANT_FOR_SELF.
545 		 * However, we add one special case of also recording it for
546 		 * first_time_in_loop because find_basename_matches() can
547 		 * use that as a hint to find a good pairing.
548 		 */
549 		if (dirs_removed)
550 			drd_flag = strintmap_get(dirs_removed, old_dir);
551 		if (drd_flag == RELEVANT_FOR_SELF || first_time_in_loop)
552 			increment_count(info, old_dir, new_dir);
553 
554 		first_time_in_loop = 0;
555 		if (drd_flag == NOT_RELEVANT)
556 			break;
557 		/* If we hit toplevel directory ("") for old or new dir, quit */
558 		if (!*old_dir || !*new_dir)
559 			break;
560 	}
561 
562 	/* Free resources we don't need anymore */
563 	free(old_dir);
564 	free(new_dir);
565 }
566 
initialize_dir_rename_info(struct dir_rename_info * info,struct strintmap * relevant_sources,struct strintmap * dirs_removed,struct strmap * dir_rename_count,struct strmap * cached_pairs)567 static void initialize_dir_rename_info(struct dir_rename_info *info,
568 				       struct strintmap *relevant_sources,
569 				       struct strintmap *dirs_removed,
570 				       struct strmap *dir_rename_count,
571 				       struct strmap *cached_pairs)
572 {
573 	struct hashmap_iter iter;
574 	struct strmap_entry *entry;
575 	int i;
576 
577 	if (!dirs_removed && !relevant_sources) {
578 		info->setup = 0;
579 		return;
580 	}
581 	info->setup = 1;
582 
583 	info->dir_rename_count = dir_rename_count;
584 	if (!info->dir_rename_count) {
585 		info->dir_rename_count = xmalloc(sizeof(*dir_rename_count));
586 		strmap_init(info->dir_rename_count);
587 	}
588 	strintmap_init_with_options(&info->idx_map, -1, NULL, 0);
589 	strmap_init_with_options(&info->dir_rename_guess, NULL, 0);
590 
591 	/* Setup info->relevant_source_dirs */
592 	info->relevant_source_dirs = NULL;
593 	if (dirs_removed || !relevant_sources) {
594 		info->relevant_source_dirs = dirs_removed; /* might be NULL */
595 	} else {
596 		info->relevant_source_dirs = xmalloc(sizeof(struct strintmap));
597 		strintmap_init(info->relevant_source_dirs, 0 /* unused */);
598 		strintmap_for_each_entry(relevant_sources, &iter, entry) {
599 			char *dirname = get_dirname(entry->key);
600 			if (!dirs_removed ||
601 			    strintmap_contains(dirs_removed, dirname))
602 				strintmap_set(info->relevant_source_dirs,
603 					      dirname, 0 /* value irrelevant */);
604 			free(dirname);
605 		}
606 	}
607 
608 	/*
609 	 * Loop setting up both info->idx_map, and doing setup of
610 	 * info->dir_rename_count.
611 	 */
612 	for (i = 0; i < rename_dst_nr; ++i) {
613 		/*
614 		 * For non-renamed files, make idx_map contain mapping of
615 		 *   filename -> index (index within rename_dst, that is)
616 		 */
617 		if (!rename_dst[i].is_rename) {
618 			char *filename = rename_dst[i].p->two->path;
619 			strintmap_set(&info->idx_map, filename, i);
620 			continue;
621 		}
622 
623 		/*
624 		 * For everything else (i.e. renamed files), make
625 		 * dir_rename_count contain a map of a map:
626 		 *   old_directory -> {new_directory -> count}
627 		 * In other words, for every pair look at the directories for
628 		 * the old filename and the new filename and count how many
629 		 * times that pairing occurs.
630 		 */
631 		update_dir_rename_counts(info, dirs_removed,
632 					 rename_dst[i].p->one->path,
633 					 rename_dst[i].p->two->path);
634 	}
635 
636 	/* Add cached_pairs to counts */
637 	strmap_for_each_entry(cached_pairs, &iter, entry) {
638 		const char *old_name = entry->key;
639 		const char *new_name = entry->value;
640 		if (!new_name)
641 			/* known delete; ignore it */
642 			continue;
643 
644 		update_dir_rename_counts(info, dirs_removed, old_name, new_name);
645 	}
646 
647 	/*
648 	 * Now we collapse
649 	 *    dir_rename_count: old_directory -> {new_directory -> count}
650 	 * down to
651 	 *    dir_rename_guess: old_directory -> best_new_directory
652 	 * where best_new_directory is the one with the highest count.
653 	 */
654 	strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
655 		/* entry->key is source_dir */
656 		struct strintmap *counts = entry->value;
657 		char *best_newdir;
658 
659 		best_newdir = xstrdup(get_highest_rename_path(counts));
660 		strmap_put(&info->dir_rename_guess, entry->key,
661 			   best_newdir);
662 	}
663 }
664 
partial_clear_dir_rename_count(struct strmap * dir_rename_count)665 void partial_clear_dir_rename_count(struct strmap *dir_rename_count)
666 {
667 	struct hashmap_iter iter;
668 	struct strmap_entry *entry;
669 
670 	strmap_for_each_entry(dir_rename_count, &iter, entry) {
671 		struct strintmap *counts = entry->value;
672 		strintmap_clear(counts);
673 	}
674 	strmap_partial_clear(dir_rename_count, 1);
675 }
676 
cleanup_dir_rename_info(struct dir_rename_info * info,struct strintmap * dirs_removed,int keep_dir_rename_count)677 static void cleanup_dir_rename_info(struct dir_rename_info *info,
678 				    struct strintmap *dirs_removed,
679 				    int keep_dir_rename_count)
680 {
681 	struct hashmap_iter iter;
682 	struct strmap_entry *entry;
683 	struct string_list to_remove = STRING_LIST_INIT_NODUP;
684 	int i;
685 
686 	if (!info->setup)
687 		return;
688 
689 	/* idx_map */
690 	strintmap_clear(&info->idx_map);
691 
692 	/* dir_rename_guess */
693 	strmap_clear(&info->dir_rename_guess, 1);
694 
695 	/* relevant_source_dirs */
696 	if (info->relevant_source_dirs &&
697 	    info->relevant_source_dirs != dirs_removed) {
698 		strintmap_clear(info->relevant_source_dirs);
699 		FREE_AND_NULL(info->relevant_source_dirs);
700 	}
701 
702 	/* dir_rename_count */
703 	if (!keep_dir_rename_count) {
704 		partial_clear_dir_rename_count(info->dir_rename_count);
705 		strmap_clear(info->dir_rename_count, 1);
706 		FREE_AND_NULL(info->dir_rename_count);
707 		return;
708 	}
709 
710 	/*
711 	 * Although dir_rename_count was passed in
712 	 * diffcore_rename_extended() and we want to keep it around and
713 	 * return it to that caller, we first want to remove any counts in
714 	 * the maps associated with UNKNOWN_DIR entries and any data
715 	 * associated with directories that weren't renamed.
716 	 */
717 	strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
718 		const char *source_dir = entry->key;
719 		struct strintmap *counts = entry->value;
720 
721 		if (!strintmap_get(dirs_removed, source_dir)) {
722 			string_list_append(&to_remove, source_dir);
723 			strintmap_clear(counts);
724 			continue;
725 		}
726 
727 		if (strintmap_contains(counts, UNKNOWN_DIR))
728 			strintmap_remove(counts, UNKNOWN_DIR);
729 	}
730 	for (i = 0; i < to_remove.nr; ++i)
731 		strmap_remove(info->dir_rename_count,
732 			      to_remove.items[i].string, 1);
733 	string_list_clear(&to_remove, 0);
734 }
735 
get_basename(const char * filename)736 static const char *get_basename(const char *filename)
737 {
738 	/*
739 	 * gitbasename() has to worry about special drives, multiple
740 	 * directory separator characters, trailing slashes, NULL or
741 	 * empty strings, etc.  We only work on filenames as stored in
742 	 * git, and thus get to ignore all those complications.
743 	 */
744 	const char *base = strrchr(filename, '/');
745 	return base ? base + 1 : filename;
746 }
747 
idx_possible_rename(char * filename,struct dir_rename_info * info)748 static int idx_possible_rename(char *filename, struct dir_rename_info *info)
749 {
750 	/*
751 	 * Our comparison of files with the same basename (see
752 	 * find_basename_matches() below), is only helpful when after exact
753 	 * rename detection we have exactly one file with a given basename
754 	 * among the rename sources and also only exactly one file with
755 	 * that basename among the rename destinations.  When we have
756 	 * multiple files with the same basename in either set, we do not
757 	 * know which to compare against.  However, there are some
758 	 * filenames that occur in large numbers (particularly
759 	 * build-related filenames such as 'Makefile', '.gitignore', or
760 	 * 'build.gradle' that potentially exist within every single
761 	 * subdirectory), and for performance we want to be able to quickly
762 	 * find renames for these files too.
763 	 *
764 	 * The reason basename comparisons are a useful heuristic was that it
765 	 * is common for people to move files across directories while keeping
766 	 * their filename the same.  If we had a way of determining or even
767 	 * making a good educated guess about which directory these non-unique
768 	 * basename files had moved the file to, we could check it.
769 	 * Luckily...
770 	 *
771 	 * When an entire directory is in fact renamed, we have two factors
772 	 * helping us out:
773 	 *   (a) the original directory disappeared giving us a hint
774 	 *       about when we can apply an extra heuristic.
775 	 *   (a) we often have several files within that directory and
776 	 *       subdirectories that are renamed without changes
777 	 * So, rules for a heuristic:
778 	 *   (0) If there basename matches are non-unique (the condition under
779 	 *       which this function is called) AND
780 	 *   (1) the directory in which the file was found has disappeared
781 	 *       (i.e. dirs_removed is non-NULL and has a relevant entry) THEN
782 	 *   (2) use exact renames of files within the directory to determine
783 	 *       where the directory is likely to have been renamed to.  IF
784 	 *       there is at least one exact rename from within that
785 	 *       directory, we can proceed.
786 	 *   (3) If there are multiple places the directory could have been
787 	 *       renamed to based on exact renames, ignore all but one of them.
788 	 *       Just use the destination with the most renames going to it.
789 	 *   (4) Check if applying that directory rename to the original file
790 	 *       would result in a destination filename that is in the
791 	 *       potential rename set.  If so, return the index of the
792 	 *       destination file (the index within rename_dst).
793 	 *   (5) Compare the original file and returned destination for
794 	 *       similarity, and if they are sufficiently similar, record the
795 	 *       rename.
796 	 *
797 	 * This function, idx_possible_rename(), is only responsible for (4).
798 	 * The conditions/steps in (1)-(3) are handled via setting up
799 	 * dir_rename_count and dir_rename_guess in
800 	 * initialize_dir_rename_info().  Steps (0) and (5) are handled by
801 	 * the caller of this function.
802 	 */
803 	char *old_dir, *new_dir;
804 	struct strbuf new_path = STRBUF_INIT;
805 	int idx;
806 
807 	if (!info->setup)
808 		return -1;
809 
810 	old_dir = get_dirname(filename);
811 	new_dir = strmap_get(&info->dir_rename_guess, old_dir);
812 	free(old_dir);
813 	if (!new_dir)
814 		return -1;
815 
816 	strbuf_addstr(&new_path, new_dir);
817 	strbuf_addch(&new_path, '/');
818 	strbuf_addstr(&new_path, get_basename(filename));
819 
820 	idx = strintmap_get(&info->idx_map, new_path.buf);
821 	strbuf_release(&new_path);
822 	return idx;
823 }
824 
825 struct basename_prefetch_options {
826 	struct repository *repo;
827 	struct strintmap *relevant_sources;
828 	struct strintmap *sources;
829 	struct strintmap *dests;
830 	struct dir_rename_info *info;
831 };
basename_prefetch(void * prefetch_options)832 static void basename_prefetch(void *prefetch_options)
833 {
834 	struct basename_prefetch_options *options = prefetch_options;
835 	struct strintmap *relevant_sources = options->relevant_sources;
836 	struct strintmap *sources = options->sources;
837 	struct strintmap *dests = options->dests;
838 	struct dir_rename_info *info = options->info;
839 	int i;
840 	struct oid_array to_fetch = OID_ARRAY_INIT;
841 
842 	/*
843 	 * TODO: The following loops mirror the code/logic from
844 	 * find_basename_matches(), though not quite exactly.  Maybe
845 	 * abstract the iteration logic out somehow?
846 	 */
847 	for (i = 0; i < rename_src_nr; ++i) {
848 		char *filename = rename_src[i].p->one->path;
849 		const char *base = NULL;
850 		intptr_t src_index;
851 		intptr_t dst_index;
852 
853 		/* Skip irrelevant sources */
854 		if (relevant_sources &&
855 		    !strintmap_contains(relevant_sources, filename))
856 			continue;
857 
858 		/*
859 		 * If the basename is unique among remaining sources, then
860 		 * src_index will equal 'i' and we can attempt to match it
861 		 * to a unique basename in the destinations.  Otherwise,
862 		 * use directory rename heuristics, if possible.
863 		 */
864 		base = get_basename(filename);
865 		src_index = strintmap_get(sources, base);
866 		assert(src_index == -1 || src_index == i);
867 
868 		if (strintmap_contains(dests, base)) {
869 			struct diff_filespec *one, *two;
870 
871 			/* Find a matching destination, if possible */
872 			dst_index = strintmap_get(dests, base);
873 			if (src_index == -1 || dst_index == -1) {
874 				src_index = i;
875 				dst_index = idx_possible_rename(filename, info);
876 			}
877 			if (dst_index == -1)
878 				continue;
879 
880 			/* Ignore this dest if already used in a rename */
881 			if (rename_dst[dst_index].is_rename)
882 				continue; /* already used previously */
883 
884 			one = rename_src[src_index].p->one;
885 			two = rename_dst[dst_index].p->two;
886 
887 			/* Add the pairs */
888 			diff_add_if_missing(options->repo, &to_fetch, two);
889 			diff_add_if_missing(options->repo, &to_fetch, one);
890 		}
891 	}
892 
893 	promisor_remote_get_direct(options->repo, to_fetch.oid, to_fetch.nr);
894 	oid_array_clear(&to_fetch);
895 }
896 
find_basename_matches(struct diff_options * options,int minimum_score,struct dir_rename_info * info,struct strintmap * relevant_sources,struct strintmap * dirs_removed)897 static int find_basename_matches(struct diff_options *options,
898 				 int minimum_score,
899 				 struct dir_rename_info *info,
900 				 struct strintmap *relevant_sources,
901 				 struct strintmap *dirs_removed)
902 {
903 	/*
904 	 * When I checked in early 2020, over 76% of file renames in linux
905 	 * just moved files to a different directory but kept the same
906 	 * basename.  gcc did that with over 64% of renames, gecko did it
907 	 * with over 79%, and WebKit did it with over 89%.
908 	 *
909 	 * Therefore we can bypass the normal exhaustive NxM matrix
910 	 * comparison of similarities between all potential rename sources
911 	 * and destinations by instead using file basename as a hint (i.e.
912 	 * the portion of the filename after the last '/'), checking for
913 	 * similarity between files with the same basename, and if we find
914 	 * a pair that are sufficiently similar, record the rename pair and
915 	 * exclude those two from the NxM matrix.
916 	 *
917 	 * This *might* cause us to find a less than optimal pairing (if
918 	 * there is another file that we are even more similar to but has a
919 	 * different basename).  Given the huge performance advantage
920 	 * basename matching provides, and given the frequency with which
921 	 * people use the same basename in real world projects, that's a
922 	 * trade-off we are willing to accept when doing just rename
923 	 * detection.
924 	 *
925 	 * If someone wants copy detection that implies they are willing to
926 	 * spend more cycles to find similarities between files, so it may
927 	 * be less likely that this heuristic is wanted.  If someone is
928 	 * doing break detection, that means they do not want filename
929 	 * similarity to imply any form of content similiarity, and thus
930 	 * this heuristic would definitely be incompatible.
931 	 */
932 
933 	int i, renames = 0;
934 	struct strintmap sources;
935 	struct strintmap dests;
936 	struct diff_populate_filespec_options dpf_options = {
937 		.check_binary = 0,
938 		.missing_object_cb = NULL,
939 		.missing_object_data = NULL
940 	};
941 	struct basename_prefetch_options prefetch_options = {
942 		.repo = options->repo,
943 		.relevant_sources = relevant_sources,
944 		.sources = &sources,
945 		.dests = &dests,
946 		.info = info
947 	};
948 
949 	/*
950 	 * Create maps of basename -> fullname(s) for remaining sources and
951 	 * dests.
952 	 */
953 	strintmap_init_with_options(&sources, -1, NULL, 0);
954 	strintmap_init_with_options(&dests, -1, NULL, 0);
955 	for (i = 0; i < rename_src_nr; ++i) {
956 		char *filename = rename_src[i].p->one->path;
957 		const char *base;
958 
959 		/* exact renames removed in remove_unneeded_paths_from_src() */
960 		assert(!rename_src[i].p->one->rename_used);
961 
962 		/* Record index within rename_src (i) if basename is unique */
963 		base = get_basename(filename);
964 		if (strintmap_contains(&sources, base))
965 			strintmap_set(&sources, base, -1);
966 		else
967 			strintmap_set(&sources, base, i);
968 	}
969 	for (i = 0; i < rename_dst_nr; ++i) {
970 		char *filename = rename_dst[i].p->two->path;
971 		const char *base;
972 
973 		if (rename_dst[i].is_rename)
974 			continue; /* involved in exact match already. */
975 
976 		/* Record index within rename_dst (i) if basename is unique */
977 		base = get_basename(filename);
978 		if (strintmap_contains(&dests, base))
979 			strintmap_set(&dests, base, -1);
980 		else
981 			strintmap_set(&dests, base, i);
982 	}
983 
984 	if (options->repo == the_repository && has_promisor_remote()) {
985 		dpf_options.missing_object_cb = basename_prefetch;
986 		dpf_options.missing_object_data = &prefetch_options;
987 	}
988 
989 	/* Now look for basename matchups and do similarity estimation */
990 	for (i = 0; i < rename_src_nr; ++i) {
991 		char *filename = rename_src[i].p->one->path;
992 		const char *base = NULL;
993 		intptr_t src_index;
994 		intptr_t dst_index;
995 
996 		/* Skip irrelevant sources */
997 		if (relevant_sources &&
998 		    !strintmap_contains(relevant_sources, filename))
999 			continue;
1000 
1001 		/*
1002 		 * If the basename is unique among remaining sources, then
1003 		 * src_index will equal 'i' and we can attempt to match it
1004 		 * to a unique basename in the destinations.  Otherwise,
1005 		 * use directory rename heuristics, if possible.
1006 		 */
1007 		base = get_basename(filename);
1008 		src_index = strintmap_get(&sources, base);
1009 		assert(src_index == -1 || src_index == i);
1010 
1011 		if (strintmap_contains(&dests, base)) {
1012 			struct diff_filespec *one, *two;
1013 			int score;
1014 
1015 			/* Find a matching destination, if possible */
1016 			dst_index = strintmap_get(&dests, base);
1017 			if (src_index == -1 || dst_index == -1) {
1018 				src_index = i;
1019 				dst_index = idx_possible_rename(filename, info);
1020 			}
1021 			if (dst_index == -1)
1022 				continue;
1023 
1024 			/* Ignore this dest if already used in a rename */
1025 			if (rename_dst[dst_index].is_rename)
1026 				continue; /* already used previously */
1027 
1028 			/* Estimate the similarity */
1029 			one = rename_src[src_index].p->one;
1030 			two = rename_dst[dst_index].p->two;
1031 			score = estimate_similarity(options->repo, one, two,
1032 						    minimum_score, &dpf_options);
1033 
1034 			/* If sufficiently similar, record as rename pair */
1035 			if (score < minimum_score)
1036 				continue;
1037 			record_rename_pair(dst_index, src_index, score);
1038 			renames++;
1039 			update_dir_rename_counts(info, dirs_removed,
1040 						 one->path, two->path);
1041 
1042 			/*
1043 			 * Found a rename so don't need text anymore; if we
1044 			 * didn't find a rename, the filespec_blob would get
1045 			 * re-used when doing the matrix of comparisons.
1046 			 */
1047 			diff_free_filespec_blob(one);
1048 			diff_free_filespec_blob(two);
1049 		}
1050 	}
1051 
1052 	strintmap_clear(&sources);
1053 	strintmap_clear(&dests);
1054 
1055 	return renames;
1056 }
1057 
1058 #define NUM_CANDIDATE_PER_DST 4
record_if_better(struct diff_score m[],struct diff_score * o)1059 static void record_if_better(struct diff_score m[], struct diff_score *o)
1060 {
1061 	int i, worst;
1062 
1063 	/* find the worst one */
1064 	worst = 0;
1065 	for (i = 1; i < NUM_CANDIDATE_PER_DST; i++)
1066 		if (score_compare(&m[i], &m[worst]) > 0)
1067 			worst = i;
1068 
1069 	/* is it better than the worst one? */
1070 	if (score_compare(&m[worst], o) > 0)
1071 		m[worst] = *o;
1072 }
1073 
1074 /*
1075  * Returns:
1076  * 0 if we are under the limit;
1077  * 1 if we need to disable inexact rename detection;
1078  * 2 if we would be under the limit if we were given -C instead of -C -C.
1079  */
too_many_rename_candidates(int num_destinations,int num_sources,struct diff_options * options)1080 static int too_many_rename_candidates(int num_destinations, int num_sources,
1081 				      struct diff_options *options)
1082 {
1083 	int rename_limit = options->rename_limit;
1084 	int i, limited_sources;
1085 
1086 	options->needed_rename_limit = 0;
1087 
1088 	/*
1089 	 * This basically does a test for the rename matrix not
1090 	 * growing larger than a "rename_limit" square matrix, ie:
1091 	 *
1092 	 *    num_destinations * num_sources > rename_limit * rename_limit
1093 	 *
1094 	 * We use st_mult() to check overflow conditions; in the
1095 	 * exceptional circumstance that size_t isn't large enough to hold
1096 	 * the multiplication, the system won't be able to allocate enough
1097 	 * memory for the matrix anyway.
1098 	 */
1099 	if (rename_limit <= 0)
1100 		return 0; /* treat as unlimited */
1101 	if (st_mult(num_destinations, num_sources)
1102 	    <= st_mult(rename_limit, rename_limit))
1103 		return 0;
1104 
1105 	options->needed_rename_limit =
1106 		num_sources > num_destinations ? num_sources : num_destinations;
1107 
1108 	/* Are we running under -C -C? */
1109 	if (!options->flags.find_copies_harder)
1110 		return 1;
1111 
1112 	/* Would we bust the limit if we were running under -C? */
1113 	for (limited_sources = i = 0; i < num_sources; i++) {
1114 		if (diff_unmodified_pair(rename_src[i].p))
1115 			continue;
1116 		limited_sources++;
1117 	}
1118 	if (st_mult(num_destinations, limited_sources)
1119 	    <= st_mult(rename_limit, rename_limit))
1120 		return 2;
1121 	return 1;
1122 }
1123 
find_renames(struct diff_score * mx,int dst_cnt,int minimum_score,int copies,struct dir_rename_info * info,struct strintmap * dirs_removed)1124 static int find_renames(struct diff_score *mx,
1125 			int dst_cnt,
1126 			int minimum_score,
1127 			int copies,
1128 			struct dir_rename_info *info,
1129 			struct strintmap *dirs_removed)
1130 {
1131 	int count = 0, i;
1132 
1133 	for (i = 0; i < dst_cnt * NUM_CANDIDATE_PER_DST; i++) {
1134 		struct diff_rename_dst *dst;
1135 
1136 		if ((mx[i].dst < 0) ||
1137 		    (mx[i].score < minimum_score))
1138 			break; /* there is no more usable pair. */
1139 		dst = &rename_dst[mx[i].dst];
1140 		if (dst->is_rename)
1141 			continue; /* already done, either exact or fuzzy. */
1142 		if (!copies && rename_src[mx[i].src].p->one->rename_used)
1143 			continue;
1144 		record_rename_pair(mx[i].dst, mx[i].src, mx[i].score);
1145 		count++;
1146 		update_dir_rename_counts(info, dirs_removed,
1147 					 rename_src[mx[i].src].p->one->path,
1148 					 rename_dst[mx[i].dst].p->two->path);
1149 	}
1150 	return count;
1151 }
1152 
remove_unneeded_paths_from_src(int detecting_copies,struct strintmap * interesting)1153 static void remove_unneeded_paths_from_src(int detecting_copies,
1154 					   struct strintmap *interesting)
1155 {
1156 	int i, new_num_src;
1157 
1158 	if (detecting_copies && !interesting)
1159 		return; /* nothing to remove */
1160 	if (break_idx)
1161 		return; /* culling incompatible with break detection */
1162 
1163 	/*
1164 	 * Note on reasons why we cull unneeded sources but not destinations:
1165 	 *   1) Pairings are stored in rename_dst (not rename_src), which we
1166 	 *      need to keep around.  So, we just can't cull rename_dst even
1167 	 *      if we wanted to.  But doing so wouldn't help because...
1168 	 *
1169 	 *   2) There is a matrix pairwise comparison that follows the
1170 	 *      "Performing inexact rename detection" progress message.
1171 	 *      Iterating over the destinations is done in the outer loop,
1172 	 *      hence we only iterate over each of those once and we can
1173 	 *      easily skip the outer loop early if the destination isn't
1174 	 *      relevant.  That's only one check per destination path to
1175 	 *      skip.
1176 	 *
1177 	 *      By contrast, the sources are iterated in the inner loop; if
1178 	 *      we check whether a source can be skipped, then we'll be
1179 	 *      checking it N separate times, once for each destination.
1180 	 *      We don't want to have to iterate over known-not-needed
1181 	 *      sources N times each, so avoid that by removing the sources
1182 	 *      from rename_src here.
1183 	 */
1184 	for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1185 		struct diff_filespec *one = rename_src[i].p->one;
1186 
1187 		/*
1188 		 * renames are stored in rename_dst, so if a rename has
1189 		 * already been detected using this source, we can just
1190 		 * remove the source knowing rename_dst has its info.
1191 		 */
1192 		if (!detecting_copies && one->rename_used)
1193 			continue;
1194 
1195 		/* If we don't care about the source path, skip it */
1196 		if (interesting && !strintmap_contains(interesting, one->path))
1197 			continue;
1198 
1199 		if (new_num_src < i)
1200 			memcpy(&rename_src[new_num_src], &rename_src[i],
1201 			       sizeof(struct diff_rename_src));
1202 		new_num_src++;
1203 	}
1204 
1205 	rename_src_nr = new_num_src;
1206 }
1207 
handle_early_known_dir_renames(struct dir_rename_info * info,struct strintmap * relevant_sources,struct strintmap * dirs_removed)1208 static void handle_early_known_dir_renames(struct dir_rename_info *info,
1209 					   struct strintmap *relevant_sources,
1210 					   struct strintmap *dirs_removed)
1211 {
1212 	/*
1213 	 * Directory renames are determined via an aggregate of all renames
1214 	 * under them and using a "majority wins" rule.  The fact that
1215 	 * "majority wins", though, means we don't need all the renames
1216 	 * under the given directory, we only need enough to ensure we have
1217 	 * a majority.
1218 	 */
1219 
1220 	int i, new_num_src;
1221 	struct hashmap_iter iter;
1222 	struct strmap_entry *entry;
1223 
1224 	if (!dirs_removed || !relevant_sources)
1225 		return; /* nothing to cull */
1226 	if (break_idx)
1227 		return; /* culling incompatbile with break detection */
1228 
1229 	/*
1230 	 * Supplement dir_rename_count with number of potential renames,
1231 	 * marking all potential rename sources as mapping to UNKNOWN_DIR.
1232 	 */
1233 	for (i = 0; i < rename_src_nr; i++) {
1234 		char *old_dir;
1235 		struct diff_filespec *one = rename_src[i].p->one;
1236 
1237 		/*
1238 		 * sources that are part of a rename will have already been
1239 		 * removed by a prior call to remove_unneeded_paths_from_src()
1240 		 */
1241 		assert(!one->rename_used);
1242 
1243 		old_dir = get_dirname(one->path);
1244 		while (*old_dir != '\0' &&
1245 		       NOT_RELEVANT != strintmap_get(dirs_removed, old_dir)) {
1246 			char *freeme = old_dir;
1247 
1248 			increment_count(info, old_dir, UNKNOWN_DIR);
1249 			old_dir = get_dirname(old_dir);
1250 
1251 			/* Free resources we don't need anymore */
1252 			free(freeme);
1253 		}
1254 		/*
1255 		 * old_dir and new_dir free'd in increment_count, but
1256 		 * get_dirname() gives us a new pointer we need to free for
1257 		 * old_dir.  Also, if the loop runs 0 times we need old_dir
1258 		 * to be freed.
1259 		 */
1260 		free(old_dir);
1261 	}
1262 
1263 	/*
1264 	 * For any directory which we need a potential rename detected for
1265 	 * (i.e. those marked as RELEVANT_FOR_SELF in dirs_removed), check
1266 	 * whether we have enough renames to satisfy the "majority rules"
1267 	 * requirement such that detecting any more renames of files under
1268 	 * it won't change the result.  For any such directory, mark that
1269 	 * we no longer need to detect a rename for it.  However, since we
1270 	 * might need to still detect renames for an ancestor of that
1271 	 * directory, use RELEVANT_FOR_ANCESTOR.
1272 	 */
1273 	strmap_for_each_entry(info->dir_rename_count, &iter, entry) {
1274 		/* entry->key is source_dir */
1275 		struct strintmap *counts = entry->value;
1276 
1277 		if (strintmap_get(dirs_removed, entry->key) ==
1278 		    RELEVANT_FOR_SELF &&
1279 		    dir_rename_already_determinable(counts)) {
1280 			strintmap_set(dirs_removed, entry->key,
1281 				      RELEVANT_FOR_ANCESTOR);
1282 		}
1283 	}
1284 
1285 	for (i = 0, new_num_src = 0; i < rename_src_nr; i++) {
1286 		struct diff_filespec *one = rename_src[i].p->one;
1287 		int val;
1288 
1289 		val = strintmap_get(relevant_sources, one->path);
1290 
1291 		/*
1292 		 * sources that were not found in relevant_sources should
1293 		 * have already been removed by a prior call to
1294 		 * remove_unneeded_paths_from_src()
1295 		 */
1296 		assert(val != -1);
1297 
1298 		if (val == RELEVANT_LOCATION) {
1299 			int removable = 1;
1300 			char *dir = get_dirname(one->path);
1301 			while (1) {
1302 				char *freeme = dir;
1303 				int res = strintmap_get(dirs_removed, dir);
1304 
1305 				/* Quit if not found or irrelevant */
1306 				if (res == NOT_RELEVANT)
1307 					break;
1308 				/* If RELEVANT_FOR_SELF, can't remove */
1309 				if (res == RELEVANT_FOR_SELF) {
1310 					removable = 0;
1311 					break;
1312 				}
1313 				/* Else continue searching upwards */
1314 				assert(res == RELEVANT_FOR_ANCESTOR);
1315 				dir = get_dirname(dir);
1316 				free(freeme);
1317 			}
1318 			free(dir);
1319 			if (removable) {
1320 				strintmap_set(relevant_sources, one->path,
1321 					      RELEVANT_NO_MORE);
1322 				continue;
1323 			}
1324 		}
1325 
1326 		if (new_num_src < i)
1327 			memcpy(&rename_src[new_num_src], &rename_src[i],
1328 			       sizeof(struct diff_rename_src));
1329 		new_num_src++;
1330 	}
1331 
1332 	rename_src_nr = new_num_src;
1333 }
1334 
free_filespec_data(struct diff_filespec * spec)1335 static void free_filespec_data(struct diff_filespec *spec)
1336 {
1337 	if (!--spec->count)
1338 		diff_free_filespec_data(spec);
1339 }
1340 
pool_free_filespec(struct mem_pool * pool,struct diff_filespec * spec)1341 static void pool_free_filespec(struct mem_pool *pool,
1342 			       struct diff_filespec *spec)
1343 {
1344 	if (!pool) {
1345 		free_filespec(spec);
1346 		return;
1347 	}
1348 
1349 	/*
1350 	 * Similar to free_filespec(), but only frees the data.  The spec
1351 	 * itself was allocated in the pool and should not be individually
1352 	 * freed.
1353 	 */
1354 	free_filespec_data(spec);
1355 }
1356 
pool_diff_free_filepair(struct mem_pool * pool,struct diff_filepair * p)1357 void pool_diff_free_filepair(struct mem_pool *pool,
1358 			     struct diff_filepair *p)
1359 {
1360 	if (!pool) {
1361 		diff_free_filepair(p);
1362 		return;
1363 	}
1364 
1365 	/*
1366 	 * Similar to diff_free_filepair() but only frees the data from the
1367 	 * filespecs; not the filespecs or the filepair which were
1368 	 * allocated from the pool.
1369 	 */
1370 	free_filespec_data(p->one);
1371 	free_filespec_data(p->two);
1372 }
1373 
diffcore_rename_extended(struct diff_options * options,struct mem_pool * pool,struct strintmap * relevant_sources,struct strintmap * dirs_removed,struct strmap * dir_rename_count,struct strmap * cached_pairs)1374 void diffcore_rename_extended(struct diff_options *options,
1375 			      struct mem_pool *pool,
1376 			      struct strintmap *relevant_sources,
1377 			      struct strintmap *dirs_removed,
1378 			      struct strmap *dir_rename_count,
1379 			      struct strmap *cached_pairs)
1380 {
1381 	int detect_rename = options->detect_rename;
1382 	int minimum_score = options->rename_score;
1383 	struct diff_queue_struct *q = &diff_queued_diff;
1384 	struct diff_queue_struct outq;
1385 	struct diff_score *mx;
1386 	int i, j, rename_count, skip_unmodified = 0;
1387 	int num_destinations, dst_cnt;
1388 	int num_sources, want_copies;
1389 	struct progress *progress = NULL;
1390 	struct mem_pool local_pool;
1391 	struct dir_rename_info info;
1392 	struct diff_populate_filespec_options dpf_options = {
1393 		.check_binary = 0,
1394 		.missing_object_cb = NULL,
1395 		.missing_object_data = NULL
1396 	};
1397 	struct inexact_prefetch_options prefetch_options = {
1398 		.repo = options->repo
1399 	};
1400 
1401 	trace2_region_enter("diff", "setup", options->repo);
1402 	info.setup = 0;
1403 	assert(!dir_rename_count || strmap_empty(dir_rename_count));
1404 	want_copies = (detect_rename == DIFF_DETECT_COPY);
1405 	if (dirs_removed && (break_idx || want_copies))
1406 		BUG("dirs_removed incompatible with break/copy detection");
1407 	if (break_idx && relevant_sources)
1408 		BUG("break detection incompatible with source specification");
1409 	if (!minimum_score)
1410 		minimum_score = DEFAULT_RENAME_SCORE;
1411 
1412 	for (i = 0; i < q->nr; i++) {
1413 		struct diff_filepair *p = q->queue[i];
1414 		if (!DIFF_FILE_VALID(p->one)) {
1415 			if (!DIFF_FILE_VALID(p->two))
1416 				continue; /* unmerged */
1417 			else if (options->single_follow &&
1418 				 strcmp(options->single_follow, p->two->path))
1419 				continue; /* not interested */
1420 			else if (!options->flags.rename_empty &&
1421 				 is_empty_blob_oid(&p->two->oid))
1422 				continue;
1423 			else if (add_rename_dst(p) < 0) {
1424 				warning("skipping rename detection, detected"
1425 					" duplicate destination '%s'",
1426 					p->two->path);
1427 				goto cleanup;
1428 			}
1429 		}
1430 		else if (!options->flags.rename_empty &&
1431 			 is_empty_blob_oid(&p->one->oid))
1432 			continue;
1433 		else if (!DIFF_PAIR_UNMERGED(p) && !DIFF_FILE_VALID(p->two)) {
1434 			/*
1435 			 * If the source is a broken "delete", and
1436 			 * they did not really want to get broken,
1437 			 * that means the source actually stays.
1438 			 * So we increment the "rename_used" score
1439 			 * by one, to indicate ourselves as a user
1440 			 */
1441 			if (p->broken_pair && !p->score)
1442 				p->one->rename_used++;
1443 			register_rename_src(p);
1444 		}
1445 		else if (want_copies) {
1446 			/*
1447 			 * Increment the "rename_used" score by
1448 			 * one, to indicate ourselves as a user.
1449 			 */
1450 			p->one->rename_used++;
1451 			register_rename_src(p);
1452 		}
1453 	}
1454 	trace2_region_leave("diff", "setup", options->repo);
1455 	if (rename_dst_nr == 0 || rename_src_nr == 0)
1456 		goto cleanup; /* nothing to do */
1457 
1458 	trace2_region_enter("diff", "exact renames", options->repo);
1459 	mem_pool_init(&local_pool, 32*1024);
1460 	/*
1461 	 * We really want to cull the candidates list early
1462 	 * with cheap tests in order to avoid doing deltas.
1463 	 */
1464 	rename_count = find_exact_renames(options, &local_pool);
1465 	/*
1466 	 * Discard local_pool immediately instead of at "cleanup:" in order
1467 	 * to reduce maximum memory usage; inexact rename detection uses up
1468 	 * a fair amount of memory, and mem_pools can too.
1469 	 */
1470 	mem_pool_discard(&local_pool, 0);
1471 	trace2_region_leave("diff", "exact renames", options->repo);
1472 
1473 	/* Did we only want exact renames? */
1474 	if (minimum_score == MAX_SCORE)
1475 		goto cleanup;
1476 
1477 	num_sources = rename_src_nr;
1478 
1479 	if (want_copies || break_idx) {
1480 		/*
1481 		 * Cull sources:
1482 		 *   - remove ones corresponding to exact renames
1483 		 *   - remove ones not found in relevant_sources
1484 		 */
1485 		trace2_region_enter("diff", "cull after exact", options->repo);
1486 		remove_unneeded_paths_from_src(want_copies, relevant_sources);
1487 		trace2_region_leave("diff", "cull after exact", options->repo);
1488 	} else {
1489 		/* Determine minimum score to match basenames */
1490 		double factor = 0.5;
1491 		char *basename_factor = getenv("GIT_BASENAME_FACTOR");
1492 		int min_basename_score;
1493 
1494 		if (basename_factor)
1495 			factor = strtol(basename_factor, NULL, 10)/100.0;
1496 		assert(factor >= 0.0 && factor <= 1.0);
1497 		min_basename_score = minimum_score +
1498 			(int)(factor * (MAX_SCORE - minimum_score));
1499 
1500 		/*
1501 		 * Cull sources:
1502 		 *   - remove ones involved in renames (found via exact match)
1503 		 */
1504 		trace2_region_enter("diff", "cull after exact", options->repo);
1505 		remove_unneeded_paths_from_src(want_copies, NULL);
1506 		trace2_region_leave("diff", "cull after exact", options->repo);
1507 
1508 		/* Preparation for basename-driven matching. */
1509 		trace2_region_enter("diff", "dir rename setup", options->repo);
1510 		initialize_dir_rename_info(&info, relevant_sources,
1511 					   dirs_removed, dir_rename_count,
1512 					   cached_pairs);
1513 		trace2_region_leave("diff", "dir rename setup", options->repo);
1514 
1515 		/* Utilize file basenames to quickly find renames. */
1516 		trace2_region_enter("diff", "basename matches", options->repo);
1517 		rename_count += find_basename_matches(options,
1518 						      min_basename_score,
1519 						      &info,
1520 						      relevant_sources,
1521 						      dirs_removed);
1522 		trace2_region_leave("diff", "basename matches", options->repo);
1523 
1524 		/*
1525 		 * Cull sources, again:
1526 		 *   - remove ones involved in renames (found via basenames)
1527 		 *   - remove ones not found in relevant_sources
1528 		 * and
1529 		 *   - remove ones in relevant_sources which are needed only
1530 		 *     for directory renames IF no ancestory directory
1531 		 *     actually needs to know any more individual path
1532 		 *     renames under them
1533 		 */
1534 		trace2_region_enter("diff", "cull basename", options->repo);
1535 		remove_unneeded_paths_from_src(want_copies, relevant_sources);
1536 		handle_early_known_dir_renames(&info, relevant_sources,
1537 					       dirs_removed);
1538 		trace2_region_leave("diff", "cull basename", options->repo);
1539 	}
1540 
1541 	/* Calculate how many rename destinations are left */
1542 	num_destinations = (rename_dst_nr - rename_count);
1543 	num_sources = rename_src_nr; /* rename_src_nr reflects lower number */
1544 
1545 	/* All done? */
1546 	if (!num_destinations || !num_sources)
1547 		goto cleanup;
1548 
1549 	switch (too_many_rename_candidates(num_destinations, num_sources,
1550 					   options)) {
1551 	case 1:
1552 		goto cleanup;
1553 	case 2:
1554 		options->degraded_cc_to_c = 1;
1555 		skip_unmodified = 1;
1556 		break;
1557 	default:
1558 		break;
1559 	}
1560 
1561 	trace2_region_enter("diff", "inexact renames", options->repo);
1562 	if (options->show_rename_progress) {
1563 		progress = start_delayed_progress(
1564 				_("Performing inexact rename detection"),
1565 				(uint64_t)num_destinations * (uint64_t)num_sources);
1566 	}
1567 
1568 	/* Finish setting up dpf_options */
1569 	prefetch_options.skip_unmodified = skip_unmodified;
1570 	if (options->repo == the_repository && has_promisor_remote()) {
1571 		dpf_options.missing_object_cb = inexact_prefetch;
1572 		dpf_options.missing_object_data = &prefetch_options;
1573 	}
1574 
1575 	CALLOC_ARRAY(mx, st_mult(NUM_CANDIDATE_PER_DST, num_destinations));
1576 	for (dst_cnt = i = 0; i < rename_dst_nr; i++) {
1577 		struct diff_filespec *two = rename_dst[i].p->two;
1578 		struct diff_score *m;
1579 
1580 		if (rename_dst[i].is_rename)
1581 			continue; /* exact or basename match already handled */
1582 
1583 		m = &mx[dst_cnt * NUM_CANDIDATE_PER_DST];
1584 		for (j = 0; j < NUM_CANDIDATE_PER_DST; j++)
1585 			m[j].dst = -1;
1586 
1587 		for (j = 0; j < rename_src_nr; j++) {
1588 			struct diff_filespec *one = rename_src[j].p->one;
1589 			struct diff_score this_src;
1590 
1591 			assert(!one->rename_used || want_copies || break_idx);
1592 
1593 			if (skip_unmodified &&
1594 			    diff_unmodified_pair(rename_src[j].p))
1595 				continue;
1596 
1597 			this_src.score = estimate_similarity(options->repo,
1598 							     one, two,
1599 							     minimum_score,
1600 							     &dpf_options);
1601 			this_src.name_score = basename_same(one, two);
1602 			this_src.dst = i;
1603 			this_src.src = j;
1604 			record_if_better(m, &this_src);
1605 			/*
1606 			 * Once we run estimate_similarity,
1607 			 * We do not need the text anymore.
1608 			 */
1609 			diff_free_filespec_blob(one);
1610 			diff_free_filespec_blob(two);
1611 		}
1612 		dst_cnt++;
1613 		display_progress(progress,
1614 				 (uint64_t)dst_cnt * (uint64_t)num_sources);
1615 	}
1616 	stop_progress(&progress);
1617 
1618 	/* cost matrix sorted by most to least similar pair */
1619 	STABLE_QSORT(mx, dst_cnt * NUM_CANDIDATE_PER_DST, score_compare);
1620 
1621 	rename_count += find_renames(mx, dst_cnt, minimum_score, 0,
1622 				     &info, dirs_removed);
1623 	if (want_copies)
1624 		rename_count += find_renames(mx, dst_cnt, minimum_score, 1,
1625 					     &info, dirs_removed);
1626 	free(mx);
1627 	trace2_region_leave("diff", "inexact renames", options->repo);
1628 
1629  cleanup:
1630 	/* At this point, we have found some renames and copies and they
1631 	 * are recorded in rename_dst.  The original list is still in *q.
1632 	 */
1633 	trace2_region_enter("diff", "write back to queue", options->repo);
1634 	DIFF_QUEUE_CLEAR(&outq);
1635 	for (i = 0; i < q->nr; i++) {
1636 		struct diff_filepair *p = q->queue[i];
1637 		struct diff_filepair *pair_to_free = NULL;
1638 
1639 		if (DIFF_PAIR_UNMERGED(p)) {
1640 			diff_q(&outq, p);
1641 		}
1642 		else if (!DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1643 			/* Creation */
1644 			diff_q(&outq, p);
1645 		}
1646 		else if (DIFF_FILE_VALID(p->one) && !DIFF_FILE_VALID(p->two)) {
1647 			/*
1648 			 * Deletion
1649 			 *
1650 			 * We would output this delete record if:
1651 			 *
1652 			 * (1) this is a broken delete and the counterpart
1653 			 *     broken create remains in the output; or
1654 			 * (2) this is not a broken delete, and rename_dst
1655 			 *     does not have a rename/copy to move p->one->path
1656 			 *     out of existence.
1657 			 *
1658 			 * Otherwise, the counterpart broken create
1659 			 * has been turned into a rename-edit; or
1660 			 * delete did not have a matching create to
1661 			 * begin with.
1662 			 */
1663 			if (DIFF_PAIR_BROKEN(p)) {
1664 				/* broken delete */
1665 				struct diff_rename_dst *dst = locate_rename_dst(p);
1666 				if (!dst)
1667 					BUG("tracking failed somehow; failed to find associated dst for broken pair");
1668 				if (dst->is_rename)
1669 					/* counterpart is now rename/copy */
1670 					pair_to_free = p;
1671 			}
1672 			else {
1673 				if (p->one->rename_used)
1674 					/* this path remains */
1675 					pair_to_free = p;
1676 			}
1677 
1678 			if (!pair_to_free)
1679 				diff_q(&outq, p);
1680 		}
1681 		else if (!diff_unmodified_pair(p))
1682 			/* all the usual ones need to be kept */
1683 			diff_q(&outq, p);
1684 		else
1685 			/* no need to keep unmodified pairs */
1686 			pair_to_free = p;
1687 
1688 		if (pair_to_free)
1689 			pool_diff_free_filepair(pool, pair_to_free);
1690 	}
1691 	diff_debug_queue("done copying original", &outq);
1692 
1693 	free(q->queue);
1694 	*q = outq;
1695 	diff_debug_queue("done collapsing", q);
1696 
1697 	for (i = 0; i < rename_dst_nr; i++)
1698 		if (rename_dst[i].filespec_to_free)
1699 			pool_free_filespec(pool, rename_dst[i].filespec_to_free);
1700 
1701 	cleanup_dir_rename_info(&info, dirs_removed, dir_rename_count != NULL);
1702 	FREE_AND_NULL(rename_dst);
1703 	rename_dst_nr = rename_dst_alloc = 0;
1704 	FREE_AND_NULL(rename_src);
1705 	rename_src_nr = rename_src_alloc = 0;
1706 	if (break_idx) {
1707 		strintmap_clear(break_idx);
1708 		FREE_AND_NULL(break_idx);
1709 	}
1710 	trace2_region_leave("diff", "write back to queue", options->repo);
1711 	return;
1712 }
1713 
diffcore_rename(struct diff_options * options)1714 void diffcore_rename(struct diff_options *options)
1715 {
1716 	diffcore_rename_extended(options, NULL, NULL, NULL, NULL, NULL);
1717 }
1718